Commit afe892c7fe

afe892c7feb34566d56437e0778b8964c21867c8

parent: d8713141f2

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-26 23:40 UTC

Support sending and displaying read markers (#11)

Layout: unified · split

src/base.rs +28 −3
@@ -214,6 +214,8 @@ pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
214 214
215pub type IambResult<T> = UIResult<T, IambInfo>; 215pub type IambResult<T> = UIResult<T, IambInfo>;
216 216
217pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
218
217#[derive(thiserror::Error, Debug)] 219#[derive(thiserror::Error, Debug)]
218pub enum IambError { 220pub enum IambError {
219 #[error("Invalid user identifier: {0}")] 221 #[error("Invalid user identifier: {0}")]
@@ -286,6 +288,9 @@ pub struct RoomInfo {
286 pub keys: HashMap<OwnedEventId, MessageKey>, 288 pub keys: HashMap<OwnedEventId, MessageKey>,
287 pub messages: Messages, 289 pub messages: Messages,
288 290
291 pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
292 pub read_till: Option<OwnedEventId>,
293
289 pub fetch_id: RoomFetchStatus, 294 pub fetch_id: RoomFetchStatus,
290 pub fetch_last: Option<Instant>, 295 pub fetch_last: Option<Instant>,
291 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>, 296 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
@@ -316,7 +321,7 @@ impl RoomInfo {
316 MessageEvent::Original(orig) => { 321 MessageEvent::Original(orig) => {
317 orig.content = *new_content; 322 orig.content = *new_content;
318 }, 323 },
319 MessageEvent::Local(content) => { 324 MessageEvent::Local(_, content) => {
320 *content = new_content; 325 *content = new_content;
321 }, 326 },
322 MessageEvent::Redacted(_) => { 327 MessageEvent::Redacted(_) => {
@@ -364,7 +369,7 @@ impl RoomInfo {
364 } 369 }
365 } 370 }
366 371
367 fn get_typing_spans(&self, settings: &ApplicationSettings) -> Spans { 372 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
368 let typers = self.get_typers(); 373 let typers = self.get_typers();
369 let n = typers.len(); 374 let n = typers.len();
370 375
@@ -454,6 +459,26 @@ impl ChatStore {
454 .unwrap_or_else(|| "Untitled Matrix Room".to_string()) 459 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
455 } 460 }
456 461
462 pub async fn set_receipts(&mut self, receipts: Vec<(OwnedRoomId, Receipts)>) {
463 let mut updates = vec![];
464
465 for (room_id, receipts) in receipts.into_iter() {
466 if let Some(info) = self.rooms.get_mut(&room_id) {
467 info.receipts = receipts;
468
469 if let Some(read_till) = info.read_till.take() {
470 updates.push((room_id, read_till));
471 }
472 }
473 }
474
475 for (room_id, read_till) in updates.into_iter() {
476 if let Some(room) = self.worker.client.get_joined_room(&room_id) {
477 let _ = room.read_receipt(read_till.as_ref()).await;
478 }
479 }
480 }
481
457 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) { 482 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
458 self.need_load.insert(room_id); 483 self.need_load.insert(room_id);
459 } 484 }
@@ -588,7 +613,7 @@ impl ApplicationInfo for IambInfo {
588#[cfg(test)] 613#[cfg(test)]
589pub mod tests { 614pub mod tests {
590 use super::*; 615 use super::*;
591 use crate::config::{user_style, user_style_from_color}; 616 use crate::config::user_style_from_color;
592 use crate::tests::*; 617 use crate::tests::*;
593 use modalkit::tui::style::Color; 618 use modalkit::tui::style::Color;
594 619
src/config.rs +55 −33
@@ -1,3 +1,4 @@
1use std::borrow::Cow;
1use std::collections::hash_map::DefaultHasher; 2use std::collections::hash_map::DefaultHasher;
2use std::collections::HashMap; 3use std::collections::HashMap;
3use std::fmt; 4use std::fmt;
@@ -52,10 +53,6 @@ pub fn user_style_from_color(color: Color) -> Style {
52 Style::default().fg(color).add_modifier(StyleModifier::BOLD) 53 Style::default().fg(color).add_modifier(StyleModifier::BOLD)
53} 54}
54 55
55pub fn user_style(user: &str) -> Style {
56 user_style_from_color(user_color(user))
57}
58
59fn is_profile_char(c: char) -> bool { 56fn is_profile_char(c: char) -> bool {
60 c.is_ascii_alphanumeric() || c == '.' || c == '-' 57 c.is_ascii_alphanumeric() || c == '.' || c == '-'
61} 58}
@@ -181,14 +178,18 @@ fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<Use
181 178
182#[derive(Clone)] 179#[derive(Clone)]
183pub struct TunableValues { 180pub struct TunableValues {
184 pub typing_notice: bool, 181 pub read_receipt_send: bool,
182 pub read_receipt_display: bool,
183 pub typing_notice_send: bool,
185 pub typing_notice_display: bool, 184 pub typing_notice_display: bool,
186 pub users: UserOverrides, 185 pub users: UserOverrides,
187} 186}
188 187
189#[derive(Clone, Default, Deserialize)] 188#[derive(Clone, Default, Deserialize)]
190pub struct Tunables { 189pub struct Tunables {
191 pub typing_notice: Option<bool>, 190 pub read_receipt_send: Option<bool>,
191 pub read_receipt_display: Option<bool>,
192 pub typing_notice_send: Option<bool>,
192 pub typing_notice_display: Option<bool>, 193 pub typing_notice_display: Option<bool>,
193 pub users: Option<UserOverrides>, 194 pub users: Option<UserOverrides>,
194} 195}
@@ -196,7 +197,9 @@ pub struct Tunables {
196impl Tunables { 197impl Tunables {
197 fn merge(self, other: Self) -> Self { 198 fn merge(self, other: Self) -> Self {
198 Tunables { 199 Tunables {
199 typing_notice: self.typing_notice.or(other.typing_notice), 200 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
201 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
202 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
200 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display), 203 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
201 users: merge_users(self.users, other.users), 204 users: merge_users(self.users, other.users),
202 } 205 }
@@ -204,8 +207,10 @@ impl Tunables {
204 207
205 fn values(self) -> TunableValues { 208 fn values(self) -> TunableValues {
206 TunableValues { 209 TunableValues {
207 typing_notice: self.typing_notice.unwrap_or(true), 210 read_receipt_send: self.read_receipt_send.unwrap_or(true),
208 typing_notice_display: self.typing_notice.unwrap_or(true), 211 read_receipt_display: self.read_receipt_display.unwrap_or(true),
212 typing_notice_send: self.typing_notice_send.unwrap_or(true),
213 typing_notice_display: self.typing_notice_display.unwrap_or(true),
209 users: self.users.unwrap_or_default(), 214 users: self.users.unwrap_or_default(),
210 } 215 }
211 } 216 }
@@ -374,24 +379,41 @@ impl ApplicationSettings {
374 Ok(settings) 379 Ok(settings)
375 } 380 }
376 381
382 pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
383 let (color, c) = self
384 .tunables
385 .users
386 .get(user_id)
387 .map(|user| {
388 (
389 user.color.as_ref().map(|c| c.0),
390 user.name.as_ref().and_then(|s| s.chars().next()),
391 )
392 })
393 .unwrap_or_default();
394
395 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
396 let style = user_style_from_color(color);
397
398 let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
399
400 Span::styled(String::from(c), style)
401 }
402
377 pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> { 403 pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
378 if let Some(user) = self.tunables.users.get(user_id) { 404 let (color, name) = self
379 let color = if let Some(UserColor(c)) = user.color { 405 .tunables
380 c 406 .users
381 } else { 407 .get(user_id)
382 user_color(user_id.as_str()) 408 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
383 }; 409 .unwrap_or_default();
384 410
385 let style = user_style_from_color(color); 411 let user_id = user_id.as_str();
386 412 let color = color.unwrap_or_else(|| user_color(user_id));
387 if let Some(name) = &user.name { 413 let style = user_style_from_color(color);
388 Span::styled(name.clone(), style) 414 let name = name.unwrap_or(Cow::Borrowed(user_id));
389 } else { 415
390 Span::styled(user_id.as_str(), style) 416 Span::styled(name, style)
391 }
392 } else {
393 Span::styled(user_id.as_str(), user_style(user_id.as_str()))
394 }
395 } 417 }
396} 418}
397 419
@@ -461,22 +483,22 @@ mod tests {
461 #[test] 483 #[test]
462 fn test_parse_tunables() { 484 fn test_parse_tunables() {
463 let res: Tunables = serde_json::from_str("{}").unwrap(); 485 let res: Tunables = serde_json::from_str("{}").unwrap();
464 assert_eq!(res.typing_notice, None); 486 assert_eq!(res.typing_notice_send, None);
465 assert_eq!(res.typing_notice_display, None); 487 assert_eq!(res.typing_notice_display, None);
466 assert_eq!(res.users, None); 488 assert_eq!(res.users, None);
467 489
468 let res: Tunables = serde_json::from_str("{\"typing_notice\": true}").unwrap(); 490 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
469 assert_eq!(res.typing_notice, Some(true)); 491 assert_eq!(res.typing_notice_send, Some(true));
470 assert_eq!(res.typing_notice_display, None); 492 assert_eq!(res.typing_notice_display, None);
471 assert_eq!(res.users, None); 493 assert_eq!(res.users, None);
472 494
473 let res: Tunables = serde_json::from_str("{\"typing_notice\": false}").unwrap(); 495 let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
474 assert_eq!(res.typing_notice, Some(false)); 496 assert_eq!(res.typing_notice_send, Some(false));
475 assert_eq!(res.typing_notice_display, None); 497 assert_eq!(res.typing_notice_display, None);
476 assert_eq!(res.users, None); 498 assert_eq!(res.users, None);
477 499
478 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap(); 500 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
479 assert_eq!(res.typing_notice, None); 501 assert_eq!(res.typing_notice_send, None);
480 assert_eq!(res.typing_notice_display, None); 502 assert_eq!(res.typing_notice_display, None);
481 assert_eq!(res.users, Some(HashMap::new())); 503 assert_eq!(res.users, Some(HashMap::new()));
482 504
@@ -484,7 +506,7 @@ mod tests {
484 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}", 506 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
485 ) 507 )
486 .unwrap(); 508 .unwrap();
487 assert_eq!(res.typing_notice, None); 509 assert_eq!(res.typing_notice_send, None);
488 assert_eq!(res.typing_notice_display, None); 510 assert_eq!(res.typing_notice_display, None);
489 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables { 511 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
490 color: Some(UserColor(Color::Black)), 512 color: Some(UserColor(Color::Black)),
src/message/mod.rs +123 −45
@@ -4,6 +4,7 @@ use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeMap; 4use std::collections::BTreeMap;
5use std::convert::TryFrom; 5use std::convert::TryFrom;
6use std::hash::{Hash, Hasher}; 6use std::hash::{Hash, Hasher};
7use std::slice::Iter;
7 8
8use chrono::{DateTime, NaiveDateTime, Utc}; 9use chrono::{DateTime, NaiveDateTime, Utc};
9use unicode_width::UnicodeWidthStr; 10use unicode_width::UnicodeWidthStr;
@@ -25,6 +26,7 @@ use matrix_sdk::ruma::{
25 }, 26 },
26 Redact, 27 Redact,
27 }, 28 },
29 EventId,
28 MilliSecondsSinceUnixEpoch, 30 MilliSecondsSinceUnixEpoch,
29 OwnedEventId, 31 OwnedEventId,
30 OwnedUserId, 32 OwnedUserId,
@@ -54,20 +56,28 @@ pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)
54pub type MessageKey = (MessageTimeStamp, OwnedEventId); 56pub type MessageKey = (MessageTimeStamp, OwnedEventId);
55pub type Messages = BTreeMap<MessageKey, Message>; 57pub type Messages = BTreeMap<MessageKey, Message>;
56 58
59const fn span_static(s: &'static str) -> Span<'static> {
60 Span {
61 content: Cow::Borrowed(s),
62 style: Style {
63 fg: None,
64 bg: None,
65 add_modifier: StyleModifier::empty(),
66 sub_modifier: StyleModifier::empty(),
67 },
68 }
69}
70
57const USER_GUTTER: usize = 30; 71const USER_GUTTER: usize = 30;
58const TIME_GUTTER: usize = 12; 72const TIME_GUTTER: usize = 12;
73const READ_GUTTER: usize = 5;
59const MIN_MSG_LEN: usize = 30; 74const MIN_MSG_LEN: usize = 30;
60 75
61const USER_GUTTER_EMPTY: &str = " "; 76const USER_GUTTER_EMPTY: &str = " ";
62const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span { 77const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
63 content: Cow::Borrowed(USER_GUTTER_EMPTY), 78
64 style: Style { 79const TIME_GUTTER_EMPTY: &str = " ";
65 fg: None, 80const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
66 bg: None,
67 add_modifier: StyleModifier::empty(),
68 sub_modifier: StyleModifier::empty(),
69 },
70};
71 81
72#[derive(thiserror::Error, Debug)] 82#[derive(thiserror::Error, Debug)]
73pub enum TimeStampIntError { 83pub enum TimeStampIntError {
@@ -271,10 +281,18 @@ impl PartialOrd for MessageCursor {
271pub enum MessageEvent { 281pub enum MessageEvent {
272 Original(Box<OriginalRoomMessageEvent>), 282 Original(Box<OriginalRoomMessageEvent>),
273 Redacted(Box<RedactedRoomMessageEvent>), 283 Redacted(Box<RedactedRoomMessageEvent>),
274 Local(Box<RoomMessageEventContent>), 284 Local(OwnedEventId, Box<RoomMessageEventContent>),
275} 285}
276 286
277impl MessageEvent { 287impl MessageEvent {
288 pub fn event_id(&self) -> &EventId {
289 match self {
290 MessageEvent::Original(ev) => ev.event_id.as_ref(),
291 MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
292 MessageEvent::Local(event_id, _) => event_id.as_ref(),
293 }
294 }
295
278 pub fn body(&self) -> Cow<'_, str> { 296 pub fn body(&self) -> Cow<'_, str> {
279 match self { 297 match self {
280 MessageEvent::Original(ev) => body_cow_content(&ev.content), 298 MessageEvent::Original(ev) => body_cow_content(&ev.content),
@@ -292,7 +310,7 @@ impl MessageEvent {
292 Cow::Borrowed("[Redacted]") 310 Cow::Borrowed("[Redacted]")
293 } 311 }
294 }, 312 },
295 MessageEvent::Local(content) => body_cow_content(content), 313 MessageEvent::Local(_, content) => body_cow_content(content),
296 } 314 }
297 } 315 }
298 316
@@ -300,7 +318,7 @@ impl MessageEvent {
300 let content = match self { 318 let content = match self {
301 MessageEvent::Original(ev) => &ev.content, 319 MessageEvent::Original(ev) => &ev.content,
302 MessageEvent::Redacted(_) => return None, 320 MessageEvent::Redacted(_) => return None,
303 MessageEvent::Local(content) => content, 321 MessageEvent::Local(_, content) => content,
304 }; 322 };
305 323
306 if let MessageType::Text(content) = &content.msgtype { 324 if let MessageType::Text(content) = &content.msgtype {
@@ -317,7 +335,7 @@ impl MessageEvent {
317 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) { 335 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
318 match self { 336 match self {
319 MessageEvent::Redacted(_) => return, 337 MessageEvent::Redacted(_) => return,
320 MessageEvent::Local(_) => return, 338 MessageEvent::Local(_, _) => return,
321 MessageEvent::Original(ev) => { 339 MessageEvent::Original(ev) => {
322 let redacted = ev.clone().redact(redaction, version); 340 let redacted = ev.clone().redact(redaction, version);
323 *self = MessageEvent::Redacted(Box::new(redacted)); 341 *self = MessageEvent::Redacted(Box::new(redacted));
@@ -354,27 +372,65 @@ fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
354 Cow::Borrowed(s) 372 Cow::Borrowed(s)
355} 373}
356 374
357enum MessageColumns<'a> { 375enum MessageColumns {
358 Three(usize, Option<Span<'a>>, Option<Span<'a>>), 376 /// Four columns: sender, message, timestamp, read receipts.
359 Two(usize, Option<Span<'a>>), 377 Four,
360 One(usize, Option<Span<'a>>), 378
379 /// Three columns: sender, message, timestamp.
380 Three,
381
382 /// Two columns: sender, message.
383 Two,
384
385 /// One column: message with sender on line before the message.
386 One,
361} 387}
362 388
363impl<'a> MessageColumns<'a> { 389struct MessageFormatter<'a> {
390 settings: &'a ApplicationSettings,
391 cols: MessageColumns,
392 fill: usize,
393 user: Option<Span<'a>>,
394 time: Option<Span<'a>>,
395 read: Iter<'a, OwnedUserId>,
396}
397
398impl<'a> MessageFormatter<'a> {
364 fn width(&self) -> usize { 399 fn width(&self) -> usize {
365 match self { 400 self.fill
366 MessageColumns::Three(fill, _, _) => *fill,
367 MessageColumns::Two(fill, _) => *fill,
368 MessageColumns::One(fill, _) => *fill,
369 }
370 } 401 }
371 402
372 #[inline] 403 #[inline]
373 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) { 404 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
374 match self { 405 match self.cols {
375 MessageColumns::Three(_, user, time) => { 406 MessageColumns::Four => {
376 let user = user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN); 407 let settings = self.settings;
377 let time = time.take().unwrap_or_else(|| Span::from("")); 408 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
409 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
410
411 let mut line = vec![user];
412 line.extend(spans.0);
413 line.push(time);
414
415 // Show read receipts.
416 let user_char =
417 |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
418
419 let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
420 let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
421 let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
422
423 line.push(Span::raw(" "));
424 line.push(c);
425 line.push(b);
426 line.push(a);
427 line.push(Span::raw(" "));
428
429 text.lines.push(Spans(line))
430 },
431 MessageColumns::Three => {
432 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
433 let time = self.time.take().unwrap_or_else(|| Span::from(""));
378 434
379 let mut line = vec![user]; 435 let mut line = vec![user];
380 line.extend(spans.0); 436 line.extend(spans.0);
@@ -382,15 +438,15 @@ impl<'a> MessageColumns<'a> {
382 438
383 text.lines.push(Spans(line)) 439 text.lines.push(Spans(line))
384 }, 440 },
385 MessageColumns::Two(_, opt) => { 441 MessageColumns::Two => {
386 let user = opt.take().unwrap_or(USER_GUTTER_EMPTY_SPAN); 442 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
387 let mut line = vec![user]; 443 let mut line = vec![user];
388 line.extend(spans.0); 444 line.extend(spans.0);
389 445
390 text.lines.push(Spans(line)); 446 text.lines.push(Spans(line));
391 }, 447 },
392 MessageColumns::One(_, opt) => { 448 MessageColumns::One => {
393 if let Some(user) = opt.take() { 449 if let Some(user) = self.user.take() {
394 text.lines.push(Spans(vec![user])); 450 text.lines.push(Spans(vec![user]));
395 } 451 }
396 452
@@ -428,7 +484,7 @@ impl Message {
428 484
429 pub fn reply_to(&self) -> Option<OwnedEventId> { 485 pub fn reply_to(&self) -> Option<OwnedEventId> {
430 let content = match &self.event { 486 let content = match &self.event {
431 MessageEvent::Local(content) => content, 487 MessageEvent::Local(_, content) => content,
432 MessageEvent::Original(ev) => &ev.content, 488 MessageEvent::Original(ev) => &ev.content,
433 MessageEvent::Redacted(_) => return None, 489 MessageEvent::Redacted(_) => return None,
434 }; 490 };
@@ -454,28 +510,50 @@ impl Message {
454 return style; 510 return style;
455 } 511 }
456 512
457 fn get_render_format( 513 fn get_render_format<'a>(
458 &self, 514 &'a self,
459 prev: Option<&Message>, 515 prev: Option<&Message>,
460 width: usize, 516 width: usize,
461 settings: &ApplicationSettings, 517 info: &'a RoomInfo,
462 ) -> MessageColumns { 518 settings: &'a ApplicationSettings,
463 if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width { 519 ) -> MessageFormatter<'a> {
464 let lw = width - USER_GUTTER - TIME_GUTTER; 520 if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
521 settings.tunables.read_receipt_display
522 {
523 let cols = MessageColumns::Four;
524 let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
525 let user = self.show_sender(prev, true, settings);
526 let time = self.timestamp.show();
527 let read = match info.receipts.get(self.event.event_id()) {
528 Some(read) => read.iter(),
529 None => [].iter(),
530 };
531
532 MessageFormatter { settings, cols, fill, user, time, read }
533 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
534 let cols = MessageColumns::Three;
535 let fill = width - USER_GUTTER - TIME_GUTTER;
465 let user = self.show_sender(prev, true, settings); 536 let user = self.show_sender(prev, true, settings);
466 let time = self.timestamp.show(); 537 let time = self.timestamp.show();
538 let read = [].iter();
467 539
468 MessageColumns::Three(lw, user, time) 540 MessageFormatter { settings, cols, fill, user, time, read }
469 } else if USER_GUTTER + MIN_MSG_LEN <= width { 541 } else if USER_GUTTER + MIN_MSG_LEN <= width {
470 let lw = width - USER_GUTTER; 542 let cols = MessageColumns::Two;
543 let fill = width - USER_GUTTER;
471 let user = self.show_sender(prev, true, settings); 544 let user = self.show_sender(prev, true, settings);
545 let time = None;
546 let read = [].iter();
472 547
473 MessageColumns::Two(lw, user) 548 MessageFormatter { settings, cols, fill, user, time, read }
474 } else { 549 } else {
475 let lw = width.saturating_sub(2); 550 let cols = MessageColumns::One;
551 let fill = width.saturating_sub(2);
476 let user = self.show_sender(prev, false, settings); 552 let user = self.show_sender(prev, false, settings);
553 let time = None;
554 let read = [].iter();
477 555
478 MessageColumns::One(lw, user) 556 MessageFormatter { settings, cols, fill, user, time, read }
479 } 557 }
480 } 558 }
481 559
@@ -485,12 +563,12 @@ impl Message {
485 selected: bool, 563 selected: bool,
486 vwctx: &ViewportContext<MessageCursor>, 564 vwctx: &ViewportContext<MessageCursor>,
487 info: &'a RoomInfo, 565 info: &'a RoomInfo,
488 settings: &ApplicationSettings, 566 settings: &'a ApplicationSettings,
489 ) -> Text<'a> { 567 ) -> Text<'a> {
490 let width = vwctx.get_width(); 568 let width = vwctx.get_width();
491 569
492 let style = self.get_render_style(selected); 570 let style = self.get_render_style(selected);
493 let mut fmt = self.get_render_format(prev, width, settings); 571 let mut fmt = self.get_render_format(prev, width, info, settings);
494 let mut text = Text { lines: vec![] }; 572 let mut text = Text { lines: vec![] };
495 let width = fmt.width(); 573 let width = fmt.width();
496 574
src/tests.rs +15 −4
@@ -15,13 +15,15 @@ use matrix_sdk::ruma::{
15}; 15};
16 16
17use lazy_static::lazy_static; 17use lazy_static::lazy_static;
18use modalkit::tui::style::Color; 18use modalkit::tui::style::{Color, Style};
19use tokio::sync::mpsc::unbounded_channel; 19use tokio::sync::mpsc::unbounded_channel;
20use url::Url; 20use url::Url;
21 21
22use crate::{ 22use crate::{
23 base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo}, 23 base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo},
24 config::{ 24 config::{
25 user_color,
26 user_style_from_color,
25 ApplicationSettings, 27 ApplicationSettings,
26 DirectoryValues, 28 DirectoryValues,
27 ProfileConfig, 29 ProfileConfig,
@@ -60,6 +62,10 @@ lazy_static! {
60 pub static ref MSG5_KEY: MessageKey = (OriginServer(UInt::new(8).unwrap()), MSG5_EVID.clone()); 62 pub static ref MSG5_KEY: MessageKey = (OriginServer(UInt::new(8).unwrap()), MSG5_EVID.clone());
61} 63}
62 64
65pub fn user_style(user: &str) -> Style {
66 user_style_from_color(user_color(user))
67}
68
63pub fn mock_room1_message( 69pub fn mock_room1_message(
64 content: RoomMessageEventContent, 70 content: RoomMessageEventContent,
65 sender: OwnedUserId, 71 sender: OwnedUserId,
@@ -82,7 +88,7 @@ pub fn mock_room1_message(
82 88
83pub fn mock_message1() -> Message { 89pub fn mock_message1() -> Message {
84 let content = RoomMessageEventContent::text_plain("writhe"); 90 let content = RoomMessageEventContent::text_plain("writhe");
85 let content = MessageEvent::Local(content.into()); 91 let content = MessageEvent::Local(MSG1_EVID.clone(), content.into());
86 92
87 Message::new(content, TEST_USER1.clone(), MSG1_KEY.0) 93 Message::new(content, TEST_USER1.clone(), MSG1_KEY.0)
88} 94}
@@ -138,10 +144,13 @@ pub fn mock_messages() -> Messages {
138pub fn mock_room() -> RoomInfo { 144pub fn mock_room() -> RoomInfo {
139 RoomInfo { 145 RoomInfo {
140 name: Some("Watercooler Discussion".into()), 146 name: Some("Watercooler Discussion".into()),
147 tags: None,
141 148
142 keys: mock_keys(), 149 keys: mock_keys(),
143 messages: mock_messages(), 150 messages: mock_messages(),
144 tags: None, 151
152 receipts: HashMap::new(),
153 read_till: None,
145 154
146 fetch_id: RoomFetchStatus::NotStarted, 155 fetch_id: RoomFetchStatus::NotStarted,
147 fetch_last: None, 156 fetch_last: None,
@@ -159,7 +168,9 @@ pub fn mock_dirs() -> DirectoryValues {
159 168
160pub fn mock_tunables() -> TunableValues { 169pub fn mock_tunables() -> TunableValues {
161 TunableValues { 170 TunableValues {
162 typing_notice: true, 171 read_receipt_send: true,
172 read_receipt_display: true,
173 typing_notice_send: true,
163 typing_notice_display: true, 174 typing_notice_display: true,
164 users: vec![(TEST_USER5.clone(), UserDisplayTunables { 175 users: vec![(TEST_USER5.clone(), UserDisplayTunables {
165 color: Some(UserColor(Color::Black)), 176 color: Some(UserColor(Color::Black)),
src/windows/room/chat.rs +5 −7
@@ -241,7 +241,7 @@ impl ChatState {
241 241
242 let ev = match &msg.event { 242 let ev = match &msg.event {
243 MessageEvent::Original(ev) => &ev.content, 243 MessageEvent::Original(ev) => &ev.content,
244 MessageEvent::Local(ev) => ev.deref(), 244 MessageEvent::Local(_, ev) => ev.deref(),
245 _ => { 245 _ => {
246 let msg = "Cannot edit a redacted message"; 246 let msg = "Cannot edit a redacted message";
247 let err = UIError::Failure(msg.into()); 247 let err = UIError::Failure(msg.into());
@@ -275,9 +275,7 @@ impl ChatState {
275 275
276 let event_id = match &msg.event { 276 let event_id = match &msg.event {
277 MessageEvent::Original(ev) => ev.event_id.clone(), 277 MessageEvent::Original(ev) => ev.event_id.clone(),
278 MessageEvent::Local(_) => { 278 MessageEvent::Local(event_id, _) => event_id.clone(),
279 self.scrollback.get_key(info).ok_or(IambError::NoSelectedMessage)?.1
280 },
281 MessageEvent::Redacted(_) => { 279 MessageEvent::Redacted(_) => {
282 let msg = ""; 280 let msg = "";
283 let err = UIError::Failure(msg.into()); 281 let err = UIError::Failure(msg.into());
@@ -378,8 +376,8 @@ impl ChatState {
378 376
379 if show_echo { 377 if show_echo {
380 let user = store.application.settings.profile.user_id.clone(); 378 let user = store.application.settings.profile.user_id.clone();
381 let key = (MessageTimeStamp::LocalEcho, event_id); 379 let key = (MessageTimeStamp::LocalEcho, event_id.clone());
382 let msg = MessageEvent::Local(msg.into()); 380 let msg = MessageEvent::Local(event_id, msg.into());
383 let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho); 381 let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
384 info.messages.insert(key, msg); 382 info.messages.insert(key, msg);
385 } 383 }
@@ -415,7 +413,7 @@ impl ChatState {
415 return; 413 return;
416 } 414 }
417 415
418 if !store.application.settings.tunables.typing_notice { 416 if !store.application.settings.tunables.typing_notice_send {
419 return; 417 return;
420 } 418 }
421 419
src/windows/room/scrollback.rs +7 −1
@@ -1260,7 +1260,13 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1260 y += 1; 1260 y += 1;
1261 } 1261 }
1262 1262
1263 let first_key = info.messages.first_key_value().map(|f| f.0.clone()); 1263 if settings.tunables.read_receipt_send && state.cursor.timestamp.is_none() {
1264 // If the cursor is at the last message, then update the read marker.
1265 info.read_till = info.messages.last_key_value().map(|(k, _)| k.1.clone());
1266 }
1267
1268 // Check whether we should load older messages for this room.
1269 let first_key = info.messages.first_key_value().map(|(k, _)| k.clone());
1264 if first_key == state.viewctx.corner.timestamp { 1270 if first_key == state.viewctx.corner.timestamp {
1265 // If the top of the screen is the older message, load more. 1271 // If the top of the screen is the older message, load more.
1266 self.store.application.mark_for_load(state.room_id.clone()); 1272 self.store.application.mark_for_load(state.room_id.clone());
src/worker.rs +38 −2
@@ -57,7 +57,7 @@ use matrix_sdk::{
57use modalkit::editing::action::{EditInfo, InfoMessage, UIError}; 57use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
58 58
59use crate::{ 59use crate::{
60 base::{AsyncProgramStore, IambError, IambResult, VerifyAction}, 60 base::{AsyncProgramStore, IambError, IambResult, Receipts, VerifyAction},
61 message::MessageFetchResult, 61 message::MessageFetchResult,
62 ApplicationSettings, 62 ApplicationSettings,
63}; 63};
@@ -99,6 +99,29 @@ fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) {
99 return (reply, response); 99 return (reply, response);
100} 100}
101 101
102async fn update_receipts(client: &Client) -> Vec<(OwnedRoomId, Receipts)> {
103 let mut rooms = vec![];
104
105 for room in client.joined_rooms() {
106 if let Ok(users) = room.active_members_no_sync().await {
107 let mut receipts = Receipts::new();
108
109 for member in users {
110 let res = room.user_read_receipt(member.user_id()).await;
111
112 if let Ok(Some((event_id, _))) = res {
113 let user_id = member.user_id().to_owned();
114 receipts.entry(event_id).or_default().push(user_id);
115 }
116 }
117
118 rooms.push((room.room_id().to_owned(), receipts));
119 }
120 }
121
122 return rooms;
123}
124
102pub type FetchedRoom = (MatrixRoom, DisplayName, Option<Tags>); 125pub type FetchedRoom = (MatrixRoom, DisplayName, Option<Tags>);
103 126
104pub enum WorkerTask { 127pub enum WorkerTask {
@@ -454,7 +477,7 @@ impl ClientWorker {
454 } 477 }
455 478
456 async fn init(&mut self, store: AsyncProgramStore) { 479 async fn init(&mut self, store: AsyncProgramStore) {
457 self.client.add_event_handler_context(store); 480 self.client.add_event_handler_context(store.clone());
458 481
459 let _ = self.client.add_event_handler( 482 let _ = self.client.add_event_handler(
460 |ev: SyncTypingEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| { 483 |ev: SyncTypingEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
@@ -661,6 +684,19 @@ impl ClientWorker {
661 }, 684 },
662 ); 685 );
663 686
687 let client = self.client.clone();
688 let _ = tokio::spawn(async move {
689 // Update the displayed read receipts ever 5 seconds.
690 let mut interval = tokio::time::interval(Duration::from_secs(5));
691
692 loop {
693 interval.tick().await;
694
695 let receipts = update_receipts(&client).await;
696 store.lock().await.application.set_receipts(receipts).await;
697 }
698 });
699
664 self.initialized = true; 700 self.initialized = true;
665 } 701 }
666 702