src/message/mod.rs

1047 lines · 34450 bytes

   1//! # Room Messages
   2use std::borrow::Cow;
   3use std::cmp::{Ord, Ordering, PartialOrd};
   4use std::collections::hash_map::DefaultHasher;
   5use std::collections::BTreeMap;
   6use std::convert::TryFrom;
   7use std::hash::{Hash, Hasher};
   8use std::slice::Iter;
   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::{Span, Spans, 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        },
  78    }
  79}
  80
  81const BOLD_STYLE: Style = Style {
  82    fg: None,
  83    bg: None,
  84    add_modifier: StyleModifier::BOLD,
  85    sub_modifier: StyleModifier::empty(),
  86};
  87
  88const USER_GUTTER: usize = 30;
  89const TIME_GUTTER: usize = 12;
  90const READ_GUTTER: usize = 5;
  91const MIN_MSG_LEN: usize = 30;
  92
  93const USER_GUTTER_EMPTY: &str = "                              ";
  94const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
  95
  96const TIME_GUTTER_EMPTY: &str = "            ";
  97const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
  98
  99fn text_to_message_content(input: String) -> TextMessageEventContent {
 100    let mut options = ComrakOptions::default();
 101    options.extension.shortcodes = true;
 102    options.extension.strikethrough = true;
 103    options.render.hardbreaks = true;
 104    let html = markdown_to_html(input.as_str(), &options);
 105
 106    TextMessageEventContent::html(input, html)
 107}
 108
 109pub fn text_to_message(input: String) -> RoomMessageEventContent {
 110    let msg = MessageType::Text(text_to_message_content(input));
 111    RoomMessageEventContent::new(msg)
 112}
 113
 114#[inline]
 115fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
 116    let time = i64::from(ms) / 1000;
 117    let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
 118
 119    LocalTz.from_utc_datetime(&time)
 120}
 121
 122#[derive(thiserror::Error, Debug)]
 123pub enum TimeStampIntError {
 124    #[error("Integer conversion error: {0}")]
 125    IntError(#[from] std::num::TryFromIntError),
 126
 127    #[error("UInt conversion error: {0}")]
 128    UIntError(<UInt as TryFrom<u64>>::Error),
 129}
 130
 131#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 132pub enum MessageTimeStamp {
 133    OriginServer(UInt),
 134    LocalEcho,
 135}
 136
 137impl MessageTimeStamp {
 138    fn as_datetime(&self) -> DateTime<LocalTz> {
 139        match self {
 140            MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
 141            MessageTimeStamp::LocalEcho => LocalTz::now(),
 142        }
 143    }
 144
 145    fn same_day(&self, other: &Self) -> bool {
 146        let dt1 = self.as_datetime();
 147        let dt2 = other.as_datetime();
 148
 149        dt1.date_naive() == dt2.date_naive()
 150    }
 151
 152    fn show_date(&self) -> Option<Span> {
 153        let time = self.as_datetime().format("%A, %B %d %Y").to_string();
 154
 155        Span::styled(time, BOLD_STYLE).into()
 156    }
 157
 158    fn show_time(&self) -> Option<Span> {
 159        match self {
 160            MessageTimeStamp::OriginServer(ms) => {
 161                let time = millis_to_datetime(*ms).format("%T");
 162                let time = format!("  [{time}]");
 163
 164                Span::raw(time).into()
 165            },
 166            MessageTimeStamp::LocalEcho => None,
 167        }
 168    }
 169
 170    fn is_local_echo(&self) -> bool {
 171        matches!(self, MessageTimeStamp::LocalEcho)
 172    }
 173
 174    pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
 175        match self {
 176            MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
 177            MessageTimeStamp::LocalEcho => None,
 178        }
 179    }
 180}
 181
 182impl Ord for MessageTimeStamp {
 183    fn cmp(&self, other: &Self) -> Ordering {
 184        match (self, other) {
 185            (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
 186            (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
 187            (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
 188            (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
 189        }
 190    }
 191}
 192
 193impl PartialOrd for MessageTimeStamp {
 194    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 195        self.cmp(other).into()
 196    }
 197}
 198
 199impl From<UInt> for MessageTimeStamp {
 200    fn from(millis: UInt) -> Self {
 201        MessageTimeStamp::OriginServer(millis)
 202    }
 203}
 204
 205impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
 206    fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
 207        MessageTimeStamp::OriginServer(millis.0)
 208    }
 209}
 210
 211impl TryFrom<&MessageTimeStamp> for usize {
 212    type Error = TimeStampIntError;
 213
 214    fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
 215        let n = match ts {
 216            MessageTimeStamp::LocalEcho => 0,
 217            MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
 218        };
 219
 220        Ok(n)
 221    }
 222}
 223
 224impl TryFrom<usize> for MessageTimeStamp {
 225    type Error = TimeStampIntError;
 226
 227    fn try_from(u: usize) -> Result<Self, Self::Error> {
 228        if u == 0 {
 229            Ok(MessageTimeStamp::LocalEcho)
 230        } else {
 231            let n = u64::try_from(u)?;
 232            let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
 233
 234            Ok(MessageTimeStamp::from(n))
 235        }
 236    }
 237}
 238
 239#[derive(Clone, Debug, Default, Eq, PartialEq)]
 240pub struct MessageCursor {
 241    /// When timestamp is None, the corner is determined by moving backwards from
 242    /// the most recently received message.
 243    pub timestamp: Option<MessageKey>,
 244
 245    /// A row within the [Text] representation of a [Message].
 246    pub text_row: usize,
 247}
 248
 249impl MessageCursor {
 250    pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
 251        MessageCursor { timestamp: Some(timestamp), text_row }
 252    }
 253
 254    /// Get a cursor that refers to the most recent message.
 255    pub fn latest() -> Self {
 256        MessageCursor::default()
 257    }
 258
 259    pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
 260        if let Some(ref key) = self.timestamp {
 261            Some(key)
 262        } else {
 263            Some(info.messages.last_key_value()?.0)
 264        }
 265    }
 266
 267    pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
 268        let ev_hash = u64::try_from(cursor.get_x()).ok()?;
 269        let ev_term = OwnedEventId::try_from("$").ok()?;
 270
 271        let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
 272        let start = (ts_start, ev_term);
 273        let mut mc = None;
 274
 275        for ((ts, event_id), _) in info.messages.range(start..) {
 276            let mut hasher = DefaultHasher::new();
 277            event_id.hash(&mut hasher);
 278
 279            if hasher.finish() == ev_hash {
 280                mc = Self::from((*ts, event_id.clone())).into();
 281                break;
 282            }
 283
 284            if mc.is_none() {
 285                mc = Self::from((*ts, event_id.clone())).into();
 286            }
 287
 288            if ts > &ts_start {
 289                break;
 290            }
 291        }
 292
 293        return mc;
 294    }
 295
 296    pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
 297        let (ts, event_id) = self.to_key(info)?;
 298
 299        let y: usize = usize::try_from(ts).ok()?;
 300
 301        let mut hasher = DefaultHasher::new();
 302        event_id.hash(&mut hasher);
 303        let x = usize::try_from(hasher.finish()).ok()?;
 304
 305        Cursor::new(y, x).into()
 306    }
 307}
 308
 309impl From<Option<MessageKey>> for MessageCursor {
 310    fn from(key: Option<MessageKey>) -> Self {
 311        MessageCursor { timestamp: key, text_row: 0 }
 312    }
 313}
 314
 315impl From<MessageKey> for MessageCursor {
 316    fn from(key: MessageKey) -> Self {
 317        MessageCursor { timestamp: Some(key), text_row: 0 }
 318    }
 319}
 320
 321impl Ord for MessageCursor {
 322    fn cmp(&self, other: &Self) -> Ordering {
 323        match (&self.timestamp, &other.timestamp) {
 324            (None, None) => self.text_row.cmp(&other.text_row),
 325            (None, Some(_)) => Ordering::Greater,
 326            (Some(_), None) => Ordering::Less,
 327            (Some(st), Some(ot)) => {
 328                let pcmp = st.cmp(ot);
 329                let tcmp = self.text_row.cmp(&other.text_row);
 330
 331                pcmp.then(tcmp)
 332            },
 333        }
 334    }
 335}
 336
 337impl PartialOrd for MessageCursor {
 338    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 339        self.cmp(other).into()
 340    }
 341}
 342
 343#[derive(Clone)]
 344pub enum MessageEvent {
 345    EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
 346    EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
 347    Original(Box<OriginalRoomMessageEvent>),
 348    Redacted(Box<RedactedRoomMessageEvent>),
 349    Local(OwnedEventId, Box<RoomMessageEventContent>),
 350}
 351
 352impl MessageEvent {
 353    pub fn event_id(&self) -> &EventId {
 354        match self {
 355            MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
 356            MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
 357            MessageEvent::Original(ev) => ev.event_id.as_ref(),
 358            MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
 359            MessageEvent::Local(event_id, _) => event_id.as_ref(),
 360        }
 361    }
 362
 363    pub fn content(&self) -> Option<&RoomMessageEventContent> {
 364        match self {
 365            MessageEvent::EncryptedOriginal(_) => None,
 366            MessageEvent::Original(ev) => Some(&ev.content),
 367            MessageEvent::EncryptedRedacted(_) => None,
 368            MessageEvent::Redacted(_) => None,
 369            MessageEvent::Local(_, content) => Some(content),
 370        }
 371    }
 372
 373    pub fn is_emote(&self) -> bool {
 374        matches!(
 375            self.content(),
 376            Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
 377        )
 378    }
 379
 380    pub fn body(&self) -> Cow<'_, str> {
 381        match self {
 382            MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
 383            MessageEvent::Original(ev) => body_cow_content(&ev.content),
 384            MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
 385            MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
 386            MessageEvent::Local(_, content) => body_cow_content(content),
 387        }
 388    }
 389
 390    pub fn html(&self) -> Option<StyleTree> {
 391        let content = match self {
 392            MessageEvent::EncryptedOriginal(_) => return None,
 393            MessageEvent::EncryptedRedacted(_) => return None,
 394            MessageEvent::Original(ev) => &ev.content,
 395            MessageEvent::Redacted(_) => return None,
 396            MessageEvent::Local(_, content) => content,
 397        };
 398
 399        if let MessageType::Text(content) = &content.msgtype {
 400            if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
 401                Some(parse_matrix_html(body.as_str()))
 402            } else {
 403                None
 404            }
 405        } else {
 406            None
 407        }
 408    }
 409
 410    fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
 411        match self {
 412            MessageEvent::EncryptedOriginal(_) => return,
 413            MessageEvent::EncryptedRedacted(_) => return,
 414            MessageEvent::Redacted(_) => return,
 415            MessageEvent::Local(_, _) => return,
 416            MessageEvent::Original(ev) => {
 417                let redacted = ev.clone().redact(redaction, version);
 418                *self = MessageEvent::Redacted(Box::new(redacted));
 419            },
 420        }
 421    }
 422}
 423
 424fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
 425    let s = match &content.msgtype {
 426        MessageType::Text(content) => content.body.as_str(),
 427        MessageType::VerificationRequest(_) => "[Verification Request]",
 428        MessageType::Emote(content) => content.body.as_ref(),
 429        MessageType::Notice(content) => content.body.as_str(),
 430        MessageType::ServerNotice(content) => content.body.as_str(),
 431
 432        MessageType::Audio(content) => {
 433            return Cow::Owned(format!("[Attached Audio: {}]", content.body));
 434        },
 435        MessageType::File(content) => {
 436            return Cow::Owned(format!("[Attached File: {}]", content.body));
 437        },
 438        MessageType::Image(content) => {
 439            return Cow::Owned(format!("[Attached Image: {}]", content.body));
 440        },
 441        MessageType::Video(content) => {
 442            return Cow::Owned(format!("[Attached Video: {}]", content.body));
 443        },
 444        _ => {
 445            return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
 446        },
 447    };
 448
 449    Cow::Borrowed(s)
 450}
 451
 452fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
 453    let reason = unsigned
 454        .redacted_because
 455        .as_ref()
 456        .and_then(|e| e.as_original())
 457        .and_then(|r| r.content.reason.as_ref());
 458
 459    if let Some(r) = reason {
 460        Cow::Owned(format!("[Redacted: {r:?}]"))
 461    } else {
 462        Cow::Borrowed("[Redacted]")
 463    }
 464}
 465
 466enum MessageColumns {
 467    /// Four columns: sender, message, timestamp, read receipts.
 468    Four,
 469
 470    /// Three columns: sender, message, timestamp.
 471    Three,
 472
 473    /// Two columns: sender, message.
 474    Two,
 475
 476    /// One column: message with sender on line before the message.
 477    One,
 478}
 479
 480struct MessageFormatter<'a> {
 481    settings: &'a ApplicationSettings,
 482
 483    /// How many columns to print.
 484    cols: MessageColumns,
 485
 486    /// The full, original width.
 487    orig: usize,
 488
 489    /// The width that the message contents need to fill.
 490    fill: usize,
 491
 492    /// The formatted Span for the message sender.
 493    user: Option<Span<'a>>,
 494
 495    /// The time the message was sent.
 496    time: Option<Span<'a>>,
 497
 498    /// The date the message was sent.
 499    date: Option<Span<'a>>,
 500
 501    /// Iterator over the users who have read up to this message.
 502    read: Iter<'a, OwnedUserId>,
 503}
 504
 505impl<'a> MessageFormatter<'a> {
 506    fn width(&self) -> usize {
 507        self.fill
 508    }
 509
 510    #[inline]
 511    fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
 512        if let Some(date) = self.date.take() {
 513            let len = date.content.as_ref().len();
 514            let padding = self.orig.saturating_sub(len);
 515            let leading = space_span(padding / 2, Style::default());
 516            let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
 517
 518            text.lines.push(Spans(vec![leading, date, trailing]));
 519        }
 520
 521        match self.cols {
 522            MessageColumns::Four => {
 523                let settings = self.settings;
 524                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
 525                let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
 526
 527                let mut line = vec![user];
 528                line.extend(spans.0);
 529                line.push(time);
 530
 531                // Show read receipts.
 532                let user_char =
 533                    |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
 534
 535                let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 536                let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 537                let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
 538
 539                line.push(Span::raw(" "));
 540                line.push(c);
 541                line.push(b);
 542                line.push(a);
 543                line.push(Span::raw(" "));
 544
 545                text.lines.push(Spans(line))
 546            },
 547            MessageColumns::Three => {
 548                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
 549                let time = self.time.take().unwrap_or_else(|| Span::from(""));
 550
 551                let mut line = vec![user];
 552                line.extend(spans.0);
 553                line.push(time);
 554
 555                text.lines.push(Spans(line))
 556            },
 557            MessageColumns::Two => {
 558                let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
 559                let mut line = vec![user];
 560                line.extend(spans.0);
 561
 562                text.lines.push(Spans(line));
 563            },
 564            MessageColumns::One => {
 565                if let Some(user) = self.user.take() {
 566                    text.lines.push(Spans(vec![user]));
 567                }
 568
 569                let leading = space_span(2, style);
 570                let mut line = vec![leading];
 571                line.extend(spans.0);
 572
 573                text.lines.push(Spans(line));
 574            },
 575        }
 576    }
 577
 578    fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
 579        for line in append.lines.into_iter() {
 580            self.push_spans(line, style, text);
 581        }
 582    }
 583}
 584
 585pub struct Message {
 586    pub event: MessageEvent,
 587    pub sender: OwnedUserId,
 588    pub timestamp: MessageTimeStamp,
 589    pub downloaded: bool,
 590    pub html: Option<StyleTree>,
 591}
 592
 593impl Message {
 594    pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
 595        let html = event.html();
 596        let downloaded = false;
 597
 598        Message { event, sender, timestamp, downloaded, html }
 599    }
 600
 601    pub fn reply_to(&self) -> Option<OwnedEventId> {
 602        let content = match &self.event {
 603            MessageEvent::EncryptedOriginal(_) => return None,
 604            MessageEvent::EncryptedRedacted(_) => return None,
 605            MessageEvent::Local(_, content) => content,
 606            MessageEvent::Original(ev) => &ev.content,
 607            MessageEvent::Redacted(_) => return None,
 608        };
 609
 610        if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
 611            Some(in_reply_to.event_id.clone())
 612        } else {
 613            None
 614        }
 615    }
 616
 617    fn get_render_style(&self, selected: bool) -> Style {
 618        let mut style = Style::default();
 619
 620        if selected {
 621            style = style.add_modifier(StyleModifier::REVERSED)
 622        }
 623
 624        if self.timestamp.is_local_echo() {
 625            style = style.add_modifier(StyleModifier::ITALIC);
 626        }
 627
 628        return style;
 629    }
 630
 631    fn get_render_format<'a>(
 632        &'a self,
 633        prev: Option<&Message>,
 634        width: usize,
 635        info: &'a RoomInfo,
 636        settings: &'a ApplicationSettings,
 637    ) -> MessageFormatter<'a> {
 638        let orig = width;
 639        let date = match &prev {
 640            Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
 641            _ => self.timestamp.show_date(),
 642        };
 643
 644        if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
 645            settings.tunables.read_receipt_display
 646        {
 647            let cols = MessageColumns::Four;
 648            let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
 649            let user = self.show_sender(prev, true, info, settings);
 650            let time = self.timestamp.show_time();
 651            let read = match info.receipts.get(self.event.event_id()) {
 652                Some(read) => read.iter(),
 653                None => [].iter(),
 654            };
 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 = [].iter();
 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 = [].iter();
 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 = [].iter();
 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                Spans(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.0.insert(0, Span::styled(THICK_VERTICAL, style));
 725                line.0.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}