src/message/mod.rs

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