src/message/mod.rs

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