Skip to main content

matrix_sdk_ui/room_list_service/
room_list.rs

1// Copyright 2023 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 that specific language governing permissions and
13// limitations under the License.
14
15use std::{cmp::Reverse, collections::BTreeSet, future::ready, ops::Deref, pin::pin, sync::Arc};
16
17use async_cell::sync::AsyncCell;
18use async_rx::StreamExt as _;
19use async_stream::stream;
20use eyeball::{SharedObservable, Subscriber};
21use eyeball_im::{Vector, VectorDiff};
22use eyeball_im_util::vector::VectorObserverExt;
23use futures_util::{Stream, StreamExt as _, stream};
24use matrix_sdk::{
25    Client, Room, RoomRecencyStamp, RoomState, SlidingSync, SlidingSyncList,
26    task_monitor::BackgroundTaskHandle,
27};
28use matrix_sdk_base::RoomInfoNotableUpdate;
29use ruma::{MilliSecondsSinceUnixEpoch, UInt};
30use tokio::{
31    select,
32    sync::broadcast::{self, error::RecvError},
33};
34use tracing::{error, trace};
35
36use super::{
37    Error, State,
38    filters::BoxedFilterFn,
39    sorters::{
40        new_sorter_latest_event, new_sorter_lexicographic, new_sorter_name, new_sorter_recency,
41    },
42};
43
44/// A `RoomList` represents a list of rooms, from a
45/// [`RoomListService`](super::RoomListService).
46#[derive(Debug)]
47pub struct RoomList {
48    client: Client,
49    sliding_sync_list: SlidingSyncList,
50    loading_state: SharedObservable<RoomListLoadingState>,
51    _loading_state_task: BackgroundTaskHandle,
52}
53
54impl RoomList {
55    pub(super) async fn new(
56        client: &Client,
57        sliding_sync: &Arc<SlidingSync>,
58        sliding_sync_list_name: &str,
59        room_list_service_state: Subscriber<State>,
60    ) -> Result<Self, Error> {
61        let sliding_sync_list = sliding_sync
62            .on_list(sliding_sync_list_name, |list| ready(list.clone()))
63            .await
64            .ok_or_else(|| Error::UnknownList(sliding_sync_list_name.to_owned()))?;
65
66        let loading_state =
67            SharedObservable::new(match sliding_sync_list.maximum_number_of_rooms() {
68                Some(maximum_number_of_rooms) => RoomListLoadingState::Loaded {
69                    maximum_number_of_rooms: Some(maximum_number_of_rooms),
70                },
71                None => RoomListLoadingState::NotLoaded,
72            });
73
74        Ok(Self {
75            client: client.clone(),
76            sliding_sync_list: sliding_sync_list.clone(),
77            loading_state: loading_state.clone(),
78            _loading_state_task: client
79                .task_monitor()
80                .spawn_infinite_task("room_list::loading_state_task", async move {
81                    let mut room_list_service_state = pin!(room_list_service_state);
82
83                    // As soon as `RoomListService` changes its state, if it
84                    // isn't `Terminated` nor `Error`, we know we have fetched
85                    // something, so the room list is loaded.
86                    while let Some(state) = room_list_service_state.next().await {
87                        use State::*;
88
89                        match state {
90                            Terminated { .. } | Error { .. } | Init => (),
91                            SettingUp | Recovering | Running => break,
92                        }
93                    }
94
95                    // Let's jump from `NotLoaded` to `Loaded`.
96                    let maximum_number_of_rooms = sliding_sync_list.maximum_number_of_rooms();
97
98                    loading_state.set(RoomListLoadingState::Loaded { maximum_number_of_rooms });
99
100                    // Wait for updates on the maximum number of rooms to update
101                    // again.
102                    let mut maximum_number_of_rooms_stream =
103                        sliding_sync_list.maximum_number_of_rooms_stream();
104
105                    while let Some(maximum_number_of_rooms) =
106                        maximum_number_of_rooms_stream.next().await
107                    {
108                        loading_state.set(RoomListLoadingState::Loaded { maximum_number_of_rooms });
109                    }
110                })
111                .abort_on_drop(),
112        })
113    }
114
115    /// Get a subscriber to the room list loading state.
116    ///
117    /// This method will send out the current loading state as the first update.
118    ///
119    /// See [`RoomListLoadingState`].
120    pub fn loading_state(&self) -> Subscriber<RoomListLoadingState> {
121        self.loading_state.subscribe_reset()
122    }
123
124    /// Get a stream of rooms.
125    fn entries(&self) -> (Vector<Room>, impl Stream<Item = Vec<VectorDiff<Room>>> + '_) {
126        self.client.rooms_stream()
127    }
128
129    /// Get a configurable stream of rooms.
130    ///
131    /// It's possible to provide a filter that will filter out room list
132    /// entries, and that it's also possible to “paginate” over the entries by
133    /// `page_size`. The rooms are also sorted.
134    ///
135    /// The returned stream will only start yielding diffs once a filter is set
136    /// through the returned [`RoomListDynamicEntriesController`]. For every
137    /// call to [`RoomListDynamicEntriesController::set_filter`], the stream
138    /// will yield a [`VectorDiff::Reset`] followed by any updates of the room
139    /// list under that filter (until the next reset).
140    pub fn entries_with_dynamic_adapters(
141        &self,
142        page_size: usize,
143    ) -> (impl Stream<Item = Vec<VectorDiff<RoomListItem>>> + '_, RoomListDynamicEntriesController)
144    {
145        let room_info_notable_update_receiver = self.client.room_info_notable_update_receiver();
146        let list = self.sliding_sync_list.clone();
147
148        let filter_fn_cell = AsyncCell::shared();
149
150        let limit = SharedObservable::<usize>::new(page_size);
151        let limit_stream = limit.subscribe();
152
153        let dynamic_entries_controller = RoomListDynamicEntriesController::new(
154            filter_fn_cell.clone(),
155            page_size,
156            limit,
157            list.maximum_number_of_rooms_stream(),
158        );
159
160        let stream = stream! {
161            loop {
162                let filter_fn = filter_fn_cell.take().await;
163
164                let (raw_values, raw_stream) = self.entries();
165                let mut values = raw_values.into_iter().map(Into::into).collect::<Vector<RoomListItem>>();
166                backfill_timestamps(&mut values);
167
168                // Combine normal stream events with other updates from rooms
169                let stream = merge_stream_and_receiver(values.clone(), raw_stream, room_info_notable_update_receiver.resubscribe());
170
171                let (values, stream) = (values, stream)
172                    .filter(filter_fn)
173                    .sort_by(new_sorter_lexicographic(vec![
174                        // Sort by latest event's kind, i.e. put the rooms with
175                        // a **local** latest event first.
176                        Box::new(new_sorter_latest_event()),
177                        // Sort rooms by their recency (either by looking at
178                        // their latest event's timestamp, or their
179                        // `recency_stamp`).
180                        Box::new(new_sorter_recency()),
181                        // Finally, sort by name.
182                        Box::new(new_sorter_name()),
183                    ]))
184                    .dynamic_head_with_initial_value(page_size, limit_stream.clone());
185
186                // Clearing the stream before chaining with the real stream.
187                yield stream::once(ready(vec![VectorDiff::Reset { values }]))
188                    .chain(stream);
189            }
190        }
191        .fuse()
192        .switch();
193
194        (stream, dynamic_entries_controller)
195    }
196}
197
198/// This function remembers the current state of the unfiltered room list, so it
199/// knows where all rooms are. When the receiver is triggered, a Set operation
200/// for the room position is inserted to the stream.
201fn merge_stream_and_receiver(
202    mut current_values: Vector<RoomListItem>,
203    raw_stream: impl Stream<Item = Vec<VectorDiff<Room>>>,
204    mut room_info_notable_update_receiver: broadcast::Receiver<RoomInfoNotableUpdate>,
205) -> impl Stream<Item = Vec<VectorDiff<RoomListItem>>> {
206    stream! {
207        let mut raw_stream = pin!(raw_stream);
208
209        loop {
210            select! {
211                // We want to give priority on updates from `raw_stream` as it will necessarily trigger a “refresh” of the rooms.
212                biased;
213
214                diffs = raw_stream.next() => {
215                    if let Some(diffs) = diffs {
216                        let mut diffs = diffs.into_iter().map(|diff| diff.map(RoomListItem::from)).collect::<Vec<_>>();
217
218                        for diff in &diffs {
219                            diff.clone().map(|room| {
220                                trace!(room = %room.room_id(), "updated in response");
221                                room
222                            }).apply(&mut current_values);
223                        }
224
225                        for index in backfill_timestamps(&mut current_values) {
226                            diffs.push(VectorDiff::Set { index, value: current_values[index].clone() });
227                        }
228
229                        yield diffs;
230                    } else {
231                        // Restart immediately, don't keep on waiting for the receiver
232                        break;
233                    }
234                }
235
236                update = room_info_notable_update_receiver.recv() => {
237                    match update {
238                        Ok(update) => {
239                            // Drain every update already sitting in the
240                            // channel, so that a burst of updates (e.g. a
241                            // batch of freshly computed latest events, or the
242                            // per-room updates of one sync response) is
243                            // processed as a single batch of `VectorDiff`s.
244                            // Each room is kept once, in arrival order.
245                            let mut room_ids = Vec::new();
246                            let mut seen = std::collections::HashSet::new();
247                            let mut add = |update: RoomInfoNotableUpdate| {
248                                if seen.insert(update.room_id.clone()) {
249                                    room_ids.push(update.room_id);
250                                }
251                            };
252
253                            add(update);
254
255                            loop {
256                                use broadcast::error::TryRecvError;
257
258                                match room_info_notable_update_receiver.try_recv() {
259                                    Ok(update) => add(update),
260                                    Err(TryRecvError::Lagged(n)) => {
261                                        error!(number_of_missed_updates = n, "Lag when receiving room info notable update");
262                                    }
263                                    Err(TryRecvError::Empty | TryRecvError::Closed) => break,
264                                }
265                            }
266
267                            // Emit a `VectorDiff::Set` for each updated room,
268                            // and for each room whose back-filled timestamp
269                            // changed as a consequence.
270                            let mut indices = BTreeSet::new();
271
272                            for room_id in room_ids {
273                                if let Some(index) = current_values.iter().position(|room| room.room_id() == room_id) {
274                                    current_values[index].refresh_cached_data();
275                                    indices.insert(index);
276                                }
277                            }
278
279                            indices.extend(backfill_timestamps(&mut current_values));
280
281                            let diffs = indices
282                                .into_iter()
283                                .map(|index| VectorDiff::Set { index, value: current_values[index].clone() })
284                                .collect::<Vec<_>>();
285
286                            if !diffs.is_empty() {
287                                yield diffs;
288                            }
289                        }
290
291                        Err(RecvError::Closed) => {
292                            error!("Cannot receive room info notable updates because the sender has been closed");
293
294                            break;
295                        }
296
297                        Err(RecvError::Lagged(n)) => {
298                            error!(number_of_missed_updates = n, "Lag when receiving room info notable update");
299                        }
300                    }
301                }
302            }
303        }
304    }
305}
306
307/// Compute [`RoomListItem::cached_timestamp`] for every room in `rooms`, and
308/// return the indices of the rooms where it changed.
309///
310/// A room's timestamp is its latest event's timestamp. A room without one (e.g.
311/// right after login, before its latest event is computed) would otherwise be
312/// sorted after every room having one. Instead, the rooms are walked by recency
313/// stamp, from the most recent one, and a room without a latest event
314/// timestamp copies the smallest timestamp among the rooms above it. Rooms
315/// above every room having a timestamp copy the first one. When no room has a
316/// timestamp, they all get 0.
317///
318/// The _smallest_ timestamp is used because recency stamps and timestamps don't
319/// always agree (e.g. a room with a fresh local echo but an old recency stamp):
320/// copying from the nearest room alone could move a room above another one the
321/// server considers more recent.
322fn backfill_timestamps(rooms: &mut Vector<RoomListItem>) -> Vec<usize> {
323    // From the most recent recency stamp to the least recent one. On equal
324    // recency stamps, rooms having a timestamp come first, so that the others
325    // can copy it.
326    let mut indices = (0..rooms.len()).collect::<Vec<_>>();
327    indices.sort_by_key(|&index| {
328        let room = &rooms[index];
329        Reverse((room.cached_recency_stamp, room.cached_latest_event_timestamp.is_some()))
330    });
331
332    let mut copied_timestamp = indices
333        .iter()
334        .find_map(|&index| rooms[index].cached_latest_event_timestamp)
335        .unwrap_or(MilliSecondsSinceUnixEpoch(UInt::MIN));
336    let mut changed = Vec::new();
337
338    for index in indices {
339        let room = &mut rooms[index];
340
341        let timestamp = match room.cached_latest_event_timestamp {
342            Some(timestamp) => {
343                copied_timestamp = copied_timestamp.min(timestamp);
344                timestamp
345            }
346            None => copied_timestamp,
347        };
348
349        if room.cached_timestamp != timestamp {
350            room.cached_timestamp = timestamp;
351            changed.push(index);
352        }
353    }
354
355    changed
356}
357
358/// The loading state of a [`RoomList`].
359///
360/// When a [`RoomList`] is displayed to the user, it can be in various states.
361/// This enum tries to represent those states with a correct level of
362/// abstraction.
363///
364/// See [`RoomList::loading_state`].
365#[derive(Clone, Debug, PartialEq, Eq)]
366pub enum RoomListLoadingState {
367    /// The [`RoomList`] has not been loaded yet, i.e. a sync might run or not
368    /// run at all, there is nothing to show in this `RoomList` yet. It's a good
369    /// opportunity to show a placeholder to the user.
370    ///
371    /// From [`Self::NotLoaded`], it's only possible to move to
372    /// [`Self::Loaded`].
373    NotLoaded,
374
375    /// The [`RoomList`] has been loaded, i.e. a sync has been run, or more
376    /// syncs are running, there is probably something to show to the user.
377    /// Either the user has 0 room, in this case, it's a good opportunity to
378    /// show a special screen for that, or the user has multiple rooms, and it's
379    /// the classical room list.
380    ///
381    /// The number of rooms is represented by `maximum_number_of_rooms`.
382    ///
383    /// From [`Self::Loaded`], it's not possible to move back to
384    /// [`Self::NotLoaded`].
385    Loaded {
386        /// The maximum number of rooms a [`RoomList`] contains.
387        ///
388        /// It does not mean that there are exactly this many rooms to display.
389        /// The room entries are represented by [`RoomListItem`]. The room entry
390        /// might have been synced or not synced yet, but we know for sure (from
391        /// the server), that there will be this amount of rooms in the list at
392        /// the end.
393        ///
394        /// Note that it's an `Option`, because it may be possible that the
395        /// server did miss to send us this value. It's up to you, dear reader,
396        /// to know which default to adopt in case of `None`.
397        maximum_number_of_rooms: Option<u32>,
398    },
399}
400
401/// Controller for the [`RoomList`] dynamic entries.
402///
403/// To get one value of this type, use
404/// [`RoomList::entries_with_dynamic_adapters`]
405pub struct RoomListDynamicEntriesController {
406    filter: Arc<AsyncCell<BoxedFilterFn>>,
407    page_size: usize,
408    limit: SharedObservable<usize>,
409    maximum_number_of_rooms: Subscriber<Option<u32>>,
410}
411
412impl RoomListDynamicEntriesController {
413    fn new(
414        filter: Arc<AsyncCell<BoxedFilterFn>>,
415        page_size: usize,
416        limit_stream: SharedObservable<usize>,
417        maximum_number_of_rooms: Subscriber<Option<u32>>,
418    ) -> Self {
419        Self { filter, page_size, limit: limit_stream, maximum_number_of_rooms }
420    }
421
422    /// Set the filter.
423    ///
424    /// If the associated stream has been dropped, returns `false` to indicate
425    /// the operation didn't have an effect.
426    pub fn set_filter(&self, filter: BoxedFilterFn) -> bool {
427        if Arc::strong_count(&self.filter) == 1 {
428            // there is no other reference to the boxed filter fn, setting it
429            // would be pointless (no new references can be created from self,
430            // either)
431            false
432        } else {
433            self.filter.set(filter);
434            true
435        }
436    }
437
438    /// Add one page, i.e. view `page_size` more entries in the room list if
439    /// any.
440    pub fn add_one_page(&self) {
441        let Some(max) = self.maximum_number_of_rooms.get() else {
442            return;
443        };
444
445        let max: usize = max.try_into().unwrap();
446        let limit = self.limit.get();
447
448        if limit < max {
449            // With this logic, it is possible that `limit` becomes greater than
450            // `max` if `max - limit < page_size`, and that's perfectly fine.
451            // It's OK to have a `limit` greater than `max`, but it's not OK to
452            // increase the limit indefinitely.
453            self.limit.set_if_not_eq(limit + self.page_size);
454        }
455    }
456
457    /// Reset the one page, i.e. forget all pages and move back to the first
458    /// page.
459    pub fn reset_to_one_page(&self) {
460        self.limit.set_if_not_eq(self.page_size);
461    }
462}
463
464/// A facade type that derefs to [`Room`] and that caches data from
465/// [`RoomInfo`].
466///
467/// Why caching data? [`RoomInfo`] is behind a lock. Every time a filter or a
468/// sorter calls a method on [`Room`], it's likely to hit the lock in front of
469/// [`RoomInfo`]. It creates a big contention. By caching the data, it avoids
470/// hitting the lock, improving the performance greatly.
471///
472/// Data are refreshed in `merge_stream_and_receiver` (private function).
473///
474/// [`RoomInfo`]: matrix_sdk::RoomInfo
475#[derive(Clone, Debug)]
476pub struct RoomListItem {
477    /// The inner room.
478    inner: Room,
479
480    /// Cache of `Room::latest_event_timestamp`.
481    pub(super) cached_latest_event_timestamp: Option<MilliSecondsSinceUnixEpoch>,
482
483    /// The timestamp used to sort this room: `cached_latest_event_timestamp`,
484    /// or, when this room has none, a timestamp back-filled from other rooms,
485    /// see `backfill_timestamps` (private function). Not touched by
486    /// [`Self::refresh_cached_data`].
487    pub(super) cached_timestamp: MilliSecondsSinceUnixEpoch,
488
489    /// Cache of `Room::latest_event_is_unsent`.
490    pub(super) cached_latest_event_is_unsent: bool,
491
492    /// Cache of `Room::recency_stamp`, 0 when the room has none.
493    pub(super) cached_recency_stamp: RoomRecencyStamp,
494
495    /// Cache of `Room::cached_display_name`, already as a string.
496    pub(super) cached_display_name: Option<String>,
497
498    /// Cache of `Room::is_space`.
499    pub(super) cached_is_space: bool,
500
501    // Cache of `Room::state`.
502    pub(super) cached_state: RoomState,
503}
504
505impl RoomListItem {
506    #[cfg(test)]
507    pub(super) fn inner(&self) -> &Room {
508        &self.inner
509    }
510
511    /// Deconstruct to the inner room value.
512    pub fn into_inner(self) -> Room {
513        self.inner
514    }
515
516    /// Refresh the cached data.
517    pub(super) fn refresh_cached_data(&mut self) {
518        self.cached_latest_event_timestamp = self.inner.latest_event_timestamp();
519        self.cached_latest_event_is_unsent = self.inner.latest_event_is_unsent();
520        self.cached_recency_stamp = self.inner.recency_stamp().unwrap_or(0.into());
521        self.cached_display_name = self.inner.cached_display_name().map(|name| name.to_string());
522        self.cached_is_space = self.inner.is_space();
523        self.cached_state = self.inner.state();
524    }
525}
526
527impl From<Room> for RoomListItem {
528    fn from(inner: Room) -> Self {
529        let cached_latest_event_timestamp = inner.latest_event_timestamp();
530        let cached_latest_event_is_unsent = inner.latest_event_is_unsent();
531        let cached_recency_stamp = inner.recency_stamp().unwrap_or(0.into());
532        let cached_display_name = inner.cached_display_name().map(|name| name.to_string());
533        let cached_is_space = inner.is_space();
534        let cached_state = inner.state();
535
536        Self {
537            inner,
538            cached_latest_event_timestamp,
539            cached_timestamp: cached_latest_event_timestamp
540                .unwrap_or(MilliSecondsSinceUnixEpoch(UInt::MIN)),
541            cached_latest_event_is_unsent,
542            cached_recency_stamp,
543            cached_display_name,
544            cached_is_space,
545            cached_state,
546        }
547    }
548}
549
550impl Deref for RoomListItem {
551    type Target = Room;
552
553    fn deref(&self) -> &Self::Target {
554        &self.inner
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use matrix_sdk::test_utils::mocks::MatrixMockServer;
561    use matrix_sdk_test::async_test;
562    use ruma::{OwnedRoomId, RoomId};
563
564    use super::{super::filters::new_rooms, *};
565
566    /// Create rooms with the given `(latest event timestamp, recency stamp)`.
567    async fn rooms<const N: usize>(stamps: [(Option<u32>, u64); N]) -> Vector<RoomListItem> {
568        let server = MatrixMockServer::new().await;
569        let client = server.client_builder().build().await;
570        let room_ids: [OwnedRoomId; N] =
571            std::array::from_fn(|nth| RoomId::parse(format!("!{nth}:x.y")).unwrap());
572        let mut rooms = new_rooms(room_ids.each_ref().map(AsRef::as_ref), &client, &server).await;
573
574        for (room, (timestamp, recency_stamp)) in rooms.iter_mut().zip(stamps) {
575            room.cached_latest_event_timestamp =
576                timestamp.map(|ts| MilliSecondsSinceUnixEpoch(UInt::from(ts)));
577            room.cached_timestamp =
578                room.cached_latest_event_timestamp.unwrap_or(MilliSecondsSinceUnixEpoch(UInt::MIN));
579            room.cached_recency_stamp = recency_stamp.into();
580        }
581
582        rooms.into_iter().collect()
583    }
584
585    fn timestamps(rooms: &Vector<RoomListItem>) -> Vec<u64> {
586        rooms.iter().map(|room| room.cached_timestamp.get().into()).collect()
587    }
588
589    #[async_test]
590    async fn test_backfill_timestamps() {
591        let mut rooms = rooms([
592            (Some(300), 30),
593            (None, 40), // above every timestamp: copies the first one, `!0`'s
594            (None, 10), // smallest timestamp above is `!4`'s
595            (None, 25), // smallest timestamp above is `!0`'s
596            (Some(200), 20),
597        ])
598        .await;
599
600        // Indices are reported in recency stamp order.
601        assert_eq!(backfill_timestamps(&mut rooms), vec![1, 3, 2]);
602        assert_eq!(timestamps(&rooms), vec![300, 300, 200, 300, 200]);
603
604        // Nothing changed: nothing to report.
605        assert!(backfill_timestamps(&mut rooms).is_empty());
606
607        // `!2` gets its own timestamp: it replaces the copied one.
608        rooms[2].cached_latest_event_timestamp =
609            Some(MilliSecondsSinceUnixEpoch(UInt::from(100u32)));
610
611        assert_eq!(backfill_timestamps(&mut rooms), vec![2]);
612        assert_eq!(timestamps(&rooms), vec![300, 300, 100, 300, 200]);
613
614        // `!2` loses its own timestamp: it copies one again, instead of being
615        // reset to 0.
616        rooms[2].cached_latest_event_timestamp = None;
617
618        assert_eq!(backfill_timestamps(&mut rooms), vec![2]);
619        assert_eq!(timestamps(&rooms), vec![300, 300, 200, 300, 200]);
620    }
621
622    /// A room with a fresh timestamp but an old recency stamp must not lift the
623    /// rooms below it above a room the server considers more recent.
624    #[async_test]
625    async fn test_backfill_timestamps_takes_the_smallest_timestamp() {
626        let mut rooms = rooms([
627            (Some(500), 100), // recent room
628            (Some(1000), 5),  // fresh timestamp, old recency stamp
629            (None, 4),
630        ])
631        .await;
632
633        backfill_timestamps(&mut rooms);
634
635        assert_eq!(timestamps(&rooms), vec![500, 1000, 500]);
636    }
637
638    #[async_test]
639    async fn test_backfill_timestamps_without_any_timestamp() {
640        let mut rooms = rooms([(None, 2), (None, 1)]).await;
641
642        assert!(backfill_timestamps(&mut rooms).is_empty());
643        assert_eq!(timestamps(&rooms), vec![0, 0]);
644    }
645}