src/message/mod.rs

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