src/message/mod.rs

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