-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathroom_screen.rs
More file actions
1773 lines (1608 loc) · 74.2 KB
/
room_screen.rs
File metadata and controls
1773 lines (1608 loc) · 74.2 KB
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A room screen is the UI page that displays a single Room's timeline of events/messages
//! along with a message input bar at the bottom.
use std::{borrow::Cow, collections::BTreeMap, ops::{DerefMut, Range}, sync::{Arc, Mutex}};
use imbl::Vector;
use makepad_widgets::*;
use matrix_sdk::ruma::{
events::{
room::{
guest_access::GuestAccess,
history_visibility::HistoryVisibility,
join_rules::JoinRule, message::{MessageFormat, MessageType, RoomMessageEventContent}, MediaSource,
}, AnySyncMessageLikeEvent, AnySyncTimelineEvent, FullStateEventContent, SyncMessageLikeEvent
}, uint, MilliSecondsSinceUnixEpoch, OwnedRoomId, RoomId,
};
use matrix_sdk_ui::timeline::{
self, AnyOtherFullStateEventContent, BundledReactions, EventTimelineItem, MemberProfileChange, MembershipChange, RoomMembershipChange, TimelineDetails, TimelineItem, TimelineItemContent, TimelineItemKind, VirtualTimelineItem
};
use rangemap::RangeSet;
use crate::{
media_cache::{MediaCache, MediaCacheEntry, AVATAR_CACHE},
profile::user_profile::{ShowUserProfileAction, UserProfileInfo, UserProfileSlidingPaneWidgetExt},
shared::{avatar::{AvatarRef, AvatarWidgetRefExt}, html_or_plaintext::HtmlOrPlaintextWidgetRefExt, text_or_image::TextOrImageWidgetRefExt},
sliding_sync::{submit_async_request, take_timeline_update_receiver, MatrixRequest},
utils::{self, unix_time_millis_to_datetime, MediaFormatConst},
};
live_design! {
import makepad_draw::shader::std::*;
import makepad_widgets::base::*;
import makepad_widgets::theme_desktop_dark::*;
import crate::shared::styles::*;
import crate::shared::helpers::*;
import crate::shared::search_bar::SearchBar;
import crate::shared::avatar::Avatar;
import crate::shared::text_or_image::TextOrImage;
import crate::shared::html_or_plaintext::*;
import crate::profile::user_profile::UserProfileSlidingPane;
IMG_DEFAULT_AVATAR = dep("crate://self/resources/img/default_avatar.png")
ICO_FAV = dep("crate://self/resources/icon_favorite.svg")
ICO_COMMENT = dep("crate://self/resources/icon_comment.svg")
ICO_REPLY = dep("crate://self/resources/icon_reply.svg")
ICO_SEND = dep("crate://self/resources/icon_send.svg")
ICO_LIKES = dep("crate://self/resources/icon_likes.svg")
ICO_USER = dep("crate://self/resources/icon_user.svg")
ICO_ADD = dep("crate://self/resources/icon_add.svg")
TEXT_SUB = {
font_size: (10),
font: {path: dep("crate://makepad-widgets/resources/GoNotoKurrent-Regular.ttf")}
}
TEXT_P = {
font_size: (12),
height_factor: 1.65,
font: {path: dep("crate://makepad-widgets/resources/GoNotoKurrent-Regular.ttf")}
}
COLOR_BG = #xfff8ee
COLOR_BRAND = #xf88
COLOR_BRAND_HOVER = #xf66
COLOR_META_TEXT = #xaaa
COLOR_META = #xccc
COLOR_META_INV = #xfffa
COLOR_OVERLAY_BG = #x000000d8
COLOR_READ_MARKER = #xeb2733
COLOR_PROFILE_CIRCLE = #xfff8ee
FillerY = <View> {width: Fill}
FillerX = <View> {height: Fill}
IconButton = <Button> {
draw_text: {
instance hover: 0.0
instance pressed: 0.0
text_style: {
font_size: 11.0
}
fn get_color(self) -> vec4 {
return mix(
mix(
(COLOR_META_TEXT),
(COLOR_BRAND),
self.hover
),
(COLOR_BRAND_HOVER),
self.pressed
)
}
}
draw_icon: {
svg_file: (ICO_FAV),
fn get_color(self) -> vec4 {
return mix(
mix(
(COLOR_META),
(COLOR_BRAND),
self.hover
),
(COLOR_BRAND_HOVER),
self.pressed
)
}
}
icon_walk: {width: 7.5, height: Fit, margin: {left: 5.0}}
draw_bg: {
fn pixel(self) -> vec4 {
let sdf = Sdf2d::viewport(self.pos * self.rect_size);
return sdf.result
}
}
padding: 9.0
text: ""
}
Timestamp = <Label> {
padding: { top: 10.0, bottom: 0.0, left: 0.0, right: 0.0 }
draw_text: {
text_style: <TIMESTAMP_TEXT_STYLE> {},
color: (TIMESTAMP_TEXT_COLOR)
}
text: " "
}
REACTION_TEXT_COLOR = #4c00b0
MessageMenu = <View> {
visible: false,
width: Fill,
height: Fit,
// TODO: use a set of Buttons later, so a user can click to add their own reaction.
annotations = <RobrixHtml> {
width: Fill,
height: Fit,
padding: {top: 7.5, bottom: 5.0 },
font_size: 10.5,
draw_normal: { color: (REACTION_TEXT_COLOR) },
draw_italic: { color: (REACTION_TEXT_COLOR) },
draw_bold: { color: (REACTION_TEXT_COLOR) },
draw_bold_italic: { color: (REACTION_TEXT_COLOR) },
draw_fixed: { color: (REACTION_TEXT_COLOR) },
body: ""
}
}
// An empty view that takes up no space in the portal list.
Empty = <View> { }
// The view used for each text-based message event in a room's timeline.
Message = <View> {
width: Fill,
height: Fit,
margin: 0.0
flow: Down,
padding: 0.0,
spacing: 0.0
body = <View> {
width: Fill,
height: Fit
flow: Right,
padding: 10.0,
spacing: 10.0
profile = <View> {
align: {x: 0.5, y: 0.0} // centered horizontally, top aligned
width: 65.0,
height: Fit,
margin: {top: 7.5}
flow: Down,
avatar = <Avatar> {
width: 50.,
height: 50.
// draw_bg: {
// fn pixel(self) -> vec4 {
// let sdf = Sdf2d::viewport(self.pos * self.rect_size);
// let c = self.rect_size * 0.5;
// sdf.circle(c.x, c.y, c.x - 2.)
// sdf.fill_keep(self.get_color());
// sdf.stroke((COLOR_PROFILE_CIRCLE), 1);
// return sdf.result
// }
// }
}
timestamp = <Timestamp> { }
datestamp = <Timestamp> {
padding: { top: 5.0 }
}
}
content = <View> {
width: Fill,
height: Fit
flow: Down,
padding: 0.0
username = <Label> {
width: Fill,
margin: {bottom: 10.0, top: 10.0, right: 10.0,}
draw_text: {
text_style: <USERNAME_TEXT_STYLE> {},
color: (USERNAME_TEXT_COLOR)
wrap: Ellipsis,
}
text: "<Username not available>"
}
message = <HtmlOrPlaintext> { }
// <LineH> {
// margin: {top: 13.0, bottom: 5.0}
// }
message_menu = <MessageMenu> {}
}
}
}
// The view used for a condensed message that came right after another message
// from the same sender, and thus doesn't need to display the sender's profile again.
CondensedMessage = <Message> {
padding: { top: 2.0, bottom: 2.0 }
body = {
padding: { top: 5.0, bottom: 5.0, left: 10.0, right: 10.0 },
profile = <View> {
align: {x: 0.5, y: 0.0} // centered horizontally, top aligned
width: 65.0,
height: Fit,
flow: Down,
timestamp = <Timestamp> { padding: {top: 3.0} }
}
content = <View> {
width: Fill,
height: Fit,
flow: Down,
message = <HtmlOrPlaintext> { }
message_menu = <MessageMenu> {}
}
}
}
// The view used for each static image-based message event in a room's timeline.
// This excludes stickers and other animated GIFs, video clips, audio clips, etc.
ImageMessage = <Message> {
body = {
content = {
message = <TextOrImage> {
width: Fill, height: 300,
image_view = { image = { fit: Horizontal } }
}
message_menu = <MessageMenu> {}
}
}
}
// The view used for a condensed image message that came right after another message
// from the same sender, and thus doesn't need to display the sender's profile again.
// This excludes stickers and other animated GIFs, video clips, audio clips, etc.
CondensedImageMessage = <CondensedMessage> {
body = {
content = {
message = <TextOrImage> {
width: Fill, height: 300,
image_view = { image = { fit: Horizontal } }
}
message_menu = <MessageMenu> {}
}
}
}
// The view used for each state event (non-messages) in a room's timeline.
// The timestamp, profile picture, and text are all very small.
SmallStateEvent = <View> {
width: Fill,
height: Fit,
margin: 0.0
flow: Right,
padding: { top: 1.0, bottom: 1.0 }
spacing: 0.0
body = <View> {
width: Fill,
height: Fit
flow: Right,
padding: { top: 2.0, bottom: 2.0 }
spacing: 5.0
left_container = <View> {
align: {x: 0.5, y: 0.0} // centered horizontally, top aligned
width: 70.0,
height: Fit
flow: Right,
timestamp = <Timestamp> {
padding: {top: 5.0}
draw_text: {
text_style: <TIMESTAMP_TEXT_STYLE> {},
color: (TIMESTAMP_TEXT_COLOR)
}
}
}
avatar = <Avatar> {
width: 19.,
height: 19.,
text_view = { text = { draw_text: {
text_style: <TITLE_TEXT>{ font_size: 7. }
}}}
}
content = <Label> {
width: Fill,
height: Fit
padding: {top: 5.0},
draw_text: {
wrap: Word,
text_style: <SMALL_STATE_TEXT_STYLE> {},
color: (SMALL_STATE_TEXT_COLOR)
}
text: ""
}
}
}
// The view used for each day divider in a room's timeline.
// The date text is centered between two horizontal lines.
DayDivider = <View> {
width: Fill,
height: Fit,
margin: 0.0,
flow: Right,
padding: 0.0,
spacing: 0.0,
align: {x: 0.5, y: 0.5} // center horizontally and vertically
left_line = <LineH> {
margin: {top: 10.0, bottom: 10.0}
draw_bg: {color: (COLOR_DIVIDER_DARK)}
}
date = <Label> {
padding: {left: 7.0, right: 7.0}
margin: {bottom: 10.0, top: 10.0}
draw_text: {
text_style: <TEXT_SUB> {},
color: (COLOR_DIVIDER_DARK)
}
text: "<date>"
}
right_line = <LineH> {
margin: {top: 10.0, bottom: 10.0}
draw_bg: {color: (COLOR_DIVIDER_DARK)}
}
}
// The view used for the divider indicating where the user's last-viewed message is.
// This is implemented as a DayDivider with a different color and a fixed text label.
ReadMarker = <DayDivider> {
left_line = {
draw_bg: {color: (COLOR_READ_MARKER)}
}
date = {
draw_text: {
color: (COLOR_READ_MARKER)
}
text: "New Messages"
}
right_line = {
draw_bg: {color: (COLOR_READ_MARKER)}
}
}
// The top space is used to display a loading animation while the room is being paginated.
TopSpace = <View> {
width: Fill,
height: 0.0,
label = <Label> {
text: "Loading..."
}
}
Timeline = {{Timeline}} {
width: Fill,
height: Fill,
align: {x: 0.5, y: 0.0} // center horizontally, align to top vertically
list = <PortalList> {
auto_tail: true, // set to `true` to lock the view to the last item.
height: Fill,
width: Fill
flow: Down
// Below, we must place all of the possible templates (views) that can be used in the portal list.
TopSpace = <TopSpace> {}
Message = <Message> {}
CondensedMessage = <CondensedMessage> {}
ImageMessage = <ImageMessage> {}
CondensedImageMessage = <CondensedImageMessage> {}
SmallStateEvent = <SmallStateEvent> {}
Empty = <Empty> {}
DayDivider = <DayDivider> {}
ReadMarker = <ReadMarker> {}
}
}
IMG_SMILEY_FACE_BW = dep("crate://self/resources/img/smiley_face_bw.png")
IMG_PLUS = dep("crate://self/resources/img/plus.png")
IMG_KEYBOARD_ICON = dep("crate://self/resources/img/keyboard_icon.png")
RoomScreen = {{RoomScreen}} {
width: Fill, height: Fill,
show_bg: true,
draw_bg: {
color: #fff
}
<View> {
width: Fill, height: Fill,
flow: Overlay,
<KeyboardView> {
width: Fill, height: Fill,
flow: Down,
// First, display the timeline of all messages/events.
timeline = <Timeline> {}
// Below that, display a view that holds the message input bar.
<View> {
width: Fill, height: Fit
flow: Right, align: {y: 1.0}, padding: 10.
show_bg: true,
draw_bg: {
color: #fff
}
message_input = <TextInput> {
width: Fill, height: Fit, margin: 0
align: {y: 0.5}
empty_message: "Write a message (in Markdown) ..."
draw_bg: {
color: #F9F9F9
}
draw_text: {
color: (MESSAGE_TEXT_COLOR),
text_style: <MESSAGE_TEXT_STYLE>{},
fn get_color(self) -> vec4 {
return mix(
mix(
mix(
#xFFFFFF55,
#xFFFFFF88,
self.hover
),
self.color,
self.focus
),
#BBBBBB,
self.is_empty
)
}
}
// TODO find a way to override colors
draw_cursor: {
instance focus: 0.0
uniform border_radius: 0.5
fn pixel(self) -> vec4 {
let sdf = Sdf2d::viewport(self.pos * self.rect_size);
sdf.box(
0.,
0.,
self.rect_size.x,
self.rect_size.y,
self.border_radius
)
sdf.fill(mix(#0f0, #0b0, self.focus));
return sdf.result
}
}
// TODO find a way to override colors
draw_select: {
instance hover: 0.0
instance focus: 0.0
uniform border_radius: 2.0
fn pixel(self) -> vec4 {
let sdf = Sdf2d::viewport(self.pos * self.rect_size);
sdf.box(
0.,
0.,
self.rect_size.x,
self.rect_size.y,
self.border_radius
)
sdf.fill(mix(#0e0, #0d0, self.focus)); // Pad color
return sdf.result
}
}
}
// <Image> {
// source: (IMG_SMILEY_FACE_BW),
// width: 36., height: 36.
// }
// <Image> {
// source: (IMG_PLUS),
// width: 36., height: 36.
// }
send_message_button = <IconButton> {
draw_icon: {svg_file: (ICO_SEND)},
icon_walk: {width: 15.0, height: Fit},
}
}
}
<View> {
width: Fill,
height: Fill,
align: { x: 1.0 },
flow: Right,
user_profile_sliding_pane = <UserProfileSlidingPane> { }
}
}
}
}
/// A simple deref wrapper around the `RoomScreen` widget that enables us to handle its events.
#[derive(Live, LiveHook, Widget)]
struct RoomScreen {
#[deref] view: View,
#[rust] room_id: Option<OwnedRoomId>,
#[rust] room_name: String,
}
impl Widget for RoomScreen {
fn draw_walk(&mut self, cx: &mut Cx2d, scope: &mut Scope, walk: Walk) -> DrawStep {
self.view.draw_walk(cx, scope, walk)
}
// Handle events and actions at the RoomScreen level.
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope){
let pane = self.user_profile_sliding_pane(id!(user_profile_sliding_pane));
if let Event::Actions(actions) = event {
// Handle the send message button being clicked.
if self.button(id!(send_message_button)).clicked(&actions) {
let msg_input_widget = self.text_input(id!(message_input));
let entered_text = msg_input_widget.text();
msg_input_widget.set_text_and_redraw(cx, "");
if !entered_text.is_empty() {
let room_id = self.room_id.clone().unwrap();
log!("Sending message to room {}: {:?}", room_id, entered_text);
let message = if let Some(html_text) = entered_text.strip_prefix("/html") {
RoomMessageEventContent::text_html(html_text, html_text)
} else if let Some(plain_text) = entered_text.strip_prefix("/plain") {
RoomMessageEventContent::text_plain(plain_text)
} else {
RoomMessageEventContent::text_markdown(entered_text)
};
submit_async_request(MatrixRequest::SendMessage {
room_id,
message,
// TODO: support replies to specific messages, attaching mentions, rich text (html), etc.
});
}
}
for action in actions {
// Handle the action that requests to show the user profile sliding pane.
if let ShowUserProfileAction::ShowUserProfile(avatar_info) = action.as_widget_action().cast() {
pane.set_info(UserProfileInfo {
avatar_info,
room_name: self.room_name.clone(),
});
pane.show(cx);
// TODO: Hack for error that when you first open the modal, doesnt draw until an event
// this forces the entire ui to rerender, still weird that only happens the first time.
self.redraw(cx);
}
}
}
// Only forward visibility-related events (touch/tap/scroll) to the inner timeline view
// if the user profile sliding pane is not visible.
if event.requires_visibility() && pane.is_currently_shown(cx) {
// Forward the event to the user profile sliding pane,
// preventing the underlying timeline view from receiving it.
pane.handle_event(cx, event, scope);
} else {
// Forward the event to the inner timeline view.
self.view.handle_event(cx, event, scope);
}
}
}
impl RoomScreenRef {
/// Sets this `RoomScreen` widget to display the timeline for the given room.
pub fn set_displayed_room(&self, room_name: String, room_id: OwnedRoomId) {
let Some(mut room_screen) = self.borrow_mut() else { return };
room_screen.room_name = room_name;
room_screen.room_id = Some(room_id.clone());
room_screen.timeline(id!(timeline)).set_room(room_id);
}
}
/// A message that is sent from a background async task to a room's timeline view
/// for the purpose of update the Timeline UI contents or metadata.
pub enum TimelineUpdate {
/// The content of a room's timeline was updated in the background.
NewItems {
/// The entire list of timeline items (events) for a room.
items: Vector<Arc<TimelineItem>>,
/// The range of indices in the `items` list that have been changed in this update
/// and thus must be removed from any caches of drawn items in the timeline.
/// Any items outside of this range are assumed to be unchanged and need not be redrawn.
changed_indices: Range<usize>,
/// Whether to clear the entire cache of drawn items in the timeline.
/// This supercedes `index_of_first_change` and is used when the entire timeline is being redrawn.
clear_cache: bool,
},
/// A notice that the start of the timeline has been reached, meaning that
/// there is no need to send further backwards pagination requests.
TimelineStartReached,
/// A notice that the background task doing pagination for this room has become idle,
/// meaning that it has completed its recent pagination request(s) and is now waiting
/// for more requests, but that the start of the timeline has not yet been reached.
PaginationIdle,
/// A notice that the room's members have been fetched from the server,
/// though the success or failure of the request is not yet known until the client
/// requests the member info via a timeline event's `sender_profile()` method.
RoomMembersFetched,
/// A notice that one or more requested media items (images, videos, etc.)
/// that should be displayed in this timeline have now been fetched and are available.
MediaFetched,
}
/// A Timeline widget displays the list of events (timeline "items") for a room.
#[derive(Live, LiveHook, Widget)]
pub struct Timeline {
#[deref] view: View,
/// The room ID that this timeline is currently displaying.
#[rust] room_id: Option<OwnedRoomId>,
/// The UI-relevant states for the room that this widget is currently displaying.
#[rust] tl_state: Option<TimelineUiState>,
}
/// The global set of all timeline states, one entry per room.
static TIMELINE_STATES: Mutex<BTreeMap<OwnedRoomId, TimelineUiState>> = Mutex::new(BTreeMap::new());
/// The UI-side state of a single room's timeline, which is only accessed/updated by the UI thread.
struct TimelineUiState {
/// The ID of the room that this timeline is for.
room_id: OwnedRoomId,
/// Whether this room's timeline has been fully paginated, which means
/// that the oldest (first) event in the timeline is locally synced and available.
/// When `true`, further backwards pagination requests will not be sent.
fully_paginated: bool,
/// The list of items (events) in this room's timeline that our client currently knows about.
items: Vector<Arc<TimelineItem>>,
/// The range of items (indices in the above `items` list) whose event **contents** have been drawn
/// since the last update and thus do not need to be re-populated on future draw events.
///
/// This range is partially cleared on each background update (see below) to ensure that
/// items modified during the update are properly redrawn. Thus, it is a conservative
/// "cache tracker" that may not include all items that have already been drawn,
/// but that's okay because big updates that clear out large parts of the rangeset
/// only occur during back pagination, which is both rare and slow in and of itself.
/// During typical usage, new events are appended to the end of the timeline,
/// meaning that the range of already-drawn items doesn't need to be cleared.
///
/// Upon a background update, only item indices greater than or equal to the
/// `index_of_first_change` are removed from this set.
content_drawn_since_last_update: RangeSet<usize>,
/// Same as `content_drawn_since_last_update`, but for the event **profiles** (avatar, username).
profile_drawn_since_last_update: RangeSet<usize>,
/// The channel receiver for timeline updates for this room.
///
/// Here we use a synchronous (non-async) channel because the receiver runs
/// in a sync context and the sender runs in an async context,
/// which is okay because a sender on an unbounded channel never needs to block.
update_receiver: crossbeam_channel::Receiver<TimelineUpdate>,
/// The cache of media items (images, videos, etc.) that appear in this timeline.
///
/// Currently this excludes avatars, as those are shared across multiple rooms.
media_cache: MediaCache,
/// The states relevant to the UI display of this timeline that are saved upon
/// a `Hide` action and restored upon a `Show` action.
saved_state: SavedState,
}
/// States that are necessary to save in order to maintain a consistent UI display for a timeline.
///
/// These are saved when navigating away from a timeline (upon `Hide`)
/// and restored when navigating back to a timeline (upon `Show`).
#[derive(Default, Debug)]
struct SavedState {
/// The ID of the first item in the timeline's PortalList that is currently visible.
///
/// TODO: expose scroll position from PortalList and use that instead, which is more accurate.
first_id: usize,
}
impl Timeline {
/// Invoke this when this timeline is being shown,
/// e.g., when the user navigates to this timeline.
fn show_timeline(&mut self) {
let room_id = self.room_id.clone()
.expect("BUG: Timeline::show_timeline(): no room_id was set.");
assert!( // just an optional sanity check
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 (tl_state, first_time_showing_room) = if let Some(existing) = TIMELINE_STATES.lock().unwrap().remove(&room_id) {
(existing, false)
} else {
let (update_sender, update_receiver) = take_timeline_update_receiver(&room_id)
.expect("BUG: couldn't get timeline state for first-viewed room.");
let new_tl_state = TimelineUiState {
room_id: room_id.clone(),
// We assume timelines being viewed for the first time haven't been fully paginated.
fully_paginated: false,
items: Vector::new(),
content_drawn_since_last_update: RangeSet::new(),
profile_drawn_since_last_update: RangeSet::new(),
update_receiver,
media_cache: MediaCache::new(MediaFormatConst::File, Some(update_sender)),
saved_state: SavedState::default(),
};
(new_tl_state, true)
};
// log!("Timeline::set_room(): opening room {room_id}
// content_drawn_since_last_update: {:#?}
// profile_drawn_since_last_update: {:#?}",
// tl_state.content_drawn_since_last_update,
// tl_state.profile_drawn_since_last_update,
// );
// kick off a back pagination request for this room
if !tl_state.fully_paginated {
submit_async_request(MatrixRequest::PaginateRoomTimeline {
room_id: room_id.clone(),
batch_size: 50,
max_events: 50,
})
} else {
// log!("Note: skipping pagination request for room {} because it is already fully paginated.", room_id);
}
// Even though we specify that room member profiles should be lazy-loaded,
// the matrix server still doesn't consistently send them to our client properly.
// So we kick off a request to fetch the room members here upon first viewing the room.
if first_time_showing_room {
submit_async_request(MatrixRequest::FetchRoomMembers { room_id });
// TODO: in the future, move the back pagination request to here,
// once back pagination is done dynamically based on timeline scroll position.
}
// Now, restore the visual state of this timeline from its previously-saved state.
self.restore_state(&tl_state);
// As the final step , store the tl_state for this room into the Timeline widget,
// such that it can be accessed in future event/draw handlers.
self.tl_state = Some(tl_state);
}
/// Invoke this when this timeline is being hidden or no longer being shown,
/// e.g., when the user navigates away from this timeline.
fn hide_timeline(&mut self) {
self.save_state();
}
/// Removes this Timeline's current visual UI state from this Timeline widget
/// and saves it to the map of `TIMELINE_STATES` such that it can be restored later.
///
/// Note: after calling this function, the timeline's `tl_state` will be `None`.
fn save_state(&mut self) {
let Some(mut tl) = self.tl_state.take() else {
log!("Timeline::save_state(): skipping due to missing state, room {:?}", self.room_id);
return;
};
let first_id = self.portal_list(id!(list)).first_id();
tl.saved_state.first_id = first_id;
// Store this Timeline's `TimelineUiState` in the global map of states.
TIMELINE_STATES.lock().unwrap().insert(tl.room_id.clone(), tl);
}
/// Restores the previously-saved visual UI state of this timeline.
///
/// Note: this accepts a direct reference to the timeline's UI state,
/// so this function must not try to re-obtain it by accessing `self.tl_state`.
fn restore_state(&mut self, tl_state: &TimelineUiState) {
let first_id = tl_state.saved_state.first_id;
self.portal_list(id!(list)).set_first_id(first_id);
}
}
impl TimelineRef {
/// Sets this timeline widget to display the timeline for the given room.
fn set_room(&self, room_id: OwnedRoomId) {
let Some(mut timeline) = self.borrow_mut() else { return };
timeline.room_id = Some(room_id);
}
}
impl Widget for Timeline {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
if let Event::Actions(actions) = event {
for action in actions {
// Handle the timeline being hidden or shown.
match action.as_widget_action().cast() {
StackNavigationTransitionAction::HideBegin => {
self.hide_timeline();
continue;
}
StackNavigationTransitionAction::ShowBegin => {
self.show_timeline();
self.redraw(cx);
continue;
}
StackNavigationTransitionAction::HideEnd
| StackNavigationTransitionAction::ShowDone
| StackNavigationTransitionAction::None => { }
}
// Handle a link being clicked.
if let HtmlLinkAction::Clicked { url, .. } = action.as_widget_action().cast() {
if url.starts_with("https://matrix.to/#/") {
log!("TODO: handle Matrix link internally: {url:?}");
// TODO: show a pop-up pane with the user's profile, or a room preview pane.
//
// There are four kinds of matrix.to schemes:
// See here: <https://github.com/matrix-org/matrix.to?tab=readme-ov-file#url-scheme>
// 1. Rooms: https://matrix.to/#/#matrix:matrix.org
// 2. Rooms by ID: https://matrix.to/#/!cURbafjkfsMDVwdRDQ:matrix.org
// 3. Users: https://matrix.to/#/@matthew:matrix.org
// 4. Messages: https://matrix.to/#/#matrix:matrix.org/$1448831580433WbpiJ:jki.re
} else {
if let Err(e) = robius_open::Uri::new(&url).open() {
error!("Failed to open URL {:?}. Error: {:?}", url, e);
}
}
}
// Handle other actions here
// TODO: handle actions upon an item being clicked.
// for (item_id, item) in self.list.items_with_actions(&actions) {
// if item.button(id!(likes)).clicked(&actions) {
// log!("hello {}", item_id);
// }
// }
}
}
// Currently, a Signal event is only used to tell this widget
// that its timeline events have been updated in the background.
if let Event::Signal = event {
let portal_list = self.portal_list(id!(list));
let orig_first_id = portal_list.first_id();
let Some(tl) = self.tl_state.as_mut() else { return };
let mut done_loading = false;
while let Ok(update) = tl.update_receiver.try_recv() {
match update {
TimelineUpdate::NewItems { items, changed_indices, clear_cache } => {
// Determine which item is currently visible the top of the screen
// so that we can jump back to that position instantly after applying this update.
if let Some(top_event_id) = tl.items.get(orig_first_id).map(|item| item.unique_id()) {
for (idx, item) in items.iter().enumerate() {
if item.unique_id() == top_event_id {
if orig_first_id != idx {
log!("Timeline::handle_event(): jumping view from top event index {orig_first_id} to index {idx}");
portal_list.set_first_id(idx);
}
break;
}
}
}
if clear_cache {
tl.content_drawn_since_last_update.clear();
tl.profile_drawn_since_last_update.clear();
} else {
tl.content_drawn_since_last_update.remove(changed_indices.clone());
tl.profile_drawn_since_last_update.remove(changed_indices.clone());
// log!("Timeline::handle_event(): changed_indices: {changed_indices:?}, items len: {}\ncontent drawn: {:#?}\nprofile drawn: {:#?}", items.len(), tl.content_drawn_since_last_update, tl.profile_drawn_since_last_update);
}
tl.items = items;
}
TimelineUpdate::TimelineStartReached => {
log!("Timeline::handle_event(): timeline start reached for room {}", tl.room_id);
tl.fully_paginated = true;
done_loading = true;
}
TimelineUpdate::PaginationIdle => {
done_loading = true;
}
TimelineUpdate::RoomMembersFetched => {
log!("Timeline::handle_event(): room members fetched for room {}", tl.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::MediaFetched => {
log!("Timeline::handle_event(): media fetched for room {}", tl.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.
}
}
}
if done_loading {
log!("TODO: hide topspace loading animation for room {}", tl.room_id);
// TODO FIXME: hide TopSpace loading animation, set it to invisible.
}
self.redraw(cx);
}
// Forward events to this Timeline's inner child view.
self.view.handle_event(cx, event, scope);
}
fn draw_walk(&mut self, cx: &mut Cx2d, scope: &mut Scope, walk: Walk) -> DrawStep {
let Some(tl_state) = self.tl_state.as_mut() else {
return DrawStep::done()
};
let room_id = &tl_state.room_id;
let tl_items = &tl_state.items;
// Determine length of the portal list based on the number of timeline items.
let last_item_id = tl_items.len();
let last_item_id = last_item_id + 1; // Add 1 for the TopSpace.
// Start the actual drawing procedure.
while let Some(list_item) = self.view.draw_walk(cx, scope, walk).step() {
// We only care about drawing the portal list.
let portal_list_ref = list_item.as_portal_list();
let Some(mut list_ref) = portal_list_ref.borrow_mut() else { continue };
let list = list_ref.deref_mut();
list.set_item_range(cx, 0, last_item_id);
while let Some(item_id) = list.next_visible_item(cx) {
// log!("Drawing item {}", item_id);
let item = if item_id == 0 {
list.item(cx, item_id, live_id!(TopSpace)).unwrap()
} else {
let tl_idx = (item_id - 1) as usize;
let Some(timeline_item) = tl_items.get(tl_idx) else {
// This shouldn't happen (unless the timeline gets corrupted or some other weird error),
// but we can always safely fill the item with an empty widget that takes up no space.
list.item(cx, item_id, live_id!(Empty)).unwrap();
continue;
};
// Determine whether this item's content and profile have been drawn since the last update.
// Pass this state to each of the `populate_*` functions so they can attempt to re-use
// an item in the timeline's portallist that was previously populated, if one exists.
let item_drawn_status = ItemDrawnStatus {
content_drawn: tl_state.content_drawn_since_last_update.contains(&tl_idx),
profile_drawn: tl_state.profile_drawn_since_last_update.contains(&tl_idx),
};
let (item, item_new_draw_status) = match timeline_item.kind() {
TimelineItemKind::Event(event_tl_item) => match event_tl_item.content() {
TimelineItemContent::Message(message) => {
let prev_event = tl_items.get(tl_idx.saturating_sub(1));
populate_message_view(
cx,
list,