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 return self.process_content_relations(
331 &content,
332 remote_ctx,
333 timeline_items,
334 is_thread_focus,
335 );
336 }
337 (None, None)
338 }
339
340 /// Extracts the in-reply-to details and thread root from the content of a
341 /// message-like event, and take care of internal bookkeeping as well
342 /// (like marking responses).
343 ///
344 /// Returns the in-reply-to details and the thread root event ID, if any.
345 pub(crate) fn process_content_relations(
346 &mut self,
347 content: &AnyMessageLikeEventContent,
348 remote_ctx: Option<RemoteEventContext<'_>>,
349 timeline_items: &Vector<Arc<TimelineItem>>,
350 is_thread_focus: bool,
351 ) -> (Option<InReplyToDetails>, Option<OwnedEventId>) {
352 match content {
353 AnyMessageLikeEventContent::Sticker(content) => {
354 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
355 content.relates_to.clone().and_then(|rel| rel.try_into().ok()),
356 timeline_items,
357 is_thread_focus,
358 );
359
360 if let Some(event_id) = remote_ctx.map(|ctx| ctx.event_id) {
361 self.mark_response(event_id, in_reply_to.as_ref());
362 }
363
364 (in_reply_to, thread_root)
365 }
366
367 AnyMessageLikeEventContent::UnstablePollStart(UnstablePollStartEventContent::New(
368 c,
369 )) => {
370 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
371 c.relates_to.clone(),
372 timeline_items,
373 is_thread_focus,
374 );
375
376 // Record the bundled edit in the aggregations set, if any.
377 if let Some(ctx) = remote_ctx {
378 // Extract a potentially bundled edit.
379 if let Some((edit_event_id, new_content)) =
380 extract_poll_edit_content(ctx.relations)
381 {
382 let edit_json = extract_bundled_edit_event_json(ctx.raw_event);
383 let aggregation = Aggregation::new(
384 TimelineEventItemId::EventId(edit_event_id),
385 AggregationKind::Edit(PendingEdit {
386 kind: PendingEditKind::Poll(Replacement::new(
387 ctx.event_id.to_owned(),
388 new_content,
389 )),
390 edit_json,
391 encryption_info: ctx.bundled_edit_encryption_info,
392 bundled_item_owner: Some(ctx.event_id.to_owned()),
393 }),
394 );
395 self.aggregations.add(
396 TimelineEventItemId::EventId(ctx.event_id.to_owned()),
397 aggregation,
398 );
399 }
400
401 self.mark_response(ctx.event_id, in_reply_to.as_ref());
402 }
403
404 (in_reply_to, thread_root)
405 }
406
407 AnyMessageLikeEventContent::RoomMessage(msg) => {
408 let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root(
409 msg.relates_to.clone().and_then(|rel| rel.try_into().ok()),
410 timeline_items,
411 is_thread_focus,
412 );
413
414 // Record the bundled edit in the aggregations set, if any.
415 if let Some(ctx) = remote_ctx {
416 // Extract a potentially bundled edit.
417 if let Some((edit_event_id, new_content)) =
418 extract_room_msg_edit_content(ctx.relations)
419 {
420 let edit_json = extract_bundled_edit_event_json(ctx.raw_event);
421 let aggregation = Aggregation::new(
422 TimelineEventItemId::EventId(edit_event_id),
423 AggregationKind::Edit(PendingEdit {
424 kind: PendingEditKind::RoomMessage(Replacement::new(
425 ctx.event_id.to_owned(),
426 new_content,
427 )),
428 edit_json,
429 encryption_info: ctx.bundled_edit_encryption_info,
430 bundled_item_owner: Some(ctx.event_id.to_owned()),
431 }),
432 );
433 self.aggregations.add(
434 TimelineEventItemId::EventId(ctx.event_id.to_owned()),
435 aggregation,
436 );
437 }
438
439 self.mark_response(ctx.event_id, in_reply_to.as_ref());
440 }
441
442 (in_reply_to, thread_root)
443 }
444
445 _ => (None, None),
446 }
447 }
448
449 /// Extracts the in-reply-to details and thread root from a relation, if
450 /// available.
451 fn extract_reply_and_thread_root(
452 relates_to: Option<RelationWithoutReplacement>,
453 timeline_items: &Vector<Arc<TimelineItem>>,
454 is_thread_focus: bool,
455 ) -> (Option<InReplyToDetails>, Option<OwnedEventId>) {
456 let mut thread_root = None;
457
458 let in_reply_to = relates_to.and_then(|relation| match relation {
459 RelationWithoutReplacement::Reply { in_reply_to } => {
460 Some(InReplyToDetails::new(in_reply_to.event_id, timeline_items))
461 }
462 RelationWithoutReplacement::Thread(thread) => {
463 thread_root = Some(thread.event_id);
464
465 if is_thread_focus && thread.is_falling_back {
466 // In general, a threaded event is marked as a response to the previous message
467 // in the thread, to maintain backwards compatibility with clients not
468 // supporting threads.
469 //
470 // But we can have actual replies to other in-thread events. The
471 // `is_falling_back` bool helps distinguishing both use cases.
472 //
473 // If this timeline is thread-focused, we only mark non-falling-back replies as
474 // actual in-thread replies.
475 None
476 } else {
477 thread.in_reply_to.map(|in_reply_to| {
478 InReplyToDetails::new(in_reply_to.event_id, timeline_items)
479 })
480 }
481 }
482 _ => None,
483 });
484
485 (in_reply_to, thread_root)
486 }
487
488 /// Mark a message as a response to another message, if it is a reply.
489 fn mark_response(&mut self, event_id: &EventId, in_reply_to: Option<&InReplyToDetails>) {
490 // If this message is a reply to another message, add an entry in the
491 // inverted mapping.
492 if let Some(replied_to_event_id) = in_reply_to.as_ref().map(|details| &details.event_id) {
493 // This is a reply! Add an entry.
494 self.replies
495 .entry(replied_to_event_id.to_owned())
496 .or_default()
497 .insert(event_id.to_owned());
498 }
499 }
500}
501
502/// Result of comparing events position in the timeline.
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504pub(in crate::timeline) enum RelativePosition {
505 /// Event B is after (more recent than) event A.
506 After,
507 /// They are the same event.
508 Same,
509 /// Event B is before (older than) event A.
510 Before,
511}
512
513/// Metadata about an event that needs to be kept in memory.
514#[derive(Debug, Clone)]
515pub(in crate::timeline) struct EventMeta {
516 /// The ID of the event.
517 pub event_id: OwnedEventId,
518
519 /// Whether the event is among the timeline items.
520 pub visible: bool,
521
522 /// Foundation for the mapping between remote events to timeline items.
523 ///
524 /// Let's explain it. The events represent the first set and are stored in
525 /// [`ObservableItems::all_remote_events`], and the timeline
526 /// items represent the second set and are stored in
527 /// [`ObservableItems::items`].
528 ///
529 /// Each event is mapped to at most one timeline item:
530 ///
531 /// - `None` if the event isn't rendered in the timeline (e.g. some state
532 /// events, or malformed events) or is rendered as a timeline item that
533 /// attaches to or groups with another item, like reactions,
534 /// - `Some(_)` if the event is rendered in the timeline.
535 ///
536 /// This is neither a surjection nor an injection. Every timeline item may
537 /// not be attached to an event, for example with a virtual timeline item.
538 /// We can formulate other rules:
539 ///
540 /// - a timeline item that doesn't _move_ and that is represented by an
541 /// event has a mapping to an event,
542 /// - a virtual timeline item has no mapping to an event.
543 ///
544 /// Imagine the following remote events:
545 ///
546 /// | index | remote events |
547 /// +-------+---------------+
548 /// | 0 | `$ev0` |
549 /// | 1 | `$ev1` |
550 /// | 2 | `$ev2` |
551 /// | 3 | `$ev3` |
552 /// | 4 | `$ev4` |
553 /// | 5 | `$ev5` |
554 ///
555 /// Once rendered in a timeline, it for example produces:
556 ///
557 /// | index | item | related items |
558 /// +-------+-------------------+----------------------+
559 /// | 0 | content of `$ev0` | |
560 /// | 1 | content of `$ev2` | reaction with `$ev4` |
561 /// | 2 | date divider | |
562 /// | 3 | content of `$ev3` | |
563 /// | 4 | content of `$ev5` | |
564 ///
565 /// Note the date divider that is a virtual item. Also note `$ev4` which is
566 /// a reaction to `$ev2`. Finally note that `$ev1` is not rendered in
567 /// the timeline.
568 ///
569 /// The mapping between remote event index to timeline item index will look
570 /// like this:
571 ///
572 /// | remote event index | timeline item index | comment |
573 /// +--------------------+---------------------+--------------------------------------------+
574 /// | 0 | `Some(0)` | `$ev0` is rendered as the #0 timeline item |
575 /// | 1 | `None` | `$ev1` isn't rendered in the timeline |
576 /// | 2 | `Some(1)` | `$ev2` is rendered as the #1 timeline item |
577 /// | 3 | `Some(3)` | `$ev3` is rendered as the #3 timeline item |
578 /// | 4 | `None` | `$ev4` is a reaction to item #1 |
579 /// | 5 | `Some(4)` | `$ev5` is rendered as the #4 timeline item |
580 ///
581 /// Note that the #2 timeline item (the day divider) doesn't map to any
582 /// remote event, but if it moves, it has an impact on this mapping.
583 pub timeline_item_index: Option<usize>,
584}
585
586impl EventMeta {
587 pub fn new(event_id: OwnedEventId, visible: bool) -> Self {
588 Self { event_id, visible, timeline_item_index: None }
589 }
590}