src/message/mod.rs

2237 lines · 76458 bytes

   1//! # Room Messages
   2
   3use std::cmp::{Ord, PartialOrd};
   4use std::collections::hash_map::DefaultHasher;
   5use std::convert::TryInto;
   6use std::hash::{Hash, Hasher};
   7use std::sync::Arc;
   8
   9use chrono::{DateTime, Local as LocalTz};
  10use humansize::{DECIMAL, format_size};
  11use matrix_sdk::ruma::UInt;
  12use matrix_sdk::ruma::events::Mentions;
  13use matrix_sdk::ruma::events::RedactedUnsigned;
  14use matrix_sdk::ruma::events::poll::start::RedactedPollStartEvent;
  15use matrix_sdk::ruma::events::poll::unstable_start::RedactedUnstablePollStartEvent;
  16use matrix_sdk::ruma::events::room::encrypted::{
  17    OriginalRoomEncryptedEvent,
  18    RedactedRoomEncryptedEvent,
  19    RoomEncryptedEvent,
  20};
  21use matrix_sdk::ruma::events::room::message::RoomMessageEventContentWithoutRelation;
  22use matrix_sdk::ruma::events::room::message::sanitize::remove_plain_reply_fallback;
  23use matrix_sdk::ruma::events::room::message::{
  24    FormattedBody,
  25    MessageFormat,
  26    RedactedRoomMessageEvent,
  27    RoomMessageEvent,
  28};
  29use matrix_sdk::ruma::events::room::redaction::SyncRoomRedactionEvent;
  30use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent};
  31use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
  32use matrix_sdk::ruma::{OwnedTransactionId, UserId};
  33use matrix_sdk::send_queue::SendHandle;
  34use modalkit::editing::cursor::Cursor;
  35use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL};
  36
  37use crate::base::{MessageEdits, Thread};
  38use crate::message::html::{StyleTree, parse_matrix_html};
  39use crate::message::poll::{Poll, UnstablePoll};
  40use crate::message::state::{body_cow_state, html_state};
  41use crate::prelude::*;
  42use crate::preview::ImageStatus;
  43use crate::util::{replace_emojis_in_str, space, space_span, take_width_grapheme, wrapped_text};
  44
  45mod compose;
  46mod html;
  47mod printer;
  48mod state;
  49
  50pub mod poll;
  51
  52pub use self::compose::{text_to_message, text_to_text_message_event_content};
  53pub use self::html::TreeGenState;
  54
  55/// `proto, x, y`
  56type ProtocolPreview = (Arc<SlicedProtocol>, u16, u16);
  57
  58/// The key used for uniquely identifying messages within a room and its threads.
  59///
  60/// Note that the ordering of the fields is important here, so that the derived
  61/// `Ord` trait will sort by timestamp first, and then sort by the message ID.
  62#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
  63pub struct MessageKey {
  64    pub ts: MessageTimeStamp,
  65    pub id: MessageId,
  66}
  67
  68pub struct Messages(BTreeMap<MessageKey, Message>, pub ReceiptThread);
  69
  70impl Deref for Messages {
  71    type Target = BTreeMap<MessageKey, Message>;
  72
  73    fn deref(&self) -> &Self::Target {
  74        &self.0
  75    }
  76}
  77
  78impl DerefMut for Messages {
  79    fn deref_mut(&mut self) -> &mut Self::Target {
  80        &mut self.0
  81    }
  82}
  83
  84impl Messages {
  85    pub fn new(thread: ReceiptThread) -> Self {
  86        Self(Default::default(), thread)
  87    }
  88
  89    pub fn main() -> Self {
  90        Self::new(ReceiptThread::Main)
  91    }
  92
  93    pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) {
  94        let mut msg = msg.into();
  95        if let MessageEvent::Original(ev, edits) = &mut msg.event {
  96            if has_reply_fallback(ev.content.relates_to.as_ref()) {
  97                strip_reply_fallback(&mut ev.content.msgtype);
  98            }
  99            for edit in edits.values_mut() {
 100                strip_reply_fallback(&mut edit.msgtype);
 101            }
 102        }
 103
 104        self.0.entry(key).or_insert(msg);
 105    }
 106}
 107
 108const READ_GUTTER: usize = 5;
 109const MIN_MSG_LEN: usize = 30;
 110
 111const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS;
 112
 113/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
 114/// `[Attached <type>: <content>[ (<human readable file size>)]]`
 115macro_rules! display_file_name {
 116    ( $msgtype:ident, $content:expr ) => {{
 117        format!(
 118            "[Attached {}: {}{}]",
 119            stringify!($msgtype),
 120            $content.filename(),
 121            $content
 122                .info
 123                .as_ref()
 124                .map(|info| {
 125                    info.size
 126                        .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
 127                        .unwrap_or_else(String::new)
 128                })
 129                .unwrap_or_else(String::new)
 130        )
 131    }};
 132}
 133
 134/// Macro rule extraction the text caption of a File / Image / Audio / Video
 135macro_rules! display_file_to_text {
 136    ( $msgtype:ident, $content:expr ) => {{
 137        if $content
 138            .filename
 139            .as_ref()
 140            .is_none_or(|filename| *filename == $content.body)
 141        {
 142            return Cow::Borrowed("");
 143        }
 144        $content.body.as_str()
 145    }};
 146}
 147
 148fn content_filename(msgtype: &MessageType) -> Option<String> {
 149    match msgtype {
 150        MessageType::Audio(content) => Some(display_file_name!(Audio, content)),
 151        MessageType::File(content) => Some(display_file_name!(File, content)),
 152        MessageType::Image(content) => Some(display_file_name!(Image, content)),
 153        MessageType::Video(content) => Some(display_file_name!(Video, content)),
 154        _ => None,
 155    }
 156}
 157
 158/// Convert the [u64] hash to [usize] as needed.
 159fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> {
 160    if USIZE_TOO_SMALL {
 161        (hasher.finish() % usize::MAX as u64).try_into().ok()
 162    } else {
 163        hasher.finish().try_into().ok()
 164    }
 165}
 166
 167/// Hash an [`MessageId`] into a [`usize`].
 168fn hash_message_id(id: &MessageId) -> Option<usize> {
 169    let mut hasher = DefaultHasher::new();
 170    id.hash(&mut hasher);
 171    hash_finish_usize(hasher)
 172}
 173
 174/// Before the image is loaded, already display a placeholder frame of the image size.
 175fn placeholder_frame(text: Option<&str>, outer_width: usize, image_preview_size: &Size) -> String {
 176    let Size { width, height } = image_preview_size;
 177    let width = usize::min(*width as usize, outer_width);
 178    if width < 2 || *height < 2 {
 179        let mut line = "#".repeat(width);
 180        line.push('\n');
 181        return line.repeat(*height as usize);
 182    }
 183    let mut placeholder = "\u{230c}".to_string();
 184    placeholder.push_str(&" ".repeat(width - 2));
 185    placeholder.push('\u{230d}');
 186    placeholder.push_str(&"\n".repeat((*height as usize - 1) / 2));
 187
 188    if *height > 2 &&
 189        let Some(text) = text &&
 190        text.width() <= width - 2
 191    {
 192        placeholder.push(' ');
 193        placeholder.push_str(text);
 194    }
 195
 196    placeholder.push_str(&"\n".repeat(*height as usize / 2));
 197    placeholder.push('\u{230e}');
 198    placeholder.push_str(&" ".repeat(width - 2));
 199    placeholder.push_str("\u{230f}\n");
 200    placeholder
 201}
 202
 203#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
 204pub enum MessageId {
 205    Origin(OwnedEventId),
 206    Local(OwnedTransactionId),
 207}
 208
 209impl MessageId {
 210    pub fn as_origin(&self) -> Option<&EventId> {
 211        match self {
 212            Self::Origin(id) => Some(id),
 213            _ => None,
 214        }
 215    }
 216}
 217
 218impl Display for MessageId {
 219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 220        match self {
 221            MessageId::Origin(id) => write!(f, "{}", id),
 222            MessageId::Local(id) => write!(f, "{}", id),
 223        }
 224    }
 225}
 226
 227impl From<OwnedEventId> for MessageId {
 228    fn from(value: OwnedEventId) -> Self {
 229        Self::Origin(value)
 230    }
 231}
 232
 233impl From<OwnedTransactionId> for MessageId {
 234    fn from(value: OwnedTransactionId) -> Self {
 235        Self::Local(value)
 236    }
 237}
 238
 239#[derive(thiserror::Error, Debug)]
 240pub enum TimeStampIntError {
 241    #[error("Integer conversion error: {0}")]
 242    IntError(#[from] std::num::TryFromIntError),
 243
 244    #[error("UInt conversion error: {0}")]
 245    UIntError(<UInt as TryFrom<u64>>::Error),
 246}
 247
 248#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
 249pub struct MessageTimeStamp(pub MilliSecondsSinceUnixEpoch);
 250
 251impl MessageTimeStamp {
 252    pub(crate) fn as_datetime(self) -> DateTime<LocalTz> {
 253        let time = i64::from(self.0.0) / 1000;
 254        let time = DateTime::from_timestamp(time, 0).unwrap_or_default();
 255        time.into()
 256    }
 257
 258    fn same_day(self, other: Self) -> bool {
 259        let dt1 = self.as_datetime();
 260        let dt2 = other.as_datetime();
 261
 262        dt1.date_naive() == dt2.date_naive()
 263    }
 264
 265    fn show_date(self, settings: &ApplicationSettings) -> Span<'static> {
 266        let time = self
 267            .as_datetime()
 268            .format(settings.tunables.date_format.as_str())
 269            .to_string();
 270
 271        Span::styled(time, settings.theme.timeline.date)
 272    }
 273
 274    /// A compact date and time, for places without a date separator line.
 275    pub fn show_datetime(self) -> String {
 276        self.as_datetime().format("%Y-%m-%d %H:%M").to_string()
 277    }
 278
 279    fn show_time(self, settings: &ApplicationSettings) -> Span<'static> {
 280        let time = self
 281            .as_datetime()
 282            .format(settings.tunables.time_format.as_str())
 283            .to_string();
 284
 285        Span::styled(time, settings.theme.timeline.time)
 286    }
 287}
 288
 289impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
 290    fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
 291        Self(millis)
 292    }
 293}
 294
 295impl TryFrom<&MessageTimeStamp> for usize {
 296    type Error = TimeStampIntError;
 297
 298    fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
 299        let n = usize::try_from(u64::from(ts.0.0))?;
 300
 301        Ok(n)
 302    }
 303}
 304
 305impl TryFrom<usize> for MessageTimeStamp {
 306    type Error = TimeStampIntError;
 307
 308    fn try_from(u: usize) -> Result<Self, Self::Error> {
 309        let n = u64::try_from(u)?;
 310        let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
 311
 312        Ok(MessageTimeStamp::from(MilliSecondsSinceUnixEpoch(n)))
 313    }
 314}
 315
 316#[derive(Clone, Debug, Default, Eq, PartialEq)]
 317pub struct MessageCursor {
 318    /// When timestamp is None, the corner is determined by moving backwards from
 319    /// the most recently received message.
 320    pub timestamp: Option<MessageKey>,
 321
 322    /// A row within the [Text] representation of a [Message].
 323    pub text_row: usize,
 324}
 325
 326impl MessageCursor {
 327    pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
 328        MessageCursor { timestamp: Some(timestamp), text_row }
 329    }
 330
 331    /// Get a cursor that refers to the most recent message.
 332    pub fn latest() -> Self {
 333        MessageCursor::default()
 334    }
 335
 336    pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> {
 337        if let Some(ref key) = self.timestamp {
 338            Some(key)
 339        } else {
 340            Some(thread.last_key_value()?.0)
 341        }
 342    }
 343
 344    pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> {
 345        let ev_hash = cursor.get_x();
 346        let ev_term = OwnedEventId::try_from("$").ok()?.into();
 347
 348        let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
 349        let start = MessageKey { ts: ts_start, id: ev_term };
 350
 351        for (key, _) in thread.range(&start..) {
 352            if hash_message_id(&key.id)? == ev_hash {
 353                return Self::from(key.clone()).into();
 354            }
 355
 356            if key.ts > ts_start {
 357                break;
 358            }
 359        }
 360
 361        // If we can't find the cursor, then go to the nearest timestamp.
 362        thread.range(start..).next().map(|(key, _)| Self::from(key.clone()))
 363    }
 364
 365    pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> {
 366        let key = self.to_key(thread)?;
 367
 368        let y = usize::try_from(&key.ts).ok()?;
 369        let x = hash_message_id(&key.id)?;
 370
 371        Cursor::new(y, x).into()
 372    }
 373}
 374
 375impl From<Option<MessageKey>> for MessageCursor {
 376    fn from(key: Option<MessageKey>) -> Self {
 377        MessageCursor { timestamp: key, text_row: 0 }
 378    }
 379}
 380
 381impl From<MessageKey> for MessageCursor {
 382    fn from(key: MessageKey) -> Self {
 383        MessageCursor { timestamp: Some(key), text_row: 0 }
 384    }
 385}
 386
 387impl Ord for MessageCursor {
 388    fn cmp(&self, other: &Self) -> Ordering {
 389        match (&self.timestamp, &other.timestamp) {
 390            (None, None) => self.text_row.cmp(&other.text_row),
 391            (None, Some(_)) => Ordering::Greater,
 392            (Some(_), None) => Ordering::Less,
 393            (Some(st), Some(ot)) => {
 394                let pcmp = st.cmp(ot);
 395                let tcmp = self.text_row.cmp(&other.text_row);
 396
 397                pcmp.then(tcmp)
 398            },
 399        }
 400    }
 401}
 402
 403impl PartialOrd for MessageCursor {
 404    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 405        Some(self.cmp(other))
 406    }
 407}
 408
 409fn redaction_reason_event(ev: SyncRoomRedactionEvent) -> Option<String> {
 410    let SyncRoomRedactionEvent::Original(ev) = ev else {
 411        return None;
 412    };
 413
 414    ev.content.reason
 415}
 416
 417fn has_reply_fallback(relation: Option<&Relation<RoomMessageEventContentWithoutRelation>>) -> bool {
 418    matches!(
 419        relation,
 420        Some(Relation::Reply(_) | Relation::Thread(ThreadRelation { in_reply_to: Some(_), .. }))
 421    )
 422}
 423
 424pub fn strip_reply_fallback(msgtype: &mut MessageType) {
 425    let MessageType::Text(content) = msgtype else {
 426        return;
 427    };
 428
 429    content.body = remove_plain_reply_fallback(&content.body).to_owned();
 430}
 431
 432fn content_html(msgtype: &MessageType) -> Option<StyleTree> {
 433    let formatted = match msgtype {
 434        MessageType::Text(content) => content.formatted.as_ref(),
 435        MessageType::Emote(content) => content.formatted.as_ref(),
 436        MessageType::Notice(content) => content.formatted.as_ref(),
 437
 438        MessageType::Audio(content) => content.formatted_caption(),
 439        MessageType::File(content) => content.formatted_caption(),
 440        MessageType::Video(content) => content.formatted_caption(),
 441        MessageType::Image(content) => content.formatted_caption(),
 442        _ => None,
 443    };
 444
 445    let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted {
 446        Some(parse_matrix_html(body.as_str()))
 447    } else {
 448        None
 449    };
 450
 451    if let Some(filename) = content_filename(msgtype) {
 452        let html = html.get_or_insert_with(|| {
 453            let text = body_cow_content(msgtype).into_owned();
 454            let text = html::StyleTreeNode::Text(text.into());
 455            let text = html::StyleTreeNode::Paragraph(Box::new(text));
 456            StyleTree { children: vec![text] }
 457        });
 458
 459        html.children.insert(0, html::StyleTreeNode::Text(filename.into()));
 460
 461        if let MessageType::Image(content) = msgtype {
 462            let src = content.source.clone();
 463            html.children.insert(
 464                0,
 465                html::StyleTreeNode::Image(html::Image::new(src, content.info.as_deref())),
 466            );
 467        }
 468    }
 469
 470    html
 471}
 472
 473#[derive(Clone, Debug)]
 474pub enum MessageEvent {
 475    EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
 476    EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
 477    Original(Box<OriginalRoomMessageEvent>, MessageEdits),
 478    Redacted(OwnedEventId, Option<String>),
 479    State(Box<AnySyncStateEvent>),
 480    Sticker(Box<OriginalStickerEvent>),
 481    Local(OwnedTransactionId, SendHandle, Box<RoomMessageEventContent>),
 482    Poll(Box<Poll>),
 483    UnstablePoll(Box<UnstablePoll>),
 484}
 485
 486impl MessageEvent {
 487    pub fn event_id(&self) -> Option<&EventId> {
 488        let event_id = match self {
 489            MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
 490            MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
 491            MessageEvent::Original(ev, _) => ev.event_id.as_ref(),
 492            MessageEvent::Redacted(event_id, _) => event_id.as_ref(),
 493            MessageEvent::State(ev) => ev.event_id(),
 494            MessageEvent::Local(..) => return None,
 495            MessageEvent::Sticker(ev, ..) => ev.event_id.as_ref(),
 496            MessageEvent::Poll(ev) => ev.event_id(),
 497            MessageEvent::UnstablePoll(ev) => ev.event_id(),
 498        };
 499
 500        Some(event_id)
 501    }
 502
 503    pub fn msgtype(&self) -> Option<&MessageType> {
 504        match self {
 505            MessageEvent::Original(ev, edits) => {
 506                edits
 507                    .last_key_value()
 508                    .map(|(_, ev)| &ev.msgtype)
 509                    .or(Some(&ev.content.msgtype))
 510            },
 511            MessageEvent::Local(_, _, content) => Some(&content.msgtype),
 512            MessageEvent::EncryptedOriginal(..) |
 513            MessageEvent::EncryptedRedacted(..) |
 514            MessageEvent::Redacted(..) |
 515            MessageEvent::State(..) |
 516            MessageEvent::Sticker(..) |
 517            MessageEvent::Poll(..) |
 518            MessageEvent::UnstablePoll(..) => None,
 519        }
 520    }
 521
 522    pub fn body(&self) -> Cow<'_, str> {
 523        match self {
 524            MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
 525            MessageEvent::Original(ev, edits) => {
 526                let msgtype = edits
 527                    .last_key_value()
 528                    .map(|(_, ev)| &ev.msgtype)
 529                    .unwrap_or(&ev.content.msgtype);
 530                body_cow_content(msgtype)
 531            },
 532            MessageEvent::EncryptedRedacted(ev) => {
 533                body_cow_reason(redaction_reason_unsigned(&ev.unsigned).as_deref())
 534            },
 535            MessageEvent::Redacted(_, reason) => body_cow_reason(reason.as_deref()),
 536            MessageEvent::Sticker(ev, ..) => body_cow_sticker(ev),
 537            MessageEvent::State(ev) => body_cow_state(ev),
 538            MessageEvent::Local(_, _, content) => body_cow_content(&content.msgtype),
 539            MessageEvent::Poll(poll) => poll.body_cow(),
 540            MessageEvent::UnstablePoll(poll) => poll.body_cow(),
 541        }
 542    }
 543
 544    pub fn html(&self) -> Option<StyleTree> {
 545        if let MessageEvent::State(ev) = self {
 546            return Some(html_state(ev));
 547        }
 548
 549        self.msgtype().and_then(content_html)
 550    }
 551
 552    pub fn mentions(&self) -> Option<&Mentions> {
 553        match self {
 554            MessageEvent::EncryptedOriginal(..) |
 555            MessageEvent::EncryptedRedacted(..) |
 556            MessageEvent::Redacted(..) |
 557            MessageEvent::Sticker(..) |
 558            MessageEvent::Poll(..) |
 559            MessageEvent::UnstablePoll(..) |
 560            MessageEvent::State(..) => None,
 561            MessageEvent::Original(ev, edits) => {
 562                edits
 563                    .last_key_value()
 564                    .and_then(|(_, ev)| ev.mentions.as_ref())
 565                    .or(ev.content.mentions.as_ref())
 566            },
 567            MessageEvent::Local(_, _, ev) => ev.mentions.as_ref(),
 568        }
 569    }
 570
 571    fn message_style(&self, settings: &ApplicationSettings) -> Style {
 572        let content = match self {
 573            MessageEvent::EncryptedOriginal(_) | MessageEvent::EncryptedRedacted(_) => {
 574                return settings.theme.timeline.default;
 575            },
 576            MessageEvent::Redacted(..) => return settings.theme.timeline.redacted,
 577            MessageEvent::State(_) => return settings.theme.timeline.state,
 578            MessageEvent::Original(ev, _) => &ev.content,
 579            MessageEvent::Local(_, _, content) => content,
 580            MessageEvent::Sticker(..) => return settings.theme.timeline.sticker,
 581            MessageEvent::Poll(..) | MessageEvent::UnstablePoll(..) => {
 582                return settings.theme.timeline.poll;
 583            },
 584        };
 585
 586        match &content.msgtype {
 587            MessageType::Text(_) |
 588            MessageType::Audio(_) |
 589            MessageType::Emote(_) |
 590            MessageType::File(_) |
 591            MessageType::Image(_) |
 592            MessageType::Video(_) => settings.theme.messages.default,
 593            MessageType::Notice(_) | MessageType::ServerNotice(_) => settings.theme.timeline.notice,
 594            _ => settings.theme.messages.default,
 595        }
 596    }
 597
 598    fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
 599        match self {
 600            MessageEvent::EncryptedOriginal(_) => return,
 601            MessageEvent::EncryptedRedacted(_) => return,
 602            MessageEvent::Redacted(_, _) => return,
 603            MessageEvent::State(_) => return,
 604            MessageEvent::Sticker(ev, ..) => {
 605                let event_id = ev.event_id.to_owned();
 606                let reason = redaction_reason_event(redaction);
 607                *self = MessageEvent::Redacted(event_id, reason);
 608            },
 609            MessageEvent::Local(..) => return,
 610            MessageEvent::Original(ev, _) => {
 611                let event_id = ev.event_id.to_owned();
 612                let reason = redaction_reason_event(redaction);
 613                *self = MessageEvent::Redacted(event_id, reason);
 614            },
 615            MessageEvent::Poll(ev) => {
 616                let event_id = ev.event_id().to_owned();
 617                let reason = redaction_reason_event(redaction);
 618                *self = MessageEvent::Redacted(event_id, reason);
 619            },
 620            MessageEvent::UnstablePoll(ev) => {
 621                let event_id = ev.event_id().to_owned();
 622                let reason = redaction_reason_event(redaction);
 623                *self = MessageEvent::Redacted(event_id, reason);
 624            },
 625        }
 626    }
 627
 628    fn is_edited(&self) -> bool {
 629        match self {
 630            Self::Original(_, edits) => !edits.is_empty(),
 631            Self::Poll(poll) => !poll.replacements.is_empty(),
 632            Self::UnstablePoll(poll) => !poll.replacements.is_empty(),
 633            _ => false,
 634        }
 635    }
 636}
 637
 638fn body_cow_content(msgtype: &MessageType) -> Cow<'_, str> {
 639    let s = match msgtype {
 640        MessageType::Text(content) => content.body.as_str(),
 641        MessageType::VerificationRequest(_) => "[Verification Request]",
 642        MessageType::Emote(content) => content.body.as_ref(),
 643        MessageType::Notice(content) => content.body.as_str(),
 644        MessageType::ServerNotice(content) => content.body.as_str(),
 645
 646        MessageType::Audio(content) => {
 647            display_file_to_text!(Audio, content)
 648        },
 649        MessageType::File(content) => {
 650            display_file_to_text!(File, content)
 651        },
 652        MessageType::Image(content) => {
 653            display_file_to_text!(Image, content)
 654        },
 655        MessageType::Video(content) => {
 656            display_file_to_text!(Video, content)
 657        },
 658        _ => msgtype.body(),
 659    };
 660
 661    Cow::Borrowed(s)
 662}
 663
 664fn body_cow_sticker(sticker: &OriginalStickerEvent) -> Cow<'_, str> {
 665    Cow::Owned(format!("* sent a sticker: {}", sticker.content.body))
 666}
 667
 668fn redaction_reason_unsigned(unsigned: &RedactedUnsigned) -> Option<String> {
 669    let ev = unsigned.redacted_because.deserialize().ok()?;
 670
 671    let AnyRedactionEvent::RoomRedaction(ev) = ev else {
 672        return None;
 673    };
 674
 675    ev.content.reason
 676}
 677
 678fn body_cow_reason(reason: Option<&str>) -> Cow<'static, str> {
 679    if let Some(r) = reason {
 680        Cow::Owned(format!("[Redacted: {r:?}]"))
 681    } else {
 682        Cow::Borrowed("[Redacted]")
 683    }
 684}
 685
 686enum MessageColumns {
 687    /// Four columns: sender, message, timestamp, read receipts.
 688    Four,
 689
 690    /// Three columns: sender, message, timestamp.
 691    Three,
 692
 693    /// Two columns: sender, message.
 694    Two,
 695
 696    /// One column: message with sender on line before the message.
 697    One,
 698}
 699
 700impl MessageColumns {
 701    fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
 702        if let MessageColumns::One = self {
 703            2
 704        } else {
 705            settings.tunables.user_gutter_width as u16
 706        }
 707    }
 708}
 709
 710#[derive(Default, Debug)]
 711enum SenderSpan<'a> {
 712    /// Show the sender name in the user gutter.
 713    /// This is truncated and padded to fit [`user_gutter_width`](`crate::config::TunableValues::user_gutter_width`).
 714    Gutter(Span<'a>),
 715
 716    /// Show the sender name in an extra line at the top of the message.
 717    Line(Span<'a>),
 718
 719    /// The sender name has already been printed.
 720    #[default]
 721    None,
 722}
 723
 724struct MessageFormatter<'a> {
 725    settings: &'a ApplicationSettings,
 726    info: &'a RoomInfo,
 727
 728    /// How many columns to print.
 729    cols: MessageColumns,
 730
 731    /// The full, original width.
 732    orig: usize,
 733
 734    /// The width that the message contents need to fill.
 735    fill: usize,
 736
 737    /// The formatted Span for the message sender.
 738    user: SenderSpan<'a>,
 739
 740    /// The time the message was sent.
 741    time: Option<Span<'a>>,
 742
 743    /// The date the message was sent.
 744    date: Option<Span<'a>>,
 745
 746    /// Whether to draw the read marker's trackbar above this message.
 747    trackbar: bool,
 748
 749    /// The users who have read up to this message.
 750    read: Vec<OwnedUserId>,
 751}
 752
 753impl<'a> MessageFormatter<'a> {
 754    fn width(&self) -> usize {
 755        self.fill
 756    }
 757
 758    fn message_start_line(&self) -> u16 {
 759        let mut line = 0;
 760
 761        if self.date.is_some() {
 762            line += 1;
 763        }
 764
 765        if self.trackbar {
 766            line += 1;
 767        }
 768
 769        if let SenderSpan::Line(_) = self.user {
 770            line += 1;
 771        }
 772
 773        line
 774    }
 775
 776    #[inline]
 777    fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
 778        if std::mem::take(&mut self.trackbar) {
 779            let trackbar_style = self.settings.theme.timeline.unread_marker;
 780            text.lines
 781                .push(Line::from(Span::styled(HORIZONTAL.repeat(self.orig), trackbar_style)));
 782        }
 783
 784        if let Some(date) = self.date.take() {
 785            let len = date.content.as_ref().len();
 786            let padding = self.orig.saturating_sub(len);
 787            let leading = space_span(padding / 2, Style::default());
 788            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
 789
 790            text.lines.push(Line::from(vec![leading, date, trailing]));
 791        }
 792
 793        let user_gutter_empty_span =
 794            space_span(self.settings.tunables.user_gutter_width, Style::default());
 795
 796        let user_gutter = match std::mem::take(&mut self.user) {
 797            SenderSpan::Line(user) => {
 798                text.lines.push(user.into());
 799                user_gutter_empty_span
 800            },
 801            SenderSpan::Gutter(user) => user,
 802            SenderSpan::None => user_gutter_empty_span,
 803        };
 804
 805        match self.cols {
 806            MessageColumns::Four => {
 807                let settings = self.settings;
 808                let time = self.time.take().unwrap_or_else(|| {
 809                    space_span(settings.tunables.time_gutter_width, Style::default())
 810                });
 811
 812                let mut line = vec![user_gutter];
 813                line.extend(prev_line.spans);
 814                line.push(time);
 815
 816                // Show read receipts.
 817                let user_char =
 818                    |user: OwnedUserId| -> Span { settings.get_user_char_span(&user, self.info) };
 819
 820                let a = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 821                let b = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 822                let c = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" "));
 823
 824                line.push(Span::raw(" "));
 825                line.push(c);
 826                line.push(b);
 827                line.push(a);
 828                line.push(Span::raw(" "));
 829
 830                text.lines.push(Line::from(line))
 831            },
 832            MessageColumns::Three => {
 833                let time = self.time.take().unwrap_or_else(|| Span::from(""));
 834
 835                let mut line = vec![user_gutter];
 836                line.extend(prev_line.spans);
 837                line.push(time);
 838
 839                text.lines.push(Line::from(line))
 840            },
 841            MessageColumns::Two => {
 842                let mut line = vec![user_gutter];
 843                line.extend(prev_line.spans);
 844
 845                text.lines.push(Line::from(line));
 846            },
 847            MessageColumns::One => {
 848                let leading = space_span(2, style);
 849                let mut line = vec![leading];
 850                line.extend(prev_line.spans);
 851
 852                text.lines.push(Line::from(line));
 853            },
 854        }
 855    }
 856
 857    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
 858        for line in append.lines.into_iter() {
 859            self.push_spans(line, style, text);
 860        }
 861    }
 862
 863    fn push_in_reply(
 864        &mut self,
 865        msg: &'a Message,
 866        style: Style,
 867        text: &mut Text<'a>,
 868        info: &'a RoomInfo,
 869        settings: &'a ApplicationSettings,
 870        previews: &'a PreviewManager,
 871    ) -> Vec<ProtocolPreview> {
 872        let reply_style = if settings.tunables.message_user_color {
 873            style.patch(settings.get_user_color(&msg.sender))
 874        } else {
 875            style.patch(msg.event.message_style(settings))
 876        };
 877
 878        let width = self.width();
 879        let w = width.saturating_sub(2);
 880        let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews, info);
 881        let mut sender = msg.sender_span(info, self.settings);
 882        let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
 883        let trailing = w.saturating_sub(sender_width + 1);
 884
 885        sender.style = sender.style.patch(reply_style);
 886
 887        self.push_spans(
 888            Line::from(vec![
 889                Span::styled(" ", style),
 890                Span::styled(THICK_VERTICAL, style),
 891                sender,
 892                Span::styled(":", reply_style),
 893                space_span(trailing, reply_style),
 894            ]),
 895            style,
 896            text,
 897        );
 898
 899        // Determine the image offset of the reply header, taking into account the formatting
 900        let proto = proto
 901            .into_iter()
 902            .map(|(p, x, y)| {
 903                let y_off = text.lines.len() as u16;
 904                // Adjust x_off by 2 to account for the vertical line and indent
 905                let x_off = self.cols.user_gutter_width(settings) + 2;
 906                (p, x + x_off, y + y_off)
 907            })
 908            .collect();
 909
 910        for line in replied.lines.iter_mut() {
 911            line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
 912            line.spans.insert(0, Span::styled(" ", style));
 913        }
 914
 915        self.push_text(replied, reply_style, text);
 916
 917        proto
 918    }
 919
 920    fn push_reactions(
 921        &mut self,
 922        counts: Vec<(&'a str, Vec<&'a UserId>, &'a Option<MediaSource>)>,
 923        style: Style,
 924        text: &mut Text<'a>,
 925        settings: &ApplicationSettings,
 926        previews: &'a PreviewManager,
 927    ) -> Vec<ProtocolPreview> {
 928        let mut emojis = printer::TextPrinter::new(
 929            self.width(),
 930            style,
 931            self.settings,
 932            self.info,
 933            Some(previews),
 934        );
 935        let mut reactions = 0;
 936
 937        for (key, count, source) in counts {
 938            if reactions != 0 {
 939                emojis.push_str(" ", style);
 940            }
 941
 942            let proto =
 943                match source.as_ref().and_then(|source| previews.get(source, PreviewKind::Emoji)) {
 944                    Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
 945                    // Use empty space as placeholder
 946                    Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None),
 947                    // Fall back to text
 948                    None | Some(ImageStatus::Error(_)) => None,
 949                };
 950
 951            let name = if proto.is_some() {
 952                "  "
 953            } else if self.settings.tunables.reaction_shortcode_display {
 954                if let Some(emoji) = emojis::get(key) {
 955                    if let Some(short) = emoji.shortcode() {
 956                        short
 957                    } else {
 958                        // No ASCII shortcode name to show.
 959                        continue;
 960                    }
 961                } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
 962                    key
 963                } else {
 964                    // Not an Emoji or a printable ASCII string.
 965                    continue;
 966                }
 967            } else {
 968                key
 969            };
 970
 971            emojis.push_str("[", style);
 972            if let Some(Some(proto)) = proto {
 973                emojis.push_emoji(proto, style);
 974            } else {
 975                emojis.push_str(name, style);
 976            }
 977            emojis.push_str(" ", style);
 978            emojis.push_span_nobreak(Span::styled(count.len().to_string(), style));
 979            emojis.push_str("]", style);
 980
 981            reactions += 1;
 982        }
 983
 984        if reactions > 0 {
 985            let (txt, protos) = emojis.finish();
 986
 987            let x_off = self.cols.user_gutter_width(settings);
 988            let y_off = text.lines.len() as u16;
 989
 990            self.push_text(txt, style, text);
 991
 992            protos.into_iter().map(|(p, x, y)| (p, x + x_off, y + y_off)).collect()
 993        } else {
 994            vec![]
 995        }
 996    }
 997
 998    fn push_thread_reply_count(&mut self, thread: &Thread, text: &mut Text<'a>, style: Style) {
 999        let len = thread.summary.as_ref().map(|s| s.num_replies).unwrap_or_default();
1000        let len = thread.len().max(len as usize);
1001
1002        if len == 0 {
1003            return;
1004        }
1005
1006        // If we have threaded replies to this message, show how many.
1007        let is_plural = len != 1;
1008        let mut threaded =
1009            printer::TextPrinter::new(self.width(), style, self.settings, self.info, None)
1010                .literal(true);
1011        let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
1012        threaded.push_str(" \u{2937} ", style);
1013        threaded.push_span_nobreak(len);
1014        if is_plural {
1015            threaded.push_str(" replies in thread", style);
1016        } else {
1017            threaded.push_str(" reply in thread", style);
1018        }
1019
1020        let (num, singular, plural) = if thread.unreads.num_mentions > 0 {
1021            (thread.unreads.num_mentions, "mention", "mentions")
1022        } else if thread.unreads.num_notifications > 0 {
1023            (thread.unreads.num_notifications, "notification", "notifications")
1024        } else {
1025            (thread.unreads.num_unread, "unread", "unreads")
1026        };
1027
1028        if num > 0 {
1029            threaded.push_str(" (", style);
1030            threaded.push_span_nobreak(Span::styled(num.to_string(), style.bold()));
1031            threaded.push_str(" ", style);
1032            if num > 1 {
1033                threaded.push_str(plural, style);
1034            } else {
1035                threaded.push_str(singular, style);
1036            }
1037            threaded.push_str(")", style);
1038        }
1039
1040        self.push_text(threaded.finish().0, style, text);
1041    }
1042}
1043
1044#[derive(Clone)]
1045pub struct Message {
1046    pub event: MessageEvent,
1047    pub sender: OwnedUserId,
1048    pub timestamp: MessageTimeStamp,
1049    pub html: Option<StyleTree>,
1050}
1051
1052/// Whether the read marker sits between the previous message and this one.
1053///
1054/// The marker's event is the last one the user has read, so the first message
1055/// after it is the first unread one. A missing marker, or one whose message
1056/// isn't among the loaded ones, leaves nothing to mark.
1057fn is_after_read_marker(prev: Option<&Message>, marker: Option<&OwnedEventId>) -> bool {
1058    match (prev.and_then(|msg| msg.event.event_id()), marker) {
1059        (Some(prev), Some(marker)) => prev == marker,
1060        _ => false,
1061    }
1062}
1063
1064impl Message {
1065    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
1066        let html = event.html();
1067
1068        Message { event, sender, timestamp, html }
1069    }
1070
1071    pub fn reply_to(&self) -> Option<OwnedEventId> {
1072        let content = match &self.event {
1073            MessageEvent::EncryptedOriginal(_) => return None,
1074            MessageEvent::EncryptedRedacted(_) => return None,
1075            MessageEvent::Local(_, _, content) => content,
1076            MessageEvent::Original(ev, _) => &ev.content,
1077            MessageEvent::Redacted(_, _) => return None,
1078            MessageEvent::State(_) => return None,
1079            MessageEvent::Sticker(ev, ..) => {
1080                return match &ev.content.relates_to {
1081                    Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()),
1082                    Some(Relation::Thread(ThreadRelation {
1083                        in_reply_to: Some(in_reply_to),
1084                        is_falling_back: false,
1085                        ..
1086                    })) => Some(in_reply_to.event_id.clone()),
1087                    Some(_) | None => None,
1088                };
1089            },
1090            MessageEvent::Poll(poll) => return poll.reply_to().map(ToOwned::to_owned),
1091            MessageEvent::UnstablePoll(poll) => return poll.reply_to().map(ToOwned::to_owned),
1092        };
1093
1094        match &content.relates_to {
1095            Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()),
1096            Some(Relation::Thread(ThreadRelation {
1097                in_reply_to: Some(in_reply_to),
1098                is_falling_back: false,
1099                ..
1100            })) => Some(in_reply_to.event_id.clone()),
1101            Some(_) | None => None,
1102        }
1103    }
1104
1105    /// Return the thread root if this is the first message in the thread.
1106    pub fn thread_root(&self) -> Option<OwnedEventId> {
1107        let content = match &self.event {
1108            MessageEvent::EncryptedOriginal(_) => return None,
1109            MessageEvent::EncryptedRedacted(_) => return None,
1110            MessageEvent::Local(_, _, content) => content,
1111            MessageEvent::Original(ev, _) => &ev.content,
1112            MessageEvent::Redacted(_, _) => return None,
1113            MessageEvent::State(_) => return None,
1114            MessageEvent::Sticker(..) => return None,
1115            MessageEvent::Poll(poll) => return poll.thread_root().map(ToOwned::to_owned),
1116            MessageEvent::UnstablePoll(poll) => return poll.thread_root().map(ToOwned::to_owned),
1117        };
1118
1119        match &content.relates_to {
1120            Some(Relation::Thread(ThreadRelation {
1121                event_id,
1122                in_reply_to: Some(in_reply_to),
1123                is_falling_back: true,
1124                ..
1125            })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
1126            Some(_) | None => None,
1127        }
1128    }
1129
1130    pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> {
1131        if let Some(html) = &self.html {
1132            html.image_previews()
1133        } else {
1134            vec![]
1135        }
1136    }
1137
1138    fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
1139        let mut style = self.event.message_style(settings);
1140
1141        if matches!(self.event, MessageEvent::Local(..)) {
1142            style = style.add_modifier(StyleModifier::ITALIC);
1143        }
1144
1145        if settings.tunables.message_user_color {
1146            let color = settings.get_user_color(&self.sender);
1147            style = style.fg(color);
1148        }
1149
1150        if selected {
1151            // Apply last, so that if the user or theme specified selected colors
1152            // for selected messages then it will get put on top of the user color:
1153            style = style.patch(settings.theme.selected);
1154        }
1155
1156        return style;
1157    }
1158
1159    pub fn show_date(&self, prev: Option<&Message>) -> bool {
1160        let Some(prev) = prev else { return true };
1161
1162        !prev.timestamp.same_day(self.timestamp)
1163    }
1164
1165    /// Whether the current user's read marker sits right before this message.
1166    ///
1167    /// Each thread keeps its own marker, so the rule only shows up in the view
1168    /// whose messages the marker belongs to.
1169    pub fn show_trackbar(
1170        &self,
1171        prev: Option<&Message>,
1172        info: &RoomInfo,
1173        settings: &ApplicationSettings,
1174    ) -> bool {
1175        let marker = info
1176            .user_receipts(&self.receipt_thread(info))
1177            .and_then(|receipts| receipts.get(&settings.user_id));
1178
1179        is_after_read_marker(prev, marker)
1180    }
1181
1182    /// The read receipt thread that this message was inserted into.
1183    pub(crate) fn receipt_thread(&self, info: &RoomInfo) -> ReceiptThread {
1184        self.event
1185            .event_id()
1186            .and_then(|event_id| info.get_receipt_thread(event_id))
1187            .unwrap_or(ReceiptThread::Main)
1188    }
1189
1190    pub fn message_column_width(
1191        viewctx: &ViewportContext<MessageCursor>,
1192        settings: &ApplicationSettings,
1193    ) -> usize {
1194        let width = viewctx.get_width();
1195        let user_gutter = settings.tunables.user_gutter_width;
1196        let time_gutter = settings.tunables.time_gutter_width;
1197
1198        if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width &&
1199            settings.tunables.read_receipt_display
1200        {
1201            width - user_gutter - time_gutter - READ_GUTTER
1202        } else if user_gutter + time_gutter + MIN_MSG_LEN <= width {
1203            width - user_gutter - time_gutter
1204        } else if user_gutter + MIN_MSG_LEN <= width {
1205            width - user_gutter
1206        } else {
1207            width.saturating_sub(2)
1208        }
1209    }
1210
1211    fn get_render_format<'a>(
1212        &'a self,
1213        prev: Option<&Message>,
1214        width: usize,
1215        info: &'a RoomInfo,
1216        settings: &'a ApplicationSettings,
1217    ) -> MessageFormatter<'a> {
1218        let orig = width;
1219        let date = self.show_date(prev).then(|| self.timestamp.show_date(settings));
1220        let trackbar = self.show_trackbar(prev, info, settings);
1221        let user_gutter = settings.tunables.user_gutter_width;
1222        let time_gutter = settings.tunables.time_gutter_width;
1223
1224        if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width &&
1225            settings.tunables.read_receipt_display
1226        {
1227            let cols = MessageColumns::Four;
1228            let fill = width - user_gutter - time_gutter - READ_GUTTER;
1229            let user = self.show_sender(prev, true, info, settings, width);
1230            let time = Some(self.timestamp.show_time(settings));
1231
1232            let read = self
1233                .event
1234                .event_id()
1235                .map(|event_id| {
1236                    // Iterate over both `ReceiptThread::Unthreaded` for clients unaware
1237                    // of threads, and over the appropriate `ReceiptThread::Main` or
1238                    // `ReceiptThread::Thread` for ones from thread-aware clients, like
1239                    // our own receipts or implicit receipts we've generated.
1240                    let receipt_thread = self.receipt_thread(info);
1241                    let threaded = info.read_event_users(receipt_thread, event_id);
1242                    let unthreaded = info.read_event_users(ReceiptThread::Unthreaded, event_id);
1243                    threaded
1244                        .chain(unthreaded)
1245                        .filter(|user_id| **user_id != settings.user_id)
1246                        .map(|user_id| user_id.to_owned())
1247                        .collect()
1248                })
1249                .unwrap_or_default();
1250
1251            MessageFormatter {
1252                settings,
1253                cols,
1254                orig,
1255                fill,
1256                user,
1257                date,
1258                trackbar,
1259                time,
1260                read,
1261                info,
1262            }
1263        } else if user_gutter + time_gutter + MIN_MSG_LEN <= width {
1264            let cols = MessageColumns::Three;
1265            let fill = width - user_gutter - time_gutter;
1266            let user = self.show_sender(prev, true, info, settings, width);
1267            let time = Some(self.timestamp.show_time(settings));
1268            let read = Vec::new();
1269
1270            MessageFormatter {
1271                settings,
1272                cols,
1273                orig,
1274                fill,
1275                user,
1276                date,
1277                trackbar,
1278                time,
1279                read,
1280                info,
1281            }
1282        } else if user_gutter + MIN_MSG_LEN <= width {
1283            let cols = MessageColumns::Two;
1284            let fill = width - user_gutter;
1285            let user = self.show_sender(prev, true, info, settings, width);
1286            let time = None;
1287            let read = Vec::new();
1288
1289            MessageFormatter {
1290                settings,
1291                cols,
1292                orig,
1293                fill,
1294                user,
1295                date,
1296                trackbar,
1297                time,
1298                read,
1299                info,
1300            }
1301        } else {
1302            let cols = MessageColumns::One;
1303            let fill = width.saturating_sub(2);
1304            let user = self.show_sender(prev, false, info, settings, width);
1305            let time = None;
1306            let read = Vec::new();
1307
1308            MessageFormatter {
1309                settings,
1310                cols,
1311                orig,
1312                fill,
1313                user,
1314                date,
1315                trackbar,
1316                time,
1317                read,
1318                info,
1319            }
1320        }
1321    }
1322
1323    /// Render the message as a [Text] object for the terminal.
1324    ///
1325    /// This will also get the image preview Protocol with an x/y offset.
1326    pub fn show_with_preview<'a>(
1327        &'a self,
1328        prev: Option<&Message>,
1329        selected: bool,
1330        width: usize,
1331        info: &'a RoomInfo,
1332        settings: &'a ApplicationSettings,
1333        previews: &'a PreviewManager,
1334    ) -> (Text<'a>, Vec<ProtocolPreview>) {
1335        let style = self.get_render_style(selected, settings);
1336        let mut fmt = self.get_render_format(prev, width, info, settings);
1337        let mut text = Text::default();
1338        let width = fmt.width();
1339
1340        let mut protos = Vec::new();
1341
1342        // Show the message that this one replied to, if any.
1343        let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e));
1344        if let Some(r) = reply {
1345            if let Some(r) = r {
1346                // Format the reply header, push it into the `Text` buffer, and get any image.
1347                protos = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
1348            } else {
1349                fmt.push_spans(
1350                    Line::from(vec![
1351                        Span::styled(" ", style),
1352                        Span::styled(THICK_VERTICAL, style),
1353                        Span::styled("Original message not loaded", style),
1354                        space_span(width.saturating_sub(29), style),
1355                    ]),
1356                    style,
1357                    &mut text,
1358                );
1359            }
1360        }
1361
1362        // Now show the message contents, and the inlined reply if we couldn't find it above.
1363        let (msg, proto) = self.show_msg(width, style, settings, previews, info);
1364
1365        // Given our text so far, determine the image offset.
1366        {
1367            let y_off = text.lines.len() as u16;
1368            let x_off = fmt.cols.user_gutter_width(settings);
1369
1370            // Account for extra lines printed before the message;
1371            let y_off = y_off + fmt.message_start_line();
1372
1373            for (p, x, y) in proto {
1374                protos.push((p, x + x_off, y + y_off));
1375            }
1376        }
1377
1378        fmt.push_text(msg, style, &mut text);
1379
1380        if text.lines.is_empty() {
1381            // If there was nothing in the body, just show an empty message.
1382            fmt.push_spans(space_span(width, style).into(), style, &mut text);
1383        }
1384
1385        let pinned = self.event.event_id().is_some_and(|id| info.is_pinned(id));
1386        let label = match (self.event.is_edited(), pinned) {
1387            (true, true) => Some("(pinned, edited)"),
1388            (true, false) => Some("(edited)"),
1389            (false, true) => Some("(pinned)"),
1390            (false, false) => None,
1391        };
1392
1393        if let Some(label) = label {
1394            fmt.push_spans(
1395                Line::from(vec![
1396                    Span::styled(label, style.fg(Color::Gray)),
1397                    space_span(fmt.width().saturating_sub(label.len()), style),
1398                ]),
1399                style,
1400                &mut text,
1401            );
1402        }
1403
1404        if settings.tunables.reaction_display {
1405            let reactions =
1406                self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default();
1407            let react_protos = fmt.push_reactions(reactions, style, &mut text, settings, previews);
1408            protos.extend(react_protos);
1409        }
1410
1411        if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(id)) {
1412            fmt.push_thread_reply_count(thread, &mut text, style);
1413        }
1414
1415        (text, protos)
1416    }
1417
1418    pub fn show<'a>(
1419        &'a self,
1420        prev: Option<&Message>,
1421        selected: bool,
1422        width: usize,
1423        info: &'a RoomInfo,
1424        settings: &'a ApplicationSettings,
1425        previews: &'a PreviewManager,
1426    ) -> Text<'a> {
1427        self.show_with_preview(prev, selected, width, info, settings, previews).0
1428    }
1429
1430    fn show_msg<'a>(
1431        &'a self,
1432        width: usize,
1433        style: Style,
1434        settings: &'a ApplicationSettings,
1435        previews: &'a PreviewManager,
1436        info: &'a RoomInfo,
1437    ) -> (Text<'a>, Vec<ProtocolPreview>) {
1438        let mut protos = vec![];
1439
1440        let mut text = Default::default();
1441        if let Some(html) = &self.html &&
1442            settings.tunables.message_formatted_display
1443        {
1444            let (t, p) = html.render(width, style, settings, info, previews);
1445            text += t;
1446            protos = p;
1447        } else {
1448            let mut msg = self.event.body();
1449            if settings.tunables.message_shortcode_display {
1450                msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1451            }
1452            text += wrapped_text(msg, width, style);
1453        };
1454
1455        (text, protos)
1456    }
1457
1458    fn sender_span<'a>(
1459        &'a self,
1460        info: &'a RoomInfo,
1461        settings: &'a ApplicationSettings,
1462    ) -> Span<'a> {
1463        settings.get_user_span(self.sender.as_ref(), info.display_names.get(&self.sender))
1464    }
1465
1466    fn show_sender<'a>(
1467        &'a self,
1468        prev: Option<&Message>,
1469        gutter_enabled: bool,
1470        info: &'a RoomInfo,
1471        settings: &'a ApplicationSettings,
1472        width: usize,
1473    ) -> SenderSpan<'a> {
1474        if let Some(prev) = prev &&
1475            self.sender == prev.sender &&
1476            self.timestamp.same_day(prev.timestamp) &&
1477            !matches!(self.event.msgtype(), Some(MessageType::Emote(_)))
1478        {
1479            return SenderSpan::None;
1480        }
1481
1482        let Span { content, style } = self.sender_span(info, settings);
1483        let user_gutter = settings.tunables.user_gutter_width;
1484
1485        let show_in_gutter = gutter_enabled && user_gutter > 2;
1486
1487        if show_in_gutter {
1488            let ((truncated, width), _) = take_width_grapheme(content, user_gutter - 2);
1489            let padding = user_gutter - 2 - width;
1490
1491            let sender = format!("{}{}  ", space(padding), truncated);
1492
1493            SenderSpan::Gutter(Span::styled(sender, style))
1494        } else if UnicodeWidthStr::width(content.as_ref()) > width {
1495            let ((truncated, _), _) = take_width_grapheme(content, width);
1496
1497            SenderSpan::Line(Span::styled(truncated, style))
1498        } else {
1499            SenderSpan::Line(Span::styled(content, style))
1500        }
1501    }
1502
1503    pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
1504        self.event.redact(redaction);
1505        self.html = None;
1506    }
1507
1508    pub fn set_edits(&mut self, new_edits: MessageEdits) {
1509        if let MessageEvent::Original(orig, edits) = &mut self.event {
1510            *edits = new_edits;
1511
1512            for edit in edits.values_mut() {
1513                strip_reply_fallback(&mut edit.msgtype);
1514            }
1515
1516            if let Some(most_recent) = edits.last_key_value() {
1517                self.html = content_html(&most_recent.1.msgtype);
1518            } else {
1519                self.html = content_html(&orig.content.msgtype);
1520            }
1521        }
1522    }
1523
1524    pub fn insert_edit(
1525        &mut self,
1526        key: MessageKey,
1527        mut edit: RoomMessageEventContentWithoutRelation,
1528    ) {
1529        if let MessageEvent::Original(_, edits) = &mut self.event {
1530            strip_reply_fallback(&mut edit.msgtype);
1531
1532            let inserted = edits.entry(key).insert_entry(edit);
1533            self.html = content_html(&inserted.get().msgtype);
1534        }
1535    }
1536
1537    pub fn remove_edit(&mut self, key: &MessageKey) {
1538        let MessageEvent::Original(orig_content, edits) = &mut self.event else {
1539            return;
1540        };
1541
1542        edits.remove(key);
1543
1544        let content = edits
1545            .last_key_value()
1546            .map(|(_, msg)| &msg.msgtype)
1547            .unwrap_or(&orig_content.content.msgtype);
1548
1549        self.html = content_html(content);
1550    }
1551
1552    pub fn find_links(&self) -> Vec<(char, Url)> {
1553        let mut links = if let Some(html) = &self.html {
1554            html.get_links()
1555        } else {
1556            vec![]
1557        };
1558
1559        if links.is_empty() {
1560            links = linkify::LinkFinder::new()
1561                .links(&self.event.body())
1562                .filter_map(|u| Url::parse(u.as_str()).ok())
1563                .scan(TreeGenState { link_num: 0 }, |state, u| {
1564                    state.next_link_char().map(|c| (c, u))
1565                })
1566                .collect();
1567        }
1568
1569        links
1570    }
1571}
1572
1573impl From<RoomEncryptedEvent> for Message {
1574    fn from(event: RoomEncryptedEvent) -> Self {
1575        let timestamp = event.origin_server_ts().into();
1576        let user_id = event.sender().to_owned();
1577        let content = match event {
1578            RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1579            RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1580        };
1581
1582        Message::new(content, user_id, timestamp)
1583    }
1584}
1585
1586impl From<OriginalRoomMessageEvent> for Message {
1587    fn from(event: OriginalRoomMessageEvent) -> Self {
1588        let timestamp = event.origin_server_ts.into();
1589        let user_id = event.sender.clone();
1590        let content = MessageEvent::Original(event.into(), Default::default());
1591
1592        Message::new(content, user_id, timestamp)
1593    }
1594}
1595
1596impl From<RedactedRoomMessageEvent> for Message {
1597    fn from(event: RedactedRoomMessageEvent) -> Self {
1598        let timestamp = event.origin_server_ts.into();
1599        let user_id = event.sender.clone();
1600
1601        let event_id = event.event_id;
1602        let reason = redaction_reason_unsigned(&event.unsigned);
1603        let content = MessageEvent::Redacted(event_id, reason);
1604
1605        Message::new(content, user_id, timestamp)
1606    }
1607}
1608
1609impl From<RoomMessageEvent> for Message {
1610    fn from(event: RoomMessageEvent) -> Self {
1611        match event {
1612            RoomMessageEvent::Original(ev) => ev.into(),
1613            RoomMessageEvent::Redacted(ev) => ev.into(),
1614        }
1615    }
1616}
1617
1618impl From<RedactedPollStartEvent> for Message {
1619    fn from(event: RedactedPollStartEvent) -> Self {
1620        let timestamp = event.origin_server_ts.into();
1621        let user_id = event.sender.clone();
1622
1623        let event_id = event.event_id;
1624        let reason = redaction_reason_unsigned(&event.unsigned);
1625        let content = MessageEvent::Redacted(event_id, reason);
1626
1627        Message::new(content, user_id, timestamp)
1628    }
1629}
1630
1631impl From<RedactedUnstablePollStartEvent> for Message {
1632    fn from(event: RedactedUnstablePollStartEvent) -> Self {
1633        let timestamp = event.origin_server_ts.into();
1634        let user_id = event.sender.clone();
1635
1636        let event_id = event.event_id;
1637        let reason = redaction_reason_unsigned(&event.unsigned);
1638        let content = MessageEvent::Redacted(event_id, reason);
1639
1640        Message::new(content, user_id, timestamp)
1641    }
1642}
1643
1644impl From<AnySyncStateEvent> for Message {
1645    fn from(event: AnySyncStateEvent) -> Self {
1646        let timestamp = event.origin_server_ts().into();
1647        let user_id = event.sender().to_owned();
1648        let event = MessageEvent::State(event.into());
1649
1650        Message::new(event, user_id, timestamp)
1651    }
1652}
1653
1654impl From<OriginalStickerEvent> for Message {
1655    fn from(event: OriginalStickerEvent) -> Self {
1656        let timestamp = event.origin_server_ts.into();
1657        let user_id = event.sender.clone();
1658        let source = event.content.source.clone().into();
1659
1660        let html_image =
1661            html::StyleTreeNode::Image(html::Image::new(source, Some(&event.content.info)));
1662
1663        let content = MessageEvent::Sticker(event.into());
1664        let mut msg = Message::new(content, user_id, timestamp);
1665
1666        msg.html = Some(StyleTree {
1667            children: vec![
1668                html::StyleTreeNode::Text("* sent a sticker:".into()),
1669                html_image,
1670            ],
1671        });
1672
1673        msg
1674    }
1675}
1676
1677impl From<RedactedStickerEvent> for Message {
1678    fn from(event: RedactedStickerEvent) -> Self {
1679        let timestamp = event.origin_server_ts.into();
1680        let user_id = event.sender.clone();
1681
1682        let event_id = event.event_id;
1683        let reason = redaction_reason_unsigned(&event.unsigned);
1684        let content = MessageEvent::Redacted(event_id, reason);
1685
1686        Message::new(content, user_id, timestamp)
1687    }
1688}
1689
1690impl From<StickerEvent> for Message {
1691    fn from(event: StickerEvent) -> Self {
1692        match event {
1693            MessageLikeEvent::Original(ev) => ev.into(),
1694            MessageLikeEvent::Redacted(ev) => ev.into(),
1695        }
1696    }
1697}
1698
1699impl Display for Message {
1700    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1701        write!(f, "{}", self.event.body())
1702    }
1703}
1704
1705#[cfg(test)]
1706pub mod tests {
1707    use super::*;
1708
1709    use matrix_sdk::ruma::events::relation::Reply;
1710    use matrix_sdk::ruma::events::room::ImageInfo;
1711    use matrix_sdk::ruma::events::room::message::{
1712        AudioInfo,
1713        AudioMessageEventContent,
1714        FileInfo,
1715        FileMessageEventContent,
1716        ImageMessageEventContent,
1717        TextMessageEventContent,
1718        VideoInfo,
1719        VideoMessageEventContent,
1720    };
1721
1722    use crate::base::EventLocation;
1723    use crate::config::time_gutter_width;
1724    use crate::tests::*;
1725
1726    #[test]
1727    fn test_has_reply_fallback() {
1728        let root = OwnedEventId::try_from("$root:example.org").unwrap();
1729        let target = OwnedEventId::try_from("$target:example.org").unwrap();
1730
1731        let reply: Relation<RoomMessageEventContentWithoutRelation> =
1732            Relation::Reply(Reply::with_event_id(target.clone()));
1733        assert!(has_reply_fallback(Some(&reply)));
1734
1735        let thread_reply: Relation<RoomMessageEventContentWithoutRelation> =
1736            Relation::Thread(ThreadRelation::reply(root.clone(), target.clone()));
1737        assert!(has_reply_fallback(Some(&thread_reply)));
1738
1739        let thread_fallback: Relation<RoomMessageEventContentWithoutRelation> =
1740            Relation::Thread(ThreadRelation::plain(root.clone(), target));
1741        assert!(has_reply_fallback(Some(&thread_fallback)));
1742
1743        let thread_without_fallback: Relation<RoomMessageEventContentWithoutRelation> =
1744            Relation::Thread(ThreadRelation::without_fallback(root));
1745        assert!(!has_reply_fallback(Some(&thread_without_fallback)));
1746        assert!(!has_reply_fallback(None));
1747    }
1748
1749    #[test]
1750    fn test_strip_reply_fallback() {
1751        let body = "> <@user:example.org> quoted text\n> more quoted text\n\nreply";
1752        let mut msgtype = MessageType::Text(TextMessageEventContent::plain(body));
1753
1754        strip_reply_fallback(&mut msgtype);
1755        assert_eq!(msgtype.body(), "reply");
1756    }
1757
1758    #[test]
1759    fn test_mc_cmp() {
1760        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1761        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1762        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1763        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1764        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1765
1766        // Everything is equal to itself.
1767        assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1768        assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1769        assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1770        assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1771        assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1772
1773        // Local echo is always greater than an origin server timestamp.
1774        assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1775        assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1776        assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1777        assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1778
1779        // mc2 is the smallest timestamp.
1780        assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1781        assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1782        assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1783        assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1784
1785        // mc3 should be less than mc4 because of its event ID.
1786        assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1787        assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1788        assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1789        assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1790
1791        // mc4 should be greater than mc3 because of its event ID.
1792        assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1793        assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1794        assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1795        assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1796
1797        // mc5 is the greatest OriginServer timestamp.
1798        assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1799        assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1800        assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1801        assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1802    }
1803
1804    #[test]
1805    fn test_mc_to_key() {
1806        let messages = mock_messages();
1807        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1808        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1809        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1810        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1811        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1812        let mc6 = MessageCursor::latest();
1813
1814        let k1 = mc1.to_key(&messages).unwrap();
1815        let k2 = mc2.to_key(&messages).unwrap();
1816        let k3 = mc3.to_key(&messages).unwrap();
1817        let k4 = mc4.to_key(&messages).unwrap();
1818        let k5 = mc5.to_key(&messages).unwrap();
1819        let k6 = mc6.to_key(&messages).unwrap();
1820
1821        // These should all be equal to their MSGN_KEYs.
1822        assert_eq!(k1, &MSG1_KEY.clone());
1823        assert_eq!(k2, &MSG2_KEY.clone());
1824        assert_eq!(k3, &MSG3_KEY.clone());
1825        assert_eq!(k4, &MSG4_KEY.clone());
1826        assert_eq!(k5, &MSG5_KEY.clone());
1827
1828        // MessageCursor::latest() turns into the largest key (our local echo message).
1829        assert_eq!(k6, &MSG1_KEY.clone());
1830
1831        // MessageCursor::latest() fails to convert for a room w/o messages.
1832        let messages_empty = Messages::new(ReceiptThread::Main);
1833        assert_eq!(mc6.to_key(&messages_empty), None);
1834    }
1835
1836    #[test]
1837    fn test_mc_to_from_cursor() {
1838        let messages = mock_messages();
1839        let mc1 = MessageCursor::from(MSG1_KEY.clone());
1840        let mc2 = MessageCursor::from(MSG2_KEY.clone());
1841        let mc3 = MessageCursor::from(MSG3_KEY.clone());
1842        let mc4 = MessageCursor::from(MSG4_KEY.clone());
1843        let mc5 = MessageCursor::from(MSG5_KEY.clone());
1844        let mc6 = MessageCursor::latest();
1845
1846        let identity = |mc: &MessageCursor| {
1847            let c = mc.to_cursor(&messages).unwrap();
1848
1849            MessageCursor::from_cursor(&c, &messages).unwrap()
1850        };
1851
1852        // These should all convert to a Cursor and back to the original value.
1853        assert_eq!(identity(&mc1), mc1);
1854        assert_eq!(identity(&mc2), mc2);
1855        assert_eq!(identity(&mc3), mc3);
1856        assert_eq!(identity(&mc4), mc4);
1857        assert_eq!(identity(&mc5), mc5);
1858
1859        // MessageCursor::latest() should point at the most recent message after conversion.
1860        assert_eq!(identity(&mc6), mc1);
1861    }
1862
1863    #[test]
1864    fn test_placeholder_frame() {
1865        fn pretty_frame_test(str: &str) -> String {
1866            str[1..].to_string()
1867        }
1868
1869        assert_eq!(
1870            placeholder_frame(None, 4, &Size { width: 4, height: 4 }),
1871            pretty_frame_test(
1872                r#"
1873⌌  ⌍
1874
1875
1876⌎  ⌏
1877"#
1878            )
1879        );
1880
1881        assert_eq!(
1882            placeholder_frame(None, 2, &Size { width: 4, height: 4 }),
1883            pretty_frame_test(
1884                r#"
1885⌌⌍
1886
1887
1888⌎⌏
1889"#
1890            )
1891        );
1892        assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), "#\n#\n#\n#\n");
1893
1894        assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), "####\n");
1895
1896        assert_eq!(
1897            placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }),
1898            pretty_frame_test(
1899                r#"
1900⌌  ⌍
1901 OK
1902
1903⌎  ⌏
1904"#
1905            )
1906        );
1907        assert_eq!(
1908            placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 6 }),
1909            pretty_frame_test(
1910                r#"
1911⌌    ⌍
1912
1913 OK
1914
1915
1916⌎    ⌏
1917"#
1918            )
1919        );
1920        assert_eq!(
1921            placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 7 }),
1922            pretty_frame_test(
1923                r#"
1924⌌    ⌍
1925
1926
1927 OK
1928
1929
1930⌎    ⌏
1931"#
1932            )
1933        );
1934        assert_eq!(
1935            placeholder_frame(Some("idontfit"), 4, &Size { width: 4, height: 4 }),
1936            pretty_frame_test(
1937                r#"
1938⌌  ⌍
1939
1940
1941⌎  ⌏
1942"#
1943            )
1944        );
1945        assert_eq!(
1946            placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 2 }),
1947            pretty_frame_test(
1948                r#"
1949⌌  ⌍
1950⌎  ⌏
1951"#
1952            )
1953        );
1954        assert_eq!(
1955            placeholder_frame(Some("OK"), 4, &Size { width: 2, height: 3 }),
1956            pretty_frame_test(
1957                r#"
1958⌌⌍
1959
1960⌎⌏
1961"#
1962            )
1963        );
1964    }
1965
1966    #[test]
1967    fn test_display_attachment_size() {
1968        assert_eq!(
1969            content_filename(&MessageType::Image(
1970                ImageMessageEventContent::plain(
1971                    "Alt text".to_string(),
1972                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1973                )
1974                .info(Some(Box::default()))
1975            )),
1976            "[Attached Image: Alt text]".to_string().into()
1977        );
1978
1979        let mut info = ImageInfo::default();
1980        info.size = Some(442630_u32.into());
1981        assert_eq!(
1982            content_filename(&MessageType::Image(
1983                ImageMessageEventContent::plain(
1984                    "Alt text".to_string(),
1985                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1986                )
1987                .info(Some(Box::new(info)))
1988            )),
1989            "[Attached Image: Alt text (442.63 kB)]".to_string().into()
1990        );
1991
1992        let mut info = ImageInfo::default();
1993        info.size = Some(12_u32.into());
1994        assert_eq!(
1995            content_filename(&MessageType::Image(
1996                ImageMessageEventContent::plain(
1997                    "Alt text".to_string(),
1998                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1999                )
2000                .info(Some(Box::new(info)))
2001            )),
2002            "[Attached Image: Alt text (12 B)]".to_string().into()
2003        );
2004
2005        let mut info = AudioInfo::default();
2006        info.size = Some(4294967295_u32.into());
2007        assert_eq!(
2008            content_filename(&MessageType::Audio(
2009                AudioMessageEventContent::plain(
2010                    "Alt text".to_string(),
2011                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
2012                )
2013                .info(Some(Box::new(info)))
2014            )),
2015            "[Attached Audio: Alt text (4.29 GB)]".to_string().into()
2016        );
2017
2018        let mut info = FileInfo::default();
2019        info.size = Some(4426300_u32.into());
2020        assert_eq!(
2021            content_filename(&MessageType::File(
2022                FileMessageEventContent::plain(
2023                    "Alt text".to_string(),
2024                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
2025                )
2026                .info(Some(Box::new(info)))
2027            )),
2028            "[Attached File: Alt text (4.43 MB)]".to_string().into()
2029        );
2030
2031        let mut info = VideoInfo::default();
2032        info.size = Some(44000_u32.into());
2033        assert_eq!(
2034            content_filename(&MessageType::Video(
2035                VideoMessageEventContent::plain(
2036                    "Alt text".to_string(),
2037                    "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
2038                )
2039                .info(Some(Box::new(info)))
2040            )),
2041            "[Attached Video: Alt text (44 kB)]".to_string().into()
2042        );
2043    }
2044
2045    #[test]
2046    fn test_is_after_read_marker() {
2047        let first = mock_message1();
2048        let second = mock_message2();
2049
2050        // Without a marker there's nothing to mark.
2051        assert!(!is_after_read_marker(Some(&first), None));
2052        assert!(!is_after_read_marker(None, None));
2053
2054        // The marker names the last read message, so the message immediately
2055        // after it draws the trackbar.
2056        assert!(is_after_read_marker(Some(&first), Some(&MSG1_EVID)));
2057        assert!(is_after_read_marker(Some(&second), Some(&MSG2_EVID)));
2058
2059        // A marker on the rendered message belongs to the next message instead,
2060        // so the last loaded message never draws a trackbar when it's the
2061        // marker itself.
2062        assert!(!is_after_read_marker(Some(&first), Some(&MSG2_EVID)));
2063
2064        // The first loaded message has no predecessor to prove the marker is
2065        // its neighbor, and markers for unloaded messages aren't neighbors.
2066        assert!(!is_after_read_marker(None, Some(&MSG1_EVID)));
2067        assert!(!is_after_read_marker(Some(&second), Some(&MSG5_EVID)));
2068    }
2069
2070    fn has_trackbar(text: &Text<'_>, width: usize) -> bool {
2071        text.lines.iter().any(|line| {
2072            line.spans
2073                .iter()
2074                .any(|span| span.content.as_ref() == HORIZONTAL.repeat(width))
2075        })
2076    }
2077
2078    #[test]
2079    fn test_show_trackbar() {
2080        let settings = mock_settings();
2081        let previews = PreviewManager::new(&settings);
2082        let mut info = mock_room();
2083        let width = 60;
2084
2085        let prev = mock_message1();
2086        let msg = mock_message2();
2087        let user_id = settings.user_id.clone();
2088
2089        // Without a marker, no trackbar is drawn.
2090        let text = msg.show(Some(&prev), false, width, &info, &settings, &previews);
2091        assert!(!has_trackbar(&text, 60));
2092
2093        // When the marker names the previous message, the rule leads the message.
2094        info.set_receipt(ReceiptThread::Main, user_id.clone(), MSG1_EVID.clone());
2095        let text = msg.show(Some(&prev), false, width, &info, &settings, &previews);
2096        assert!(has_trackbar(&text, 60));
2097        assert_eq!(text.lines[0].spans[0].content.as_ref(), HORIZONTAL.repeat(60));
2098
2099        // Use a fresh room because receipt updates are monotonic: this case tests a marker
2100        // already positioned on the rendered message, not moving an existing marker backwards.
2101        let mut info = mock_room();
2102        info.set_receipt(ReceiptThread::Main, user_id.clone(), MSG2_EVID.clone());
2103        let text = msg.show(Some(&prev), false, width, &info, &settings, &previews);
2104        assert!(!has_trackbar(&text, 60));
2105        let text = prev.show(Some(&msg), false, width, &info, &settings, &previews);
2106        assert!(has_trackbar(&text, 60));
2107    }
2108
2109    #[test]
2110    fn test_show_trackbar_thread() {
2111        let settings = mock_settings();
2112        let mut info = mock_room();
2113        let user_id = settings.user_id.clone();
2114
2115        let prev = mock_message1();
2116        let msg = mock_message2();
2117
2118        let root = MSG5_EVID.clone();
2119        info.keys.insert(
2120            MSG2_EVID.clone(),
2121            EventLocation::Message(Some(root.clone()), MSG2_KEY.clone()),
2122        );
2123
2124        // A marker for the thread that this message belongs to is shown.
2125        info.set_receipt(ReceiptThread::Thread(root.clone()), user_id.clone(), MSG1_EVID.clone());
2126        assert!(msg.show_trackbar(Some(&prev), &info, &settings));
2127
2128        // The main timeline's marker doesn't apply to a thread's messages.
2129        info.user_receipts_or_default(ReceiptThread::Thread(root)).clear();
2130        info.set_receipt(ReceiptThread::Main, user_id, MSG1_EVID.clone());
2131        assert!(!msg.show_trackbar(Some(&prev), &info, &settings));
2132    }
2133
2134    #[test]
2135    fn test_show_msg_html_display() {
2136        let mut settings = mock_settings();
2137        let previews = PreviewManager::new(&settings);
2138        let info = mock_room();
2139
2140        let content = RoomMessageEventContent::text_html(
2141            "**hello** <world>",
2142            "<strong>hello</strong> &lt;world&gt;",
2143        );
2144        let msg = mock_room1_message(content, TEST_USER1.clone(), MSG1_KEY.clone());
2145
2146        let render = |settings: &ApplicationSettings| -> String {
2147            let (text, _) = msg.show_msg(60, Style::default(), settings, &previews, &info);
2148
2149            let s: String = text
2150                .lines
2151                .iter()
2152                .flat_map(|line| line.spans.iter())
2153                .map(|span| span.content.as_ref())
2154                .collect();
2155
2156            // The HTML renderer pads lines out to the full width.
2157            s.trim_end().to_string()
2158        };
2159
2160        // By default, the formatted HTML body is rendered.
2161        assert!(settings.tunables.message_formatted_display);
2162        assert_eq!(render(&settings), "hello <world>");
2163
2164        // When disabled, the plain text body is shown exactly as it was sent.
2165        settings.tunables.message_formatted_display = false;
2166        assert_eq!(render(&settings), "**hello** <world>");
2167    }
2168
2169    /// `MessageTimeStamp::as_datetime` converts to the local timezone, so
2170    /// expectations are computed with the same conversion rather than a
2171    /// hard-coded wall clock.
2172    fn sample_stamp() -> (MessageTimeStamp, DateTime<LocalTz>) {
2173        let millis = MilliSecondsSinceUnixEpoch(UInt::try_from(1_705_325_130_000u64).unwrap());
2174        let ts = MessageTimeStamp::from(millis);
2175        (ts, ts.as_datetime())
2176    }
2177
2178    #[test]
2179    fn test_show_time_and_date_defaults() {
2180        let (ts, dt) = sample_stamp();
2181        let settings = mock_settings();
2182
2183        let date = ts.show_date(&settings);
2184        assert_eq!(date.content.as_ref(), dt.format("%A, %B %d %Y").to_string());
2185
2186        let time = ts.show_time(&settings);
2187        assert_eq!(time.content.as_ref(), format!("  [{}]", dt.format("%T")));
2188        assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 12);
2189        assert_eq!(settings.tunables.time_gutter_width, 12);
2190    }
2191
2192    #[test]
2193    fn test_time_gutter_width_follows_format() {
2194        let (ts, dt) = sample_stamp();
2195        let mut settings = mock_settings();
2196        let view = ViewportContext { dimensions: (120, 10), ..Default::default() };
2197        let default_cols = Message::message_column_width(&view, &settings);
2198
2199        // "%H:%M" is five columns and is not padded out to the old gutter.
2200        settings.tunables.time_format = "%H:%M".to_string();
2201        settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2202        let time = ts.show_time(&settings);
2203        let rendered = dt.format("%H:%M").to_string();
2204        assert_eq!(time.content.as_ref(), rendered);
2205        assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 5);
2206        assert_eq!(settings.tunables.time_gutter_width, 5);
2207        assert_eq!(Message::message_column_width(&view, &settings), default_cols + 7);
2208
2209        // An empty format hides the time and reserves no column.
2210        settings.tunables.time_format = String::new();
2211        settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2212        let time = ts.show_time(&settings);
2213        assert_eq!(time.content.as_ref(), "");
2214        assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 0);
2215        assert_eq!(settings.tunables.time_gutter_width, 0);
2216        assert_eq!(Message::message_column_width(&view, &settings), default_cols + 12);
2217
2218        // Wider than the historical 8-column cap, and a wide character counts as two.
2219        settings.tunables.time_format = "%H時%M分".to_string();
2220        settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2221        let time = ts.show_time(&settings);
2222        let rendered = dt.format("%H時%M分").to_string();
2223        assert_eq!(time.content.as_ref(), rendered);
2224        assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 8);
2225        assert_eq!(settings.tunables.time_gutter_width, 8);
2226        assert_eq!(Message::message_column_width(&view, &settings), default_cols + 4);
2227    }
2228
2229    #[test]
2230    fn test_show_custom_date_format() {
2231        let (ts, dt) = sample_stamp();
2232        let mut settings = mock_settings();
2233        settings.tunables.date_format = "%Y-%m-%d".to_string();
2234        let date = ts.show_date(&settings);
2235        assert_eq!(date.content.as_ref(), dt.format("%Y-%m-%d").to_string());
2236    }
2237}