src/message.rs
639 lines · 20313 bytes
1use std::borrow::Cow;
2use std::cmp::{Ord, Ordering, PartialOrd};
3use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeMap;
5use std::convert::TryFrom;
6use std::hash::{Hash, Hasher};
7use std::str::Lines;
8
9use chrono::{DateTime, NaiveDateTime, Utc};
10use unicode_segmentation::UnicodeSegmentation;
11use unicode_width::UnicodeWidthStr;
12
13use matrix_sdk::ruma::{
14 events::{
15 room::message::{MessageType, RoomMessageEventContent},
16 MessageLikeEvent,
17 },
18 MilliSecondsSinceUnixEpoch,
19 OwnedEventId,
20 OwnedUserId,
21 UInt,
22};
23
24use modalkit::tui::{
25 style::{Modifier as StyleModifier, Style},
26 text::{Span, Spans, Text},
27};
28
29use modalkit::editing::{base::ViewportContext, cursor::Cursor};
30
31use crate::{
32 base::{IambResult, RoomInfo},
33 config::ApplicationSettings,
34};
35
36pub type MessageEvent = MessageLikeEvent<RoomMessageEventContent>;
37pub type MessageFetchResult = IambResult<(Option<String>, Vec<MessageEvent>)>;
38pub type MessageKey = (MessageTimeStamp, OwnedEventId);
39pub type Messages = BTreeMap<MessageKey, Message>;
40
41const USER_GUTTER: usize = 30;
42const TIME_GUTTER: usize = 12;
43const MIN_MSG_LEN: usize = 30;
44
45const USER_GUTTER_EMPTY: &str = " ";
46const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span {
47 content: Cow::Borrowed(USER_GUTTER_EMPTY),
48 style: Style {
49 fg: None,
50 bg: None,
51 add_modifier: StyleModifier::empty(),
52 sub_modifier: StyleModifier::empty(),
53 },
54};
55
56struct WrappedLinesIterator<'a> {
57 iter: Lines<'a>,
58 curr: Option<&'a str>,
59 width: usize,
60}
61
62impl<'a> WrappedLinesIterator<'a> {
63 fn new(input: &'a str, width: usize) -> Self {
64 WrappedLinesIterator { iter: input.lines(), curr: None, width }
65 }
66}
67
68impl<'a> Iterator for WrappedLinesIterator<'a> {
69 type Item = (&'a str, usize);
70
71 fn next(&mut self) -> Option<Self::Item> {
72 if self.curr.is_none() {
73 self.curr = self.iter.next();
74 }
75
76 if let Some(s) = self.curr.take() {
77 let width = UnicodeWidthStr::width(s);
78
79 if width <= self.width {
80 return Some((s, width));
81 } else {
82 // Find where to split the line.
83 let mut width = 0;
84 let mut idx = 0;
85
86 for (i, g) in UnicodeSegmentation::grapheme_indices(s, true) {
87 let gw = UnicodeWidthStr::width(g);
88 idx = i;
89
90 if width + gw > self.width {
91 break;
92 }
93
94 width += gw;
95 }
96
97 self.curr = Some(&s[idx..]);
98
99 return Some((&s[..idx], width));
100 }
101 } else {
102 return None;
103 }
104 }
105}
106
107fn wrap(input: &str, width: usize) -> WrappedLinesIterator<'_> {
108 WrappedLinesIterator::new(input, width)
109}
110
111fn space(width: usize) -> String {
112 " ".repeat(width)
113}
114
115#[derive(thiserror::Error, Debug)]
116pub enum TimeStampIntError {
117 #[error("Integer conversion error: {0}")]
118 IntError(#[from] std::num::TryFromIntError),
119
120 #[error("UInt conversion error: {0}")]
121 UIntError(<UInt as TryFrom<u64>>::Error),
122}
123
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum MessageTimeStamp {
126 OriginServer(UInt),
127 LocalEcho,
128}
129
130impl MessageTimeStamp {
131 fn show(&self) -> Option<Span> {
132 match self {
133 MessageTimeStamp::OriginServer(ts) => {
134 let time = i64::from(*ts) / 1000;
135 let time = NaiveDateTime::from_timestamp_opt(time, 0)?;
136 let time = DateTime::<Utc>::from_utc(time, Utc);
137 let time = time.format("%T");
138 let time = format!(" [{}]", time);
139
140 Span::raw(time).into()
141 },
142 MessageTimeStamp::LocalEcho => None,
143 }
144 }
145
146 fn is_local_echo(&self) -> bool {
147 matches!(self, MessageTimeStamp::LocalEcho)
148 }
149}
150
151impl Ord for MessageTimeStamp {
152 fn cmp(&self, other: &Self) -> Ordering {
153 match (self, other) {
154 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
155 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
156 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
157 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
158 }
159 }
160}
161
162impl PartialOrd for MessageTimeStamp {
163 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
164 self.cmp(other).into()
165 }
166}
167
168impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
169 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
170 MessageTimeStamp::OriginServer(millis.0)
171 }
172}
173
174impl TryFrom<&MessageTimeStamp> for usize {
175 type Error = TimeStampIntError;
176
177 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
178 let n = match ts {
179 MessageTimeStamp::LocalEcho => 0,
180 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
181 };
182
183 Ok(n)
184 }
185}
186
187impl TryFrom<usize> for MessageTimeStamp {
188 type Error = TimeStampIntError;
189
190 fn try_from(u: usize) -> Result<Self, Self::Error> {
191 if u == 0 {
192 Ok(MessageTimeStamp::LocalEcho)
193 } else {
194 let n = u64::try_from(u)?;
195 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
196
197 Ok(MessageTimeStamp::OriginServer(n))
198 }
199 }
200}
201
202#[derive(Clone, Debug, Default, Eq, PartialEq)]
203pub struct MessageCursor {
204 /// When timestamp is None, the corner is determined by moving backwards from
205 /// the most recently received message.
206 pub timestamp: Option<MessageKey>,
207
208 /// A row within the [Text] representation of a [Message].
209 pub text_row: usize,
210}
211
212impl MessageCursor {
213 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
214 MessageCursor { timestamp: Some(timestamp), text_row }
215 }
216
217 /// Get a cursor that refers to the most recent message.
218 pub fn latest() -> Self {
219 MessageCursor::default()
220 }
221
222 pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
223 if let Some(ref key) = self.timestamp {
224 Some(key)
225 } else {
226 Some(info.messages.last_key_value()?.0)
227 }
228 }
229
230 pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
231 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
232 let ev_term = OwnedEventId::try_from("$").ok()?;
233
234 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
235 let start = (ts_start, ev_term);
236 let mut mc = None;
237
238 for ((ts, event_id), _) in info.messages.range(start..) {
239 let mut hasher = DefaultHasher::new();
240 event_id.hash(&mut hasher);
241
242 if hasher.finish() == ev_hash {
243 mc = Self::from((*ts, event_id.clone())).into();
244 break;
245 }
246
247 if mc.is_none() {
248 mc = Self::from((*ts, event_id.clone())).into();
249 }
250
251 if ts > &ts_start {
252 break;
253 }
254 }
255
256 return mc;
257 }
258
259 pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
260 let (ts, event_id) = self.to_key(info)?;
261
262 let y: usize = usize::try_from(ts).ok()?;
263
264 let mut hasher = DefaultHasher::new();
265 event_id.hash(&mut hasher);
266 let x = usize::try_from(hasher.finish()).ok()?;
267
268 Cursor::new(y, x).into()
269 }
270}
271
272impl From<Option<MessageKey>> for MessageCursor {
273 fn from(key: Option<MessageKey>) -> Self {
274 MessageCursor { timestamp: key, text_row: 0 }
275 }
276}
277
278impl From<MessageKey> for MessageCursor {
279 fn from(key: MessageKey) -> Self {
280 MessageCursor { timestamp: Some(key), text_row: 0 }
281 }
282}
283
284impl Ord for MessageCursor {
285 fn cmp(&self, other: &Self) -> Ordering {
286 match (&self.timestamp, &other.timestamp) {
287 (None, None) => self.text_row.cmp(&other.text_row),
288 (None, Some(_)) => Ordering::Greater,
289 (Some(_), None) => Ordering::Less,
290 (Some(st), Some(ot)) => {
291 let pcmp = st.cmp(ot);
292 let tcmp = self.text_row.cmp(&other.text_row);
293
294 pcmp.then(tcmp)
295 },
296 }
297 }
298}
299
300impl PartialOrd for MessageCursor {
301 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
302 self.cmp(other).into()
303 }
304}
305
306#[derive(Clone)]
307pub enum MessageContent {
308 Original(Box<RoomMessageEventContent>),
309 Redacted,
310}
311
312impl MessageContent {
313 pub fn show(&self) -> Cow<'_, str> {
314 match self {
315 MessageContent::Original(ev) => {
316 let s = match &ev.msgtype {
317 MessageType::Text(content) => content.body.as_ref(),
318 MessageType::Emote(content) => content.body.as_ref(),
319 MessageType::Notice(content) => content.body.as_str(),
320 MessageType::ServerNotice(content) => content.body.as_str(),
321
322 MessageType::VerificationRequest(_) => {
323 // XXX: implement
324
325 return Cow::Owned("[verification request]".into());
326 },
327 MessageType::Audio(content) => {
328 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
329 },
330 MessageType::File(content) => {
331 return Cow::Owned(format!("[Attached File: {}]", content.body));
332 },
333 MessageType::Image(content) => {
334 return Cow::Owned(format!("[Attached Image: {}]", content.body));
335 },
336 MessageType::Video(content) => {
337 return Cow::Owned(format!("[Attached Video: {}]", content.body));
338 },
339 _ => {
340 return Cow::Owned(format!("[Unknown message type: {:?}]", ev.msgtype()));
341 },
342 };
343
344 Cow::Borrowed(s)
345 },
346 MessageContent::Redacted => Cow::Borrowed("[redacted]"),
347 }
348 }
349}
350
351#[derive(Clone)]
352pub struct Message {
353 pub content: MessageContent,
354 pub sender: OwnedUserId,
355 pub timestamp: MessageTimeStamp,
356 pub downloaded: bool,
357}
358
359impl Message {
360 pub fn new(content: MessageContent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
361 Message { content, sender, timestamp, downloaded: false }
362 }
363
364 pub fn show(
365 &self,
366 prev: Option<&Message>,
367 selected: bool,
368 vwctx: &ViewportContext<MessageCursor>,
369 settings: &ApplicationSettings,
370 ) -> Text {
371 let width = vwctx.get_width();
372 let mut msg = self.content.show();
373
374 if self.downloaded {
375 msg.to_mut().push_str(" \u{2705}");
376 }
377
378 let msg = msg.as_ref();
379
380 let mut lines = vec![];
381
382 let mut style = Style::default();
383
384 if selected {
385 style = style.add_modifier(StyleModifier::REVERSED)
386 }
387
388 if self.timestamp.is_local_echo() {
389 style = style.add_modifier(StyleModifier::ITALIC);
390 }
391
392 if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
393 let lw = width - USER_GUTTER - TIME_GUTTER;
394
395 for (i, (line, w)) in wrap(msg, lw).enumerate() {
396 let line = Span::styled(line.to_string(), style);
397 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
398
399 if i == 0 {
400 let user = self.show_sender(prev, true, settings);
401
402 if let Some(time) = self.timestamp.show() {
403 lines.push(Spans(vec![user, line, trailing, time]))
404 } else {
405 lines.push(Spans(vec![user, line, trailing]))
406 }
407 } else {
408 let space = USER_GUTTER_EMPTY_SPAN;
409
410 lines.push(Spans(vec![space, line, trailing]))
411 }
412 }
413 } else if USER_GUTTER + MIN_MSG_LEN <= width {
414 let lw = width - USER_GUTTER;
415
416 for (i, (line, w)) in wrap(msg, lw).enumerate() {
417 let line = Span::styled(line.to_string(), style);
418 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
419
420 let prefix = if i == 0 {
421 self.show_sender(prev, true, settings)
422 } else {
423 USER_GUTTER_EMPTY_SPAN
424 };
425
426 lines.push(Spans(vec![prefix, line, trailing]))
427 }
428 } else {
429 lines.push(Spans::from(self.show_sender(prev, false, settings)));
430
431 for (line, _) in wrap(msg, width.saturating_sub(2)) {
432 let line = format!(" {}", line);
433 let line = Span::styled(line, style);
434
435 lines.push(Spans(vec![line]))
436 }
437 }
438
439 return Text { lines };
440 }
441
442 fn show_sender(
443 &self,
444 prev: Option<&Message>,
445 align_right: bool,
446 settings: &ApplicationSettings,
447 ) -> Span {
448 let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
449 USER_GUTTER_EMPTY_SPAN
450 } else {
451 settings.get_user_span(self.sender.as_ref())
452 };
453
454 let Span { content, style } = user;
455 let stop = content.len().min(28);
456 let s = &content[..stop];
457
458 let sender = if align_right {
459 format!("{: >width$} ", s, width = 28)
460 } else {
461 format!("{: <width$} ", s, width = 28)
462 };
463
464 Span::styled(sender, style)
465 }
466}
467
468impl From<MessageEvent> for Message {
469 fn from(event: MessageEvent) -> Self {
470 match event {
471 MessageLikeEvent::Original(ev) => {
472 let content = MessageContent::Original(ev.content.into());
473
474 Message::new(content, ev.sender, ev.origin_server_ts.into())
475 },
476 MessageLikeEvent::Redacted(ev) => {
477 Message::new(MessageContent::Redacted, ev.sender, ev.origin_server_ts.into())
478 },
479 }
480 }
481}
482
483impl ToString for Message {
484 fn to_string(&self) -> String {
485 self.content.show().into_owned()
486 }
487}
488
489#[cfg(test)]
490pub mod tests {
491 use super::*;
492 use crate::tests::*;
493
494 #[test]
495 fn test_wrapped_lines_ascii() {
496 let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
497
498 let mut iter = wrap(s, 100);
499 assert_eq!(iter.next(), Some(("hello world!", 12)));
500 assert_eq!(iter.next(), Some(("abcdefghijklmnopqrstuvwxyz", 26)));
501 assert_eq!(iter.next(), Some(("goodbye", 7)));
502 assert_eq!(iter.next(), None);
503
504 let mut iter = wrap(s, 5);
505 assert_eq!(iter.next(), Some(("hello", 5)));
506 assert_eq!(iter.next(), Some((" worl", 5)));
507 assert_eq!(iter.next(), Some(("d!", 2)));
508 assert_eq!(iter.next(), Some(("abcde", 5)));
509 assert_eq!(iter.next(), Some(("fghij", 5)));
510 assert_eq!(iter.next(), Some(("klmno", 5)));
511 assert_eq!(iter.next(), Some(("pqrst", 5)));
512 assert_eq!(iter.next(), Some(("uvwxy", 5)));
513 assert_eq!(iter.next(), Some(("z", 1)));
514 assert_eq!(iter.next(), Some(("goodb", 5)));
515 assert_eq!(iter.next(), Some(("ye", 2)));
516 assert_eq!(iter.next(), None);
517 }
518
519 #[test]
520 fn test_wrapped_lines_unicode() {
521 let s = "CHICKEN";
522
523 let mut iter = wrap(s, 14);
524 assert_eq!(iter.next(), Some((s, 14)));
525 assert_eq!(iter.next(), None);
526
527 let mut iter = wrap(s, 5);
528 assert_eq!(iter.next(), Some(("CH", 4)));
529 assert_eq!(iter.next(), Some(("IC", 4)));
530 assert_eq!(iter.next(), Some(("KE", 4)));
531 assert_eq!(iter.next(), Some(("N", 2)));
532 assert_eq!(iter.next(), None);
533 }
534
535 #[test]
536 fn test_mc_cmp() {
537 let mc1 = MessageCursor::from(MSG1_KEY.clone());
538 let mc2 = MessageCursor::from(MSG2_KEY.clone());
539 let mc3 = MessageCursor::from(MSG3_KEY.clone());
540 let mc4 = MessageCursor::from(MSG4_KEY.clone());
541 let mc5 = MessageCursor::from(MSG5_KEY.clone());
542
543 // Everything is equal to itself.
544 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
545 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
546 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
547 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
548 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
549
550 // Local echo is always greater than an origin server timestamp.
551 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
552 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
553 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
554 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
555
556 // mc2 is the smallest timestamp.
557 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
558 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
559 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
560 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
561
562 // mc3 should be less than mc4 because of its event ID.
563 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
564 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
565 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
566 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
567
568 // mc4 should be greater than mc3 because of its event ID.
569 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
570 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
571 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
572 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
573
574 // mc5 is the greatest OriginServer timestamp.
575 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
576 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
577 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
578 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
579 }
580
581 #[test]
582 fn test_mc_to_key() {
583 let info = mock_room();
584 let mc1 = MessageCursor::from(MSG1_KEY.clone());
585 let mc2 = MessageCursor::from(MSG2_KEY.clone());
586 let mc3 = MessageCursor::from(MSG3_KEY.clone());
587 let mc4 = MessageCursor::from(MSG4_KEY.clone());
588 let mc5 = MessageCursor::from(MSG5_KEY.clone());
589 let mc6 = MessageCursor::latest();
590
591 let k1 = mc1.to_key(&info).unwrap();
592 let k2 = mc2.to_key(&info).unwrap();
593 let k3 = mc3.to_key(&info).unwrap();
594 let k4 = mc4.to_key(&info).unwrap();
595 let k5 = mc5.to_key(&info).unwrap();
596 let k6 = mc6.to_key(&info).unwrap();
597
598 // These should all be equal to their MSGN_KEYs.
599 assert_eq!(k1, &MSG1_KEY.clone());
600 assert_eq!(k2, &MSG2_KEY.clone());
601 assert_eq!(k3, &MSG3_KEY.clone());
602 assert_eq!(k4, &MSG4_KEY.clone());
603 assert_eq!(k5, &MSG5_KEY.clone());
604
605 // MessageCursor::latest() turns into the largest key (our local echo message).
606 assert_eq!(k6, &MSG1_KEY.clone());
607
608 // MessageCursor::latest() fails to convert for a room w/o messages.
609 let info_empty = RoomInfo::default();
610 assert_eq!(mc6.to_key(&info_empty), None);
611 }
612
613 #[test]
614 fn test_mc_to_from_cursor() {
615 let info = mock_room();
616 let mc1 = MessageCursor::from(MSG1_KEY.clone());
617 let mc2 = MessageCursor::from(MSG2_KEY.clone());
618 let mc3 = MessageCursor::from(MSG3_KEY.clone());
619 let mc4 = MessageCursor::from(MSG4_KEY.clone());
620 let mc5 = MessageCursor::from(MSG5_KEY.clone());
621 let mc6 = MessageCursor::latest();
622
623 let identity = |mc: &MessageCursor| {
624 let c = mc.to_cursor(&info).unwrap();
625
626 MessageCursor::from_cursor(&c, &info).unwrap()
627 };
628
629 // These should all convert to a Cursor and back to the original value.
630 assert_eq!(identity(&mc1), mc1);
631 assert_eq!(identity(&mc2), mc2);
632 assert_eq!(identity(&mc3), mc3);
633 assert_eq!(identity(&mc4), mc4);
634 assert_eq!(identity(&mc5), mc5);
635
636 // MessageCursor::latest() should point at the most recent message after conversion.
637 assert_eq!(identity(&mc6), mc1);
638 }
639}