src/message/mod.rs

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