matrix_sdk_ui/timeline/controller/metadata.rs
1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16 collections::{BTreeSet, HashMap},
17 sync::Arc,
18};
19
20use imbl::Vector;
21use matrix_sdk::deserialized_responses::EncryptionInfo;
22use ruma::{
23 EventId, OwnedEventId, OwnedUserId,
24 events::{
25 AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent,
26 BundledMessageLikeRelations, poll::unstable_start::UnstablePollStartEventContent,
27 relation::Replacement, room::message::RelationWithoutReplacement,
28 },
29 room_version_rules::RoomVersionRules,
30 serde::Raw,
31};
32use tracing::trace;
33
34use super::{
35 super::{TimelineItem, TimelineItemKind, TimelineUniqueId, subscriber::skip::SkipCount},
36 Aggregation, AggregationKind, Aggregations, AllRemoteEvents, ObservableItemsTransaction,
37 PendingEdit, PendingEditKind,
38 read_receipts::ReadReceipts,
39};
40use crate::{
41 timeline::{
42 InReplyToDetails, TimelineEventItemId,
43 event_item::{
44 extract_bundled_edit_event_json, extract_poll_edit_content,
45 extract_room_msg_edit_content,
46 },
47 },
48 unable_to_decrypt_hook::UtdHookManager,
49};
50
51/// All parameters to [`TimelineAction::from_content`] that only apply if an
52/// event is a remote echo.
53pub(crate) struct RemoteEventContext<'a> {
54 pub event_id: &'a EventId,
55 pub raw_event: &'a Raw<AnySyncTimelineEvent>,
56 pub relations: BundledMessageLikeRelations<AnySyncMessageLikeEvent>,
57 pub bundled_edit_encryption_info: Option<Arc<EncryptionInfo>>,
58}
59
60#[derive(Clone, Debug)]
61pub(in crate::timeline) struct TimelineMetadata {
62 // **** CONSTANT FIELDS ****
63 /// An optional prefix for internal IDs, defined during construction of the
64 /// timeline.
65 ///
66 /// This value is constant over the lifetime of the metadata.
67 internal_id_prefix: Option<String>,
68
69 /// The `count` value for the `Skip` higher-order stream used by the
70 /// `TimelineSubscriber`. See its documentation to learn more.
71 pub(super) subscriber_skip_count: SkipCount,
72
73 /// The hook to call whenever we run into a unable-to-decrypt event.
74 ///
75 /// This value is constant over the lifetime of the metadata.
76 pub unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
77
78 /// A boolean indicating whether the room the timeline is attached to is
79 /// actually encrypted or not.
80 ///
81 /// May be false until we fetch the actual room encryption state.
82 pub is_room_encrypted: bool,
83
84 /// Rules of the version of the timeline's room, or a sensible default.
85 ///
86 /// This value is constant over the lifetime of the metadata.
87 pub room_version_rules: RoomVersionRules,
88
89 /// The own [`OwnedUserId`] of the client who opened the timeline.
90 pub(crate) own_user_id: OwnedUserId,
91
92 // **** DYNAMIC FIELDS ****
93 /// The next internal identifier for timeline items, used for both local and
94 /// remote echoes.
95 ///
96 /// This is never cleared, but always incremented, to avoid issues with
97 /// reusing a stale internal id across timeline clears. We don't expect
98 /// we can hit `u64::max_value()` realistically, but if this would
99 /// happen, we do a wrapping addition when incrementing this
100 /// id; the previous 0 value would have disappeared a long time ago, unless
101 /// the device has terabytes of RAM.
102 next_internal_id: u64,
103
104 /// Aggregation metadata and pending aggregations.
105 pub aggregations: Aggregations,
106
107 /// Given an event, what are all the events that are replies to it?
108 ///
109 /// Only works for remote events *and* replies which are remote-echoed.
110 pub replies: HashMap<OwnedEventId, BTreeSet<OwnedEventId>>,
111
112 /// Identifier of the fully-read event, helping knowing where to introduce
113 /// the read marker.
114 pub fully_read_event: Option<OwnedEventId>,
115
116 /// Whether we have a fully read-marker item in the timeline, that's up to
117 /// date with the room's read marker.
118 ///
119 /// This is false when:
120 /// - The fully-read marker points to an event that is not in the timeline,
121 /// - The fully-read marker item would be the last item in the timeline.
122 pub has_up_to_date_read_marker_item: bool,
123
124 /// Read receipts related state.
125 ///
126 /// TODO: move this over to the event cache (see also #3058).
127 pub(super) read_receipts: ReadReceipts,
128}
129
130impl TimelineMetadata {
131 pub(in crate::timeline) fn new(
132 own_user_id: OwnedUserId,
133 room_version_rules: RoomVersionRules,
134 internal_id_prefix: Option<String>,
135 unable_to_decrypt_hook: Option<Arc<UtdHookManager>>,
136 is_room_encrypted: bool,
137 ) -> Self {
138 Self {
139 subscriber_skip_count: SkipCount::new(),
140 own_user_id,
141 next_internal_id: Default::default(),
142 aggregations: Default::default(),
143 replies: Default::default(),
144 fully_read_event: Default::default(),
145 // It doesn't make sense to set this to false until we fill the `fully_read_event`
146 // field, otherwise we'll keep on exiting early in `Self::update_read_marker`.
147 has_up_to_date_read_marker_item: true,
148 read_receipts: Default::default(),
149 room_version_rules,
150 unable_to_decrypt_hook,
151 internal_id_prefix,
152 is_room_encrypted,
153 }
154 }
155
156 pub(super) fn clear(&mut self) {
157 // Note: we don't clear the next internal id to avoid bad cases of stale unique
158 // ids across timeline clears.
159 self.aggregations.clear();
160 self.replies.clear();
161 self.fully_read_event = None;
162 // We forgot about the fully read marker right above, so wait for a new one
163 // before attempting to update it for each new timeline item.
164 self.has_up_to_date_read_marker_item = true;
165 self.read_receipts.clear();
166 }
167
168 /// Get the relative positions of two events in the timeline.
169 ///
170 /// This method assumes that all events since the end of the timeline are
171 /// known.
172 ///
173 /// Returns `None` if none of the two events could be found in the timeline.
174 pub(in crate::timeline) fn compare_events_positions(
175 event_a: &EventId,
176 event_b: &EventId,
177 all_remote_events: &AllRemoteEvents,
178 ) -> Option<RelativePosition> {
179 if event_a == event_b {
180 return Some(RelativePosition::Same);
181 }
182
183 // We can make early returns here because we know all events since the end of
184 // the timeline, so the first event encountered is the oldest one.
185 for event_meta in all_remote_events.iter().rev() {
186 if event_meta.event_id == event_a {
187 return Some(RelativePosition::Before);
188 }
189 if event_meta.event_id == event_b {
190 return Some(RelativePosition::After);
191 }
192 }
193
194 None
195 }
196
197 /// Returns the next internal id for a timeline item (and increment our
198 /// internal counter).
199 fn next_internal_id(&mut self) -> TimelineUniqueId {
200 let val = self.next_internal_id;
201 self.next_internal_id = self.next_internal_id.wrapping_add(1);
202 let prefix = self.internal_id_prefix.as_deref().unwrap_or("");
203 TimelineUniqueId(format!("{prefix}{val}"))
204 }
205
206 /// Returns a new timeline item with a fresh internal id.
207 pub fn new_timeline_item(&mut self, kind: impl Into<TimelineItemKind>) -> Arc<TimelineItem> {
208 TimelineItem::new(kind, self.next_internal_id())
209 }
210
211 /// Try to update the read marker item in the timeline.
212 pub(crate) fn update_read_marker(&mut self, items: &mut ObservableItemsTransaction<'_>) {
213 let Some(fully_read_event) = &self.fully_read_event else { return };
214 trace!(?fully_read_event, "Updating read marker");
215
216 let read_marker_idx = items
217 .iter_remotes_region()
218 .rev()
219 .find_map(|(idx, item)| item.is_read_marker().then_some(idx));
220
221 let mut fully_read_event_idx = items.iter_remotes_region().rev().find_map(|(idx, item)| {
222 (item.as_event()?.event_id() == Some(fully_read_event)).then_some(idx)
223 });
224
225 if let Some(fully_read_event_idx) = &mut fully_read_event_idx {
226 // The item at position `i` is the first item that's fully read, we're about to
227 // insert a read marker just after it.
228 //
229 // Do another forward pass to skip all the events we've sent too.
230
231 // Find the position of the first element…
232 let next = items
233 .iter_remotes_region()
234 // …strictly *after* the fully read event…
235 .skip_while(|(idx, _)| idx <= fully_read_event_idx)
236 // …that's not virtual and not sent by us…
237 .find_map(|(idx, item)| {
238 (item.as_event()?.sender() != self.own_user_id).then_some(idx)
239 });
240
241 if let Some(next) = next {
242 // `next` point to the first item that's not sent by us, so the *previous* of
243 // next is the right place where to insert the fully read marker.
244 *fully_read_event_idx = next.wrapping_sub(1);
245 } else {
246 // There's no event after the read marker that's not sent by us, i.e. the full
247 // timeline has been read: the fully read marker goes to the end, even after the
248 // local timeline items.
249 //
250 // TODO (@hywan): Should we introduce a `items.position_of_last_remote()` to
251 // insert before the local timeline items?
252 *fully_read_event_idx = items.len().wrapping_sub(1);
253 }
254 }
255
256 match (read_marker_idx, fully_read_event_idx) {
257 (None, None) => {
258 // We didn't have a previous read marker, and we didn't find the fully-read
259 // event in the timeline items. Don't do anything, and retry on
260 // the next event we add.
261 self.has_up_to_date_read_marker_item = false;
262 }
263
264 (None, Some(idx)) => {
265 // Only insert the read marker if it is not at the end of the timeline.
266 if idx + 1 < items.len() {
267 let idx = idx + 1;
268 items.insert(idx, TimelineItem::read_marker(), None);
269 self.has_up_to_date_read_marker_item = true;
270 } else {
271 // The next event might require a read marker to be inserted at the current
272 // end.
273 self.has_up_to_date_read_marker_item = false;
274 }
275 }
276
277 (Some(_), None) => {
278 // We didn't find the timeline item containing the event referred to by the read
279 // marker. Retry next time we get a new event.
280 self.has_up_to_date_read_marker_item = false;
281 }
282
283 (Some(from), Some(to)) => {
284 if from >= to {
285 // The read marker can't move backwards.
286 if from + 1 == items.len() {
287 // The read marker has nothing after it. An item disappeared; remove it.
288 items.remove(from);
289 }
290 self.has_up_to_date_read_marker_item = true;
291 return;
292 }
293
294 let prev_len = items.len();
295 let read_marker = items.remove(from);
296
297 // Only insert the read marker if it is not at the end of the timeline.
298 if to + 1 < prev_len {
299 // Since the fully-read event's index was shifted to the left
300 // by one position by the remove call above, insert the fully-
301 // read marker at its previous position, rather than that + 1
302 items.insert(to, read_marker, None);
303 self.has_up_to_date_read_marker_item = true;
304 } else {
305 self.has_up_to_date_read_marker_item = false;
306 }
307 }
308 }
309 }
310
311 /// Extract the content from a remote message-like event and process its
312 /// relations.
313 pub(crate) fn process_event_relations(
314 &mut self,
315 event: &AnySyncTimelineEvent,
316 raw_event: &Raw<AnySyncTimelineEvent>,
317 bundled_edit_encryption_info: Option<Arc<EncryptionInfo>>,
318 timeline_items: &Vector<Arc<TimelineItem>>,
319 is_thread_focus: bool,
320 ) -> (Option<InReplyToDetails>, Option<OwnedEventId>) {
321 if let AnySyncTimelineEvent::MessageLike(ev) = event
322 && let Some(content) = ev.original_content()
323 {
324 let remote_ctx = Some(RemoteEventContext {
325 event_id: ev.event_id(),
326 raw_event,
327 relations: ev.relations(),
328 bundled_edit_encryption_info,
329 });
330 self.process_content_relations(&content, remote_ctx, timeline_items, is_thread_focus)
331 } else {
332 (None, None)
333 }
334 }
335
336 /// Extracts the in-reply-to details and thread root from the content of a
337 /// message-like event, and take care of internal bookkeeping as well
338 /// (like marking responses).
339 ///
340 /// Returns the in-reply-to details and the thread root event ID, if any.
341 pub(crate) fn process_content_relations(
342 &mut self,
343 content: &AnyMessageLikeEventContent,
344 remote_ctx: Option<RemoteEventContext<'_>>,
345 timeline_items: &Vector<Arc<TimelineItem>>,
346 is_thread_focus: bool,
347 ) -> (Option<InReplyToDetails>, Option<OwnedEventId>) {
348 match content {
349 AnyMessageLikeEventContent::Sticker(content) => {
350 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
351 content.relates_to.clone().and_then(|rel| rel.try_into().ok()),
352 timeline_items,
353 is_thread_focus,
354 );
355
356 if let Some(event_id) = remote_ctx.map(|ctx| ctx.event_id) {
357 self.mark_response(event_id, in_reply_to.as_ref());
358 }
359
360 (in_reply_to, thread_root)
361 }
362
363 AnyMessageLikeEventContent::UnstablePollStart(UnstablePollStartEventContent::New(
364 c,
365 )) => {
366 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
367 c.relates_to.clone(),
368 timeline_items,
369 is_thread_focus,
370 );
371
372 // Record the bundled edit in the aggregations set, if any.
373 if let Some(ctx) = remote_ctx {
374 // Extract a potentially bundled edit.
375 if let Some((edit_event_id, new_content)) =
376 extract_poll_edit_content(ctx.relations)
377 {
378 let edit_json = extract_bundled_edit_event_json(ctx.raw_event);
379 let aggregation = Aggregation::new(
380 TimelineEventItemId::EventId(edit_event_id),
381 AggregationKind::Edit(PendingEdit {
382 kind: PendingEditKind::Poll(Replacement::new(
383 ctx.event_id.to_owned(),
384 new_content,
385 )),
386 edit_json,
387 encryption_info: ctx.bundled_edit_encryption_info,
388 bundled_item_owner: Some(ctx.event_id.to_owned()),
389 }),
390 );
391 self.aggregations.add(
392 TimelineEventItemId::EventId(ctx.event_id.to_owned()),
393 aggregation,
394 );
395 }
396
397 self.mark_response(ctx.event_id, in_reply_to.as_ref());
398 }
399
400 (in_reply_to, thread_root)
401 }
402
403 AnyMessageLikeEventContent::RoomMessage(msg) => {
404 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
405 msg.relates_to.clone().and_then(|rel| rel.try_into().ok()),
406 timeline_items,
407 is_thread_focus,
408 );
409
410 // Record the bundled edit in the aggregations set, if any.
411 if let Some(ctx) = remote_ctx {
412 // Extract a potentially bundled edit.
413 if let Some((edit_event_id, new_content)) =
414 extract_room_msg_edit_content(ctx.relations)
415 {
416 let edit_json = extract_bundled_edit_event_json(ctx.raw_event);
417 let aggregation = Aggregation::new(
418 TimelineEventItemId::EventId(edit_event_id),
419 AggregationKind::Edit(PendingEdit {
420 kind: PendingEditKind::RoomMessage(Replacement::new(
421 ctx.event_id.to_owned(),
422 new_content,
423 )),
424 edit_json,
425 encryption_info: ctx.bundled_edit_encryption_info,
426 bundled_item_owner: Some(ctx.event_id.to_owned()),
427 }),
428 );
429 self.aggregations.add(
430 TimelineEventItemId::EventId(ctx.event_id.to_owned()),
431 aggregation,
432 );
433 }
434
435 self.mark_response(ctx.event_id, in_reply_to.as_ref());
436 }
437
438 (in_reply_to, thread_root)
439 }
440
441 _ => (None, None),
442 }
443 }
444
445 /// Extracts the in-reply-to details and thread root from a relation, if
446 /// available.
447 fn extract_reply_and_thread_root(
448 relates_to: Option<RelationWithoutReplacement>,
449 timeline_items: &Vector<Arc<TimelineItem>>,
450 is_thread_focus: bool,
451 ) -> (Option<InReplyToDetails>, Option<OwnedEventId>) {
452 let mut thread_root = None;
453
454 let in_reply_to = relates_to.and_then(|relation| match relation {
455 RelationWithoutReplacement::Reply { in_reply_to } => {
456 Some(InReplyToDetails::new(in_reply_to.event_id, timeline_items))
457 }
458 RelationWithoutReplacement::Thread(thread) => {
459 thread_root = Some(thread.event_id);
460
461 if is_thread_focus && thread.is_falling_back {
462 // In general, a threaded event is marked as a response to the previous message
463 // in the thread, to maintain backwards compatibility with clients not
464 // supporting threads.
465 //
466 // But we can have actual replies to other in-thread events. The
467 // `is_falling_back` bool helps distinguishing both use cases.
468 //
469 // If this timeline is thread-focused, we only mark non-falling-back replies as
470 // actual in-thread replies.
471 None
472 } else {
473 thread.in_reply_to.map(|in_reply_to| {
474 InReplyToDetails::new(in_reply_to.event_id, timeline_items)
475 })
476 }
477 }
478 _ => None,
479 });
480
481 (in_reply_to, thread_root)
482 }
483
484 /// Mark a message as a response to another message, if it is a reply.
485 fn mark_response(&mut self, event_id: &EventId, in_reply_to: Option<&InReplyToDetails>) {
486 // If this message is a reply to another message, add an entry in the
487 // inverted mapping.
488 if let Some(replied_to_event_id) = in_reply_to.as_ref().map(|details| &details.event_id) {
489 // This is a reply! Add an entry.
490 self.replies
491 .entry(replied_to_event_id.to_owned())
492 .or_default()
493 .insert(event_id.to_owned());
494 }
495 }
496}
497
498/// Result of comparing events position in the timeline.
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub(in crate::timeline) enum RelativePosition {
501 /// Event B is after (more recent than) event A.
502 After,
503 /// They are the same event.
504 Same,
505 /// Event B is before (older than) event A.
506 Before,
507}
508
509/// Metadata about an event that needs to be kept in memory.
510#[derive(Debug, Clone)]
511pub(in crate::timeline) struct EventMeta {
512 /// The ID of the event.
513 pub event_id: OwnedEventId,
514
515 /// If this event is part of a thread, this will contain its thread root
516 /// event id.
517 pub thread_root_id: Option<OwnedEventId>,
518
519 /// Whether the event is among the timeline items.
520 pub visible: bool,
521
522 /// Whether the event can show read receipts.
523 pub can_show_read_receipts: bool,
524
525 /// Foundation for the mapping between remote events to timeline items.
526 ///
527 /// Let's explain it. The events represent the first set and are stored in
528 /// [`ObservableItems::all_remote_events`], and the timeline
529 /// items represent the second set and are stored in
530 /// [`ObservableItems::items`].
531 ///
532 /// Each event is mapped to at most one timeline item:
533 ///
534 /// - `None` if the event isn't rendered in the timeline (e.g. some state
535 /// events, or malformed events) or is rendered as a timeline item that
536 /// attaches to or groups with another item, like reactions,
537 /// - `Some(_)` if the event is rendered in the timeline.
538 ///
539 /// This is neither a surjection nor an injection. Every timeline item may
540 /// not be attached to an event, for example with a virtual timeline item.
541 /// We can formulate other rules:
542 ///
543 /// - a timeline item that doesn't _move_ and that is represented by an
544 /// event has a mapping to an event,
545 /// - a virtual timeline item has no mapping to an event.
546 ///
547 /// Imagine the following remote events:
548 ///
549 /// | index | remote events |
550 /// +-------+---------------+
551 /// | 0 | `$ev0` |
552 /// | 1 | `$ev1` |
553 /// | 2 | `$ev2` |
554 /// | 3 | `$ev3` |
555 /// | 4 | `$ev4` |
556 /// | 5 | `$ev5` |
557 ///
558 /// Once rendered in a timeline, it for example produces:
559 ///
560 /// | index | item | related items |
561 /// +-------+-------------------+----------------------+
562 /// | 0 | content of `$ev0` | |
563 /// | 1 | content of `$ev2` | reaction with `$ev4` |
564 /// | 2 | date divider | |
565 /// | 3 | content of `$ev3` | |
566 /// | 4 | content of `$ev5` | |
567 ///
568 /// Note the date divider that is a virtual item. Also note `$ev4` which is
569 /// a reaction to `$ev2`. Finally note that `$ev1` is not rendered in
570 /// the timeline.
571 ///
572 /// The mapping between remote event index to timeline item index will look
573 /// like this:
574 ///
575 /// | remote event index | timeline item index | comment |
576 /// +--------------------+---------------------+--------------------------------------------+
577 /// | 0 | `Some(0)` | `$ev0` is rendered as the #0 timeline item |
578 /// | 1 | `None` | `$ev1` isn't rendered in the timeline |
579 /// | 2 | `Some(1)` | `$ev2` is rendered as the #1 timeline item |
580 /// | 3 | `Some(3)` | `$ev3` is rendered as the #3 timeline item |
581 /// | 4 | `None` | `$ev4` is a reaction to item #1 |
582 /// | 5 | `Some(4)` | `$ev5` is rendered as the #4 timeline item |
583 ///
584 /// Note that the #2 timeline item (the day divider) doesn't map to any
585 /// remote event, but if it moves, it has an impact on this mapping.
586 pub timeline_item_index: Option<usize>,
587}
588
589impl EventMeta {
590 pub fn new(
591 event_id: OwnedEventId,
592 visible: bool,
593 can_show_read_receipts: bool,
594 thread_root_id: Option<OwnedEventId>,
595 ) -> Self {
596 Self {
597 event_id,
598 thread_root_id,
599 visible,
600 can_show_read_receipts,
601 timeline_item_index: None,
602 }
603 }
604}