src/message/mod.rs

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