//! # Room Messages use std::cmp::{Ord, PartialOrd}; use std::collections::hash_map::DefaultHasher; use std::convert::TryInto; use std::hash::{Hash, Hasher}; use std::sync::Arc; use chrono::{DateTime, Local as LocalTz}; use humansize::{DECIMAL, format_size}; use matrix_sdk::ruma::UInt; use matrix_sdk::ruma::events::Mentions; use matrix_sdk::ruma::events::RedactedUnsigned; use matrix_sdk::ruma::events::poll::start::RedactedPollStartEvent; use matrix_sdk::ruma::events::poll::unstable_start::RedactedUnstablePollStartEvent; use matrix_sdk::ruma::events::room::encrypted::{ OriginalRoomEncryptedEvent, RedactedRoomEncryptedEvent, RoomEncryptedEvent, }; use matrix_sdk::ruma::events::room::message::RoomMessageEventContentWithoutRelation; use matrix_sdk::ruma::events::room::message::sanitize::remove_plain_reply_fallback; use matrix_sdk::ruma::events::room::message::{ FormattedBody, MessageFormat, RedactedRoomMessageEvent, RoomMessageEvent, }; use matrix_sdk::ruma::events::room::redaction::SyncRoomRedactionEvent; use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent}; use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; use matrix_sdk::ruma::{OwnedTransactionId, UserId}; use matrix_sdk::send_queue::SendHandle; use modalkit::editing::cursor::Cursor; use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL}; use crate::base::{MessageEdits, Thread}; use crate::message::html::{StyleTree, parse_matrix_html}; use crate::message::poll::{Poll, UnstablePoll}; use crate::message::state::{body_cow_state, html_state}; use crate::prelude::*; use crate::preview::ImageStatus; use crate::util::{replace_emojis_in_str, space, space_span, take_width_grapheme, wrapped_text}; mod compose; mod html; mod printer; mod state; pub mod poll; pub use self::compose::{text_to_message, text_to_text_message_event_content}; pub use self::html::TreeGenState; /// `proto, x, y` type ProtocolPreview = (Arc, u16, u16); /// The key used for uniquely identifying messages within a room and its threads. /// /// Note that the ordering of the fields is important here, so that the derived /// `Ord` trait will sort by timestamp first, and then sort by the message ID. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct MessageKey { pub ts: MessageTimeStamp, pub id: MessageId, } pub struct Messages(BTreeMap, pub ReceiptThread); impl Deref for Messages { type Target = BTreeMap; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Messages { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Messages { pub fn new(thread: ReceiptThread) -> Self { Self(Default::default(), thread) } pub fn main() -> Self { Self::new(ReceiptThread::Main) } pub fn insert_message(&mut self, key: MessageKey, msg: impl Into) { let mut msg = msg.into(); if let MessageEvent::Original(ev, edits) = &mut msg.event { if has_reply_fallback(ev.content.relates_to.as_ref()) { strip_reply_fallback(&mut ev.content.msgtype); } for edit in edits.values_mut() { strip_reply_fallback(&mut edit.msgtype); } } self.0.entry(key).or_insert(msg); } } const READ_GUTTER: usize = 5; const MIN_MSG_LEN: usize = 30; const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS; /// Macro rule converting a File / Image / Audio / Video to its text content with the shape: /// `[Attached : [ ()]]` macro_rules! display_file_name { ( $msgtype:ident, $content:expr ) => {{ format!( "[Attached {}: {}{}]", stringify!($msgtype), $content.filename(), $content .info .as_ref() .map(|info| { info.size .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL))) .unwrap_or_else(String::new) }) .unwrap_or_else(String::new) ) }}; } /// Macro rule extraction the text caption of a File / Image / Audio / Video macro_rules! display_file_to_text { ( $msgtype:ident, $content:expr ) => {{ if $content .filename .as_ref() .is_none_or(|filename| *filename == $content.body) { return Cow::Borrowed(""); } $content.body.as_str() }}; } fn content_filename(msgtype: &MessageType) -> Option { match msgtype { MessageType::Audio(content) => Some(display_file_name!(Audio, content)), MessageType::File(content) => Some(display_file_name!(File, content)), MessageType::Image(content) => Some(display_file_name!(Image, content)), MessageType::Video(content) => Some(display_file_name!(Video, content)), _ => None, } } /// Convert the [u64] hash to [usize] as needed. fn hash_finish_usize(hasher: DefaultHasher) -> Option { if USIZE_TOO_SMALL { (hasher.finish() % usize::MAX as u64).try_into().ok() } else { hasher.finish().try_into().ok() } } /// Hash an [`MessageId`] into a [`usize`]. fn hash_message_id(id: &MessageId) -> Option { let mut hasher = DefaultHasher::new(); id.hash(&mut hasher); hash_finish_usize(hasher) } /// Before the image is loaded, already display a placeholder frame of the image size. fn placeholder_frame(text: Option<&str>, outer_width: usize, image_preview_size: &Size) -> String { let Size { width, height } = image_preview_size; let width = usize::min(*width as usize, outer_width); if width < 2 || *height < 2 { let mut line = "#".repeat(width); line.push('\n'); return line.repeat(*height as usize); } let mut placeholder = "\u{230c}".to_string(); placeholder.push_str(&" ".repeat(width - 2)); placeholder.push('\u{230d}'); placeholder.push_str(&"\n".repeat((*height as usize - 1) / 2)); if *height > 2 && let Some(text) = text && text.width() <= width - 2 { placeholder.push(' '); placeholder.push_str(text); } placeholder.push_str(&"\n".repeat(*height as usize / 2)); placeholder.push('\u{230e}'); placeholder.push_str(&" ".repeat(width - 2)); placeholder.push_str("\u{230f}\n"); placeholder } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum MessageId { Origin(OwnedEventId), Local(OwnedTransactionId), } impl MessageId { pub fn as_origin(&self) -> Option<&EventId> { match self { Self::Origin(id) => Some(id), _ => None, } } } impl Display for MessageId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MessageId::Origin(id) => write!(f, "{}", id), MessageId::Local(id) => write!(f, "{}", id), } } } impl From for MessageId { fn from(value: OwnedEventId) -> Self { Self::Origin(value) } } impl From for MessageId { fn from(value: OwnedTransactionId) -> Self { Self::Local(value) } } #[derive(thiserror::Error, Debug)] pub enum TimeStampIntError { #[error("Integer conversion error: {0}")] IntError(#[from] std::num::TryFromIntError), #[error("UInt conversion error: {0}")] UIntError(>::Error), } #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] pub struct MessageTimeStamp(pub MilliSecondsSinceUnixEpoch); impl MessageTimeStamp { pub(crate) fn as_datetime(self) -> DateTime { let time = i64::from(self.0.0) / 1000; let time = DateTime::from_timestamp(time, 0).unwrap_or_default(); time.into() } fn same_day(self, other: Self) -> bool { let dt1 = self.as_datetime(); let dt2 = other.as_datetime(); dt1.date_naive() == dt2.date_naive() } fn show_date(self, settings: &ApplicationSettings) -> Span<'static> { let time = self .as_datetime() .format(settings.tunables.date_format.as_str()) .to_string(); Span::styled(time, settings.theme.timeline.date) } /// A compact date and time, for places without a date separator line. pub fn show_datetime(self) -> String { self.as_datetime().format("%Y-%m-%d %H:%M").to_string() } fn show_time(self, settings: &ApplicationSettings) -> Span<'static> { let time = self .as_datetime() .format(settings.tunables.time_format.as_str()) .to_string(); Span::styled(time, settings.theme.timeline.time) } } impl From for MessageTimeStamp { fn from(millis: MilliSecondsSinceUnixEpoch) -> Self { Self(millis) } } impl TryFrom<&MessageTimeStamp> for usize { type Error = TimeStampIntError; fn try_from(ts: &MessageTimeStamp) -> Result { let n = usize::try_from(u64::from(ts.0.0))?; Ok(n) } } impl TryFrom for MessageTimeStamp { type Error = TimeStampIntError; fn try_from(u: usize) -> Result { let n = u64::try_from(u)?; let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?; Ok(MessageTimeStamp::from(MilliSecondsSinceUnixEpoch(n))) } } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct MessageCursor { /// When timestamp is None, the corner is determined by moving backwards from /// the most recently received message. pub timestamp: Option, /// A row within the [Text] representation of a [Message]. pub text_row: usize, } impl MessageCursor { pub fn new(timestamp: MessageKey, text_row: usize) -> Self { MessageCursor { timestamp: Some(timestamp), text_row } } /// Get a cursor that refers to the most recent message. pub fn latest() -> Self { MessageCursor::default() } pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> { if let Some(ref key) = self.timestamp { Some(key) } else { Some(thread.last_key_value()?.0) } } pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option { let ev_hash = cursor.get_x(); let ev_term = OwnedEventId::try_from("$").ok()?.into(); let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?; let start = MessageKey { ts: ts_start, id: ev_term }; for (key, _) in thread.range(&start..) { if hash_message_id(&key.id)? == ev_hash { return Self::from(key.clone()).into(); } if key.ts > ts_start { break; } } // If we can't find the cursor, then go to the nearest timestamp. thread.range(start..).next().map(|(key, _)| Self::from(key.clone())) } pub fn to_cursor(&self, thread: &Messages) -> Option { let key = self.to_key(thread)?; let y = usize::try_from(&key.ts).ok()?; let x = hash_message_id(&key.id)?; Cursor::new(y, x).into() } } impl From> for MessageCursor { fn from(key: Option) -> Self { MessageCursor { timestamp: key, text_row: 0 } } } impl From for MessageCursor { fn from(key: MessageKey) -> Self { MessageCursor { timestamp: Some(key), text_row: 0 } } } impl Ord for MessageCursor { fn cmp(&self, other: &Self) -> Ordering { match (&self.timestamp, &other.timestamp) { (None, None) => self.text_row.cmp(&other.text_row), (None, Some(_)) => Ordering::Greater, (Some(_), None) => Ordering::Less, (Some(st), Some(ot)) => { let pcmp = st.cmp(ot); let tcmp = self.text_row.cmp(&other.text_row); pcmp.then(tcmp) }, } } } impl PartialOrd for MessageCursor { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } fn redaction_reason_event(ev: SyncRoomRedactionEvent) -> Option { let SyncRoomRedactionEvent::Original(ev) = ev else { return None; }; ev.content.reason } fn has_reply_fallback(relation: Option<&Relation>) -> bool { matches!( relation, Some(Relation::Reply(_) | Relation::Thread(ThreadRelation { in_reply_to: Some(_), .. })) ) } pub fn strip_reply_fallback(msgtype: &mut MessageType) { let MessageType::Text(content) = msgtype else { return; }; content.body = remove_plain_reply_fallback(&content.body).to_owned(); } fn content_html(msgtype: &MessageType) -> Option { let formatted = match msgtype { MessageType::Text(content) => content.formatted.as_ref(), MessageType::Emote(content) => content.formatted.as_ref(), MessageType::Notice(content) => content.formatted.as_ref(), MessageType::Audio(content) => content.formatted_caption(), MessageType::File(content) => content.formatted_caption(), MessageType::Video(content) => content.formatted_caption(), MessageType::Image(content) => content.formatted_caption(), _ => None, }; let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted { Some(parse_matrix_html(body.as_str())) } else { None }; if let Some(filename) = content_filename(msgtype) { let html = html.get_or_insert_with(|| { let text = body_cow_content(msgtype).into_owned(); let text = html::StyleTreeNode::Text(text.into()); let text = html::StyleTreeNode::Paragraph(Box::new(text)); StyleTree { children: vec![text] } }); html.children.insert(0, html::StyleTreeNode::Text(filename.into())); if let MessageType::Image(content) = msgtype { let src = content.source.clone(); html.children.insert( 0, html::StyleTreeNode::Image(html::Image::new(src, content.info.as_deref())), ); } } html } #[derive(Clone, Debug)] pub enum MessageEvent { EncryptedOriginal(Box), EncryptedRedacted(Box), Original(Box, MessageEdits), Redacted(OwnedEventId, Option), State(Box), Sticker(Box), Local(OwnedTransactionId, SendHandle, Box), Poll(Box), UnstablePoll(Box), } impl MessageEvent { pub fn event_id(&self) -> Option<&EventId> { let event_id = match self { MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(), MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(), MessageEvent::Original(ev, _) => ev.event_id.as_ref(), MessageEvent::Redacted(event_id, _) => event_id.as_ref(), MessageEvent::State(ev) => ev.event_id(), MessageEvent::Local(..) => return None, MessageEvent::Sticker(ev, ..) => ev.event_id.as_ref(), MessageEvent::Poll(ev) => ev.event_id(), MessageEvent::UnstablePoll(ev) => ev.event_id(), }; Some(event_id) } pub fn msgtype(&self) -> Option<&MessageType> { match self { MessageEvent::Original(ev, edits) => { edits .last_key_value() .map(|(_, ev)| &ev.msgtype) .or(Some(&ev.content.msgtype)) }, MessageEvent::Local(_, _, content) => Some(&content.msgtype), MessageEvent::EncryptedOriginal(..) | MessageEvent::EncryptedRedacted(..) | MessageEvent::Redacted(..) | MessageEvent::State(..) | MessageEvent::Sticker(..) | MessageEvent::Poll(..) | MessageEvent::UnstablePoll(..) => None, } } pub fn body(&self) -> Cow<'_, str> { match self { MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(), MessageEvent::Original(ev, edits) => { let msgtype = edits .last_key_value() .map(|(_, ev)| &ev.msgtype) .unwrap_or(&ev.content.msgtype); body_cow_content(msgtype) }, MessageEvent::EncryptedRedacted(ev) => { body_cow_reason(redaction_reason_unsigned(&ev.unsigned).as_deref()) }, MessageEvent::Redacted(_, reason) => body_cow_reason(reason.as_deref()), MessageEvent::Sticker(ev, ..) => body_cow_sticker(ev), MessageEvent::State(ev) => body_cow_state(ev), MessageEvent::Local(_, _, content) => body_cow_content(&content.msgtype), MessageEvent::Poll(poll) => poll.body_cow(), MessageEvent::UnstablePoll(poll) => poll.body_cow(), } } pub fn html(&self) -> Option { if let MessageEvent::State(ev) = self { return Some(html_state(ev)); } self.msgtype().and_then(content_html) } pub fn mentions(&self) -> Option<&Mentions> { match self { MessageEvent::EncryptedOriginal(..) | MessageEvent::EncryptedRedacted(..) | MessageEvent::Redacted(..) | MessageEvent::Sticker(..) | MessageEvent::Poll(..) | MessageEvent::UnstablePoll(..) | MessageEvent::State(..) => None, MessageEvent::Original(ev, edits) => { edits .last_key_value() .and_then(|(_, ev)| ev.mentions.as_ref()) .or(ev.content.mentions.as_ref()) }, MessageEvent::Local(_, _, ev) => ev.mentions.as_ref(), } } fn message_style(&self, settings: &ApplicationSettings) -> Style { let content = match self { MessageEvent::EncryptedOriginal(_) | MessageEvent::EncryptedRedacted(_) => { return settings.theme.timeline.default; }, MessageEvent::Redacted(..) => return settings.theme.timeline.redacted, MessageEvent::State(_) => return settings.theme.timeline.state, MessageEvent::Original(ev, _) => &ev.content, MessageEvent::Local(_, _, content) => content, MessageEvent::Sticker(..) => return settings.theme.timeline.sticker, MessageEvent::Poll(..) | MessageEvent::UnstablePoll(..) => { return settings.theme.timeline.poll; }, }; match &content.msgtype { MessageType::Text(_) | MessageType::Audio(_) | MessageType::Emote(_) | MessageType::File(_) | MessageType::Image(_) | MessageType::Video(_) => settings.theme.messages.default, MessageType::Notice(_) | MessageType::ServerNotice(_) => settings.theme.timeline.notice, _ => settings.theme.messages.default, } } fn redact(&mut self, redaction: SyncRoomRedactionEvent) { match self { MessageEvent::EncryptedOriginal(_) => return, MessageEvent::EncryptedRedacted(_) => return, MessageEvent::Redacted(_, _) => return, MessageEvent::State(_) => return, MessageEvent::Sticker(ev, ..) => { let event_id = ev.event_id.to_owned(); let reason = redaction_reason_event(redaction); *self = MessageEvent::Redacted(event_id, reason); }, MessageEvent::Local(..) => return, MessageEvent::Original(ev, _) => { let event_id = ev.event_id.to_owned(); let reason = redaction_reason_event(redaction); *self = MessageEvent::Redacted(event_id, reason); }, MessageEvent::Poll(ev) => { let event_id = ev.event_id().to_owned(); let reason = redaction_reason_event(redaction); *self = MessageEvent::Redacted(event_id, reason); }, MessageEvent::UnstablePoll(ev) => { let event_id = ev.event_id().to_owned(); let reason = redaction_reason_event(redaction); *self = MessageEvent::Redacted(event_id, reason); }, } } fn is_edited(&self) -> bool { match self { Self::Original(_, edits) => !edits.is_empty(), Self::Poll(poll) => !poll.replacements.is_empty(), Self::UnstablePoll(poll) => !poll.replacements.is_empty(), _ => false, } } } fn body_cow_content(msgtype: &MessageType) -> Cow<'_, str> { let s = match msgtype { MessageType::Text(content) => content.body.as_str(), MessageType::VerificationRequest(_) => "[Verification Request]", MessageType::Emote(content) => content.body.as_ref(), MessageType::Notice(content) => content.body.as_str(), MessageType::ServerNotice(content) => content.body.as_str(), MessageType::Audio(content) => { display_file_to_text!(Audio, content) }, MessageType::File(content) => { display_file_to_text!(File, content) }, MessageType::Image(content) => { display_file_to_text!(Image, content) }, MessageType::Video(content) => { display_file_to_text!(Video, content) }, _ => msgtype.body(), }; Cow::Borrowed(s) } fn body_cow_sticker(sticker: &OriginalStickerEvent) -> Cow<'_, str> { Cow::Owned(format!("* sent a sticker: {}", sticker.content.body)) } fn redaction_reason_unsigned(unsigned: &RedactedUnsigned) -> Option { let ev = unsigned.redacted_because.deserialize().ok()?; let AnyRedactionEvent::RoomRedaction(ev) = ev else { return None; }; ev.content.reason } fn body_cow_reason(reason: Option<&str>) -> Cow<'static, str> { if let Some(r) = reason { Cow::Owned(format!("[Redacted: {r:?}]")) } else { Cow::Borrowed("[Redacted]") } } enum MessageColumns { /// Four columns: sender, message, timestamp, read receipts. Four, /// Three columns: sender, message, timestamp. Three, /// Two columns: sender, message. Two, /// One column: message with sender on line before the message. One, } impl MessageColumns { fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 { if let MessageColumns::One = self { 2 } else { settings.tunables.user_gutter_width as u16 } } } #[derive(Default, Debug)] enum SenderSpan<'a> { /// Show the sender name in the user gutter. /// This is truncated and padded to fit [`user_gutter_width`](`crate::config::TunableValues::user_gutter_width`). Gutter(Span<'a>), /// Show the sender name in an extra line at the top of the message. Line(Span<'a>), /// The sender name has already been printed. #[default] None, } struct MessageFormatter<'a> { settings: &'a ApplicationSettings, info: &'a RoomInfo, /// How many columns to print. cols: MessageColumns, /// The full, original width. orig: usize, /// The width that the message contents need to fill. fill: usize, /// The formatted Span for the message sender. user: SenderSpan<'a>, /// The time the message was sent. time: Option>, /// The date the message was sent. date: Option>, /// Whether to draw the read marker's trackbar above this message. trackbar: bool, /// The users who have read up to this message. read: Vec, } impl<'a> MessageFormatter<'a> { fn width(&self) -> usize { self.fill } fn message_start_line(&self) -> u16 { let mut line = 0; if self.date.is_some() { line += 1; } if self.trackbar { line += 1; } if let SenderSpan::Line(_) = self.user { line += 1; } line } #[inline] fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) { if std::mem::take(&mut self.trackbar) { let trackbar_style = self.settings.theme.timeline.unread_marker; text.lines .push(Line::from(Span::styled(HORIZONTAL.repeat(self.orig), trackbar_style))); } if let Some(date) = self.date.take() { let len = date.content.as_ref().len(); let padding = self.orig.saturating_sub(len); let leading = space_span(padding / 2, Style::default()); let trailing = space_span(padding.saturating_sub(padding / 2), Style::default()); text.lines.push(Line::from(vec![leading, date, trailing])); } let user_gutter_empty_span = space_span(self.settings.tunables.user_gutter_width, Style::default()); let user_gutter = match std::mem::take(&mut self.user) { SenderSpan::Line(user) => { text.lines.push(user.into()); user_gutter_empty_span }, SenderSpan::Gutter(user) => user, SenderSpan::None => user_gutter_empty_span, }; match self.cols { MessageColumns::Four => { let settings = self.settings; let time = self.time.take().unwrap_or_else(|| { space_span(settings.tunables.time_gutter_width, Style::default()) }); let mut line = vec![user_gutter]; line.extend(prev_line.spans); line.push(time); // Show read receipts. let user_char = |user: OwnedUserId| -> Span { settings.get_user_char_span(&user, self.info) }; let a = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" ")); let b = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" ")); let c = self.read.pop().map(user_char).unwrap_or_else(|| Span::raw(" ")); line.push(Span::raw(" ")); line.push(c); line.push(b); line.push(a); line.push(Span::raw(" ")); text.lines.push(Line::from(line)) }, MessageColumns::Three => { let time = self.time.take().unwrap_or_else(|| Span::from("")); let mut line = vec![user_gutter]; line.extend(prev_line.spans); line.push(time); text.lines.push(Line::from(line)) }, MessageColumns::Two => { let mut line = vec![user_gutter]; line.extend(prev_line.spans); text.lines.push(Line::from(line)); }, MessageColumns::One => { let leading = space_span(2, style); let mut line = vec![leading]; line.extend(prev_line.spans); text.lines.push(Line::from(line)); }, } } fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) { for line in append.lines.into_iter() { self.push_spans(line, style, text); } } fn push_in_reply( &mut self, msg: &'a Message, style: Style, text: &mut Text<'a>, info: &'a RoomInfo, settings: &'a ApplicationSettings, previews: &'a PreviewManager, ) -> Vec { let reply_style = if settings.tunables.message_user_color { style.patch(settings.get_user_color(&msg.sender)) } else { style.patch(msg.event.message_style(settings)) }; let width = self.width(); let w = width.saturating_sub(2); let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews, info); let mut sender = msg.sender_span(info, self.settings); let sender_width = UnicodeWidthStr::width(sender.content.as_ref()); let trailing = w.saturating_sub(sender_width + 1); sender.style = sender.style.patch(reply_style); self.push_spans( Line::from(vec![ Span::styled(" ", style), Span::styled(THICK_VERTICAL, style), sender, Span::styled(":", reply_style), space_span(trailing, reply_style), ]), style, text, ); // Determine the image offset of the reply header, taking into account the formatting let proto = proto .into_iter() .map(|(p, x, y)| { let y_off = text.lines.len() as u16; // Adjust x_off by 2 to account for the vertical line and indent let x_off = self.cols.user_gutter_width(settings) + 2; (p, x + x_off, y + y_off) }) .collect(); for line in replied.lines.iter_mut() { line.spans.insert(0, Span::styled(THICK_VERTICAL, style)); line.spans.insert(0, Span::styled(" ", style)); } self.push_text(replied, reply_style, text); proto } fn push_reactions( &mut self, counts: Vec<(&'a str, Vec<&'a UserId>, &'a Option)>, style: Style, text: &mut Text<'a>, settings: &ApplicationSettings, previews: &'a PreviewManager, ) -> Vec { let mut emojis = printer::TextPrinter::new( self.width(), style, self.settings, self.info, Some(previews), ); let mut reactions = 0; for (key, count, source) in counts { if reactions != 0 { emojis.push_str(" ", style); } let proto = match source.as_ref().and_then(|source| previews.get(source, PreviewKind::Emoji)) { Some(ImageStatus::Loaded(backend)) => Some(Some(backend)), // Use empty space as placeholder Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None), // Fall back to text None | Some(ImageStatus::Error(_)) => None, }; let name = if proto.is_some() { " " } else if self.settings.tunables.reaction_shortcode_display { if let Some(emoji) = emojis::get(key) { if let Some(short) = emoji.shortcode() { short } else { // No ASCII shortcode name to show. continue; } } else if key.chars().all(|c| c.is_ascii_alphanumeric()) { key } else { // Not an Emoji or a printable ASCII string. continue; } } else { key }; emojis.push_str("[", style); if let Some(Some(proto)) = proto { emojis.push_emoji(proto, style); } else { emojis.push_str(name, style); } emojis.push_str(" ", style); emojis.push_span_nobreak(Span::styled(count.len().to_string(), style)); emojis.push_str("]", style); reactions += 1; } if reactions > 0 { let (txt, protos) = emojis.finish(); let x_off = self.cols.user_gutter_width(settings); let y_off = text.lines.len() as u16; self.push_text(txt, style, text); protos.into_iter().map(|(p, x, y)| (p, x + x_off, y + y_off)).collect() } else { vec![] } } fn push_thread_reply_count(&mut self, thread: &Thread, text: &mut Text<'a>, style: Style) { let len = thread.summary.as_ref().map(|s| s.num_replies).unwrap_or_default(); let len = thread.len().max(len as usize); if len == 0 { return; } // If we have threaded replies to this message, show how many. let is_plural = len != 1; let mut threaded = printer::TextPrinter::new(self.width(), style, self.settings, self.info, None) .literal(true); let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD)); threaded.push_str(" \u{2937} ", style); threaded.push_span_nobreak(len); if is_plural { threaded.push_str(" replies in thread", style); } else { threaded.push_str(" reply in thread", style); } let (num, singular, plural) = if thread.unreads.num_mentions > 0 { (thread.unreads.num_mentions, "mention", "mentions") } else if thread.unreads.num_notifications > 0 { (thread.unreads.num_notifications, "notification", "notifications") } else { (thread.unreads.num_unread, "unread", "unreads") }; if num > 0 { threaded.push_str(" (", style); threaded.push_span_nobreak(Span::styled(num.to_string(), style.bold())); threaded.push_str(" ", style); if num > 1 { threaded.push_str(plural, style); } else { threaded.push_str(singular, style); } threaded.push_str(")", style); } self.push_text(threaded.finish().0, style, text); } } #[derive(Clone)] pub struct Message { pub event: MessageEvent, pub sender: OwnedUserId, pub timestamp: MessageTimeStamp, pub html: Option, } /// Whether the read marker sits between the previous message and this one. /// /// The marker's event is the last one the user has read, so the first message /// after it is the first unread one. A missing marker, or one whose message /// isn't among the loaded ones, leaves nothing to mark. fn is_after_read_marker(prev: Option<&Message>, marker: Option<&OwnedEventId>) -> bool { match (prev.and_then(|msg| msg.event.event_id()), marker) { (Some(prev), Some(marker)) => prev == marker, _ => false, } } impl Message { pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self { let html = event.html(); Message { event, sender, timestamp, html } } pub fn reply_to(&self) -> Option { let content = match &self.event { MessageEvent::EncryptedOriginal(_) => return None, MessageEvent::EncryptedRedacted(_) => return None, MessageEvent::Local(_, _, content) => content, MessageEvent::Original(ev, _) => &ev.content, MessageEvent::Redacted(_, _) => return None, MessageEvent::State(_) => return None, MessageEvent::Sticker(ev, ..) => { return match &ev.content.relates_to { Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()), Some(Relation::Thread(ThreadRelation { in_reply_to: Some(in_reply_to), is_falling_back: false, .. })) => Some(in_reply_to.event_id.clone()), Some(_) | None => None, }; }, MessageEvent::Poll(poll) => return poll.reply_to().map(ToOwned::to_owned), MessageEvent::UnstablePoll(poll) => return poll.reply_to().map(ToOwned::to_owned), }; match &content.relates_to { Some(Relation::Reply(reply)) => Some(reply.in_reply_to.event_id.clone()), Some(Relation::Thread(ThreadRelation { in_reply_to: Some(in_reply_to), is_falling_back: false, .. })) => Some(in_reply_to.event_id.clone()), Some(_) | None => None, } } /// Return the thread root if this is the first message in the thread. pub fn thread_root(&self) -> Option { let content = match &self.event { MessageEvent::EncryptedOriginal(_) => return None, MessageEvent::EncryptedRedacted(_) => return None, MessageEvent::Local(_, _, content) => content, MessageEvent::Original(ev, _) => &ev.content, MessageEvent::Redacted(_, _) => return None, MessageEvent::State(_) => return None, MessageEvent::Sticker(..) => return None, MessageEvent::Poll(poll) => return poll.thread_root().map(ToOwned::to_owned), MessageEvent::UnstablePoll(poll) => return poll.thread_root().map(ToOwned::to_owned), }; match &content.relates_to { Some(Relation::Thread(ThreadRelation { event_id, in_reply_to: Some(in_reply_to), is_falling_back: true, .. })) if event_id == &in_reply_to.event_id => Some(event_id.clone()), Some(_) | None => None, } } pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> { if let Some(html) = &self.html { html.image_previews() } else { vec![] } } fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style { let mut style = self.event.message_style(settings); if matches!(self.event, MessageEvent::Local(..)) { style = style.add_modifier(StyleModifier::ITALIC); } if settings.tunables.message_user_color { let color = settings.get_user_color(&self.sender); style = style.fg(color); } if selected { // Apply last, so that if the user or theme specified selected colors // for selected messages then it will get put on top of the user color: style = style.patch(settings.theme.selected); } return style; } pub fn show_date(&self, prev: Option<&Message>) -> bool { let Some(prev) = prev else { return true }; !prev.timestamp.same_day(self.timestamp) } /// Whether the current user's read marker sits right before this message. /// /// Each thread keeps its own marker, so the rule only shows up in the view /// whose messages the marker belongs to. pub fn show_trackbar( &self, prev: Option<&Message>, info: &RoomInfo, settings: &ApplicationSettings, ) -> bool { let marker = info .user_receipts(&self.receipt_thread(info)) .and_then(|receipts| receipts.get(&settings.user_id)); is_after_read_marker(prev, marker) } /// The read receipt thread that this message was inserted into. pub(crate) fn receipt_thread(&self, info: &RoomInfo) -> ReceiptThread { self.event .event_id() .and_then(|event_id| info.get_receipt_thread(event_id)) .unwrap_or(ReceiptThread::Main) } pub fn message_column_width( viewctx: &ViewportContext, settings: &ApplicationSettings, ) -> usize { let width = viewctx.get_width(); let user_gutter = settings.tunables.user_gutter_width; let time_gutter = settings.tunables.time_gutter_width; if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width && settings.tunables.read_receipt_display { width - user_gutter - time_gutter - READ_GUTTER } else if user_gutter + time_gutter + MIN_MSG_LEN <= width { width - user_gutter - time_gutter } else if user_gutter + MIN_MSG_LEN <= width { width - user_gutter } else { width.saturating_sub(2) } } fn get_render_format<'a>( &'a self, prev: Option<&Message>, width: usize, info: &'a RoomInfo, settings: &'a ApplicationSettings, ) -> MessageFormatter<'a> { let orig = width; let date = self.show_date(prev).then(|| self.timestamp.show_date(settings)); let trackbar = self.show_trackbar(prev, info, settings); let user_gutter = settings.tunables.user_gutter_width; let time_gutter = settings.tunables.time_gutter_width; if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width && settings.tunables.read_receipt_display { let cols = MessageColumns::Four; let fill = width - user_gutter - time_gutter - READ_GUTTER; let user = self.show_sender(prev, true, info, settings, width); let time = Some(self.timestamp.show_time(settings)); let read = self .event .event_id() .map(|event_id| { // Iterate over both `ReceiptThread::Unthreaded` for clients unaware // of threads, and over the appropriate `ReceiptThread::Main` or // `ReceiptThread::Thread` for ones from thread-aware clients, like // our own receipts or implicit receipts we've generated. let receipt_thread = self.receipt_thread(info); let threaded = info.read_event_users(receipt_thread, event_id); let unthreaded = info.read_event_users(ReceiptThread::Unthreaded, event_id); threaded .chain(unthreaded) .filter(|user_id| **user_id != settings.user_id) .map(|user_id| user_id.to_owned()) .collect() }) .unwrap_or_default(); MessageFormatter { settings, cols, orig, fill, user, date, trackbar, time, read, info, } } else if user_gutter + time_gutter + MIN_MSG_LEN <= width { let cols = MessageColumns::Three; let fill = width - user_gutter - time_gutter; let user = self.show_sender(prev, true, info, settings, width); let time = Some(self.timestamp.show_time(settings)); let read = Vec::new(); MessageFormatter { settings, cols, orig, fill, user, date, trackbar, time, read, info, } } else if user_gutter + MIN_MSG_LEN <= width { let cols = MessageColumns::Two; let fill = width - user_gutter; let user = self.show_sender(prev, true, info, settings, width); let time = None; let read = Vec::new(); MessageFormatter { settings, cols, orig, fill, user, date, trackbar, time, read, info, } } else { let cols = MessageColumns::One; let fill = width.saturating_sub(2); let user = self.show_sender(prev, false, info, settings, width); let time = None; let read = Vec::new(); MessageFormatter { settings, cols, orig, fill, user, date, trackbar, time, read, info, } } } /// Render the message as a [Text] object for the terminal. /// /// This will also get the image preview Protocol with an x/y offset. pub fn show_with_preview<'a>( &'a self, prev: Option<&Message>, selected: bool, width: usize, info: &'a RoomInfo, settings: &'a ApplicationSettings, previews: &'a PreviewManager, ) -> (Text<'a>, Vec) { let style = self.get_render_style(selected, settings); let mut fmt = self.get_render_format(prev, width, info, settings); let mut text = Text::default(); let width = fmt.width(); let mut protos = Vec::new(); // Show the message that this one replied to, if any. let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e)); if let Some(r) = reply { if let Some(r) = r { // Format the reply header, push it into the `Text` buffer, and get any image. protos = fmt.push_in_reply(r, style, &mut text, info, settings, previews); } else { fmt.push_spans( Line::from(vec![ Span::styled(" ", style), Span::styled(THICK_VERTICAL, style), Span::styled("Original message not loaded", style), space_span(width.saturating_sub(29), style), ]), style, &mut text, ); } } // Now show the message contents, and the inlined reply if we couldn't find it above. let (msg, proto) = self.show_msg(width, style, settings, previews, info); // Given our text so far, determine the image offset. { let y_off = text.lines.len() as u16; let x_off = fmt.cols.user_gutter_width(settings); // Account for extra lines printed before the message; let y_off = y_off + fmt.message_start_line(); for (p, x, y) in proto { protos.push((p, x + x_off, y + y_off)); } } fmt.push_text(msg, style, &mut text); if text.lines.is_empty() { // If there was nothing in the body, just show an empty message. fmt.push_spans(space_span(width, style).into(), style, &mut text); } let pinned = self.event.event_id().is_some_and(|id| info.is_pinned(id)); let label = match (self.event.is_edited(), pinned) { (true, true) => Some("(pinned, edited)"), (true, false) => Some("(edited)"), (false, true) => Some("(pinned)"), (false, false) => None, }; if let Some(label) = label { fmt.push_spans( Line::from(vec![ Span::styled(label, style.fg(Color::Gray)), space_span(fmt.width().saturating_sub(label.len()), style), ]), style, &mut text, ); } if settings.tunables.reaction_display { let reactions = self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default(); let react_protos = fmt.push_reactions(reactions, style, &mut text, settings, previews); protos.extend(react_protos); } if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(id)) { fmt.push_thread_reply_count(thread, &mut text, style); } (text, protos) } pub fn show<'a>( &'a self, prev: Option<&Message>, selected: bool, width: usize, info: &'a RoomInfo, settings: &'a ApplicationSettings, previews: &'a PreviewManager, ) -> Text<'a> { self.show_with_preview(prev, selected, width, info, settings, previews).0 } fn show_msg<'a>( &'a self, width: usize, style: Style, settings: &'a ApplicationSettings, previews: &'a PreviewManager, info: &'a RoomInfo, ) -> (Text<'a>, Vec) { let mut protos = vec![]; let mut text = Default::default(); if let Some(html) = &self.html && settings.tunables.message_formatted_display { let (t, p) = html.render(width, style, settings, info, previews); text += t; protos = p; } else { let mut msg = self.event.body(); if settings.tunables.message_shortcode_display { msg = Cow::Owned(replace_emojis_in_str(msg.as_ref())); } text += wrapped_text(msg, width, style); }; (text, protos) } fn sender_span<'a>( &'a self, info: &'a RoomInfo, settings: &'a ApplicationSettings, ) -> Span<'a> { settings.get_user_span(self.sender.as_ref(), info.display_names.get(&self.sender)) } fn show_sender<'a>( &'a self, prev: Option<&Message>, gutter_enabled: bool, info: &'a RoomInfo, settings: &'a ApplicationSettings, width: usize, ) -> SenderSpan<'a> { if let Some(prev) = prev && self.sender == prev.sender && self.timestamp.same_day(prev.timestamp) && !matches!(self.event.msgtype(), Some(MessageType::Emote(_))) { return SenderSpan::None; } let Span { content, style } = self.sender_span(info, settings); let user_gutter = settings.tunables.user_gutter_width; let show_in_gutter = gutter_enabled && user_gutter > 2; if show_in_gutter { let ((truncated, width), _) = take_width_grapheme(content, user_gutter - 2); let padding = user_gutter - 2 - width; let sender = format!("{}{} ", space(padding), truncated); SenderSpan::Gutter(Span::styled(sender, style)) } else if UnicodeWidthStr::width(content.as_ref()) > width { let ((truncated, _), _) = take_width_grapheme(content, width); SenderSpan::Line(Span::styled(truncated, style)) } else { SenderSpan::Line(Span::styled(content, style)) } } pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) { self.event.redact(redaction); self.html = None; } pub fn set_edits(&mut self, new_edits: MessageEdits) { if let MessageEvent::Original(orig, edits) = &mut self.event { *edits = new_edits; for edit in edits.values_mut() { strip_reply_fallback(&mut edit.msgtype); } if let Some(most_recent) = edits.last_key_value() { self.html = content_html(&most_recent.1.msgtype); } else { self.html = content_html(&orig.content.msgtype); } } } pub fn insert_edit( &mut self, key: MessageKey, mut edit: RoomMessageEventContentWithoutRelation, ) { if let MessageEvent::Original(_, edits) = &mut self.event { strip_reply_fallback(&mut edit.msgtype); let inserted = edits.entry(key).insert_entry(edit); self.html = content_html(&inserted.get().msgtype); } } pub fn remove_edit(&mut self, key: &MessageKey) { let MessageEvent::Original(orig_content, edits) = &mut self.event else { return; }; edits.remove(key); let content = edits .last_key_value() .map(|(_, msg)| &msg.msgtype) .unwrap_or(&orig_content.content.msgtype); self.html = content_html(content); } pub fn find_links(&self) -> Vec<(char, Url)> { let mut links = if let Some(html) = &self.html { html.get_links() } else { vec![] }; if links.is_empty() { links = linkify::LinkFinder::new() .links(&self.event.body()) .filter_map(|u| Url::parse(u.as_str()).ok()) .scan(TreeGenState { link_num: 0 }, |state, u| { state.next_link_char().map(|c| (c, u)) }) .collect(); } links } } impl From for Message { fn from(event: RoomEncryptedEvent) -> Self { let timestamp = event.origin_server_ts().into(); let user_id = event.sender().to_owned(); let content = match event { RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()), RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()), }; Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: OriginalRoomMessageEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let content = MessageEvent::Original(event.into(), Default::default()); Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: RedactedRoomMessageEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let event_id = event.event_id; let reason = redaction_reason_unsigned(&event.unsigned); let content = MessageEvent::Redacted(event_id, reason); Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: RoomMessageEvent) -> Self { match event { RoomMessageEvent::Original(ev) => ev.into(), RoomMessageEvent::Redacted(ev) => ev.into(), } } } impl From for Message { fn from(event: RedactedPollStartEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let event_id = event.event_id; let reason = redaction_reason_unsigned(&event.unsigned); let content = MessageEvent::Redacted(event_id, reason); Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: RedactedUnstablePollStartEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let event_id = event.event_id; let reason = redaction_reason_unsigned(&event.unsigned); let content = MessageEvent::Redacted(event_id, reason); Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: AnySyncStateEvent) -> Self { let timestamp = event.origin_server_ts().into(); let user_id = event.sender().to_owned(); let event = MessageEvent::State(event.into()); Message::new(event, user_id, timestamp) } } impl From for Message { fn from(event: OriginalStickerEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let source = event.content.source.clone().into(); let html_image = html::StyleTreeNode::Image(html::Image::new(source, Some(&event.content.info))); let content = MessageEvent::Sticker(event.into()); let mut msg = Message::new(content, user_id, timestamp); msg.html = Some(StyleTree { children: vec![ html::StyleTreeNode::Text("* sent a sticker:".into()), html_image, ], }); msg } } impl From for Message { fn from(event: RedactedStickerEvent) -> Self { let timestamp = event.origin_server_ts.into(); let user_id = event.sender.clone(); let event_id = event.event_id; let reason = redaction_reason_unsigned(&event.unsigned); let content = MessageEvent::Redacted(event_id, reason); Message::new(content, user_id, timestamp) } } impl From for Message { fn from(event: StickerEvent) -> Self { match event { MessageLikeEvent::Original(ev) => ev.into(), MessageLikeEvent::Redacted(ev) => ev.into(), } } } impl Display for Message { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.event.body()) } } #[cfg(test)] pub mod tests { use super::*; use matrix_sdk::ruma::events::relation::Reply; use matrix_sdk::ruma::events::room::ImageInfo; use matrix_sdk::ruma::events::room::message::{ AudioInfo, AudioMessageEventContent, FileInfo, FileMessageEventContent, ImageMessageEventContent, TextMessageEventContent, VideoInfo, VideoMessageEventContent, }; use crate::base::EventLocation; use crate::config::time_gutter_width; use crate::tests::*; #[test] fn test_has_reply_fallback() { let root = OwnedEventId::try_from("$root:example.org").unwrap(); let target = OwnedEventId::try_from("$target:example.org").unwrap(); let reply: Relation = Relation::Reply(Reply::with_event_id(target.clone())); assert!(has_reply_fallback(Some(&reply))); let thread_reply: Relation = Relation::Thread(ThreadRelation::reply(root.clone(), target.clone())); assert!(has_reply_fallback(Some(&thread_reply))); let thread_fallback: Relation = Relation::Thread(ThreadRelation::plain(root.clone(), target)); assert!(has_reply_fallback(Some(&thread_fallback))); let thread_without_fallback: Relation = Relation::Thread(ThreadRelation::without_fallback(root)); assert!(!has_reply_fallback(Some(&thread_without_fallback))); assert!(!has_reply_fallback(None)); } #[test] fn test_strip_reply_fallback() { let body = "> <@user:example.org> quoted text\n> more quoted text\n\nreply"; let mut msgtype = MessageType::Text(TextMessageEventContent::plain(body)); strip_reply_fallback(&mut msgtype); assert_eq!(msgtype.body(), "reply"); } #[test] fn test_mc_cmp() { let mc1 = MessageCursor::from(MSG1_KEY.clone()); let mc2 = MessageCursor::from(MSG2_KEY.clone()); let mc3 = MessageCursor::from(MSG3_KEY.clone()); let mc4 = MessageCursor::from(MSG4_KEY.clone()); let mc5 = MessageCursor::from(MSG5_KEY.clone()); // Everything is equal to itself. assert_eq!(mc1.cmp(&mc1), Ordering::Equal); assert_eq!(mc2.cmp(&mc2), Ordering::Equal); assert_eq!(mc3.cmp(&mc3), Ordering::Equal); assert_eq!(mc4.cmp(&mc4), Ordering::Equal); assert_eq!(mc5.cmp(&mc5), Ordering::Equal); // Local echo is always greater than an origin server timestamp. assert_eq!(mc1.cmp(&mc2), Ordering::Greater); assert_eq!(mc1.cmp(&mc3), Ordering::Greater); assert_eq!(mc1.cmp(&mc4), Ordering::Greater); assert_eq!(mc1.cmp(&mc5), Ordering::Greater); // mc2 is the smallest timestamp. assert_eq!(mc2.cmp(&mc1), Ordering::Less); assert_eq!(mc2.cmp(&mc3), Ordering::Less); assert_eq!(mc2.cmp(&mc4), Ordering::Less); assert_eq!(mc2.cmp(&mc5), Ordering::Less); // mc3 should be less than mc4 because of its event ID. assert_eq!(mc3.cmp(&mc1), Ordering::Less); assert_eq!(mc3.cmp(&mc2), Ordering::Greater); assert_eq!(mc3.cmp(&mc4), Ordering::Less); assert_eq!(mc3.cmp(&mc5), Ordering::Less); // mc4 should be greater than mc3 because of its event ID. assert_eq!(mc4.cmp(&mc1), Ordering::Less); assert_eq!(mc4.cmp(&mc2), Ordering::Greater); assert_eq!(mc4.cmp(&mc3), Ordering::Greater); assert_eq!(mc4.cmp(&mc5), Ordering::Less); // mc5 is the greatest OriginServer timestamp. assert_eq!(mc5.cmp(&mc1), Ordering::Less); assert_eq!(mc5.cmp(&mc2), Ordering::Greater); assert_eq!(mc5.cmp(&mc3), Ordering::Greater); assert_eq!(mc5.cmp(&mc4), Ordering::Greater); } #[test] fn test_mc_to_key() { let messages = mock_messages(); let mc1 = MessageCursor::from(MSG1_KEY.clone()); let mc2 = MessageCursor::from(MSG2_KEY.clone()); let mc3 = MessageCursor::from(MSG3_KEY.clone()); let mc4 = MessageCursor::from(MSG4_KEY.clone()); let mc5 = MessageCursor::from(MSG5_KEY.clone()); let mc6 = MessageCursor::latest(); let k1 = mc1.to_key(&messages).unwrap(); let k2 = mc2.to_key(&messages).unwrap(); let k3 = mc3.to_key(&messages).unwrap(); let k4 = mc4.to_key(&messages).unwrap(); let k5 = mc5.to_key(&messages).unwrap(); let k6 = mc6.to_key(&messages).unwrap(); // These should all be equal to their MSGN_KEYs. assert_eq!(k1, &MSG1_KEY.clone()); assert_eq!(k2, &MSG2_KEY.clone()); assert_eq!(k3, &MSG3_KEY.clone()); assert_eq!(k4, &MSG4_KEY.clone()); assert_eq!(k5, &MSG5_KEY.clone()); // MessageCursor::latest() turns into the largest key (our local echo message). assert_eq!(k6, &MSG1_KEY.clone()); // MessageCursor::latest() fails to convert for a room w/o messages. let messages_empty = Messages::new(ReceiptThread::Main); assert_eq!(mc6.to_key(&messages_empty), None); } #[test] fn test_mc_to_from_cursor() { let messages = mock_messages(); let mc1 = MessageCursor::from(MSG1_KEY.clone()); let mc2 = MessageCursor::from(MSG2_KEY.clone()); let mc3 = MessageCursor::from(MSG3_KEY.clone()); let mc4 = MessageCursor::from(MSG4_KEY.clone()); let mc5 = MessageCursor::from(MSG5_KEY.clone()); let mc6 = MessageCursor::latest(); let identity = |mc: &MessageCursor| { let c = mc.to_cursor(&messages).unwrap(); MessageCursor::from_cursor(&c, &messages).unwrap() }; // These should all convert to a Cursor and back to the original value. assert_eq!(identity(&mc1), mc1); assert_eq!(identity(&mc2), mc2); assert_eq!(identity(&mc3), mc3); assert_eq!(identity(&mc4), mc4); assert_eq!(identity(&mc5), mc5); // MessageCursor::latest() should point at the most recent message after conversion. assert_eq!(identity(&mc6), mc1); } #[test] fn test_placeholder_frame() { fn pretty_frame_test(str: &str) -> String { str[1..].to_string() } assert_eq!( placeholder_frame(None, 4, &Size { width: 4, height: 4 }), pretty_frame_test( r#" ⌌ ⌍ ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(None, 2, &Size { width: 4, height: 4 }), pretty_frame_test( r#" ⌌⌍ ⌎⌏ "# ) ); assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), "#\n#\n#\n#\n"); assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), "####\n"); assert_eq!( placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }), pretty_frame_test( r#" ⌌ ⌍ OK ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 6 }), pretty_frame_test( r#" ⌌ ⌍ OK ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 7 }), pretty_frame_test( r#" ⌌ ⌍ OK ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(Some("idontfit"), 4, &Size { width: 4, height: 4 }), pretty_frame_test( r#" ⌌ ⌍ ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 2 }), pretty_frame_test( r#" ⌌ ⌍ ⌎ ⌏ "# ) ); assert_eq!( placeholder_frame(Some("OK"), 4, &Size { width: 2, height: 3 }), pretty_frame_test( r#" ⌌⌍ ⌎⌏ "# ) ); } #[test] fn test_display_attachment_size() { assert_eq!( content_filename(&MessageType::Image( ImageMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::default())) )), "[Attached Image: Alt text]".to_string().into() ); let mut info = ImageInfo::default(); info.size = Some(442630_u32.into()); assert_eq!( content_filename(&MessageType::Image( ImageMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::new(info))) )), "[Attached Image: Alt text (442.63 kB)]".to_string().into() ); let mut info = ImageInfo::default(); info.size = Some(12_u32.into()); assert_eq!( content_filename(&MessageType::Image( ImageMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::new(info))) )), "[Attached Image: Alt text (12 B)]".to_string().into() ); let mut info = AudioInfo::default(); info.size = Some(4294967295_u32.into()); assert_eq!( content_filename(&MessageType::Audio( AudioMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::new(info))) )), "[Attached Audio: Alt text (4.29 GB)]".to_string().into() ); let mut info = FileInfo::default(); info.size = Some(4426300_u32.into()); assert_eq!( content_filename(&MessageType::File( FileMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::new(info))) )), "[Attached File: Alt text (4.43 MB)]".to_string().into() ); let mut info = VideoInfo::default(); info.size = Some(44000_u32.into()); assert_eq!( content_filename(&MessageType::Video( VideoMessageEventContent::plain( "Alt text".to_string(), "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into() ) .info(Some(Box::new(info))) )), "[Attached Video: Alt text (44 kB)]".to_string().into() ); } #[test] fn test_is_after_read_marker() { let first = mock_message1(); let second = mock_message2(); // Without a marker there's nothing to mark. assert!(!is_after_read_marker(Some(&first), None)); assert!(!is_after_read_marker(None, None)); // The marker names the last read message, so the message immediately // after it draws the trackbar. assert!(is_after_read_marker(Some(&first), Some(&MSG1_EVID))); assert!(is_after_read_marker(Some(&second), Some(&MSG2_EVID))); // A marker on the rendered message belongs to the next message instead, // so the last loaded message never draws a trackbar when it's the // marker itself. assert!(!is_after_read_marker(Some(&first), Some(&MSG2_EVID))); // The first loaded message has no predecessor to prove the marker is // its neighbor, and markers for unloaded messages aren't neighbors. assert!(!is_after_read_marker(None, Some(&MSG1_EVID))); assert!(!is_after_read_marker(Some(&second), Some(&MSG5_EVID))); } fn has_trackbar(text: &Text<'_>, width: usize) -> bool { text.lines.iter().any(|line| { line.spans .iter() .any(|span| span.content.as_ref() == HORIZONTAL.repeat(width)) }) } #[test] fn test_show_trackbar() { let settings = mock_settings(); let previews = PreviewManager::new(&settings); let mut info = mock_room(); let width = 60; let prev = mock_message1(); let msg = mock_message2(); let user_id = settings.user_id.clone(); // Without a marker, no trackbar is drawn. let text = msg.show(Some(&prev), false, width, &info, &settings, &previews); assert!(!has_trackbar(&text, 60)); // When the marker names the previous message, the rule leads the message. info.set_receipt(ReceiptThread::Main, user_id.clone(), MSG1_EVID.clone()); let text = msg.show(Some(&prev), false, width, &info, &settings, &previews); assert!(has_trackbar(&text, 60)); assert_eq!(text.lines[0].spans[0].content.as_ref(), HORIZONTAL.repeat(60)); // Use a fresh room because receipt updates are monotonic: this case tests a marker // already positioned on the rendered message, not moving an existing marker backwards. let mut info = mock_room(); info.set_receipt(ReceiptThread::Main, user_id.clone(), MSG2_EVID.clone()); let text = msg.show(Some(&prev), false, width, &info, &settings, &previews); assert!(!has_trackbar(&text, 60)); let text = prev.show(Some(&msg), false, width, &info, &settings, &previews); assert!(has_trackbar(&text, 60)); } #[test] fn test_show_trackbar_thread() { let settings = mock_settings(); let mut info = mock_room(); let user_id = settings.user_id.clone(); let prev = mock_message1(); let msg = mock_message2(); let root = MSG5_EVID.clone(); info.keys.insert( MSG2_EVID.clone(), EventLocation::Message(Some(root.clone()), MSG2_KEY.clone()), ); // A marker for the thread that this message belongs to is shown. info.set_receipt(ReceiptThread::Thread(root.clone()), user_id.clone(), MSG1_EVID.clone()); assert!(msg.show_trackbar(Some(&prev), &info, &settings)); // The main timeline's marker doesn't apply to a thread's messages. info.user_receipts_or_default(ReceiptThread::Thread(root)).clear(); info.set_receipt(ReceiptThread::Main, user_id, MSG1_EVID.clone()); assert!(!msg.show_trackbar(Some(&prev), &info, &settings)); } #[test] fn test_show_msg_html_display() { let mut settings = mock_settings(); let previews = PreviewManager::new(&settings); let info = mock_room(); let content = RoomMessageEventContent::text_html( "**hello** ", "hello <world>", ); let msg = mock_room1_message(content, TEST_USER1.clone(), MSG1_KEY.clone()); let render = |settings: &ApplicationSettings| -> String { let (text, _) = msg.show_msg(60, Style::default(), settings, &previews, &info); let s: String = text .lines .iter() .flat_map(|line| line.spans.iter()) .map(|span| span.content.as_ref()) .collect(); // The HTML renderer pads lines out to the full width. s.trim_end().to_string() }; // By default, the formatted HTML body is rendered. assert!(settings.tunables.message_formatted_display); assert_eq!(render(&settings), "hello "); // When disabled, the plain text body is shown exactly as it was sent. settings.tunables.message_formatted_display = false; assert_eq!(render(&settings), "**hello** "); } /// `MessageTimeStamp::as_datetime` converts to the local timezone, so /// expectations are computed with the same conversion rather than a /// hard-coded wall clock. fn sample_stamp() -> (MessageTimeStamp, DateTime) { let millis = MilliSecondsSinceUnixEpoch(UInt::try_from(1_705_325_130_000u64).unwrap()); let ts = MessageTimeStamp::from(millis); (ts, ts.as_datetime()) } #[test] fn test_show_time_and_date_defaults() { let (ts, dt) = sample_stamp(); let settings = mock_settings(); let date = ts.show_date(&settings); assert_eq!(date.content.as_ref(), dt.format("%A, %B %d %Y").to_string()); let time = ts.show_time(&settings); assert_eq!(time.content.as_ref(), format!(" [{}]", dt.format("%T"))); assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 12); assert_eq!(settings.tunables.time_gutter_width, 12); } #[test] fn test_time_gutter_width_follows_format() { let (ts, dt) = sample_stamp(); let mut settings = mock_settings(); let view = ViewportContext { dimensions: (120, 10), ..Default::default() }; let default_cols = Message::message_column_width(&view, &settings); // "%H:%M" is five columns and is not padded out to the old gutter. settings.tunables.time_format = "%H:%M".to_string(); settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format); let time = ts.show_time(&settings); let rendered = dt.format("%H:%M").to_string(); assert_eq!(time.content.as_ref(), rendered); assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 5); assert_eq!(settings.tunables.time_gutter_width, 5); assert_eq!(Message::message_column_width(&view, &settings), default_cols + 7); // An empty format hides the time and reserves no column. settings.tunables.time_format = String::new(); settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format); let time = ts.show_time(&settings); assert_eq!(time.content.as_ref(), ""); assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 0); assert_eq!(settings.tunables.time_gutter_width, 0); assert_eq!(Message::message_column_width(&view, &settings), default_cols + 12); // Wider than the historical 8-column cap, and a wide character counts as two. settings.tunables.time_format = "%H時%M分".to_string(); settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format); let time = ts.show_time(&settings); let rendered = dt.format("%H時%M分").to_string(); assert_eq!(time.content.as_ref(), rendered); assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 8); assert_eq!(settings.tunables.time_gutter_width, 8); assert_eq!(Message::message_column_width(&view, &settings), default_cols + 4); } #[test] fn test_show_custom_date_format() { let (ts, dt) = sample_stamp(); let mut settings = mock_settings(); settings.tunables.date_format = "%Y-%m-%d".to_string(); let date = ts.show_date(&settings); assert_eq!(date.content.as_ref(), dt.format("%Y-%m-%d").to_string()); } }