src/message/mod.rs

1759 lines · 56270 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::{OriginalStickerEvent, RedactedStickerEvent, 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, PreviewKind, 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) -> Span<'static> {
 262        let time = self.as_datetime().format("%A, %B %d %Y").to_string();
 263
 264        Span::styled(time, BOLD_STYLE)
 265    }
 266
 267    fn show_time(self) -> Span<'static> {
 268        let time = self.as_datetime().format("%T");
 269        let time = format!("  [{time}]");
 270
 271        Span::raw(time)
 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<OriginalStickerEvent>, MediaSource),
 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.as_ref(),
 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(sticker: &OriginalStickerEvent) -> Cow<'_, str> {
 621    Cow::Owned(format!("* sent a sticker: {}", sticker.content.body))
 622}
 623
 624fn redaction_reason_unsigned(unsigned: &RedactedUnsigned) -> Option<String> {
 625    let ev = unsigned.redacted_because.deserialize().ok()?;
 626
 627    let AnyRedactionEvent::RoomRedaction(ev) = ev else {
 628        return None;
 629    };
 630
 631    ev.content.reason
 632}
 633
 634fn body_cow_reason(reason: Option<&str>) -> Cow<'static, str> {
 635    if let Some(r) = reason {
 636        Cow::Owned(format!("[Redacted: {r:?}]"))
 637    } else {
 638        Cow::Borrowed("[Redacted]")
 639    }
 640}
 641
 642enum MessageColumns {
 643    /// Four columns: sender, message, timestamp, read receipts.
 644    Four,
 645
 646    /// Three columns: sender, message, timestamp.
 647    Three,
 648
 649    /// Two columns: sender, message.
 650    Two,
 651
 652    /// One column: message with sender on line before the message.
 653    One,
 654}
 655
 656impl MessageColumns {
 657    fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
 658        if let MessageColumns::One = self {
 659            0
 660        } else {
 661            settings.tunables.user_gutter_width as u16
 662        }
 663    }
 664}
 665
 666#[derive(Default, Debug)]
 667enum SenderSpan<'a> {
 668    /// Show the sender name in the user gutter.
 669    /// This is truncated and padded to fit [`user_gutter_width`](`crate::config::TunableValues::user_gutter_width`).
 670    Gutter(Span<'a>),
 671
 672    /// Show the sender name in an extra line at the top of the message.
 673    Line(Span<'a>),
 674
 675    /// The sender name has already been printed.
 676    #[default]
 677    None,
 678}
 679
 680struct MessageFormatter<'a> {
 681    settings: &'a ApplicationSettings,
 682
 683    /// How many columns to print.
 684    cols: MessageColumns,
 685
 686    /// The full, original width.
 687    orig: usize,
 688
 689    /// The width that the message contents need to fill.
 690    fill: usize,
 691
 692    /// The formatted Span for the message sender.
 693    user: SenderSpan<'a>,
 694
 695    /// The time the message was sent.
 696    time: Option<Span<'a>>,
 697
 698    /// The date the message was sent.
 699    date: Option<Span<'a>>,
 700
 701    /// The users who have read up to this message.
 702    read: Vec<OwnedUserId>,
 703}
 704
 705impl<'a> MessageFormatter<'a> {
 706    fn width(&self) -> usize {
 707        self.fill
 708    }
 709
 710    fn message_start_line(&self) -> u16 {
 711        let mut line = 0;
 712
 713        if self.date.is_some() {
 714            line += 1;
 715        }
 716
 717        if let SenderSpan::Line(_) = self.user {
 718            line += 1;
 719        }
 720
 721        line
 722    }
 723
 724    #[inline]
 725    fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
 726        if let Some(date) = self.date.take() {
 727            let len = date.content.as_ref().len();
 728            let padding = self.orig.saturating_sub(len);
 729            let leading = space_span(padding / 2, Style::default());
 730            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
 731
 732            text.lines.push(Line::from(vec![leading, date, trailing]));
 733        }
 734
 735        let user_gutter_empty_span =
 736            space_span(self.settings.tunables.user_gutter_width, Style::default());
 737
 738        let user_gutter = match std::mem::take(&mut self.user) {
 739            SenderSpan::Line(user) => {
 740                text.lines.push(user.into());
 741                user_gutter_empty_span
 742            },
 743            SenderSpan::Gutter(user) => user,
 744            SenderSpan::None => user_gutter_empty_span,
 745        };
 746
 747        match self.cols {
 748            MessageColumns::Four => {
 749                let settings = self.settings;
 750                let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
 751
 752                let mut line = vec![user_gutter];
 753                line.extend(prev_line.spans);
 754                line.push(time);
 755
 756                // Show read receipts.
 757                let user_char = |user: OwnedUserId| -> Span { settings.get_user_char_span(&user) };
 758
 759                let a = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 760                let b = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 761                let c = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 762
 763                line.push(Span::raw(" "));
 764                line.push(c);
 765                line.push(b);
 766                line.push(a);
 767                line.push(Span::raw(" "));
 768
 769                text.lines.push(Line::from(line))
 770            },
 771            MessageColumns::Three => {
 772                let time = self.time.take().unwrap_or_else(|| Span::from(""));
 773
 774                let mut line = vec![user_gutter];
 775                line.extend(prev_line.spans);
 776                line.push(time);
 777
 778                text.lines.push(Line::from(line))
 779            },
 780            MessageColumns::Two => {
 781                let mut line = vec![user_gutter];
 782                line.extend(prev_line.spans);
 783
 784                text.lines.push(Line::from(line));
 785            },
 786            MessageColumns::One => {
 787                let leading = space_span(2, style);
 788                let mut line = vec![leading];
 789                line.extend(prev_line.spans);
 790
 791                text.lines.push(Line::from(line));
 792            },
 793        }
 794    }
 795
 796    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
 797        for line in append.lines.into_iter() {
 798            self.push_spans(line, style, text);
 799        }
 800    }
 801
 802    fn push_in_reply(
 803        &mut self,
 804        msg: &'a Message,
 805        style: Style,
 806        text: &mut Text<'a>,
 807        info: &'a RoomInfo,
 808        settings: &'a ApplicationSettings,
 809        previews: &'a PreviewManager,
 810    ) -> Option<ProtocolPreview<'a>> {
 811        let reply_style = if settings.tunables.message_user_color {
 812            style.patch(settings.get_user_color(&msg.sender))
 813        } else {
 814            style
 815        };
 816
 817        let width = self.width();
 818        let w = width.saturating_sub(2);
 819        let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews);
 820        let mut sender = msg.sender_span(info, self.settings);
 821        let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
 822        let trailing = w.saturating_sub(sender_width + 1);
 823
 824        sender.style = sender.style.patch(reply_style);
 825
 826        self.push_spans(
 827            Line::from(vec![
 828                Span::styled(" ", style),
 829                Span::styled(THICK_VERTICAL, style),
 830                sender,
 831                Span::styled(":", reply_style),
 832                space_span(trailing, reply_style),
 833            ]),
 834            style,
 835            text,
 836        );
 837
 838        // Determine the image offset of the reply header, taking into account the formatting
 839        let proto = proto.map(|p| {
 840            let y_off = text.lines.len() as u16;
 841            // Adjust x_off by 2 to account for the vertical line and indent
 842            let x_off = self.cols.user_gutter_width(settings) + 2;
 843            (p, x_off, y_off)
 844        });
 845
 846        for line in replied.lines.iter_mut() {
 847            line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
 848            line.spans.insert(0, Span::styled(" ", style));
 849        }
 850
 851        self.push_text(replied, reply_style, text);
 852
 853        proto
 854    }
 855
 856    fn push_reactions(
 857        &mut self,
 858        counts: Vec<(&'a str, usize, &'a Option<MediaSource>)>,
 859        style: Style,
 860        text: &mut Text<'a>,
 861        settings: &ApplicationSettings,
 862        previews: &'a PreviewManager,
 863    ) -> Vec<ProtocolPreview<'a>> {
 864        let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings);
 865        let mut reactions = 0;
 866        let mut protos = Vec::new();
 867
 868        for (key, count, source) in counts {
 869            if reactions != 0 {
 870                emojis.push_str(" ", style);
 871            }
 872
 873            let proto = match source
 874                .as_ref()
 875                .and_then(|source| previews.get(source, PreviewKind::Reaction))
 876            {
 877                Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
 878                // Use empty space as placeholder
 879                Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None),
 880                // Fall back to text
 881                None | Some(ImageStatus::Error(_)) => None,
 882            };
 883
 884            let name = if proto.is_some() {
 885                "  "
 886            } else if self.settings.tunables.reaction_shortcode_display {
 887                if let Some(emoji) = emojis::get(key) {
 888                    if let Some(short) = emoji.shortcode() {
 889                        short
 890                    } else {
 891                        // No ASCII shortcode name to show.
 892                        continue;
 893                    }
 894                } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
 895                    key
 896                } else {
 897                    // Not an Emoji or a printable ASCII string.
 898                    continue;
 899                }
 900            } else {
 901                key
 902            };
 903
 904            emojis.push_str("[", style);
 905            if let Some(Some(proto)) = proto {
 906                let (x, y) = emojis.cursor_pos();
 907                let y = (y + text.lines.len()) as u16;
 908                let x = x as u16 + self.cols.user_gutter_width(settings);
 909
 910                protos.push((proto, x, y));
 911            }
 912            emojis.push_str(name, style);
 913            emojis.push_str(" ", style);
 914            emojis.push_span_nobreak(Span::styled(count.to_string(), style));
 915            emojis.push_str("]", style);
 916
 917            reactions += 1;
 918        }
 919
 920        if reactions > 0 {
 921            self.push_text(emojis.finish(), style, text);
 922        }
 923
 924        protos
 925    }
 926
 927    fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
 928        if len == 0 {
 929            return;
 930        }
 931
 932        // If we have threaded replies to this message, show how many.
 933        let plural = len != 1;
 934        let style = Style::default();
 935        let mut threaded =
 936            printer::TextPrinter::new(self.width(), style, self.settings).literal(true);
 937        let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
 938        threaded.push_str(" \u{2937} ", style);
 939        threaded.push_span_nobreak(len);
 940        if plural {
 941            threaded.push_str(" replies in thread", style);
 942        } else {
 943            threaded.push_str(" reply in thread", style);
 944        }
 945
 946        self.push_text(threaded.finish(), style, text);
 947    }
 948}
 949
 950pub struct Message {
 951    pub event: MessageEvent,
 952    pub sender: OwnedUserId,
 953    pub timestamp: MessageTimeStamp,
 954    pub downloaded: bool,
 955    pub html: Option<StyleTree>,
 956}
 957
 958impl Message {
 959    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
 960        let html = event.html();
 961        let downloaded = false;
 962
 963        Message { event, sender, timestamp, downloaded, html }
 964    }
 965
 966    pub fn reply_to(&self) -> Option<OwnedEventId> {
 967        let content = match &self.event {
 968            MessageEvent::EncryptedOriginal(_) => return None,
 969            MessageEvent::EncryptedRedacted(_) => return None,
 970            MessageEvent::Local(_, _, content) => content,
 971            MessageEvent::Original(ev, _) => &ev.content,
 972            MessageEvent::Redacted(_, _) => return None,
 973            MessageEvent::State(_) => return None,
 974            MessageEvent::Sticker(ev, ..) => {
 975                return match &ev.content.relates_to {
 976                    Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()),
 977                    Some(Relation::Thread(Thread {
 978                        in_reply_to: Some(in_reply_to),
 979                        is_falling_back: false,
 980                        ..
 981                    })) => Some(in_reply_to.event_id.clone()),
 982                    Some(_) | None => None,
 983                };
 984            },
 985        };
 986
 987        match &content.relates_to {
 988            Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()),
 989            Some(Relation::Thread(Thread {
 990                in_reply_to: Some(in_reply_to),
 991                is_falling_back: false,
 992                ..
 993            })) => Some(in_reply_to.event_id.clone()),
 994            Some(_) | None => None,
 995        }
 996    }
 997
 998    pub fn thread_root(&self) -> Option<OwnedEventId> {
 999        let content = match &self.event {
1000            MessageEvent::EncryptedOriginal(_) => return None,
1001            MessageEvent::EncryptedRedacted(_) => return None,
1002            MessageEvent::Local(_, _, content) => content,
1003            MessageEvent::Original(ev, _) => &ev.content,
1004            MessageEvent::Redacted(_, _) => return None,
1005            MessageEvent::State(_) => return None,
1006            MessageEvent::Sticker(..) => return None,
1007        };
1008
1009        match &content.relates_to {
1010            Some(Relation::Thread(Thread {
1011                event_id,
1012                in_reply_to: Some(in_reply_to),
1013                is_falling_back: true,
1014                ..
1015            })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
1016            Some(_) | None => None,
1017        }
1018    }
1019
1020    pub fn image_preview(&self) -> Option<&MediaSource> {
1021        if let Some(MessageType::Image(c)) = self.event.msgtype() {
1022            return Some(&c.source);
1023        }
1024
1025        match &self.event {
1026            MessageEvent::Sticker(_, source) => Some(source),
1027
1028            _ => None,
1029        }
1030    }
1031
1032    fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
1033        let mut style = Style::default();
1034
1035        if selected {
1036            style = style.add_modifier(StyleModifier::REVERSED)
1037        }
1038
1039        if matches!(self.event, MessageEvent::Local(..)) {
1040            style = style.add_modifier(StyleModifier::ITALIC);
1041        }
1042
1043        if settings.tunables.message_user_color {
1044            let color = settings.get_user_color(&self.sender);
1045            style = style.fg(color);
1046        }
1047
1048        return style;
1049    }
1050
1051    pub fn show_date(&self, prev: Option<&Message>) -> bool {
1052        let Some(prev) = prev else { return true };
1053
1054        !prev.timestamp.same_day(self.timestamp)
1055    }
1056
1057    fn get_render_format<'a>(
1058        &'a self,
1059        prev: Option<&Message>,
1060        width: usize,
1061        info: &'a RoomInfo,
1062        settings: &'a ApplicationSettings,
1063    ) -> MessageFormatter<'a> {
1064        let orig = width;
1065        let date = self.show_date(prev).then(|| self.timestamp.show_date());
1066        let user_gutter = settings.tunables.user_gutter_width;
1067
1068        if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1069            settings.tunables.read_receipt_display
1070        {
1071            let cols = MessageColumns::Four;
1072            let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
1073            let user = self.show_sender(prev, true, info, settings, width);
1074            let time = Some(self.timestamp.show_time());
1075            let read = info
1076                .event_receipts
1077                .values()
1078                .filter_map(|receipts| self.event.event_id().and_then(|id| receipts.get(id)))
1079                .flat_map(|read| read.iter())
1080                .map(|user_id| user_id.to_owned())
1081                .collect();
1082
1083            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1084        } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1085            let cols = MessageColumns::Three;
1086            let fill = width - user_gutter - TIME_GUTTER;
1087            let user = self.show_sender(prev, true, info, settings, width);
1088            let time = Some(self.timestamp.show_time());
1089            let read = Vec::new();
1090
1091            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1092        } else if user_gutter + MIN_MSG_LEN <= width {
1093            let cols = MessageColumns::Two;
1094            let fill = width - user_gutter;
1095            let user = self.show_sender(prev, true, info, settings, width);
1096            let time = None;
1097            let read = Vec::new();
1098
1099            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1100        } else {
1101            let cols = MessageColumns::One;
1102            let fill = width.saturating_sub(2);
1103            let user = self.show_sender(prev, false, info, settings, width);
1104            let time = None;
1105            let read = Vec::new();
1106
1107            MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1108        }
1109    }
1110
1111    /// Render the message as a [Text] object for the terminal.
1112    ///
1113    /// This will also get the image preview Protocol with an x/y offset.
1114    pub fn show_with_preview<'a>(
1115        &'a self,
1116        prev: Option<&Message>,
1117        selected: bool,
1118        vwctx: &ViewportContext<MessageCursor>,
1119        info: &'a RoomInfo,
1120        settings: &'a ApplicationSettings,
1121        previews: &'a PreviewManager,
1122    ) -> (Text<'a>, Vec<ProtocolPreview<'a>>) {
1123        let width = vwctx.get_width();
1124
1125        let style = self.get_render_style(selected, settings);
1126        let mut fmt = self.get_render_format(prev, width, info, settings);
1127        let mut text = Text::default();
1128        let width = fmt.width();
1129
1130        let mut protos = Vec::new();
1131
1132        // Show the message that this one replied to, if any.
1133        let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e));
1134        if let Some(r) = reply {
1135            if let Some(r) = r {
1136                // Format the reply header, push it into the `Text` buffer, and get any image.
1137                let proto_reply = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
1138                if let Some(proto) = proto_reply {
1139                    protos.push(proto)
1140                }
1141            } else {
1142                fmt.push_spans(
1143                    Line::from(vec![
1144                        Span::styled(" ", style),
1145                        Span::styled(THICK_VERTICAL, style),
1146                        Span::styled("Original message not loaded", style),
1147                        space_span(width.saturating_sub(29), style),
1148                    ]),
1149                    style,
1150                    &mut text,
1151                );
1152            }
1153        }
1154
1155        // Now show the message contents, and the inlined reply if we couldn't find it above.
1156        let (msg, proto) = self.show_msg(width, style, settings, previews);
1157
1158        // Given our text so far, determine the image offset.
1159        if let Some(p) = proto {
1160            let y_off = text.lines.len() as u16;
1161            let x_off = fmt.cols.user_gutter_width(settings);
1162
1163            // Account for extra lines printed before the message;
1164            let y_off = y_off + fmt.message_start_line();
1165            protos.push((p, x_off, y_off));
1166        }
1167
1168        fmt.push_text(msg, style, &mut text);
1169
1170        if text.lines.is_empty() {
1171            // If there was nothing in the body, just show an empty message.
1172            fmt.push_spans(space_span(width, style).into(), style, &mut text);
1173        }
1174
1175        if self.event.is_edited() {
1176            fmt.push_spans(
1177                Line::from(vec![
1178                    Span::styled("(edited)", style.fg(Color::Gray)),
1179                    space_span(fmt.width().saturating_sub(8), style),
1180                ]),
1181                style,
1182                &mut text,
1183            );
1184        }
1185
1186        if settings.tunables.reaction_display {
1187            let reactions =
1188                self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default();
1189            let react_protos = fmt.push_reactions(reactions, style, &mut text, settings, previews);
1190            protos.extend(react_protos);
1191        }
1192
1193        if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) {
1194            fmt.push_thread_reply_count(thread.len(), &mut text);
1195        }
1196
1197        (text, protos)
1198    }
1199
1200    pub fn show<'a>(
1201        &'a self,
1202        prev: Option<&Message>,
1203        selected: bool,
1204        vwctx: &ViewportContext<MessageCursor>,
1205        info: &'a RoomInfo,
1206        settings: &'a ApplicationSettings,
1207        previews: &'a PreviewManager,
1208    ) -> Text<'a> {
1209        self.show_with_preview(prev, selected, vwctx, info, settings, previews).0
1210    }
1211
1212    fn show_msg<'a>(
1213        &'a self,
1214        width: usize,
1215        style: Style,
1216        settings: &'a ApplicationSettings,
1217        previews: &'a PreviewManager,
1218    ) -> (Text<'a>, Option<&'a Protocol>) {
1219        let mut proto = None;
1220        let placeholder = match self
1221            .image_preview()
1222            .and_then(|source| previews.get(source, PreviewKind::Message))
1223        {
1224            None => None,
1225            Some(ImageStatus::Queued(image_preview_size)) => {
1226                placeholder_frame(Some("Queued..."), width, image_preview_size)
1227            },
1228            Some(ImageStatus::Downloading(image_preview_size)) => {
1229                placeholder_frame(Some("Downloading..."), width, image_preview_size)
1230            },
1231            Some(ImageStatus::Loaded(backend)) => {
1232                proto = Some(backend);
1233                placeholder_frame(Some("No Space..."), width, &backend.size().into())
1234            },
1235            Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1236        };
1237
1238        let mut text = if let Some(placeholder) = placeholder {
1239            wrapped_text(placeholder, width, style)
1240        } else {
1241            Default::default()
1242        };
1243
1244        if let Some(mut filename) = self.event.filename() {
1245            if self.downloaded {
1246                filename.push_str(" \u{2705}");
1247            }
1248
1249            text += wrapped_text(filename, width, style);
1250        }
1251
1252        if let Some(html) = &self.html {
1253            text += html.to_text(width, style, settings);
1254        } else {
1255            let mut msg = self.event.body();
1256            if settings.tunables.message_shortcode_display {
1257                msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1258            }
1259            text += wrapped_text(msg, width, style);
1260        };
1261
1262        (text, proto)
1263    }
1264
1265    fn sender_span<'a>(
1266        &'a self,
1267        info: &'a RoomInfo,
1268        settings: &'a ApplicationSettings,
1269    ) -> Span<'a> {
1270        settings.get_user_span(self.sender.as_ref(), info)
1271    }
1272
1273    fn show_sender<'a>(
1274        &'a self,
1275        prev: Option<&Message>,
1276        gutter_enabled: bool,
1277        info: &'a RoomInfo,
1278        settings: &'a ApplicationSettings,
1279        width: usize,
1280    ) -> SenderSpan<'a> {
1281        if let Some(prev) = prev &&
1282            self.sender == prev.sender &&
1283            self.timestamp.same_day(prev.timestamp) &&
1284            !matches!(self.event.msgtype(), Some(MessageType::Emote(_)))
1285        {
1286            return SenderSpan::None;
1287        }
1288
1289        let Span { content, style } = self.sender_span(info, settings);
1290        let user_gutter = settings.tunables.user_gutter_width;
1291
1292        let show_in_gutter = gutter_enabled && user_gutter > 2;
1293
1294        if show_in_gutter {
1295            let ((truncated, width), _) = take_width(content, user_gutter - 2);
1296            let padding = user_gutter - 2 - width;
1297
1298            let sender = format!("{}{}  ", space(padding), truncated);
1299
1300            SenderSpan::Gutter(Span::styled(sender, style))
1301        } else if UnicodeWidthStr::width(content.as_ref()) > width {
1302            let ((truncated, _), _) = take_width(content, width);
1303
1304            SenderSpan::Line(Span::styled(truncated, style))
1305        } else {
1306            SenderSpan::Line(Span::styled(content, style))
1307        }
1308    }
1309
1310    pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
1311        self.event.redact(redaction);
1312        self.html = None;
1313        self.downloaded = false;
1314    }
1315
1316    pub fn set_edits(&mut self, new_edits: MessageEdits) {
1317        if let MessageEvent::Original(orig, edits) = &mut self.event {
1318            *edits = new_edits;
1319
1320            for edit in edits.values_mut() {
1321                strip_reply_fallback(&mut edit.msgtype);
1322            }
1323
1324            if let Some(most_recent) = edits.last_key_value() {
1325                self.html = content_html(&most_recent.1.msgtype);
1326            } else {
1327                self.html = content_html(&orig.content.msgtype);
1328            }
1329        }
1330    }
1331
1332    pub fn insert_edit(
1333        &mut self,
1334        key: MessageKey,
1335        mut edit: RoomMessageEventContentWithoutRelation,
1336    ) {
1337        if let MessageEvent::Original(_, edits) = &mut self.event {
1338            strip_reply_fallback(&mut edit.msgtype);
1339
1340            let inserted = edits.entry(key).insert_entry(edit);
1341            self.html = content_html(&inserted.get().msgtype);
1342        }
1343    }
1344
1345    pub fn remove_edit(&mut self, key: &MessageKey) {
1346        let MessageEvent::Original(orig_content, edits) = &mut self.event else {
1347            return;
1348        };
1349
1350        edits.remove(key);
1351
1352        let content = edits
1353            .last_key_value()
1354            .map(|(_, msg)| &msg.msgtype)
1355            .unwrap_or(&orig_content.content.msgtype);
1356
1357        self.html = content_html(content);
1358    }
1359}
1360
1361impl From<RoomEncryptedEvent> for Message {
1362    fn from(event: RoomEncryptedEvent) -> Self {
1363        let timestamp = event.origin_server_ts().into();
1364        let user_id = event.sender().to_owned();
1365        let content = match event {
1366            RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1367            RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1368        };
1369
1370        Message::new(content, user_id, timestamp)
1371    }
1372}
1373
1374impl From<OriginalRoomMessageEvent> for Message {
1375    fn from(event: OriginalRoomMessageEvent) -> Self {
1376        let timestamp = event.origin_server_ts.into();
1377        let user_id = event.sender.clone();
1378        let content = MessageEvent::Original(event.into(), Default::default());
1379
1380        Message::new(content, user_id, timestamp)
1381    }
1382}
1383
1384impl From<RedactedRoomMessageEvent> for Message {
1385    fn from(event: RedactedRoomMessageEvent) -> Self {
1386        let timestamp = event.origin_server_ts.into();
1387        let user_id = event.sender.clone();
1388
1389        let event_id = event.event_id;
1390        let reason = redaction_reason_unsigned(&event.unsigned);
1391        let content = MessageEvent::Redacted(event_id, reason);
1392
1393        Message::new(content, user_id, timestamp)
1394    }
1395}
1396
1397impl From<RoomMessageEvent> for Message {
1398    fn from(event: RoomMessageEvent) -> Self {
1399        match event {
1400            RoomMessageEvent::Original(ev) => ev.into(),
1401            RoomMessageEvent::Redacted(ev) => ev.into(),
1402        }
1403    }
1404}
1405
1406impl From<AnySyncStateEvent> for Message {
1407    fn from(event: AnySyncStateEvent) -> Self {
1408        let timestamp = event.origin_server_ts().into();
1409        let user_id = event.sender().to_owned();
1410        let event = MessageEvent::State(event.into());
1411
1412        Message::new(event, user_id, timestamp)
1413    }
1414}
1415
1416impl From<OriginalStickerEvent> for Message {
1417    fn from(event: OriginalStickerEvent) -> Self {
1418        let timestamp = event.origin_server_ts.into();
1419        let user_id = event.sender.clone();
1420        let source = event.content.source.clone().into();
1421        let content = MessageEvent::Sticker(event.into(), source);
1422
1423        Message::new(content, user_id, timestamp)
1424    }
1425}
1426
1427impl From<RedactedStickerEvent> for Message {
1428    fn from(event: RedactedStickerEvent) -> Self {
1429        let timestamp = event.origin_server_ts.into();
1430        let user_id = event.sender.clone();
1431
1432        let event_id = event.event_id;
1433        let reason = redaction_reason_unsigned(&event.unsigned);
1434        let content = MessageEvent::Redacted(event_id, reason);
1435
1436        Message::new(content, user_id, timestamp)
1437    }
1438}
1439
1440impl From<StickerEvent> for Message {
1441    fn from(event: StickerEvent) -> Self {
1442        match event {
1443            MessageLikeEvent::Original(ev) => ev.into(),
1444            MessageLikeEvent::Redacted(ev) => ev.into(),
1445        }
1446    }
1447}
1448
1449impl Display for Message {
1450    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1451        write!(f, "{}", self.event.body())
1452    }
1453}
1454
1455#[cfg(test)]
1456pub mod tests {
1457    use matrix_sdk::ruma::events::room::{
1458        ImageInfo,
1459        message::{
1460            AudioInfo,
1461            AudioMessageEventContent,
1462            FileInfo,
1463            FileMessageEventContent,
1464            ImageMessageEventContent,
1465            VideoInfo,
1466            VideoMessageEventContent,
1467        },
1468    };
1469
1470    use super::*;
1471    use crate::tests::*;
1472
1473    #[test]
1474    fn test_mc_cmp() {
1475        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1476        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1477        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1478        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1479        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1480
1481        // Everything is equal to itself.
1482        assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1483        assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1484        assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1485        assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1486        assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1487
1488        // Local echo is always greater than an origin server timestamp.
1489        assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1490        assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1491        assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1492        assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1493
1494        // mc2 is the smallest timestamp.
1495        assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1496        assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1497        assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1498        assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1499
1500        // mc3 should be less than mc4 because of its event ID.
1501        assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1502        assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1503        assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1504        assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1505
1506        // mc4 should be greater than mc3 because of its event ID.
1507        assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1508        assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1509        assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1510        assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1511
1512        // mc5 is the greatest OriginServer timestamp.
1513        assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1514        assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1515        assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1516        assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1517    }
1518
1519    #[test]
1520    fn test_mc_to_key() {
1521        let messages = mock_messages();
1522        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1523        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1524        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1525        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1526        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1527        let mc6 = MessageCursor::latest();
1528
1529        let k1 = mc1.to_key(&messages).unwrap();
1530        let k2 = mc2.to_key(&messages).unwrap();
1531        let k3 = mc3.to_key(&messages).unwrap();
1532        let k4 = mc4.to_key(&messages).unwrap();
1533        let k5 = mc5.to_key(&messages).unwrap();
1534        let k6 = mc6.to_key(&messages).unwrap();
1535
1536        // These should all be equal to their MSGN_KEYs.
1537        assert_eq!(k1, &MSG1_KEY.clone());
1538        assert_eq!(k2, &MSG2_KEY.clone());
1539        assert_eq!(k3, &MSG3_KEY.clone());
1540        assert_eq!(k4, &MSG4_KEY.clone());
1541        assert_eq!(k5, &MSG5_KEY.clone());
1542
1543        // MessageCursor::latest() turns into the largest key (our local echo message).
1544        assert_eq!(k6, &MSG1_KEY.clone());
1545
1546        // MessageCursor::latest() fails to convert for a room w/o messages.
1547        let messages_empty = Messages::new(ReceiptThread::Main);
1548        assert_eq!(mc6.to_key(&messages_empty), None);
1549    }
1550
1551    #[test]
1552    fn test_mc_to_from_cursor() {
1553        let messages = mock_messages();
1554        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1555        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1556        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1557        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1558        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1559        let mc6 = MessageCursor::latest();
1560
1561        let identity = |mc: &MessageCursor| {
1562            let c = mc.to_cursor(&messages).unwrap();
1563
1564            MessageCursor::from_cursor(&c, &messages).unwrap()
1565        };
1566
1567        // These should all convert to a Cursor and back to the original value.
1568        assert_eq!(identity(&mc1), mc1);
1569        assert_eq!(identity(&mc2), mc2);
1570        assert_eq!(identity(&mc3), mc3);
1571        assert_eq!(identity(&mc4), mc4);
1572        assert_eq!(identity(&mc5), mc5);
1573
1574        // MessageCursor::latest() should point at the most recent message after conversion.
1575        assert_eq!(identity(&mc6), mc1);
1576    }
1577
1578    #[test]
1579    fn test_placeholder_frame() {
1580        fn pretty_frame_test(str: &str) -> Option<String> {
1581            Some(str[1..].to_string())
1582        }
1583
1584        assert_eq!(
1585            placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
1586            pretty_frame_test(
1587                r#"
1588⌌  ⌍
1589
1590
1591⌎  ⌏
1592"#
1593            )
1594        );
1595
1596        assert_eq!(
1597            placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }),
1598            pretty_frame_test(
1599                r#"
1600⌌⌍
1601
1602
1603⌎⌏
1604"#
1605            )
1606        );
1607        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None);
1608
1609        assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None);
1610
1611        assert_eq!(
1612            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1613            pretty_frame_test(
1614                r#"
1615⌌  ⌍
1616 OK
1617
1618⌎  ⌏
1619"#
1620            )
1621        );
1622        assert_eq!(
1623            placeholder_frame(Some("OK"), 6, &ImagePreviewSize { width: 6, height: 6 }),
1624            pretty_frame_test(
1625                r#"
1626⌌    ⌍
1627
1628 OK
1629
1630
1631⌎    ⌏
1632"#
1633            )
1634        );
1635        assert_eq!(
1636            placeholder_frame(Some("OK"), 6, &ImagePreviewSize { width: 6, height: 7 }),
1637            pretty_frame_test(
1638                r#"
1639⌌    ⌍
1640
1641
1642 OK
1643
1644
1645⌎    ⌏
1646"#
1647            )
1648        );
1649        assert_eq!(
1650            placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1651            pretty_frame_test(
1652                r#"
1653⌌  ⌍
1654
1655
1656⌎  ⌏
1657"#
1658            )
1659        );
1660        assert_eq!(
1661            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
1662            pretty_frame_test(
1663                r#"
1664⌌  ⌍
1665⌎  ⌏
1666"#
1667            )
1668        );
1669        assert_eq!(
1670            placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
1671            pretty_frame_test(
1672                r#"
1673⌌⌍
1674
1675⌎⌏
1676"#
1677            )
1678        );
1679    }
1680
1681    #[test]
1682    fn test_display_attachment_size() {
1683        assert_eq!(
1684            content_filename(&MessageType::Image(
1685                ImageMessageEventContent::plain(
1686                    "Alt text".to_string(),
1687                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1688                )
1689                .info(Some(Box::default()))
1690            )),
1691            "[Attached Image: Alt text]".to_string().into()
1692        );
1693
1694        let mut info = ImageInfo::default();
1695        info.size = Some(442630_u32.into());
1696        assert_eq!(
1697            content_filename(&MessageType::Image(
1698                ImageMessageEventContent::plain(
1699                    "Alt text".to_string(),
1700                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1701                )
1702                .info(Some(Box::new(info)))
1703            )),
1704            "[Attached Image: Alt text (442.63 kB)]".to_string().into()
1705        );
1706
1707        let mut info = ImageInfo::default();
1708        info.size = Some(12_u32.into());
1709        assert_eq!(
1710            content_filename(&MessageType::Image(
1711                ImageMessageEventContent::plain(
1712                    "Alt text".to_string(),
1713                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1714                )
1715                .info(Some(Box::new(info)))
1716            )),
1717            "[Attached Image: Alt text (12 B)]".to_string().into()
1718        );
1719
1720        let mut info = AudioInfo::default();
1721        info.size = Some(4294967295_u32.into());
1722        assert_eq!(
1723            content_filename(&MessageType::Audio(
1724                AudioMessageEventContent::plain(
1725                    "Alt text".to_string(),
1726                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1727                )
1728                .info(Some(Box::new(info)))
1729            )),
1730            "[Attached Audio: Alt text (4.29 GB)]".to_string().into()
1731        );
1732
1733        let mut info = FileInfo::default();
1734        info.size = Some(4426300_u32.into());
1735        assert_eq!(
1736            content_filename(&MessageType::File(
1737                FileMessageEventContent::plain(
1738                    "Alt text".to_string(),
1739                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1740                )
1741                .info(Some(Box::new(info)))
1742            )),
1743            "[Attached File: Alt text (4.43 MB)]".to_string().into()
1744        );
1745
1746        let mut info = VideoInfo::default();
1747        info.size = Some(44000_u32.into());
1748        assert_eq!(
1749            content_filename(&MessageType::Video(
1750                VideoMessageEventContent::plain(
1751                    "Alt text".to_string(),
1752                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1753                )
1754                .info(Some(Box::new(info)))
1755            )),
1756            "[Attached Video: Alt text (44 kB)]".to_string().into()
1757        );
1758    }
1759}