1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use std::{collections::BTreeMap, sync::Arc};
use matrix_sdk::{
room::RoomMemberRole,
ruma::{
OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId, events::room::member::MembershipState,
},
};
use matrix_sdk_ui::{eyeball_im::Vector, timeline::TimelineItem};
use serde::Serialize;
use tokio::sync::oneshot;
use tracing::{debug, error, trace, warn};
use crate::{
events::timeline::{
PaginationDirection, TIMELINE_STATES, TimelineEndpoints, TimelineKind, TimelineUiState,
TimelineUpdate, take_timeline_endpoints,
},
models::{
async_requests::{MatrixRequest, submit_async_request},
events::{ToastNotificationRequest, ToastNotificationVariant},
state_updater::StateUpdater,
},
room::notifications::enqueue_toast_notification,
user::user_power_level::{FrontendUserPowerLevel, UserPowerLevels},
utils::room_name_or_id,
};
/// A serializable struct representing the state of a given Matrix Room.
/// Fields are not exposed to the adapter directly, the adapter can only serialize this struct.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RoomScreen {
/// The timeline currently displayed by this RoomScreen, if any.
timeline_kind: Option<TimelineKind>,
/// The display name of the currently-shown room.
room_name: String,
/// The persistent UI-relevant states for the room that this widget is currently displaying.
tl_state: Option<TimelineUiState>,
/// Known members of this room
members: BTreeMap<OwnedUserId, FrontendRoomMember>,
/// The set of pinned events in this room.
pinned_events: Vec<OwnedEventId>,
/// Whether this room has been successfully loaded (received from the homeserver).
is_loaded: bool,
/// Whether or not all rooms have been loaded (received from the homeserver).
all_rooms_loaded: bool,
/// The state updater passed by the adapter
#[serde(skip)]
state_updaters: Arc<Box<dyn StateUpdater>>,
}
impl Drop for RoomScreen {
fn drop(&mut self) {
// This ensures that the `TimelineUiState` instance owned by this room is *always* returned
// back to to `TIMELINE_STATES`, which ensures that its UI state(s) are not lost
// and that other RoomScreen instances can show this room in the future.
// RoomScreen will be dropped whenever its widget instance is destroyed, e.g.,
// when a Tab is closed or the app is resized to a different AdaptiveView layout.
self.hide_timeline();
}
}
impl RoomScreen {
pub fn new(
updaters: Arc<Box<dyn StateUpdater>>,
timeline_kind: Option<TimelineKind>,
room_name: String,
) -> Self {
Self {
timeline_kind,
room_name,
tl_state: None,
members: BTreeMap::new(),
all_rooms_loaded: false,
is_loaded: false,
pinned_events: Vec::new(),
state_updaters: updaters,
}
}
fn update_frontend_state(&self) {
if let Err(e) = self.state_updaters.update_room(self) {
enqueue_toast_notification(ToastNotificationRequest::new(
format!(
"Cannot update room state for room {}. Error: {e}",
self.room_name
),
None,
ToastNotificationVariant::Error,
))
}
}
/// Processes all pending background updates to the currently-shown timeline.
pub fn process_timeline_updates(&mut self) {
let curr_first_id: usize = 0; // TODO: replace this dummy value
let mut _typing_users = None;
let Some(tl) = self.tl_state.as_mut() else {
return;
};
let mut should_continue_backwards_pagination = false;
let mut num_updates = 0;
while let Ok(update) = tl.update_receiver.try_recv() {
num_updates += 1;
match update {
TimelineUpdate::FirstUpdate { initial_items } => {
tl.fully_paginated = false;
tl.items = initial_items;
self.is_loaded = true;
}
TimelineUpdate::NewItems {
new_items,
clear_cache,
} => {
if new_items.is_empty() && !tl.items.is_empty() {
trace!(
"Timeline::handle_event(): timeline (had {} items) was cleared for room {}",
tl.items.len(),
tl.kind.room_id()
);
// For now, we paginate a cleared timeline in order to be able to show something at least.
// A proper solution would be what's described below, which would be to save a few event IDs
// and then either focus on them (if we're not close to the end of the timeline)
// or paginate backwards until we find them (only if we are close the end of the timeline).
should_continue_backwards_pagination = true;
}
if new_items.len() == tl.items.len() {
trace!(
"Timeline::handle_event(): no jump necessary for updated timeline of same length: {}",
tl.items.len()
);
} else if curr_first_id > new_items.len() {
trace!(
"Timeline::handle_event(): jumping to bottom: curr_first_id {} is out of bounds for {} new items",
curr_first_id,
new_items.len()
);
} else if let Some((curr_item_idx, new_item_idx, new_item_scroll, _event_id)) =
find_new_item_matching_current_item(
0,
Some(0.0), // TODO replace
curr_first_id,
&tl.items,
&new_items,
)
{
if curr_item_idx != new_item_idx {
trace!(
"Timeline::handle_event(): jumping view from event index {curr_item_idx} to new index {new_item_idx}, scroll {new_item_scroll}, event ID {_event_id}"
);
// Set scrolled_past_read_marker false when we jump to a new event
tl.scrolled_past_read_marker = false;
}
}
//
// TODO: after an (un)ignore user event, all timelines are cleared. Handle that here.
//
else {
// warn!("!!! Couldn't find new event with matching ID for ANY event currently visible in the portal list");
}
if clear_cache {
tl.fully_paginated = false;
}
tl.items = new_items;
self.is_loaded = true;
}
TimelineUpdate::NewUnreadMessagesCount(_unread_messages_count) => {
// jump_to_bottom.show_unread_message_badge(unread_messages_count);
}
TimelineUpdate::TargetEventFound {
target_event_id,
index,
} => {
// trace!("Target event found in room {}: {target_event_id}, index: {index}", tl.room_id);
tl.request_sender.send_if_modified(|requests| {
requests.retain(|r| r.room_id != *tl.kind.room_id());
// no need to notify/wake-up all receivers for a completed request
false
});
// sanity check: ensure the target event is in the timeline at the given `index`.
let item = tl.items.get(index);
let is_valid = item.is_some_and(|item| {
item.as_event()
.is_some_and(|ev| ev.event_id() == Some(&target_event_id))
});
trace!(
"TargetEventFound: is_valid? {is_valid}. room {}, event {target_event_id}, index {index} of {}\n --> item: {item:?}",
tl.kind.room_id(),
tl.items.len()
);
if is_valid {
} else {
// Here, the target event was not found in the current timeline,
// or we found it previously but it is no longer in the timeline (or has moved),
// which means we encountered an error and are unable to jump to the target event.
warn!(
"Target event index {index} of {} is out of bounds for room {}",
tl.items.len(),
tl.kind.room_id()
);
}
should_continue_backwards_pagination = false;
}
TimelineUpdate::PaginationRunning(direction) => {
trace!(
"Pagination running in room {} in {direction} direction",
tl.kind.room_id()
);
if direction == PaginationDirection::Backwards {
self.is_loaded = false;
} else {
warn!("Unexpected PaginationRunning update in the Forwards direction");
}
}
TimelineUpdate::PaginationError { error, direction } => {
error!(
"Pagination error ({direction}) in room {}: {error:?}",
tl.kind.room_id()
);
self.is_loaded = true;
}
TimelineUpdate::PaginationIdle {
fully_paginated,
direction,
} => {
if direction == PaginationDirection::Backwards {
// Don't set `done_loading` to `true`` here, because we want to keep the top space visible
// (with the "loading" message) until the corresponding `NewItems` update is received.
tl.fully_paginated = fully_paginated;
if fully_paginated {
self.is_loaded = true;
}
} else {
warn!("Unexpected PaginationIdle update in the Forwards direction");
}
}
TimelineUpdate::EventDetailsFetched { event_id, result } => {
if let Err(_e) = result {
warn!(
"Failed to fetch details fetched for event {event_id} in room {}. Error: {_e:?}",
tl.kind.room_id()
);
}
// Here, to be most efficient, we could redraw only the updated event,
// but for now we just fall through and let the final `redraw()` call re-draw the whole timeline view.
}
TimelineUpdate::RoomMembersSynced => {
trace!(
"Timeline::handle_event(): room members fetched for room {}",
tl.kind.room_id()
);
// Here, to be most efficient, we could redraw only the user avatars and names in the timeline,
// but for now we just fall through and let the final `redraw()` call re-draw the whole timeline view.
}
TimelineUpdate::RoomMembersListFetched { members } => {
debug!("RoomMembers list fetched !");
// We clear the map before so we're sure there aren't
// any members at previous membership state.
self.members.clear();
members.iter().for_each(|member| {
self.members.insert(
member.user_id().to_owned(),
FrontendRoomMember {
name: member.name().to_owned(),
display_name_ambiguous: member.name_ambiguous(),
is_ignored: member.is_ignored(),
max_power_level: member.normalized_power_level().into(),
avatar: member.avatar_url().map(|u| u.to_owned()),
role: member.suggested_role_for_power_level().into(),
membership: member.membership().to_owned(),
},
);
});
debug!("{:?}", self.members);
}
TimelineUpdate::_MediaFetched => {
trace!(
"Timeline::handle_event(): media fetched for room {}",
tl.kind.room_id()
);
// Here, to be most efficient, we could redraw only the media items in the timeline,
// but for now we just fall through and let the final `redraw()` call re-draw the whole timeline view.
}
TimelineUpdate::MessageEdited {
timeline_event_item_id: timeline_event_id,
result,
} => {
if result.is_ok() {
enqueue_toast_notification(ToastNotificationRequest::new(
"Successfully edited message.".to_owned(),
None,
ToastNotificationVariant::Success,
));
} else {
error!("Error editing event with id {timeline_event_id:?}");
enqueue_toast_notification(ToastNotificationRequest::new(
"Error while editing event.".to_owned(),
None,
ToastNotificationVariant::Error,
));
}
}
TimelineUpdate::TypingUsers { users } => {
// TODO: USE THIS
_typing_users = Some(users);
}
TimelineUpdate::UserPowerLevels(user_power_level) => {
tl.user_power = user_power_level;
}
TimelineUpdate::OwnUserReadReceipt(receipt) => {
tl.latest_own_user_receipt = Some(receipt);
}
}
}
if should_continue_backwards_pagination {
trace!("Continuing backwards pagination...");
submit_async_request(MatrixRequest::PaginateTimeline {
timeline_kind: tl.kind.clone(),
num_events: 50,
direction: PaginationDirection::Backwards,
});
}
if num_updates > 0 {
debug!(
"Applied {} timeline updates for room {}, redrawing with {} items...",
num_updates,
tl.kind.room_id(),
tl.items.len()
);
self.update_frontend_state();
}
}
/// Invoke this when this timeline is being shown,
/// e.g., when the user navigates to this timeline.
pub fn show_timeline(&mut self) {
let kind = self
.timeline_kind
.clone()
.expect("BUG: Timeline::show_timeline(): no timeline_kind was set.");
let room_id = kind.room_id().clone();
// just an optional sanity check
assert!(
self.tl_state.is_none(),
"BUG: tried to show_timeline() into a timeline with existing state. \
Did you forget to save the timeline state back to the global map of states?",
);
let state_opt = {
let mut lock = TIMELINE_STATES.lock().unwrap();
lock.remove(&kind)
};
let (tl_state, first_time_showing_room) = if let Some(existing) = state_opt {
(existing, false)
} else {
// This part differs a bit from robrix. Here we wait for
// the thread timeline to be built before proceeding.
let timeline_endpoints = match take_timeline_endpoints(&kind) {
Some(te) => te,
None if let Some(thread_root) = kind.thread_root_event_id() => {
let (tx, rx) = oneshot::channel();
submit_async_request(MatrixRequest::CreateThreadTimeline {
room_id: room_id.clone(),
thread_root_event_id: thread_root.clone(),
sender: tx,
});
match futures::executor::block_on(rx) {
Ok(_) => take_timeline_endpoints(&kind).expect("msg"),
Err(e) => {
warn!("Timeline hasn't been created. {e}");
return;
}
}
}
None if !self.is_loaded && self.all_rooms_loaded => panic!(
"BUG: timeline {kind} is not loaded, but its RoomScreen \
was not waiting for its timeline to be loaded either."
),
None => return,
};
let TimelineEndpoints {
update_receiver,
_update_sender: _,
request_sender,
_successor_room: _,
} = timeline_endpoints;
// Start with the basic tombstone info, and fetch the full details
// if the room has been tombstoned.
// let tombstone_info = if let Some(sr) = successor_room {
// submit_async_request(MatrixRequest::GetSuccessorRoomDetails {
// tombstoned_room_id: room_id.clone(),
// });
// Some(SuccessorRoomDetails::Basic(sr))
// } else {
// None
// };
let tl_state = TimelineUiState {
kind,
// Initially, we assume the user has all power levels by default.
// This avoids unexpectedly hiding any UI elements that should be visible to the user.
// This doesn't mean that the user can actually perform all actions;
// the power levels will be updated from the homeserver once the room is opened.
user_power: UserPowerLevels::all(),
// Room members start as None and get populated when fetched from the server
// We assume timelines being viewed for the first time haven't been fully paginated.
fully_paginated: false,
items: Vector::new(),
update_receiver,
request_sender,
scrolled_past_read_marker: false,
latest_own_user_receipt: None,
};
(tl_state, true)
};
// TODO: support typing notices in frontend
// Subscribe to typing notices, but hide the typing notice view initially.
// submit_async_request(MatrixRequest::SubscribeToTypingNotices {
// room_id: room_id.clone(),
// subscribe: true,
// });
submit_async_request(MatrixRequest::SubscribeToOwnUserReadReceiptsChanged {
timeline_kind: tl_state.kind.clone(),
subscribe: true,
});
// Kick off a back pagination request for this room. This is "urgent",
// because we want to show the user some messages as soon as possible
// when they first open the room, and there might not be any messages yet.
if first_time_showing_room && !tl_state.fully_paginated {
debug!(
"Sending a first-time backwards pagination request for room {}",
room_id
);
submit_async_request(MatrixRequest::PaginateTimeline {
timeline_kind: tl_state.kind.clone(),
num_events: 50,
direction: PaginationDirection::Backwards,
});
}
// This fetches the room members of the displayed timeline.
submit_async_request(MatrixRequest::SyncRoomMemberList {
timeline_kind: tl_state.kind.clone(),
});
// As the final step, store the tl_state for this room into this RoomScreen widget,
// such that it can be accessed in future event/draw handlers.
self.tl_state = Some(tl_state);
// Now that we have restored the TimelineUiState into this RoomScreen widget,
// we can proceed to processing pending background updates, and if any were processed,
// the timeline will also be redrawn.
if first_time_showing_room {
self.process_timeline_updates();
}
self.update_frontend_state();
}
/// Invoke this when this RoomScreen/timeline is being hidden or no longer being shown.
fn hide_timeline(&mut self) {
let Some(timeline_kind) = self.timeline_kind.clone() else {
return;
};
self.save_state();
// When closing a room view, we do the following with non-persistent states.
// (This should be the inverse of what's done in `show_timeline()`.)
// * Unsubscribe from typing notices, since we don't care about them
// when a given room isn't visible.
// * Unsubscribe from updates to this room's pinned events, for the same reason.
// * Unsubscribe from updates to our own user's read receipts, for the same reason.
if matches!(timeline_kind, TimelineKind::MainRoom { .. }) {
submit_async_request(MatrixRequest::SubscribeToTypingNotices {
room_id: timeline_kind.room_id().clone(),
subscribe: false,
});
// submit_async_request(MatrixRequest::SubscribeToPinnedEvents {
// room_id: timeline_kind.room_id().clone(),
// subscribe: false,
// });
}
submit_async_request(MatrixRequest::SubscribeToOwnUserReadReceiptsChanged {
timeline_kind,
subscribe: false,
});
}
/// Removes the current room's visual UI state from this widget
/// and saves it to the map of `TIMELINE_STATES` such that it can be restored later.
///
/// Note: after calling this function, the widget's `tl_state` will be `None`.
fn save_state(&mut self) {
let Some(tl) = self.tl_state.take() else {
warn!(
"Timeline::save_state(): skipping due to missing state, room {:?}",
self.timeline_kind
);
return;
};
// Store this Timeline's `TimelineUiState` in the global map of states.
TIMELINE_STATES.lock().unwrap().insert(tl.kind.clone(), tl);
}
/// Sets this `RoomScreen` widget to display the timeline for the given room.
pub fn set_displayed_room(
&mut self,
room_id: OwnedRoomId,
room_name: String,
thread_root_event_id: Option<OwnedEventId>,
) {
let timeline_kind = if let Some(thread_root_event_id) = thread_root_event_id {
TimelineKind::Thread {
room_id: room_id.clone(),
thread_root_event_id,
}
} else {
TimelineKind::MainRoom {
room_id: room_id.clone(),
}
};
// If this timeline is already displayed, we don't need to do anything major,
// but we do need update the `room_name_id` in case it has changed, or it has been cleared.
if self
.timeline_kind
.as_ref()
.is_some_and(|kind| kind == &timeline_kind)
{
self.room_name = room_name;
return;
}
self.hide_timeline();
self.timeline_kind = Some(timeline_kind.clone());
self.room_name = room_name_or_id(room_name.into(), &room_id);
self.show_timeline();
}
}
/// Returns info about the item in the list of `new_items` that matches the event ID
/// of a visible item in the given `curr_items` list.
///
/// This info includes a tuple of:
/// 1. the index of the item in the current items list,
/// 2. the index of the item in the new items list,
/// 3. the positional "scroll" offset of the corresponding current item in the portal list,
/// 4. the unique event ID of the item.
fn find_new_item_matching_current_item(
visible_items: usize, // DUMMY PARAM TODO CHANGE THIS
position_of_item: Option<f64>, // DUMMY PARAM TODO CHANGE THIS
starting_at_curr_idx: usize,
curr_items: &Vector<Arc<TimelineItem>>,
new_items: &Vector<Arc<TimelineItem>>,
) -> Option<(usize, usize, f64, OwnedEventId)> {
let mut curr_item_focus = curr_items.focus();
let mut idx_curr = starting_at_curr_idx;
let mut curr_items_with_ids: Vec<(usize, OwnedEventId)> = Vec::with_capacity(visible_items);
// Find all items with real event IDs that are currently visible in the portal list.
// TODO: if this is slow, we could limit it to 3-5 events at the most.
if curr_items_with_ids.len() <= visible_items {
while let Some(curr_item) = curr_item_focus.get(idx_curr) {
if let Some(event_id) = curr_item.as_event().and_then(|ev| ev.event_id()) {
curr_items_with_ids.push((idx_curr, event_id.to_owned()));
}
if curr_items_with_ids.len() >= visible_items {
break;
}
idx_curr += 1;
}
}
// Find a new item that has the same real event ID as any of the current items.
for (idx_new, new_item) in new_items.iter().enumerate() {
let Some(event_id) = new_item.as_event().and_then(|ev| ev.event_id()) else {
continue;
};
if let Some((idx_curr, _)) = curr_items_with_ids
.iter()
.find(|(_, ev_id)| ev_id == event_id)
{
// Not all items in the portal list are guaranteed to have a position offset,
// some may be zeroed-out, so we need to account for that possibility by only
// using events that have a real non-zero area
if let Some(pos_offset) = position_of_item {
trace!(
"Found matching event ID {event_id} at index {idx_new} in new items list, corresponding to current item index {idx_curr} at pos offset {pos_offset}"
);
return Some((*idx_curr, idx_new, pos_offset, event_id.to_owned()));
}
}
}
None
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FrontendRoomMember {
name: String,
// This looks shitty but we cannot use serde flatten and ts_rs type together
max_power_level: FrontendUserPowerLevel,
display_name_ambiguous: bool,
is_ignored: bool,
avatar: Option<OwnedMxcUri>,
role: FrontendRoomMemberRole,
membership: MembershipState,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all_fields = "camelCase", rename_all = "camelCase")]
/// Same as RoomMemberRole with Serialize
pub enum FrontendRoomMemberRole {
/// The member is a creator.
///
/// A creator has an infinite power level and cannot be demoted, so this
/// role is immutable. A room can have several creators.
///
/// It is available in room versions where
/// `explicitly_privilege_room_creators` in [`AuthorizationRules`] is set to
/// `true`.
///
/// [`AuthorizationRules`]: ruma::room_version_rules::AuthorizationRules
Creator,
/// The member is an administrator.
Administrator,
/// The member is a moderator.
Moderator,
/// The member is a regular user.
User,
}
impl From<RoomMemberRole> for FrontendRoomMemberRole {
fn from(value: RoomMemberRole) -> Self {
match value {
RoomMemberRole::Creator => Self::Creator,
RoomMemberRole::Administrator => Self::Administrator,
RoomMemberRole::Moderator => Self::Moderator,
RoomMemberRole::User => Self::User,
}
}
}