src/message/mod.rs

1623 lines · 52004 bytes

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