src/windows/room/space.rs

260 lines · 7939 bytes

  1//! Window for Matrix spaces
  2use std::ops::{Deref, DerefMut};
  3use std::str::FromStr;
  4use std::time::{Duration, Instant};
  5
  6use matrix_sdk::ruma::OwnedSpaceChildOrder;
  7use matrix_sdk::ruma::events::StateEventType;
  8use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
  9use matrix_sdk::{
 10    room::Room as MatrixRoom,
 11    ruma::{OwnedRoomId, RoomId},
 12};
 13
 14use modalkit::prelude::{EditInfo, InfoMessage};
 15use ratatui::{
 16    buffer::Buffer,
 17    layout::Rect,
 18    style::{Color, Style},
 19    text::{Line, Span, Text},
 20    widgets::StatefulWidget,
 21};
 22
 23use modalkit_ratatui::{
 24    TermOffset,
 25    TerminalCursor,
 26    WindowOps,
 27    list::{List, ListState},
 28};
 29
 30use crate::base::{
 31    IambBufferId,
 32    IambError,
 33    IambInfo,
 34    IambResult,
 35    ProgramContext,
 36    ProgramStore,
 37    RoomFocus,
 38    SpaceAction,
 39};
 40
 41use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp};
 42
 43const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
 44
 45/// State needed for rendering [Space].
 46pub struct SpaceState {
 47    room_id: OwnedRoomId,
 48    room: MatrixRoom,
 49    list: ListState<RoomItem, IambInfo>,
 50    last_fetch: Option<Instant>,
 51}
 52
 53impl SpaceState {
 54    pub fn new(room: MatrixRoom) -> Self {
 55        let room_id = room.room_id().to_owned();
 56        let content = IambBufferId::Room(room_id.clone(), None, RoomFocus::Scrollback);
 57        let list = ListState::new(content, vec![]);
 58        let last_fetch = None;
 59
 60        SpaceState { room_id, room, list, last_fetch }
 61    }
 62
 63    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 64        if let Some(room) = store.application.worker.client.get_room(self.id()) {
 65            self.room = room;
 66        }
 67    }
 68
 69    pub fn room(&self) -> &MatrixRoom {
 70        &self.room
 71    }
 72
 73    pub fn id(&self) -> &RoomId {
 74        &self.room_id
 75    }
 76
 77    pub fn dup(&self, store: &mut ProgramStore) -> Self {
 78        SpaceState {
 79            room_id: self.room_id.clone(),
 80            room: self.room.clone(),
 81            list: self.list.dup(store),
 82            last_fetch: self.last_fetch,
 83        }
 84    }
 85
 86    pub async fn space_command(
 87        &mut self,
 88        act: SpaceAction,
 89        _: ProgramContext,
 90        store: &mut ProgramStore,
 91    ) -> IambResult<EditInfo> {
 92        match act {
 93            SpaceAction::SetChild { child, order, suggested } => {
 94                if !self
 95                    .room
 96                    .power_levels()
 97                    .await
 98                    .map_err(matrix_sdk::Error::from)
 99                    .map_err(IambError::from)?
100                    .user_can_send_state(
101                        &store.application.settings.profile.user_id,
102                        StateEventType::SpaceChild,
103                    )
104                {
105                    return Err(IambError::InsufficientPermission.into());
106                }
107
108                let child_id = store.application.worker.join_room(child)?;
109
110                let via = self.room.route().await.map_err(IambError::from)?;
111                let mut ev = SpaceChildEventContent::new(via);
112                ev.order = order
113                    .as_deref()
114                    .map(OwnedSpaceChildOrder::from_str)
115                    .transpose()
116                    .map_err(IambError::InvalidSpaceChildOrder)?;
117                ev.suggested = suggested;
118                let _ = self
119                    .room
120                    .send_state_event_for_key(&child_id, ev)
121                    .await
122                    .map_err(IambError::from)?;
123
124                Ok(InfoMessage::from("Space updated").into())
125            },
126            SpaceAction::RemoveChild => {
127                let space = self.list.get().ok_or(IambError::NoSelectedRoomOrSpaceItem)?;
128                if !self
129                    .room
130                    .power_levels()
131                    .await
132                    .map_err(matrix_sdk::Error::from)
133                    .map_err(IambError::from)?
134                    .user_can_send_state(
135                        &store.application.settings.profile.user_id,
136                        StateEventType::SpaceChild,
137                    )
138                {
139                    return Err(IambError::InsufficientPermission.into());
140                }
141
142                let ev = SpaceChildEventContent::new(vec![]);
143                let event_id = self
144                    .room
145                    .send_state_event_for_key(&space.room_id().to_owned(), ev)
146                    .await
147                    .map_err(IambError::from)?;
148
149                // Fix for element (see https://github.com/element-hq/element-web/issues/29606)
150                let _ = self
151                    .room
152                    .redact(&event_id.event_id, Some("workaround for element bug"), None)
153                    .await
154                    .map_err(IambError::from)?;
155
156                Ok(InfoMessage::from("Room removed").into())
157            },
158        }
159    }
160}
161
162impl TerminalCursor for SpaceState {
163    fn get_term_cursor(&self) -> Option<TermOffset> {
164        self.list.get_term_cursor()
165    }
166
167    fn hide_term_cursor(&self) -> bool {
168        self.list.hide_term_cursor()
169    }
170}
171
172impl Deref for SpaceState {
173    type Target = ListState<RoomItem, IambInfo>;
174
175    fn deref(&self) -> &Self::Target {
176        &self.list
177    }
178}
179
180impl DerefMut for SpaceState {
181    fn deref_mut(&mut self) -> &mut Self::Target {
182        &mut self.list
183    }
184}
185
186/// [StatefulWidget] for Matrix spaces.
187pub struct Space<'a> {
188    focused: bool,
189    store: &'a mut ProgramStore,
190}
191
192impl<'a> Space<'a> {
193    pub fn new(store: &'a mut ProgramStore) -> Self {
194        Space { focused: false, store }
195    }
196
197    pub fn focus(mut self, focused: bool) -> Self {
198        self.focused = focused;
199        self
200    }
201}
202
203impl StatefulWidget for Space<'_> {
204    type State = SpaceState;
205
206    fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
207        state.set_ignorecase(self.store.application.settings.tunables.ignorecase);
208
209        let mut empty_message = None;
210        let need_fetch = match state.last_fetch {
211            Some(i) => i.elapsed() >= SPACE_HIERARCHY_DEBOUNCE,
212            None => true,
213        };
214
215        if need_fetch {
216            let res = self.store.application.worker.space_members(state.room_id.clone());
217
218            match res {
219                Ok(members) => {
220                    let mut items = members
221                        .into_iter()
222                        .filter_map(|id| {
223                            let (room, _, tags) =
224                                self.store.application.worker.get_room(id.clone()).ok()?;
225                            let room_info = std::sync::Arc::new((room, tags));
226
227                            if id != state.room_id {
228                                Some(RoomItem::new(room_info, self.store))
229                            } else {
230                                None
231                            }
232                        })
233                        .collect::<Vec<_>>();
234                    let fields = &self.store.application.settings.tunables.sort.rooms;
235                    let collator = &mut self.store.application.collator;
236                    items.sort_by(|a, b| room_fields_cmp(a, b, fields, collator));
237
238                    state.list.set(items);
239                    state.last_fetch = Some(Instant::now());
240                },
241                Err(e) => {
242                    let lines = vec![
243                        Line::from("Unable to fetch space room hierarchy:"),
244                        Span::styled(e.to_string(), Style::default().fg(Color::Red)).into(),
245                    ];
246
247                    empty_message = Text::from(lines).into();
248                },
249            }
250        }
251
252        let mut list = List::new(self.store).focus(self.focused);
253
254        if let Some(text) = empty_message {
255            list = list.empty_message(text);
256        }
257
258        list.render(area, buffer, &mut state.list)
259    }
260}