src/message/mod.rs

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