src/message/mod.rs

1246 lines · 40639 bytes

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