src/message/mod.rs

1570 lines · 50304 bytes

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