Commit 999399a70f

999399a70f4f741390fa8ed113ea9ef06ad14b46

parent: b33759cbc3

Unregistered key

Benjamin Grosse <ste3ls@gmail.com> · 2023-12-19 04:55 UTC
committer: <noreply@github.com>

Fix not showing display names in already synced rooms (#171)

Fixes #149

Layout: unified · split

src/base.rs +49 −6
@@ -2,6 +2,7 @@
22//!
33//! The types defined here get used throughout iamb.
44use std::borrow::Cow;
5use std::collections::hash_map::IntoIter;
56use std::collections::{HashMap, HashSet};
67use std::convert::TryFrom;
78use std::fmt::{self, Display};
@@ -1042,6 +1043,38 @@ pub struct SyncInfo {
10421043 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
10431044}
10441045
1046bitflags::bitflags! {
1047 /// Load-needs
1048 #[derive(Debug, Default, PartialEq)]
1049 pub struct Need: u32 {
1050 const EMPTY = 0b00000000;
1051 const MESSAGES = 0b00000001;
1052 const MEMBERS = 0b00000010;
1053 }
1054}
1055
1056/// Things that need loading for different rooms.
1057#[derive(Default)]
1058pub struct RoomNeeds {
1059 needs: HashMap<OwnedRoomId, Need>,
1060}
1061
1062impl RoomNeeds {
1063 /// Mark a room for needing something to be loaded.
1064 pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1065 self.needs.entry(room_id).or_default().insert(need);
1066 }
1067}
1068
1069impl IntoIterator for RoomNeeds {
1070 type Item = (OwnedRoomId, Need);
1071 type IntoIter = IntoIter<OwnedRoomId, Need>;
1072
1073 fn into_iter(self) -> Self::IntoIter {
1074 self.needs.into_iter()
1075 }
1076}
1077
10451078/// The main application state.
10461079pub struct ChatStore {
10471080 /// `:`-commands
@@ -1066,7 +1099,7 @@ pub struct ChatStore {
10661099 pub settings: ApplicationSettings,
10671100
10681101 /// Set of rooms that need more messages loaded in their scrollback.
1069 pub need_load: HashSet<OwnedRoomId>,
1102 pub need_load: RoomNeeds,
10701103
10711104 /// [CompletionMap] of Emoji shortcodes.
10721105 pub emojis: CompletionMap<String, &'static Emoji>,
@@ -1113,11 +1146,6 @@ impl ChatStore {
11131146 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
11141147 }
11151148
1116 /// Mark a room for loading more scrollback.
1117 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
1118 self.need_load.insert(room_id);
1119 }
1120
11211149 /// Get the [RoomInfo] for a given room identifier.
11221150 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
11231151 self.rooms.get_or_default(room_id)
@@ -1659,6 +1687,21 @@ pub mod tests {
16591687 );
16601688 }
16611689
1690 #[test]
1691 fn test_need_load() {
1692 let room_id = TEST_ROOM1_ID.clone();
1693
1694 let mut need_load = RoomNeeds::default();
1695
1696 need_load.insert(room_id.clone(), Need::MESSAGES);
1697 need_load.insert(room_id.clone(), Need::MEMBERS);
1698
1699 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
1700 room_id,
1701 Need::MESSAGES | Need::MEMBERS,
1702 )],);
1703 }
1704
16621705 #[tokio::test]
16631706 async fn test_complete_msgbar() {
16641707 let store = mock_store().await;
src/windows/mod.rs +3
@@ -77,6 +77,7 @@ use crate::base::{
7777 IambInfo,
7878 IambResult,
7979 MessageAction,
80 Need,
8081 ProgramAction,
8182 ProgramContext,
8283 ProgramStore,
@@ -659,6 +660,7 @@ impl Window<IambInfo> for IambWindow {
659660 let (room, name, tags) = store.application.worker.get_room(room_id)?;
660661 let room = RoomState::new(room, name, tags, store);
661662
663 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
662664 return Ok(room.into());
663665 },
664666 IambId::DirectList => {
@@ -710,6 +712,7 @@ impl Window<IambInfo> for IambWindow {
710712 let (room, name, tags) = store.application.worker.get_room(room_id)?;
711713 let room = RoomState::new(room, name, tags, store);
712714
715 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
713716 Ok(room.into())
714717 }
715718 }
src/windows/room/scrollback.rs +53 −34
@@ -1,5 +1,4 @@
11//! Message scrollback
2use std::collections::HashSet;
32
43use ratatui_image::FixedImage;
54use regex::Regex;
@@ -73,7 +72,16 @@ use modalkit::editing::{
7372};
7473
7574use crate::{
76 base::{IambBufferId, IambInfo, IambResult, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
75 base::{
76 IambBufferId,
77 IambInfo,
78 IambResult,
79 Need,
80 ProgramContext,
81 ProgramStore,
82 RoomFocus,
83 RoomInfo,
84 },
7785 config::ApplicationSettings,
7886 message::{Message, MessageCursor, MessageKey, Messages},
7987};
@@ -468,8 +476,7 @@ impl ScrollbackState {
468476 needle: &Regex,
469477 mut count: usize,
470478 info: &RoomInfo,
471 need_load: &mut HashSet<OwnedRoomId>,
472 ) -> Option<MessageCursor> {
479 ) -> (Option<MessageCursor>, bool) {
473480 let mut mc = None;
474481
475482 for (key, msg) in info.messages.range(..&end).rev() {
@@ -483,11 +490,7 @@ impl ScrollbackState {
483490 }
484491 }
485492
486 if count > 0 {
487 need_load.insert(self.room_id.clone());
488 }
489
490 return mc;
493 return (mc, count > 0);
491494 }
492495
493496 fn find_message(
@@ -497,11 +500,10 @@ impl ScrollbackState {
497500 needle: &Regex,
498501 count: usize,
499502 info: &RoomInfo,
500 need_load: &mut HashSet<OwnedRoomId>,
501 ) -> Option<MessageCursor> {
503 ) -> (Option<MessageCursor>, bool) {
502504 match dir {
503 MoveDir1D::Next => self.find_message_next(key, needle, count, info),
504 MoveDir1D::Previous => self.find_message_prev(key, needle, count, info, need_load),
505 MoveDir1D::Next => (self.find_message_next(key, needle, count, info), false),
506 MoveDir1D::Previous => self.find_message_prev(key, needle, count, info),
505507 }
506508 }
507509}
@@ -628,14 +630,14 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
628630 },
629631 };
630632
631 self.find_message(
632 key,
633 dir,
634 &needle,
635 count,
636 info,
637 &mut store.application.need_load,
638 )
633 let (mc, needs_load) = self.find_message(key, dir, &needle, count, info);
634 if needs_load {
635 store
636 .application
637 .need_load
638 .insert(self.room_id.clone(), Need::MESSAGES);
639 }
640 mc
639641 },
640642 EditTarget::Search(SearchType::Word(_, _), _, _) => {
641643 let msg = "Cannot perform word search in a list";
@@ -714,15 +716,15 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
714716 },
715717 };
716718
717 self.find_message(
718 key,
719 dir,
720 &needle,
721 count,
722 info,
723 &mut store.application.need_load,
724 )
725 .map(|c| self._range_to(c))
719 let (mc, needs_load) = self.find_message(key, dir, &needle, count, info);
720 if needs_load {
721 store
722 .application
723 .need_load
724 .insert(self.room_id.to_owned(), Need::MESSAGES);
725 }
726
727 mc.map(|c| self._range_to(c))
726728 },
727729 EditTarget::Search(SearchType::Word(_, _), _, _) => {
728730 let msg = "Cannot perform word search in a list";
@@ -1288,7 +1290,10 @@ impl<'a> StatefulWidget for Scrollback<'a> {
12881290 let cursor_key = if let Some(k) = cursor.to_key(info) {
12891291 k
12901292 } else {
1291 self.store.application.mark_for_load(state.room_id.clone());
1293 self.store
1294 .application
1295 .need_load
1296 .insert(state.room_id.to_owned(), Need::MESSAGES);
12921297 return;
12931298 };
12941299
@@ -1389,7 +1394,10 @@ impl<'a> StatefulWidget for Scrollback<'a> {
13891394 let first_key = info.messages.first_key_value().map(|(k, _)| k.clone());
13901395 if first_key == state.viewctx.corner.timestamp {
13911396 // If the top of the screen is the older message, load more.
1392 self.store.application.mark_for_load(state.room_id.clone());
1397 self.store
1398 .application
1399 .need_load
1400 .insert(state.room_id.to_owned(), Need::MESSAGES);
13931401 }
13941402 }
13951403}
@@ -1427,12 +1435,23 @@ mod tests {
14271435 // Search backwards to MSG2.
14281436 scrollback.search(prev.clone(), 1.into(), &ctx, &mut store).unwrap();
14291437 assert_eq!(scrollback.cursor, MSG2_KEY.clone().into());
1430 assert_eq!(store.application.need_load.contains(&room_id), false);
1438 assert_eq!(
1439 std::mem::take(&mut store.application.need_load)
1440 .into_iter()
1441 .collect::<Vec<(OwnedRoomId, Need)>>()
1442 .is_empty(),
1443 true,
1444 );
14311445
14321446 // Can't go any further; need_load now contains the room ID.
14331447 scrollback.search(prev.clone(), 1.into(), &ctx, &mut store).unwrap();
14341448 assert_eq!(scrollback.cursor, MSG2_KEY.clone().into());
1435 assert_eq!(store.application.need_load.contains(&room_id), true);
1449 assert_eq!(
1450 std::mem::take(&mut store.application.need_load)
1451 .into_iter()
1452 .collect::<Vec<(OwnedRoomId, Need)>>(),
1453 vec![(room_id.clone(), Need::MESSAGES)]
1454 );
14361455
14371456 // Search forward twice to MSG1.
14381457 scrollback.search(next.clone(), 2.into(), &ctx, &mut store).unwrap();
src/worker.rs +82 −40
@@ -78,6 +78,7 @@ use matrix_sdk::{
7878
7979use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
8080
81use crate::base::Need;
8182use crate::{
8283 base::{
8384 AsyncProgramStore,
@@ -187,34 +188,64 @@ async fn update_event_receipts(info: &mut RoomInfo, room: &MatrixRoom, event_id:
187188 }
188189}
189190
190async fn load_plan(store: &AsyncProgramStore) -> HashMap<OwnedRoomId, Option<String>> {
191#[derive(Debug)]
192enum Plan {
193 Messages(OwnedRoomId, Option<String>),
194 Members(OwnedRoomId),
195}
196
197async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> {
191198 let mut locked = store.lock().await;
192199 let ChatStore { need_load, rooms, .. } = &mut locked.application;
193 let mut plan = HashMap::new();
200 let mut plan = vec![];
194201
195 for room_id in std::mem::take(need_load).into_iter() {
196 let info = rooms.get_or_default(room_id.clone());
202 for (room_id, mut need) in std::mem::take(need_load).into_iter() {
203 if need.contains(Need::MESSAGES) {
204 let info = rooms.get_or_default(room_id.clone());
197205
198 if info.recently_fetched() || info.fetching {
199 need_load.insert(room_id);
200 continue;
201 } else {
202 info.fetch_last = Instant::now().into();
203 info.fetching = true;
204 }
206 if !info.recently_fetched() && !info.fetching {
207 info.fetch_last = Instant::now().into();
208 info.fetching = true;
205209
206 let fetch_id = match &info.fetch_id {
207 RoomFetchStatus::Done => continue,
208 RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
209 RoomFetchStatus::NotStarted => None,
210 };
210 let fetch_id = match &info.fetch_id {
211 RoomFetchStatus::Done => continue,
212 RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
213 RoomFetchStatus::NotStarted => None,
214 };
211215
212 plan.insert(room_id, fetch_id);
216 plan.push(Plan::Messages(room_id.to_owned(), fetch_id));
217 need.remove(Need::MESSAGES);
218 }
219 }
220 if need.contains(Need::MEMBERS) {
221 plan.push(Plan::Members(room_id.to_owned()));
222 need.remove(Need::MEMBERS);
223 }
224 if !need.is_empty() {
225 need_load.insert(room_id, need);
226 }
213227 }
214228
215229 return plan;
216230}
217231
232async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan) {
233 match plan {
234 Plan::Messages(room_id, fetch_id) => {
235 let limit = MIN_MSG_LOAD;
236 let client = client.clone();
237 let store = store.clone();
238
239 let res = load_older_one(&client, &room_id, fetch_id, limit).await;
240 load_insert(room_id, res, store).await;
241 },
242 Plan::Members(room_id) => {
243 let res = members_load(client, &room_id).await;
244 members_insert(room_id, res, store).await
245 },
246 }
247}
248
218249async fn load_older_one(
219250 client: &Client,
220251 room_id: &RoomId,
@@ -246,15 +277,7 @@ async fn load_older_one(
246277
247278async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
248279 let mut locked = store.lock().await;
249 let ChatStore {
250 need_load,
251 presences,
252 rooms,
253 worker,
254 picker,
255 settings,
256 ..
257 } = &mut locked.application;
280 let ChatStore { presences, rooms, worker, picker, settings, .. } = &mut locked.application;
258281 let info = rooms.get_or_default(room_id.clone());
259282 info.fetching = false;
260283 let client = &worker.client;
@@ -296,33 +319,52 @@ async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: Async
296319 warn!(room_id = room_id.as_str(), err = e.to_string(), "Failed to load older messages");
297320
298321 // Wait and try again.
299 need_load.insert(room_id);
322 locked.application.need_load.insert(room_id, Need::MESSAGES);
300323 },
301324 }
302325}
303326
304327async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize {
305 let limit = MIN_MSG_LOAD;
306
307 // Fetch each room separately, so they don't block each other.
308 load_plan(store)
328 // Plans are run in parallel. Any room *may* have several plans.
329 load_plans(store)
309330 .await
310331 .into_iter()
311 .map(|(room_id, fetch_id)| {
312 let store = store.clone();
313
314 async move {
315 let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
316 load_insert(room_id, res, store).await;
317 }
318 })
332 .map(|plan| run_plan(client, store, plan))
319333 .collect::<FuturesUnordered<_>>()
320334 .count()
321335 .await
322336}
323337
338async fn members_load(client: &Client, room_id: &RoomId) -> IambResult<Vec<RoomMember>> {
339 if let Some(room) = client.get_room(room_id) {
340 Ok(room.members_no_sync().await.map_err(IambError::from)?)
341 } else {
342 Err(IambError::UnknownRoom(room_id.to_owned()).into())
343 }
344}
345
346async fn members_insert(
347 room_id: OwnedRoomId,
348 res: IambResult<Vec<RoomMember>>,
349 store: &AsyncProgramStore,
350) {
351 if let Ok(members) = res {
352 let mut locked = store.lock().await;
353 let ChatStore { rooms, .. } = &mut locked.application;
354 let info = rooms.get_or_default(room_id.clone());
355
356 for member in members {
357 let user_id = member.user_id();
358 let display_name =
359 member.display_name().map_or(user_id.to_string(), |str| str.to_string());
360 info.display_names.insert(user_id.to_owned(), display_name);
361 }
362 }
363 // else ???
364}
365
324366async fn load_older_forever(client: &Client, store: &AsyncProgramStore) {
325 // Load older messages every 2 seconds.
367 // Load any pending older messages or members every 2 seconds.
326368 let mut interval = tokio::time::interval(Duration::from_secs(2));
327369
328370 loop {