src/message/mod.rs

1046 lines · 34430 bytes

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