src/message/mod.rs

2218 lines · 75560 bytes

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