src/message/mod.rs

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