src/message/mod.rs

1429 lines · 46022 bytes

   1//! # Room Messages
   2use std::borrow::Cow;
   3use std::cmp::{Ord, Ordering, PartialOrd};
   4use std::collections::hash_map::DefaultHasher;
   5use std::collections::hash_set;
   6use std::collections::BTreeMap;
   7use std::convert::{TryFrom, TryInto};
   8use std::fmt::{self, Display};
   9use std::hash::{Hash, Hasher};
  10use std::ops::{Deref, DerefMut};
  11
  12use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
  13use humansize::{format_size, DECIMAL};
  14use serde_json::json;
  15use unicode_width::UnicodeWidthStr;
  16
  17use matrix_sdk::ruma::{
  18    events::{
  19        relation::Thread,
  20        room::{
  21            encrypted::{
  22                OriginalRoomEncryptedEvent,
  23                RedactedRoomEncryptedEvent,
  24                RoomEncryptedEvent,
  25            },
  26            message::{
  27                FormattedBody,
  28                MessageFormat,
  29                MessageType,
  30                OriginalRoomMessageEvent,
  31                RedactedRoomMessageEvent,
  32                Relation,
  33                RoomMessageEvent,
  34                RoomMessageEventContent,
  35            },
  36            redaction::SyncRoomRedactionEvent,
  37        },
  38        RedactContent,
  39        RedactedUnsigned,
  40    },
  41    EventId,
  42    MilliSecondsSinceUnixEpoch,
  43    OwnedEventId,
  44    OwnedUserId,
  45    RoomVersionId,
  46    UInt,
  47};
  48
  49use ratatui::{
  50    style::{Modifier as StyleModifier, Style},
  51    symbols::line::THICK_VERTICAL,
  52    text::{Line, Span, Text},
  53};
  54
  55use modalkit::editing::cursor::Cursor;
  56use modalkit::prelude::*;
  57use ratatui_image::protocol::Protocol;
  58
  59use crate::config::ImagePreviewSize;
  60use crate::{
  61    base::RoomInfo,
  62    config::ApplicationSettings,
  63    message::html::{parse_matrix_html, StyleTree},
  64    util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
  65};
  66
  67mod compose;
  68mod html;
  69mod printer;
  70
  71pub use self::compose::text_to_message;
  72
  73pub type MessageKey = (MessageTimeStamp, OwnedEventId);
  74
  75#[derive(Default)]
  76pub struct Messages(BTreeMap<MessageKey, Message>);
  77
  78impl Deref for Messages {
  79    type Target = BTreeMap<MessageKey, Message>;
  80
  81    fn deref(&self) -> &Self::Target {
  82        &self.0
  83    }
  84}
  85
  86impl DerefMut for Messages {
  87    fn deref_mut(&mut self) -> &mut Self::Target {
  88        &mut self.0
  89    }
  90}
  91
  92impl Messages {
  93    pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) {
  94        let event_id = key.1.clone();
  95        let msg = msg.into();
  96
  97        self.0.insert(key, msg);
  98
  99        // Remove any echo.
 100        let key = (MessageTimeStamp::LocalEcho, event_id);
 101        let _ = self.0.remove(&key);
 102    }
 103}
 104
 105const fn span_static(s: &'static str) -> Span<'static> {
 106    Span {
 107        content: Cow::Borrowed(s),
 108        style: Style {
 109            fg: None,
 110            bg: None,
 111            add_modifier: StyleModifier::empty(),
 112            sub_modifier: StyleModifier::empty(),
 113            underline_color: None,
 114        },
 115    }
 116}
 117
 118const BOLD_STYLE: Style = Style {
 119    fg: None,
 120    bg: None,
 121    add_modifier: StyleModifier::BOLD,
 122    sub_modifier: StyleModifier::empty(),
 123    underline_color: None,
 124};
 125
 126const TIME_GUTTER: usize = 12;
 127const READ_GUTTER: usize = 5;
 128const MIN_MSG_LEN: usize = 30;
 129
 130const TIME_GUTTER_EMPTY: &str = "            ";
 131const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
 132
 133const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS;
 134
 135/// Convert the [u64] hash to [usize] as needed.
 136fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> {
 137    if USIZE_TOO_SMALL {
 138        (hasher.finish() % usize::MAX as u64).try_into().ok()
 139    } else {
 140        hasher.finish().try_into().ok()
 141    }
 142}
 143
 144/// Hash an [EventId] into a [usize].
 145fn hash_event_id(event_id: &EventId) -> Option<usize> {
 146    let mut hasher = DefaultHasher::new();
 147    event_id.hash(&mut hasher);
 148    hash_finish_usize(hasher)
 149}
 150
 151/// Before the image is loaded, already display a placeholder frame of the image size.
 152fn placeholder_frame(
 153    text: Option<&str>,
 154    outer_width: usize,
 155    image_preview_size: &ImagePreviewSize,
 156) -> Option<String> {
 157    let ImagePreviewSize { width, height } = image_preview_size;
 158    if outer_width < *width || (*width < 2 || *height < 2) {
 159        return None;
 160    }
 161    let mut placeholder = "\u{230c}".to_string();
 162    placeholder.push_str(&" ".repeat(width - 2));
 163    placeholder.push_str("\u{230d}\n");
 164    if *height > 2 {
 165        if let Some(text) = text {
 166            if text.width() <= width - 2 {
 167                placeholder.push(' ');
 168                placeholder.push_str(text);
 169            }
 170        }
 171    }
 172
 173    placeholder.push_str(&"\n".repeat(height - 2));
 174    placeholder.push('\u{230e}');
 175    placeholder.push_str(&" ".repeat(width - 2));
 176    placeholder.push_str("\u{230f}\n");
 177    Some(placeholder)
 178}
 179
 180#[inline]
 181fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
 182    let time = i64::from(ms) / 1000;
 183    let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
 184
 185    LocalTz.from_utc_datetime(&time)
 186}
 187
 188#[derive(thiserror::Error, Debug)]
 189pub enum TimeStampIntError {
 190    #[error("Integer conversion error: {0}")]
 191    IntError(#[from] std::num::TryFromIntError),
 192
 193    #[error("UInt conversion error: {0}")]
 194    UIntError(<UInt as TryFrom<u64>>::Error),
 195}
 196
 197#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 198pub enum MessageTimeStamp {
 199    OriginServer(UInt),
 200    LocalEcho,
 201}
 202
 203impl MessageTimeStamp {
 204    fn as_datetime(&self) -> DateTime<LocalTz> {
 205        match self {
 206            MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
 207            MessageTimeStamp::LocalEcho => LocalTz::now(),
 208        }
 209    }
 210
 211    fn same_day(&self, other: &Self) -> bool {
 212        let dt1 = self.as_datetime();
 213        let dt2 = other.as_datetime();
 214
 215        dt1.date_naive() == dt2.date_naive()
 216    }
 217
 218    fn show_date(&self) -> Option<Span> {
 219        let time = self.as_datetime().format("%A, %B %d %Y").to_string();
 220
 221        Span::styled(time, BOLD_STYLE).into()
 222    }
 223
 224    fn show_time(&self) -> Option<Span> {
 225        match self {
 226            MessageTimeStamp::OriginServer(ms) => {
 227                let time = millis_to_datetime(*ms).format("%T");
 228                let time = format!("  [{time}]");
 229
 230                Span::raw(time).into()
 231            },
 232            MessageTimeStamp::LocalEcho => None,
 233        }
 234    }
 235
 236    fn is_local_echo(&self) -> bool {
 237        matches!(self, MessageTimeStamp::LocalEcho)
 238    }
 239
 240    pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
 241        match self {
 242            MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
 243            MessageTimeStamp::LocalEcho => None,
 244        }
 245    }
 246}
 247
 248impl Ord for MessageTimeStamp {
 249    fn cmp(&self, other: &Self) -> Ordering {
 250        match (self, other) {
 251            (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
 252            (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
 253            (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
 254            (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
 255        }
 256    }
 257}
 258
 259impl PartialOrd for MessageTimeStamp {
 260    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 261        Some(self.cmp(other))
 262    }
 263}
 264
 265impl From<UInt> for MessageTimeStamp {
 266    fn from(millis: UInt) -> Self {
 267        MessageTimeStamp::OriginServer(millis)
 268    }
 269}
 270
 271impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
 272    fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
 273        MessageTimeStamp::OriginServer(millis.0)
 274    }
 275}
 276
 277impl TryFrom<&MessageTimeStamp> for usize {
 278    type Error = TimeStampIntError;
 279
 280    fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
 281        let n = match ts {
 282            MessageTimeStamp::LocalEcho => 0,
 283            MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
 284        };
 285
 286        Ok(n)
 287    }
 288}
 289
 290impl TryFrom<usize> for MessageTimeStamp {
 291    type Error = TimeStampIntError;
 292
 293    fn try_from(u: usize) -> Result<Self, Self::Error> {
 294        if u == 0 {
 295            Ok(MessageTimeStamp::LocalEcho)
 296        } else {
 297            let n = u64::try_from(u)?;
 298            let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
 299
 300            Ok(MessageTimeStamp::from(n))
 301        }
 302    }
 303}
 304
 305#[derive(Clone, Debug, Default, Eq, PartialEq)]
 306pub struct MessageCursor {
 307    /// When timestamp is None, the corner is determined by moving backwards from
 308    /// the most recently received message.
 309    pub timestamp: Option<MessageKey>,
 310
 311    /// A row within the [Text] representation of a [Message].
 312    pub text_row: usize,
 313}
 314
 315impl MessageCursor {
 316    pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
 317        MessageCursor { timestamp: Some(timestamp), text_row }
 318    }
 319
 320    /// Get a cursor that refers to the most recent message.
 321    pub fn latest() -> Self {
 322        MessageCursor::default()
 323    }
 324
 325    pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> {
 326        if let Some(ref key) = self.timestamp {
 327            Some(key)
 328        } else {
 329            Some(thread.last_key_value()?.0)
 330        }
 331    }
 332
 333    pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> {
 334        let ev_hash = cursor.get_x();
 335        let ev_term = OwnedEventId::try_from("$").ok()?;
 336
 337        let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
 338        let start = (ts_start, ev_term);
 339
 340        for ((ts, event_id), _) in thread.range(&start..) {
 341            if hash_event_id(event_id)? == ev_hash {
 342                return Self::from((*ts, event_id.clone())).into();
 343            }
 344
 345            if ts > &ts_start {
 346                break;
 347            }
 348        }
 349
 350        // If we can't find the cursor, then go to the nearest timestamp.
 351        thread
 352            .range(start..)
 353            .next()
 354            .map(|((ts, ev), _)| Self::from((*ts, ev.clone())))
 355    }
 356
 357    pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> {
 358        let (ts, event_id) = self.to_key(thread)?;
 359
 360        let y = usize::try_from(ts).ok()?;
 361        let x = hash_event_id(event_id)?;
 362
 363        Cursor::new(y, x).into()
 364    }
 365}
 366
 367impl From<Option<MessageKey>> for MessageCursor {
 368    fn from(key: Option<MessageKey>) -> Self {
 369        MessageCursor { timestamp: key, text_row: 0 }
 370    }
 371}
 372
 373impl From<MessageKey> for MessageCursor {
 374    fn from(key: MessageKey) -> Self {
 375        MessageCursor { timestamp: Some(key), text_row: 0 }
 376    }
 377}
 378
 379impl Ord for MessageCursor {
 380    fn cmp(&self, other: &Self) -> Ordering {
 381        match (&self.timestamp, &other.timestamp) {
 382            (None, None) => self.text_row.cmp(&other.text_row),
 383            (None, Some(_)) => Ordering::Greater,
 384            (Some(_), None) => Ordering::Less,
 385            (Some(st), Some(ot)) => {
 386                let pcmp = st.cmp(ot);
 387                let tcmp = self.text_row.cmp(&other.text_row);
 388
 389                pcmp.then(tcmp)
 390            },
 391        }
 392    }
 393}
 394
 395impl PartialOrd for MessageCursor {
 396    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 397        Some(self.cmp(other))
 398    }
 399}
 400
 401fn redaction_reason(ev: &SyncRoomRedactionEvent) -> Option<&str> {
 402    let SyncRoomRedactionEvent::Original(ev) = ev else {
 403        return None;
 404    };
 405
 406    return ev.content.reason.as_deref();
 407}
 408
 409fn redaction_unsigned(ev: SyncRoomRedactionEvent) -> RedactedUnsigned {
 410    let reason = redaction_reason(&ev);
 411    let redacted_because = json!({
 412        "content": {
 413            "reason": reason
 414        },
 415        "event_id": ev.event_id(),
 416        "sender": ev.sender(),
 417        "origin_server_ts": ev.origin_server_ts(),
 418        "unsigned": {},
 419    });
 420    RedactedUnsigned::new(serde_json::from_value(redacted_because).unwrap())
 421}
 422
 423#[derive(Clone)]
 424pub enum MessageEvent {
 425    EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
 426    EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
 427    Original(Box<OriginalRoomMessageEvent>),
 428    Redacted(Box<RedactedRoomMessageEvent>),
 429    Local(OwnedEventId, Box<RoomMessageEventContent>),
 430}
 431
 432impl MessageEvent {
 433    pub fn event_id(&self) -> &EventId {
 434        match self {
 435            MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
 436            MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
 437            MessageEvent::Original(ev) => ev.event_id.as_ref(),
 438            MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
 439            MessageEvent::Local(event_id, _) => event_id.as_ref(),
 440        }
 441    }
 442
 443    pub fn content(&self) -> Option<&RoomMessageEventContent> {
 444        match self {
 445            MessageEvent::EncryptedOriginal(_) => None,
 446            MessageEvent::Original(ev) => Some(&ev.content),
 447            MessageEvent::EncryptedRedacted(_) => None,
 448            MessageEvent::Redacted(_) => None,
 449            MessageEvent::Local(_, content) => Some(content),
 450        }
 451    }
 452
 453    pub fn is_emote(&self) -> bool {
 454        matches!(
 455            self.content(),
 456            Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
 457        )
 458    }
 459
 460    pub fn body(&self) -> Cow<'_, str> {
 461        match self {
 462            MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
 463            MessageEvent::Original(ev) => body_cow_content(&ev.content),
 464            MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
 465            MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
 466            MessageEvent::Local(_, content) => body_cow_content(content),
 467        }
 468    }
 469
 470    pub fn html(&self) -> Option<StyleTree> {
 471        let content = match self {
 472            MessageEvent::EncryptedOriginal(_) => return None,
 473            MessageEvent::EncryptedRedacted(_) => return None,
 474            MessageEvent::Original(ev) => &ev.content,
 475            MessageEvent::Redacted(_) => return None,
 476            MessageEvent::Local(_, content) => content,
 477        };
 478
 479        if let MessageType::Text(content) = &content.msgtype {
 480            if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
 481                Some(parse_matrix_html(body.as_str()))
 482            } else {
 483                None
 484            }
 485        } else {
 486            None
 487        }
 488    }
 489
 490    fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
 491        match self {
 492            MessageEvent::EncryptedOriginal(_) => return,
 493            MessageEvent::EncryptedRedacted(_) => return,
 494            MessageEvent::Redacted(_) => return,
 495            MessageEvent::Local(_, _) => return,
 496            MessageEvent::Original(ev) => {
 497                let redacted = RedactedRoomMessageEvent {
 498                    content: ev.content.clone().redact(version),
 499                    event_id: ev.event_id.clone(),
 500                    sender: ev.sender.clone(),
 501                    origin_server_ts: ev.origin_server_ts,
 502                    room_id: ev.room_id.clone(),
 503                    unsigned: redaction_unsigned(redaction),
 504                };
 505                *self = MessageEvent::Redacted(Box::new(redacted));
 506            },
 507        }
 508    }
 509}
 510
 511/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
 512/// `[Attached <type>: <content>[ (<human readable file size>)]]`
 513macro_rules! display_file_to_text {
 514    ( $msgtype:ident, $content:expr ) => {
 515        return Cow::Owned(format!(
 516            "[Attached {}: {}{}]",
 517            stringify!($msgtype),
 518            $content.body,
 519            $content
 520                .info
 521                .as_ref()
 522                .map(|info| {
 523                    info.size
 524                        .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
 525                        .unwrap_or_else(String::new)
 526                })
 527                .unwrap_or_else(String::new)
 528        ))
 529    };
 530}
 531
 532fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
 533    let s = match &content.msgtype {
 534        MessageType::Text(content) => content.body.as_str(),
 535        MessageType::VerificationRequest(_) => "[Verification Request]",
 536        MessageType::Emote(content) => content.body.as_ref(),
 537        MessageType::Notice(content) => content.body.as_str(),
 538        MessageType::ServerNotice(content) => content.body.as_str(),
 539
 540        MessageType::Audio(content) => {
 541            display_file_to_text!(Audio, content);
 542        },
 543        MessageType::File(content) => {
 544            display_file_to_text!(File, content);
 545        },
 546        MessageType::Image(content) => {
 547            display_file_to_text!(Image, content);
 548        },
 549        MessageType::Video(content) => {
 550            display_file_to_text!(Video, content);
 551        },
 552        _ => {
 553            match content.msgtype() {
 554                // Just show the body text for the special Element messages.
 555                "nic.custom.confetti" |
 556                "nic.custom.fireworks" |
 557                "io.element.effect.hearts" |
 558                "io.element.effect.rainfall" |
 559                "io.element.effect.snowfall" |
 560                "io.element.effects.space_invaders" => content.body(),
 561                other => {
 562                    return Cow::Owned(format!("[Unknown message type: {other:?}]"));
 563                },
 564            }
 565        },
 566    };
 567
 568    Cow::Borrowed(s)
 569}
 570
 571fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
 572    let reason = unsigned.redacted_because.content.reason.as_ref();
 573
 574    if let Some(r) = reason {
 575        Cow::Owned(format!("[Redacted: {r:?}]"))
 576    } else {
 577        Cow::Borrowed("[Redacted]")
 578    }
 579}
 580
 581enum MessageColumns {
 582    /// Four columns: sender, message, timestamp, read receipts.
 583    Four,
 584
 585    /// Three columns: sender, message, timestamp.
 586    Three,
 587
 588    /// Two columns: sender, message.
 589    Two,
 590
 591    /// One column: message with sender on line before the message.
 592    One,
 593}
 594
 595impl MessageColumns {
 596    fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
 597        if let MessageColumns::One = self {
 598            0
 599        } else {
 600            settings.tunables.user_gutter_width as u16
 601        }
 602    }
 603}
 604
 605struct MessageFormatter<'a> {
 606    settings: &'a ApplicationSettings,
 607
 608    /// How many columns to print.
 609    cols: MessageColumns,
 610
 611    /// The full, original width.
 612    orig: usize,
 613
 614    /// The width that the message contents need to fill.
 615    fill: usize,
 616
 617    /// The formatted Span for the message sender.
 618    user: Option<Span<'a>>,
 619
 620    /// The time the message was sent.
 621    time: Option<Span<'a>>,
 622
 623    /// The date the message was sent.
 624    date: Option<Span<'a>>,
 625
 626    /// Iterator over the users who have read up to this message.
 627    read: Option<hash_set::Iter<'a, OwnedUserId>>,
 628}
 629
 630impl<'a> MessageFormatter<'a> {
 631    fn width(&self) -> usize {
 632        self.fill
 633    }
 634
 635    #[inline]
 636    fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
 637        if let Some(date) = self.date.take() {
 638            let len = date.content.as_ref().len();
 639            let padding = self.orig.saturating_sub(len);
 640            let leading = space_span(padding / 2, Style::default());
 641            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
 642
 643            text.lines.push(Line::from(vec![leading, date, trailing]));
 644        }
 645
 646        let user_gutter_empty_span =
 647            space_span(self.settings.tunables.user_gutter_width, Style::default());
 648
 649        match self.cols {
 650            MessageColumns::Four => {
 651                let settings = self.settings;
 652                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 653                let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
 654
 655                let mut line = vec![user];
 656                line.extend(prev_line.spans);
 657                line.push(time);
 658
 659                // Show read receipts.
 660                let user_char =
 661                    |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
 662                let mut read = self.read.iter_mut().flatten();
 663
 664                let a = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 665                let b = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 666                let c = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 667
 668                line.push(Span::raw(" "));
 669                line.push(c);
 670                line.push(b);
 671                line.push(a);
 672                line.push(Span::raw(" "));
 673
 674                text.lines.push(Line::from(line))
 675            },
 676            MessageColumns::Three => {
 677                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 678                let time = self.time.take().unwrap_or_else(|| Span::from(""));
 679
 680                let mut line = vec![user];
 681                line.extend(prev_line.spans);
 682                line.push(time);
 683
 684                text.lines.push(Line::from(line))
 685            },
 686            MessageColumns::Two => {
 687                let user = self.user.take().unwrap_or(user_gutter_empty_span);
 688                let mut line = vec![user];
 689                line.extend(prev_line.spans);
 690
 691                text.lines.push(Line::from(line));
 692            },
 693            MessageColumns::One => {
 694                if let Some(user) = self.user.take() {
 695                    text.lines.push(Line::from(vec![user]));
 696                }
 697
 698                let leading = space_span(2, style);
 699                let mut line = vec![leading];
 700                line.extend(prev_line.spans);
 701
 702                text.lines.push(Line::from(line));
 703            },
 704        }
 705    }
 706
 707    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
 708        for line in append.lines.into_iter() {
 709            self.push_spans(line, style, text);
 710        }
 711    }
 712
 713    fn push_in_reply(
 714        &mut self,
 715        msg: &'a Message,
 716        style: Style,
 717        text: &mut Text<'a>,
 718        info: &'a RoomInfo,
 719    ) {
 720        let width = self.width();
 721        let w = width.saturating_sub(2);
 722        let shortcodes = self.settings.tunables.message_shortcode_display;
 723        let (mut replied, _) = msg.show_msg(w, style, true, shortcodes);
 724        let mut sender = msg.sender_span(info, self.settings);
 725        let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
 726        let trailing = w.saturating_sub(sender_width + 1);
 727
 728        sender.style = sender.style.patch(style);
 729
 730        self.push_spans(
 731            Line::from(vec![
 732                Span::styled(" ", style),
 733                Span::styled(THICK_VERTICAL, style),
 734                sender,
 735                Span::styled(":", style),
 736                space_span(trailing, style),
 737            ]),
 738            style,
 739            text,
 740        );
 741
 742        for line in replied.lines.iter_mut() {
 743            line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
 744            line.spans.insert(0, Span::styled(" ", style));
 745        }
 746
 747        self.push_text(replied, style, text);
 748    }
 749
 750    fn push_reactions(&mut self, counts: Vec<(&'a str, usize)>, style: Style, text: &mut Text<'a>) {
 751        let mut emojis = printer::TextPrinter::new(self.width(), style, false, false);
 752        let mut reactions = 0;
 753
 754        for (key, count) in counts {
 755            if reactions != 0 {
 756                emojis.push_str(" ", style);
 757            }
 758
 759            let name = if self.settings.tunables.reaction_shortcode_display {
 760                if let Some(emoji) = emojis::get(key) {
 761                    if let Some(short) = emoji.shortcode() {
 762                        short
 763                    } else {
 764                        // No ASCII shortcode name to show.
 765                        continue;
 766                    }
 767                } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
 768                    key
 769                } else {
 770                    // Not an Emoji or a printable ASCII string.
 771                    continue;
 772                }
 773            } else {
 774                key
 775            };
 776
 777            emojis.push_str("[", style);
 778            emojis.push_str(name, style);
 779            emojis.push_str(" ", style);
 780            emojis.push_span_nobreak(Span::styled(count.to_string(), style));
 781            emojis.push_str("]", style);
 782
 783            reactions += 1;
 784        }
 785
 786        if reactions > 0 {
 787            self.push_text(emojis.finish(), style, text);
 788        }
 789    }
 790
 791    fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
 792        if len == 0 {
 793            return;
 794        }
 795
 796        // If we have threaded replies to this message, show how many.
 797        let plural = len != 1;
 798        let style = Style::default();
 799        let mut threaded =
 800            printer::TextPrinter::new(self.width(), style, false, false).literal(true);
 801        let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
 802        threaded.push_str(" \u{2937} ", style);
 803        threaded.push_span_nobreak(len);
 804        if plural {
 805            threaded.push_str(" replies in thread", style);
 806        } else {
 807            threaded.push_str(" reply in thread", style);
 808        }
 809
 810        self.push_text(threaded.finish(), style, text);
 811    }
 812}
 813
 814pub enum ImageStatus {
 815    None,
 816    Downloading(ImagePreviewSize),
 817    Loaded(Box<dyn Protocol>),
 818    Error(String),
 819}
 820
 821pub struct Message {
 822    pub event: MessageEvent,
 823    pub sender: OwnedUserId,
 824    pub timestamp: MessageTimeStamp,
 825    pub downloaded: bool,
 826    pub html: Option<StyleTree>,
 827    pub image_preview: ImageStatus,
 828}
 829
 830impl Message {
 831    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
 832        let html = event.html();
 833        let downloaded = false;
 834
 835        Message {
 836            event,
 837            sender,
 838            timestamp,
 839            downloaded,
 840            html,
 841            image_preview: ImageStatus::None,
 842        }
 843    }
 844
 845    pub fn reply_to(&self) -> Option<OwnedEventId> {
 846        let content = match &self.event {
 847            MessageEvent::EncryptedOriginal(_) => return None,
 848            MessageEvent::EncryptedRedacted(_) => return None,
 849            MessageEvent::Local(_, content) => content,
 850            MessageEvent::Original(ev) => &ev.content,
 851            MessageEvent::Redacted(_) => return None,
 852        };
 853
 854        match &content.relates_to {
 855            Some(Relation::Reply { in_reply_to }) => Some(in_reply_to.event_id.clone()),
 856            Some(Relation::Thread(Thread {
 857                in_reply_to: Some(in_reply_to),
 858                is_falling_back: false,
 859                ..
 860            })) => Some(in_reply_to.event_id.clone()),
 861            Some(_) | None => None,
 862        }
 863    }
 864
 865    fn thread_root(&self) -> Option<OwnedEventId> {
 866        let content = match &self.event {
 867            MessageEvent::EncryptedOriginal(_) => return None,
 868            MessageEvent::EncryptedRedacted(_) => return None,
 869            MessageEvent::Local(_, content) => content,
 870            MessageEvent::Original(ev) => &ev.content,
 871            MessageEvent::Redacted(_) => return None,
 872        };
 873
 874        match &content.relates_to {
 875            Some(Relation::Thread(Thread {
 876                event_id,
 877                in_reply_to: Some(in_reply_to),
 878                is_falling_back: true,
 879                ..
 880            })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
 881            Some(_) | None => None,
 882        }
 883    }
 884
 885    fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
 886        let mut style = Style::default();
 887
 888        if selected {
 889            style = style.add_modifier(StyleModifier::REVERSED)
 890        }
 891
 892        if self.timestamp.is_local_echo() {
 893            style = style.add_modifier(StyleModifier::ITALIC);
 894        }
 895
 896        if settings.tunables.message_user_color {
 897            let color = settings.get_user_color(&self.sender);
 898            style = style.fg(color);
 899        }
 900
 901        return style;
 902    }
 903
 904    fn get_render_format<'a>(
 905        &'a self,
 906        prev: Option<&Message>,
 907        width: usize,
 908        info: &'a RoomInfo,
 909        settings: &'a ApplicationSettings,
 910    ) -> MessageFormatter<'a> {
 911        let orig = width;
 912        let date = match &prev {
 913            Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
 914            _ => self.timestamp.show_date(),
 915        };
 916        let user_gutter = settings.tunables.user_gutter_width;
 917
 918        if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
 919            settings.tunables.read_receipt_display
 920        {
 921            let cols = MessageColumns::Four;
 922            let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
 923            let user = self.show_sender(prev, true, info, settings);
 924            let time = self.timestamp.show_time();
 925            let read = info.event_receipts.get(self.event.event_id()).map(|read| read.iter());
 926
 927            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 928        } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
 929            let cols = MessageColumns::Three;
 930            let fill = width - user_gutter - TIME_GUTTER;
 931            let user = self.show_sender(prev, true, info, settings);
 932            let time = self.timestamp.show_time();
 933            let read = None;
 934
 935            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 936        } else if user_gutter + MIN_MSG_LEN <= width {
 937            let cols = MessageColumns::Two;
 938            let fill = width - user_gutter;
 939            let user = self.show_sender(prev, true, info, settings);
 940            let time = None;
 941            let read = None;
 942
 943            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 944        } else {
 945            let cols = MessageColumns::One;
 946            let fill = width.saturating_sub(2);
 947            let user = self.show_sender(prev, false, info, settings);
 948            let time = None;
 949            let read = None;
 950
 951            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
 952        }
 953    }
 954
 955    /// Render the message as a [Text] object for the terminal.
 956    ///
 957    /// This will also get the image preview Protocol with an x/y offset.
 958    pub fn show_with_preview<'a>(
 959        &'a self,
 960        prev: Option<&Message>,
 961        selected: bool,
 962        vwctx: &ViewportContext<MessageCursor>,
 963        info: &'a RoomInfo,
 964        settings: &'a ApplicationSettings,
 965    ) -> (Text<'a>, Option<(&dyn Protocol, u16, u16)>) {
 966        let width = vwctx.get_width();
 967
 968        let style = self.get_render_style(selected, settings);
 969        let mut fmt = self.get_render_format(prev, width, info, settings);
 970        let mut text = Text::default();
 971        let width = fmt.width();
 972
 973        // Show the message that this one replied to, if any.
 974        let reply = self
 975            .reply_to()
 976            .or_else(|| self.thread_root())
 977            .and_then(|e| info.get_event(&e));
 978
 979        if let Some(r) = &reply {
 980            fmt.push_in_reply(r, style, &mut text, info);
 981        }
 982
 983        // Now show the message contents, and the inlined reply if we couldn't find it above.
 984        let (msg, proto) = self.show_msg(
 985            width,
 986            style,
 987            reply.is_some(),
 988            settings.tunables.message_shortcode_display,
 989        );
 990
 991        // Given our text so far, determine the image offset.
 992        let proto = proto.map(|p| {
 993            let y_off = text.lines.len() as u16;
 994            let x_off = fmt.cols.user_gutter_width(settings);
 995            // Adjust y_off by 1 if a date was printed before the message to account for the extra line.
 996            let y_off = if fmt.date.is_some() { y_off + 1 } else { y_off };
 997            (p, x_off, y_off)
 998        });
 999
1000        fmt.push_text(msg, style, &mut text);
1001
1002        if text.lines.is_empty() {
1003            // If there was nothing in the body, just show an empty message.
1004            fmt.push_spans(space_span(width, style).into(), style, &mut text);
1005        }
1006
1007        if settings.tunables.reaction_display {
1008            let reactions = info.get_reactions(self.event.event_id());
1009            fmt.push_reactions(reactions, style, &mut text);
1010        }
1011
1012        if let Some(thread) = info.get_thread(Some(self.event.event_id())) {
1013            fmt.push_thread_reply_count(thread.len(), &mut text);
1014        }
1015
1016        (text, proto)
1017    }
1018
1019    pub fn show<'a>(
1020        &'a self,
1021        prev: Option<&Message>,
1022        selected: bool,
1023        vwctx: &ViewportContext<MessageCursor>,
1024        info: &'a RoomInfo,
1025        settings: &'a ApplicationSettings,
1026    ) -> Text<'a> {
1027        self.show_with_preview(prev, selected, vwctx, info, settings).0
1028    }
1029
1030    fn show_msg(
1031        &self,
1032        width: usize,
1033        style: Style,
1034        hide_reply: bool,
1035        emoji_shortcodes: bool,
1036    ) -> (Text, Option<&dyn Protocol>) {
1037        if let Some(html) = &self.html {
1038            (html.to_text(width, style, hide_reply, emoji_shortcodes), None)
1039        } else {
1040            let mut msg = self.event.body();
1041            if emoji_shortcodes {
1042                msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1043            }
1044
1045            if self.downloaded {
1046                msg.to_mut().push_str(" \u{2705}");
1047            }
1048
1049            let mut proto = None;
1050            let placeholder = match &self.image_preview {
1051                ImageStatus::None => None,
1052                ImageStatus::Downloading(image_preview_size) => {
1053                    placeholder_frame(Some("Downloading..."), width, image_preview_size)
1054                },
1055                ImageStatus::Loaded(backend) => {
1056                    proto = Some(backend.as_ref());
1057                    placeholder_frame(None, width, &backend.rect().into())
1058                },
1059                ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
1060            };
1061
1062            if let Some(placeholder) = placeholder {
1063                msg.to_mut().insert_str(0, &placeholder);
1064            }
1065
1066            (wrapped_text(msg, width, style), proto)
1067        }
1068    }
1069
1070    fn sender_span<'a>(
1071        &'a self,
1072        info: &'a RoomInfo,
1073        settings: &'a ApplicationSettings,
1074    ) -> Span<'a> {
1075        settings.get_user_span(self.sender.as_ref(), info)
1076    }
1077
1078    fn show_sender<'a>(
1079        &'a self,
1080        prev: Option<&Message>,
1081        align_right: bool,
1082        info: &'a RoomInfo,
1083        settings: &'a ApplicationSettings,
1084    ) -> Option<Span<'a>> {
1085        if let Some(prev) = prev {
1086            if self.sender == prev.sender &&
1087                self.timestamp.same_day(&prev.timestamp) &&
1088                !self.event.is_emote()
1089            {
1090                return None;
1091            }
1092        }
1093
1094        let Span { content, style } = self.sender_span(info, settings);
1095        let user_gutter = settings.tunables.user_gutter_width;
1096        let ((truncated, width), _) = take_width(content, user_gutter - 2);
1097        let padding = user_gutter - 2 - width;
1098
1099        let sender = if align_right {
1100            space(padding) + &truncated + "  "
1101        } else {
1102            truncated.into_owned() + &space(padding) + "  "
1103        };
1104
1105        Span::styled(sender, style).into()
1106    }
1107
1108    pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
1109        self.event.redact(redaction, version);
1110        self.html = None;
1111    }
1112}
1113
1114impl From<RoomEncryptedEvent> for Message {
1115    fn from(event: RoomEncryptedEvent) -> Self {
1116        let timestamp = event.origin_server_ts().into();
1117        let user_id = event.sender().to_owned();
1118        let content = match event {
1119            RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1120            RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1121        };
1122
1123        Message::new(content, user_id, timestamp)
1124    }
1125}
1126
1127impl From<OriginalRoomMessageEvent> for Message {
1128    fn from(event: OriginalRoomMessageEvent) -> Self {
1129        let timestamp = event.origin_server_ts.into();
1130        let user_id = event.sender.clone();
1131        let content = MessageEvent::Original(event.into());
1132
1133        Message::new(content, user_id, timestamp)
1134    }
1135}
1136
1137impl From<RedactedRoomMessageEvent> for Message {
1138    fn from(event: RedactedRoomMessageEvent) -> Self {
1139        let timestamp = event.origin_server_ts.into();
1140        let user_id = event.sender.clone();
1141        let content = MessageEvent::Redacted(event.into());
1142
1143        Message::new(content, user_id, timestamp)
1144    }
1145}
1146
1147impl From<RoomMessageEvent> for Message {
1148    fn from(event: RoomMessageEvent) -> Self {
1149        match event {
1150            RoomMessageEvent::Original(ev) => ev.into(),
1151            RoomMessageEvent::Redacted(ev) => ev.into(),
1152        }
1153    }
1154}
1155
1156impl Display for Message {
1157    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158        write!(f, "{}", self.event.body())
1159    }
1160}
1161
1162#[cfg(test)]
1163pub mod tests {
1164    use matrix_sdk::ruma::events::room::{
1165        message::{
1166            AudioInfo,
1167            AudioMessageEventContent,
1168            FileInfo,
1169            FileMessageEventContent,
1170            ImageMessageEventContent,
1171            VideoInfo,
1172            VideoMessageEventContent,
1173        },
1174        ImageInfo,
1175    };
1176
1177    use super::*;
1178    use crate::tests::*;
1179
1180    #[test]
1181    fn test_mc_cmp() {
1182        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1183        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1184        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1185        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1186        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1187
1188        // Everything is equal to itself.
1189        assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1190        assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1191        assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1192        assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1193        assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1194
1195        // Local echo is always greater than an origin server timestamp.
1196        assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1197        assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1198        assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1199        assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1200
1201        // mc2 is the smallest timestamp.
1202        assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1203        assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1204        assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1205        assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1206
1207        // mc3 should be less than mc4 because of its event ID.
1208        assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1209        assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1210        assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1211        assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1212
1213        // mc4 should be greater than mc3 because of its event ID.
1214        assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1215        assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1216        assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1217        assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1218
1219        // mc5 is the greatest OriginServer timestamp.
1220        assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1221        assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1222        assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1223        assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1224    }
1225
1226    #[test]
1227    fn test_mc_to_key() {
1228        let messages = mock_messages();
1229        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1230        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1231        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1232        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1233        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1234        let mc6 = MessageCursor::latest();
1235
1236        let k1 = mc1.to_key(&messages).unwrap();
1237        let k2 = mc2.to_key(&messages).unwrap();
1238        let k3 = mc3.to_key(&messages).unwrap();
1239        let k4 = mc4.to_key(&messages).unwrap();
1240        let k5 = mc5.to_key(&messages).unwrap();
1241        let k6 = mc6.to_key(&messages).unwrap();
1242
1243        // These should all be equal to their MSGN_KEYs.
1244        assert_eq!(k1, &MSG1_KEY.clone());
1245        assert_eq!(k2, &MSG2_KEY.clone());
1246        assert_eq!(k3, &MSG3_KEY.clone());
1247        assert_eq!(k4, &MSG4_KEY.clone());
1248        assert_eq!(k5, &MSG5_KEY.clone());
1249
1250        // MessageCursor::latest() turns into the largest key (our local echo message).
1251        assert_eq!(k6, &MSG1_KEY.clone());
1252
1253        // MessageCursor::latest() fails to convert for a room w/o messages.
1254        let messages_empty = Messages::default();
1255        assert_eq!(mc6.to_key(&messages_empty), None);
1256    }
1257
1258    #[test]
1259    fn test_mc_to_from_cursor() {
1260        let messages = mock_messages();
1261        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1262        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1263        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1264        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1265        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1266        let mc6 = MessageCursor::latest();
1267
1268        let identity = |mc: &MessageCursor| {
1269            let c = mc.to_cursor(&messages).unwrap();
1270
1271            MessageCursor::from_cursor(&c, &messages).unwrap()
1272        };
1273
1274        // These should all convert to a Cursor and back to the original value.
1275        assert_eq!(identity(&mc1), mc1);
1276        assert_eq!(identity(&mc2), mc2);
1277        assert_eq!(identity(&mc3), mc3);
1278        assert_eq!(identity(&mc4), mc4);
1279        assert_eq!(identity(&mc5), mc5);
1280
1281        // MessageCursor::latest() should point at the most recent message after conversion.
1282        assert_eq!(identity(&mc6), mc1);
1283    }
1284
1285    #[test]
1286    fn test_placeholder_frame() {
1287        fn pretty_frame_test(str: &str) -> Option<String> {
1288            Some(str[1..].to_string())
1289        }
1290
1291        assert_eq!(
1292            placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
1293            pretty_frame_test(
1294                r#"
1295⌌  ⌍
1296
1297
1298⌎  ⌏
1299"#
1300            )
1301        );
1302
1303        assert_eq!(placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }), None);
1304        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None);
1305
1306        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None);
1307
1308        assert_eq!(
1309            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1310            pretty_frame_test(
1311                r#"
1312⌌  ⌍
1313 OK
1314
1315⌎  ⌏
1316"#
1317            )
1318        );
1319        assert_eq!(
1320            placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1321            pretty_frame_test(
1322                r#"
1323⌌  ⌍
1324
1325
1326⌎  ⌏
1327"#
1328            )
1329        );
1330        assert_eq!(
1331            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
1332            pretty_frame_test(
1333                r#"
1334⌌  ⌍
1335⌎  ⌏
1336"#
1337            )
1338        );
1339        assert_eq!(
1340            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
1341            pretty_frame_test(
1342                r#"
1343⌌⌍
1344
1345⌎⌏
1346"#
1347            )
1348        );
1349    }
1350
1351    #[test]
1352    fn test_display_attachment_size() {
1353        assert_eq!(
1354            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1355                ImageMessageEventContent::plain(
1356                    "Alt text".to_string(),
1357                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1358                )
1359                .info(Some(Box::default()))
1360            ))),
1361            "[Attached Image: Alt text]".to_string()
1362        );
1363
1364        let mut info = ImageInfo::default();
1365        info.size = Some(442630_u32.into());
1366        assert_eq!(
1367            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1368                ImageMessageEventContent::plain(
1369                    "Alt text".to_string(),
1370                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1371                )
1372                .info(Some(Box::new(info)))
1373            ))),
1374            "[Attached Image: Alt text (442.63 kB)]".to_string()
1375        );
1376
1377        let mut info = ImageInfo::default();
1378        info.size = Some(12_u32.into());
1379        assert_eq!(
1380            body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1381                ImageMessageEventContent::plain(
1382                    "Alt text".to_string(),
1383                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1384                )
1385                .info(Some(Box::new(info)))
1386            ))),
1387            "[Attached Image: Alt text (12 B)]".to_string()
1388        );
1389
1390        let mut info = AudioInfo::default();
1391        info.size = Some(4294967295_u32.into());
1392        assert_eq!(
1393            body_cow_content(&RoomMessageEventContent::new(MessageType::Audio(
1394                AudioMessageEventContent::plain(
1395                    "Alt text".to_string(),
1396                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1397                )
1398                .info(Some(Box::new(info)))
1399            ))),
1400            "[Attached Audio: Alt text (4.29 GB)]".to_string()
1401        );
1402
1403        let mut info = FileInfo::default();
1404        info.size = Some(4426300_u32.into());
1405        assert_eq!(
1406            body_cow_content(&RoomMessageEventContent::new(MessageType::File(
1407                FileMessageEventContent::plain(
1408                    "Alt text".to_string(),
1409                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1410                )
1411                .info(Some(Box::new(info)))
1412            ))),
1413            "[Attached File: Alt text (4.43 MB)]".to_string()
1414        );
1415
1416        let mut info = VideoInfo::default();
1417        info.size = Some(44000_u32.into());
1418        assert_eq!(
1419            body_cow_content(&RoomMessageEventContent::new(MessageType::Video(
1420                VideoMessageEventContent::plain(
1421                    "Alt text".to_string(),
1422                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1423                )
1424                .info(Some(Box::new(info)))
1425            ))),
1426            "[Attached Video: Alt text (44 kB)]".to_string()
1427        );
1428    }
1429}