src/message/mod.rs

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