Commit a2a708f1ae

a2a708f1ae1dc8d08620f1b302b2cafb159cb40a

parent: 3ed87aae05

Unregistered key

Ulyssa <git@ulyssa.dev> · 2024-02-28 17:03 UTC
committer: <noreply@github.com>

Indicate and sort on rooms with unread messages (#205)

Fixes #83 

Layout: unified · split

src/base.rs +52 −3
@@ -53,6 +53,7 @@ use matrix_sdk::{
53 OwnedRoomId, 53 OwnedRoomId,
54 OwnedUserId, 54 OwnedUserId,
55 RoomId, 55 RoomId,
56 UserId,
56 }, 57 },
57}; 58};
58 59
@@ -209,11 +210,26 @@ bitflags::bitflags! {
209/// Fields that rooms and spaces can be sorted by. 210/// Fields that rooms and spaces can be sorted by.
210#[derive(Clone, Debug, Eq, PartialEq)] 211#[derive(Clone, Debug, Eq, PartialEq)]
211pub enum SortFieldRoom { 212pub enum SortFieldRoom {
213 /// Sort rooms by whether they have the Favorite tag.
212 Favorite, 214 Favorite,
215
216 /// Sort rooms by whether they have the Low Priority tag.
213 LowPriority, 217 LowPriority,
218
219 /// Sort rooms by their room name.
214 Name, 220 Name,
221
222 /// Sort rooms by their canonical room alias.
215 Alias, 223 Alias,
224
225 /// Sort rooms by their Matrix room identifier.
216 RoomId, 226 RoomId,
227
228 /// Sort rooms by whether they have unread messages.
229 Unread,
230
231 /// Sort rooms by the timestamps of their most recent messages.
232 Recent,
217} 233}
218 234
219/// Fields that users can be sorted by. 235/// Fields that users can be sorted by.
@@ -273,6 +289,8 @@ impl<'de> Visitor<'de> for SortRoomVisitor {
273 let field = match value { 289 let field = match value {
274 "favorite" => SortFieldRoom::Favorite, 290 "favorite" => SortFieldRoom::Favorite,
275 "lowpriority" => SortFieldRoom::LowPriority, 291 "lowpriority" => SortFieldRoom::LowPriority,
292 "recent" => SortFieldRoom::Recent,
293 "unread" => SortFieldRoom::Unread,
276 "name" => SortFieldRoom::Name, 294 "name" => SortFieldRoom::Name,
277 "alias" => SortFieldRoom::Alias, 295 "alias" => SortFieldRoom::Alias,
278 "id" => SortFieldRoom::RoomId, 296 "id" => SortFieldRoom::RoomId,
@@ -672,6 +690,22 @@ impl EventLocation {
672 } 690 }
673} 691}
674 692
693#[derive(Clone, Debug, Default, Eq, PartialEq)]
694pub struct UnreadInfo {
695 pub(crate) unread: bool,
696 pub(crate) latest: Option<MessageTimeStamp>,
697}
698
699impl UnreadInfo {
700 pub fn is_unread(&self) -> bool {
701 self.unread
702 }
703
704 pub fn latest(&self) -> Option<&MessageTimeStamp> {
705 self.latest.as_ref()
706 }
707}
708
675/// Information about room's the user's joined. 709/// Information about room's the user's joined.
676#[derive(Default)] 710#[derive(Default)]
677pub struct RoomInfo { 711pub struct RoomInfo {
@@ -697,9 +731,6 @@ pub struct RoomInfo {
697 /// older than the oldest loaded event, that user will not be included. 731 /// older than the oldest loaded event, that user will not be included.
698 pub user_receipts: HashMap<OwnedUserId, OwnedEventId>, 732 pub user_receipts: HashMap<OwnedUserId, OwnedEventId>,
699 733
700 /// An event ID for where we should indicate we've read up to.
701 pub read_till: Option<OwnedEventId>,
702
703 /// A map of message identifiers to a map of reaction events. 734 /// A map of message identifiers to a map of reaction events.
704 pub reactions: HashMap<OwnedEventId, MessageReactions>, 735 pub reactions: HashMap<OwnedEventId, MessageReactions>,
705 736
@@ -810,6 +841,20 @@ impl RoomInfo {
810 msg.html = msg.event.html(); 841 msg.html = msg.event.html();
811 } 842 }
812 843
844 /// Indicates whether this room has unread messages.
845 pub fn unreads(&self, settings: &ApplicationSettings) -> UnreadInfo {
846 let last_message = self.messages.last_key_value();
847 let last_receipt = self.get_receipt(&settings.profile.user_id);
848
849 match (last_message, last_receipt) {
850 (Some(((ts, recent), _)), Some(last_read)) => {
851 UnreadInfo { unread: last_read != recent, latest: Some(*ts) }
852 },
853 (Some(((ts, _), _)), None) => UnreadInfo { unread: false, latest: Some(*ts) },
854 (None, _) => UnreadInfo::default(),
855 }
856 }
857
813 /// Inserts events that couldn't be decrypted into the scrollback. 858 /// Inserts events that couldn't be decrypted into the scrollback.
814 pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) { 859 pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
815 let event_id = msg.event_id().to_owned(); 860 let event_id = msg.event_id().to_owned();
@@ -901,6 +946,10 @@ impl RoomInfo {
901 self.user_receipts.insert(user_id, event_id); 946 self.user_receipts.insert(user_id, event_id);
902 } 947 }
903 948
949 pub fn get_receipt(&self, user_id: &UserId) -> Option<&OwnedEventId> {
950 self.user_receipts.get(user_id)
951 }
952
904 fn get_typers(&self) -> &[OwnedUserId] { 953 fn get_typers(&self) -> &[OwnedUserId] {
905 if let Some((t, users)) = &self.users_typing { 954 if let Some((t, users)) = &self.users_typing {
906 if t.elapsed() < Duration::from_secs(4) { 955 if t.elapsed() < Duration::from_secs(4) {
src/config.rs +2 −1
@@ -32,9 +32,10 @@ const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 2] = [
32 SortColumn(SortFieldUser::UserId, SortOrder::Ascending), 32 SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
33]; 33];
34 34
35const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 3] = [ 35const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 4] = [
36 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending), 36 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
37 SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending), 37 SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
38 SortColumn(SortFieldRoom::Unread, SortOrder::Ascending),
38 SortColumn(SortFieldRoom::Name, SortOrder::Ascending), 39 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
39]; 40];
40 41
src/main.rs +3 −22
@@ -27,17 +27,10 @@ use std::sync::Arc;
27use std::time::Duration; 27use std::time::Duration;
28 28
29use clap::Parser; 29use clap::Parser;
30use matrix_sdk::ruma::OwnedUserId;
30use tokio::sync::Mutex as AsyncMutex; 31use tokio::sync::Mutex as AsyncMutex;
31use tracing_subscriber::FmtSubscriber; 32use tracing_subscriber::FmtSubscriber;
32 33
33use matrix_sdk::{
34 config::SyncSettings,
35 ruma::{
36 api::client::filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
37 OwnedUserId,
38 },
39};
40
41use modalkit::crossterm::{ 34use modalkit::crossterm::{
42 self, 35 self,
43 cursor::Show as CursorShow, 36 cursor::Show as CursorShow,
@@ -719,20 +712,6 @@ async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<
719 } 712 }
720 } 713 }
721 714
722 // Perform an initial, lazily-loaded sync.
723 let mut room = RoomEventFilter::default();
724 room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
725
726 let mut room_ev = RoomFilter::default();
727 room_ev.state = room;
728
729 let mut filter = FilterDefinition::default();
730 filter.room = room_ev;
731
732 let settings = SyncSettings::new().filter(filter.into());
733
734 worker.client.sync_once(settings).await.map_err(IambError::from)?;
735
736 Ok(()) 715 Ok(())
737} 716}
738 717
@@ -744,12 +723,14 @@ fn print_exit<T: Display, N>(v: T) -> N {
744async fn run(settings: ApplicationSettings) -> IambResult<()> { 723async fn run(settings: ApplicationSettings) -> IambResult<()> {
745 // Set up the async worker thread and global store. 724 // Set up the async worker thread and global store.
746 let worker = ClientWorker::spawn(settings.clone()).await; 725 let worker = ClientWorker::spawn(settings.clone()).await;
726 let client = worker.client.clone();
747 let store = ChatStore::new(worker.clone(), settings.clone()); 727 let store = ChatStore::new(worker.clone(), settings.clone());
748 let store = Store::new(store); 728 let store = Store::new(store);
749 let store = Arc::new(AsyncMutex::new(store)); 729 let store = Arc::new(AsyncMutex::new(store));
750 worker.init(store.clone()); 730 worker.init(store.clone());
751 731
752 login(worker, &settings).await.unwrap_or_else(print_exit); 732 login(worker, &settings).await.unwrap_or_else(print_exit);
733 worker::do_first_sync(client, &store).await;
753 734
754 fn restore_tty() { 735 fn restore_tty() {
755 let _ = crossterm::terminal::disable_raw_mode(); 736 let _ = crossterm::terminal::disable_raw_mode();
src/tests.rs −1
@@ -156,7 +156,6 @@ pub fn mock_room() -> RoomInfo {
156 156
157 event_receipts: HashMap::new(), 157 event_receipts: HashMap::new(),
158 user_receipts: HashMap::new(), 158 user_receipts: HashMap::new(),
159 read_till: None,
160 reactions: HashMap::new(), 159 reactions: HashMap::new(),
161 160
162 fetching: false, 161 fetching: false,
src/windows/mod.rs +169 −31
@@ -79,9 +79,11 @@ use crate::base::{
79 SortFieldRoom, 79 SortFieldRoom,
80 SortFieldUser, 80 SortFieldUser,
81 SortOrder, 81 SortOrder,
82 UnreadInfo,
82}; 83};
83 84
84use self::{room::RoomState, welcome::WelcomeState}; 85use self::{room::RoomState, welcome::WelcomeState};
86use crate::message::MessageTimeStamp;
85 87
86pub mod room; 88pub mod room;
87pub mod welcome; 89pub mod welcome;
@@ -124,11 +126,31 @@ fn selected_text(s: &str, selected: bool) -> Text {
124 Text::from(selected_span(s, selected)) 126 Text::from(selected_span(s, selected))
125} 127}
126 128
129fn name_and_labels(name: &str, unread: bool, style: Style) -> (Span<'_>, Vec<Vec<Span<'_>>>) {
130 let name_style = if unread {
131 style.add_modifier(StyleModifier::BOLD)
132 } else {
133 style
134 };
135
136 let name = Span::styled(name, name_style);
137 let labels = if unread {
138 vec![vec![Span::styled("Unread", style)]]
139 } else {
140 vec![]
141 };
142
143 (name, labels)
144}
145
127/// Sort `Some` to be less than `None` so that list items with values come before those without. 146/// Sort `Some` to be less than `None` so that list items with values come before those without.
128#[inline] 147#[inline]
129fn some_cmp<T: Ord>(a: Option<T>, b: Option<T>) -> Ordering { 148fn some_cmp<T, F>(a: Option<T>, b: Option<T>, f: F) -> Ordering
149where
150 F: Fn(&T, &T) -> Ordering,
151{
130 match (a, b) { 152 match (a, b) {
131 (Some(a), Some(b)) => a.cmp(&b), 153 (Some(a), Some(b)) => f(&a, &b),
132 (None, None) => Ordering::Equal, 154 (None, None) => Ordering::Equal,
133 (None, Some(_)) => Ordering::Greater, 155 (None, Some(_)) => Ordering::Greater,
134 (Some(_), None) => Ordering::Less, 156 (Some(_), None) => Ordering::Less,
@@ -167,8 +189,16 @@ fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
167 lowa.cmp(&lowb) 189 lowa.cmp(&lowb)
168 }, 190 },
169 SortFieldRoom::Name => a.name().cmp(b.name()), 191 SortFieldRoom::Name => a.name().cmp(b.name()),
170 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias()), 192 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias(), Ord::cmp),
171 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()), 193 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
194 SortFieldRoom::Unread => {
195 // Sort true (unread) before false (read)
196 b.is_unread().cmp(&a.is_unread())
197 },
198 SortFieldRoom::Recent => {
199 // sort larger timestamps towards the top.
200 some_cmp(a.recent_ts(), b.recent_ts(), |a, b| b.cmp(a))
201 },
172 } 202 }
173} 203}
174 204
@@ -243,6 +273,8 @@ fn append_tags<'a>(tags: Vec<Vec<Span<'a>>>, spans: &mut Vec<Span<'a>>, style: S
243trait RoomLikeItem { 273trait RoomLikeItem {
244 fn room_id(&self) -> &RoomId; 274 fn room_id(&self) -> &RoomId;
245 fn has_tag(&self, tag: TagName) -> bool; 275 fn has_tag(&self, tag: TagName) -> bool;
276 fn is_unread(&self) -> bool;
277 fn recent_ts(&self) -> Option<&MessageTimeStamp>;
246 fn alias(&self) -> Option<&RoomAliasId>; 278 fn alias(&self) -> Option<&RoomAliasId>;
247 fn name(&self) -> &str; 279 fn name(&self) -> &str;
248} 280}
@@ -780,6 +812,7 @@ pub struct GenericChatItem {
780 room_info: MatrixRoomInfo, 812 room_info: MatrixRoomInfo,
781 name: String, 813 name: String,
782 alias: Option<OwnedRoomAliasId>, 814 alias: Option<OwnedRoomAliasId>,
815 unread: UnreadInfo,
783 is_dm: bool, 816 is_dm: bool,
784} 817}
785 818
@@ -788,17 +821,17 @@ impl GenericChatItem {
788 let room = &room_info.deref().0; 821 let room = &room_info.deref().0;
789 let room_id = room.room_id(); 822 let room_id = room.room_id();
790 823
791 let info = store.application.get_room_info(room_id.to_owned()); 824 let info = store.application.rooms.get_or_default(room_id.to_owned());
792
793 let name = info.name.clone().unwrap_or_default(); 825 let name = info.name.clone().unwrap_or_default();
794 let alias = room.canonical_alias(); 826 let alias = room.canonical_alias();
827 let unread = info.unreads(&store.application.settings);
795 info.tags = room_info.deref().1.clone(); 828 info.tags = room_info.deref().1.clone();
796 829
797 if let Some(alias) = &alias { 830 if let Some(alias) = &alias {
798 store.application.names.insert(alias.to_string(), room_id.to_owned()); 831 store.application.names.insert(alias.to_string(), room_id.to_owned());
799 } 832 }
800 833
801 GenericChatItem { room_info, name, alias, is_dm } 834 GenericChatItem { room_info, name, alias, is_dm, unread }
802 } 835 }
803 836
804 #[inline] 837 #[inline]
@@ -832,6 +865,14 @@ impl RoomLikeItem for GenericChatItem {
832 false 865 false
833 } 866 }
834 } 867 }
868
869 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
870 self.unread.latest()
871 }
872
873 fn is_unread(&self) -> bool {
874 self.unread.is_unread()
875 }
835} 876}
836 877
837impl ToString for GenericChatItem { 878impl ToString for GenericChatItem {
@@ -842,13 +883,16 @@ impl ToString for GenericChatItem {
842 883
843impl ListItem<IambInfo> for GenericChatItem { 884impl ListItem<IambInfo> for GenericChatItem {
844 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text { 885 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
886 let unread = self.unread.is_unread();
845 let style = selected_style(selected); 887 let style = selected_style(selected);
846 let mut spans = vec![Span::styled(self.name.as_str(), style)]; 888 let (name, mut labels) = name_and_labels(&self.name, unread, style);
847 let mut labels = if self.is_dm { 889 let mut spans = vec![name];
848 vec![vec![Span::styled("DM", style)]] 890
891 labels.push(if self.is_dm {
892 vec![Span::styled("DM", style)]
849 } else { 893 } else {
850 vec![vec![Span::styled("Room", style)]] 894 vec![Span::styled("Room", style)]
851 }; 895 });
852 896
853 if let Some(tags) = &self.tags() { 897 if let Some(tags) = &self.tags() {
854 labels.extend(tags.keys().map(|t| tag_to_span(t, style))); 898 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
@@ -879,6 +923,7 @@ pub struct RoomItem {
879 room_info: MatrixRoomInfo, 923 room_info: MatrixRoomInfo,
880 name: String, 924 name: String,
881 alias: Option<OwnedRoomAliasId>, 925 alias: Option<OwnedRoomAliasId>,
926 unread: UnreadInfo,
882} 927}
883 928
884impl RoomItem { 929impl RoomItem {
@@ -886,16 +931,17 @@ impl RoomItem {
886 let room = &room_info.deref().0; 931 let room = &room_info.deref().0;
887 let room_id = room.room_id(); 932 let room_id = room.room_id();
888 933
889 let info = store.application.get_room_info(room_id.to_owned()); 934 let info = store.application.rooms.get_or_default(room_id.to_owned());
890 let name = info.name.clone().unwrap_or_default(); 935 let name = info.name.clone().unwrap_or_default();
891 let alias = room.canonical_alias(); 936 let alias = room.canonical_alias();
937 let unread = info.unreads(&store.application.settings);
892 info.tags = room_info.deref().1.clone(); 938 info.tags = room_info.deref().1.clone();
893 939
894 if let Some(alias) = &alias { 940 if let Some(alias) = &alias {
895 store.application.names.insert(alias.to_string(), room_id.to_owned()); 941 store.application.names.insert(alias.to_string(), room_id.to_owned());
896 } 942 }
897 943
898 RoomItem { room_info, name, alias } 944 RoomItem { room_info, name, alias, unread }
899 } 945 }
900 946
901 #[inline] 947 #[inline]
@@ -929,6 +975,14 @@ impl RoomLikeItem for RoomItem {
929 false 975 false
930 } 976 }
931 } 977 }
978
979 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
980 self.unread.latest()
981 }
982
983 fn is_unread(&self) -> bool {
984 self.unread.is_unread()
985 }
932} 986}
933 987
934impl ToString for RoomItem { 988impl ToString for RoomItem {
@@ -939,17 +993,18 @@ impl ToString for RoomItem {
939 993
940impl ListItem<IambInfo> for RoomItem { 994impl ListItem<IambInfo> for RoomItem {
941 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text { 995 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
996 let unread = self.unread.is_unread();
997 let style = selected_style(selected);
998 let (name, mut labels) = name_and_labels(&self.name, unread, style);
999 let mut spans = vec![name];
1000
942 if let Some(tags) = &self.tags() { 1001 if let Some(tags) = &self.tags() {
943 let style = selected_style(selected); 1002 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
944 let mut spans = vec![Span::styled(self.name.as_str(), style)]; 1003 }
945 let tags = tags.keys().map(|t| tag_to_span(t, style)).collect();
946 1004
947 append_tags(tags, &mut spans, style); 1005 append_tags(labels, &mut spans, style);
948 1006
949 Text::from(Line::from(spans)) 1007 Text::from(Line::from(spans))
950 } else {
951 selected_text(self.name.as_str(), selected)
952 }
953 } 1008 }
954 1009
955 fn get_word(&self) -> Option<String> { 1010 fn get_word(&self) -> Option<String> {
@@ -973,15 +1028,20 @@ pub struct DirectItem {
973 room_info: MatrixRoomInfo, 1028 room_info: MatrixRoomInfo,
974 name: String, 1029 name: String,
975 alias: Option<OwnedRoomAliasId>, 1030 alias: Option<OwnedRoomAliasId>,
1031 unread: UnreadInfo,
976} 1032}
977 1033
978impl DirectItem { 1034impl DirectItem {
979 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self { 1035 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
980 let room_id = room_info.0.room_id().to_owned(); 1036 let room_id = room_info.0.room_id().to_owned();
981 let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
982 let alias = room_info.0.canonical_alias(); 1037 let alias = room_info.0.canonical_alias();
983 1038
984 DirectItem { room_info, name, alias } 1039 let info = store.application.rooms.get_or_default(room_id);
1040 let name = info.name.clone().unwrap_or_default();
1041 let unread = info.unreads(&store.application.settings);
1042 info.tags = room_info.deref().1.clone();
1043
1044 DirectItem { room_info, name, alias, unread }
985 } 1045 }
986 1046
987 #[inline] 1047 #[inline]
@@ -1015,6 +1075,14 @@ impl RoomLikeItem for DirectItem {
1015 fn room_id(&self) -> &RoomId { 1075 fn room_id(&self) -> &RoomId {
1016 self.room().room_id() 1076 self.room().room_id()
1017 } 1077 }
1078
1079 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1080 self.unread.latest()
1081 }
1082
1083 fn is_unread(&self) -> bool {
1084 self.unread.is_unread()
1085 }
1018} 1086}
1019 1087
1020impl ToString for DirectItem { 1088impl ToString for DirectItem {
@@ -1025,17 +1093,18 @@ impl ToString for DirectItem {
1025 1093
1026impl ListItem<IambInfo> for DirectItem { 1094impl ListItem<IambInfo> for DirectItem {
1027 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text { 1095 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1096 let unread = self.unread.is_unread();
1097 let style = selected_style(selected);
1098 let (name, mut labels) = name_and_labels(&self.name, unread, style);
1099 let mut spans = vec![name];
1100
1028 if let Some(tags) = &self.tags() { 1101 if let Some(tags) = &self.tags() {
1029 let style = selected_style(selected); 1102 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
1030 let mut spans = vec![Span::styled(self.name.as_str(), style)]; 1103 }
1031 let tags = tags.keys().map(|t| tag_to_span(t, style)).collect();
1032 1104
1033 append_tags(tags, &mut spans, style); 1105 append_tags(labels, &mut spans, style);
1034 1106
1035 Text::from(Line::from(spans)) 1107 Text::from(Line::from(spans))
1036 } else {
1037 selected_text(self.name.as_str(), selected)
1038 }
1039 } 1108 }
1040 1109
1041 fn get_word(&self) -> Option<String> { 1110 fn get_word(&self) -> Option<String> {
@@ -1103,6 +1172,16 @@ impl RoomLikeItem for SpaceItem {
1103 // exposes them, so we'll just always return false here for now. 1172 // exposes them, so we'll just always return false here for now.
1104 false 1173 false
1105 } 1174 }
1175
1176 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1177 // XXX: this needs to determine the room with most recent message and return its timestamp.
1178 None
1179 }
1180
1181 fn is_unread(&self) -> bool {
1182 // XXX: this needs to check whether the space contains rooms with unread messages
1183 false
1184 }
1106} 1185}
1107 1186
1108impl ToString for SpaceItem { 1187impl ToString for SpaceItem {
@@ -1433,6 +1512,7 @@ mod tests {
1433 tags: Vec<TagName>, 1512 tags: Vec<TagName>,
1434 alias: Option<OwnedRoomAliasId>, 1513 alias: Option<OwnedRoomAliasId>,
1435 name: &'static str, 1514 name: &'static str,
1515 unread: UnreadInfo,
1436 } 1516 }
1437 1517
1438 impl RoomLikeItem for &TestRoomItem { 1518 impl RoomLikeItem for &TestRoomItem {
@@ -1451,6 +1531,14 @@ mod tests {
1451 fn name(&self) -> &str { 1531 fn name(&self) -> &str {
1452 self.name 1532 self.name
1453 } 1533 }
1534
1535 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1536 self.unread.latest()
1537 }
1538
1539 fn is_unread(&self) -> bool {
1540 self.unread.is_unread()
1541 }
1454 } 1542 }
1455 1543
1456 #[test] 1544 #[test]
@@ -1462,6 +1550,7 @@ mod tests {
1462 tags: vec![TagName::Favorite], 1550 tags: vec![TagName::Favorite],
1463 alias: Some(room_alias_id!("#room1:example.com").to_owned()), 1551 alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1464 name: "Z", 1552 name: "Z",
1553 unread: UnreadInfo::default(),
1465 }; 1554 };
1466 1555
1467 let room2 = TestRoomItem { 1556 let room2 = TestRoomItem {
@@ -1469,6 +1558,7 @@ mod tests {
1469 tags: vec![], 1558 tags: vec![],
1470 alias: Some(room_alias_id!("#a:example.com").to_owned()), 1559 alias: Some(room_alias_id!("#a:example.com").to_owned()),
1471 name: "Unnamed Room", 1560 name: "Unnamed Room",
1561 unread: UnreadInfo::default(),
1472 }; 1562 };
1473 1563
1474 let room3 = TestRoomItem { 1564 let room3 = TestRoomItem {
@@ -1476,6 +1566,7 @@ mod tests {
1476 tags: vec![], 1566 tags: vec![],
1477 alias: None, 1567 alias: None,
1478 name: "Cool Room", 1568 name: "Cool Room",
1569 unread: UnreadInfo::default(),
1479 }; 1570 };
1480 1571
1481 // Sort by Name ascending. 1572 // Sort by Name ascending.
@@ -1510,4 +1601,51 @@ mod tests {
1510 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields)); 1601 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1511 assert_eq!(rooms, vec![&room2, &room3, &room1]); 1602 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1512 } 1603 }
1604
1605 #[test]
1606 fn test_sort_room_recents() {
1607 let server = server_name!("example.com");
1608
1609 let room1 = TestRoomItem {
1610 room_id: RoomId::new(server).to_owned(),
1611 tags: vec![],
1612 alias: None,
1613 name: "Room 1",
1614 unread: UnreadInfo { unread: false, latest: None },
1615 };
1616
1617 let room2 = TestRoomItem {
1618 room_id: RoomId::new(server).to_owned(),
1619 tags: vec![],
1620 alias: None,
1621 name: "Room 2",
1622 unread: UnreadInfo {
1623 unread: false,
1624 latest: Some(MessageTimeStamp::OriginServer(40u32.into())),
1625 },
1626 };
1627
1628 let room3 = TestRoomItem {
1629 room_id: RoomId::new(server).to_owned(),
1630 tags: vec![],
1631 alias: None,
1632 name: "Room 3",
1633 unread: UnreadInfo {
1634 unread: false,
1635 latest: Some(MessageTimeStamp::OriginServer(20u32.into())),
1636 },
1637 };
1638
1639 // Sort by Recent ascending.
1640 let mut rooms = vec![&room1, &room2, &room3];
1641 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Ascending)];
1642 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1643 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1644
1645 // Sort by Recent descending.
1646 let mut rooms = vec![&room1, &room2, &room3];
1647 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Descending)];
1648 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1649 assert_eq!(rooms, vec![&room1, &room3, &room2]);
1650 }
1513} 1651}
src/windows/room/scrollback.rs +3 −1
@@ -1342,7 +1342,9 @@ impl<'a> StatefulWidget for Scrollback<'a> {
1342 state.cursor.timestamp.is_none() 1342 state.cursor.timestamp.is_none()
1343 { 1343 {
1344 // If the cursor is at the last message, then update the read marker. 1344 // If the cursor is at the last message, then update the read marker.
1345 info.read_till = info.messages.last_key_value().map(|(k, _)| k.1.clone()); 1345 if let Some((k, _)) = info.messages.last_key_value() {
1346 info.set_receipt(settings.profile.user_id.clone(), k.1.clone());
1347 }
1346 } 1348 }
1347 1349
1348 // Check whether we should load older messages for this room. 1350 // Check whether we should load older messages for this room.
src/worker.rs +40 −3
@@ -26,6 +26,7 @@ use matrix_sdk::{
26 room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember}, 26 room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
27 ruma::{ 27 ruma::{
28 api::client::{ 28 api::client::{
29 filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
29 room::create_room::v3::{CreationContent, Request as CreateRoomRequest, RoomPreset}, 30 room::create_room::v3::{CreationContent, Request as CreateRoomRequest, RoomPreset},
30 room::Visibility, 31 room::Visibility,
31 space::get_hierarchy::v1::Request as SpaceHierarchyRequest, 32 space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
@@ -424,9 +425,8 @@ async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) {
424 let mut interval = tokio::time::interval(Duration::from_secs(5)); 425 let mut interval = tokio::time::interval(Duration::from_secs(5));
425 426
426 loop { 427 loop {
427 interval.tick().await;
428
429 refresh_rooms(client, store).await; 428 refresh_rooms(client, store).await;
429 interval.tick().await;
430 } 430 }
431} 431}
432 432
@@ -438,13 +438,14 @@ async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) {
438 interval.tick().await; 438 interval.tick().await;
439 439
440 let locked = store.lock().await; 440 let locked = store.lock().await;
441 let user_id = &locked.application.settings.profile.user_id;
441 let updates = client 442 let updates = client
442 .joined_rooms() 443 .joined_rooms()
443 .into_iter() 444 .into_iter()
444 .filter_map(|room| { 445 .filter_map(|room| {
445 let room_id = room.room_id().to_owned(); 446 let room_id = room.room_id().to_owned();
446 let info = locked.application.rooms.get(&room_id)?; 447 let info = locked.application.rooms.get(&room_id)?;
447 let new_receipt = info.read_till.as_ref()?; 448 let new_receipt = info.get_receipt(user_id)?;
448 let old_receipt = sent.get(&room_id); 449 let old_receipt = sent.get(&room_id);
449 if Some(new_receipt) != old_receipt { 450 if Some(new_receipt) != old_receipt {
450 Some((room_id, new_receipt.clone())) 451 Some((room_id, new_receipt.clone()))
@@ -469,6 +470,42 @@ async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) {
469 } 470 }
470} 471}
471 472
473pub async fn do_first_sync(client: Client, store: &AsyncProgramStore) {
474 // Perform an initial, lazily-loaded sync.
475 let mut room = RoomEventFilter::default();
476 room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
477
478 let mut room_ev = RoomFilter::default();
479 room_ev.state = room;
480
481 let mut filter = FilterDefinition::default();
482 filter.room = room_ev;
483
484 let settings = SyncSettings::new().filter(filter.into());
485
486 if let Err(e) = client.sync_once(settings).await {
487 tracing::error!(err = e.to_string(), "Failed to perform initial sync; will retry later");
488 return;
489 }
490
491 // Populate sync_info with our initial set of rooms/dms/spaces.
492 refresh_rooms(&client, store).await;
493
494 // Insert Need::Messages to fetch accurate recent timestamps in the background.
495 let mut locked = store.lock().await;
496 let ChatStore { sync_info, need_load, .. } = &mut locked.application;
497
498 for room in sync_info.rooms.iter() {
499 let room_id = room.as_ref().0.room_id().to_owned();
500 need_load.insert(room_id, Need::MESSAGES);
501 }
502
503 for room in sync_info.dms.iter() {
504 let room_id = room.as_ref().0.room_id().to_owned();
505 need_load.insert(room_id, Need::MESSAGES);
506 }
507}
508
472#[derive(Debug)] 509#[derive(Debug)]
473pub enum LoginStyle { 510pub enum LoginStyle {
474 SessionRestore(Session), 511 SessionRestore(Session),