src/message/mod.rs

1474 lines · 47838 bytes

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