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