src/message/mod.rs

1442 lines · 46687 bytes

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