src/base.rs

517 lines · 14858 bytes

  1use std::collections::{HashMap, HashSet};
  2use std::hash::Hash;
  3use std::sync::Arc;
  4use std::time::{Duration, Instant};
  5
  6use tokio::sync::Mutex as AsyncMutex;
  7use tracing::warn;
  8
  9use matrix_sdk::{
 10    encryption::verification::SasVerification,
 11    ruma::{OwnedRoomId, OwnedUserId, RoomId},
 12};
 13
 14use modalkit::{
 15    editing::{
 16        action::{Action, UIError, UIResult},
 17        application::{
 18            ApplicationAction,
 19            ApplicationContentId,
 20            ApplicationError,
 21            ApplicationInfo,
 22            ApplicationStore,
 23            ApplicationWindowId,
 24        },
 25        context::EditContext,
 26        store::Store,
 27    },
 28    env::vim::{
 29        command::{CommandContext, VimCommand, VimCommandMachine},
 30        keybindings::VimMachine,
 31        VimContext,
 32    },
 33    input::bindings::SequenceStatus,
 34    input::key::TerminalKey,
 35    tui::{
 36        buffer::Buffer,
 37        layout::{Alignment, Rect},
 38        text::{Span, Spans},
 39        widgets::{Paragraph, Widget},
 40    },
 41};
 42
 43use crate::{
 44    message::{user_style, Message, Messages},
 45    worker::Requester,
 46    ApplicationSettings,
 47};
 48
 49const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(3);
 50
 51#[derive(Clone, Debug, Eq, PartialEq)]
 52pub enum IambInfo {}
 53
 54#[derive(Clone, Debug, Eq, PartialEq)]
 55pub enum VerifyAction {
 56    Accept,
 57    Cancel,
 58    Confirm,
 59    Mismatch,
 60}
 61
 62#[derive(Clone, Debug, Eq, PartialEq)]
 63pub enum SetRoomField {
 64    Name(String),
 65    Topic(String),
 66}
 67
 68#[derive(Clone, Debug, Eq, PartialEq)]
 69pub enum RoomAction {
 70    Members(Box<CommandContext<ProgramContext>>),
 71    Set(SetRoomField),
 72}
 73
 74impl From<SetRoomField> for RoomAction {
 75    fn from(act: SetRoomField) -> Self {
 76        RoomAction::Set(act)
 77    }
 78}
 79
 80#[derive(Clone, Debug, Eq, PartialEq)]
 81pub enum IambAction {
 82    Room(RoomAction),
 83    Verify(VerifyAction, String),
 84    VerifyRequest(String),
 85    SendMessage(OwnedRoomId, String),
 86    ToggleScrollbackFocus,
 87}
 88
 89impl From<RoomAction> for IambAction {
 90    fn from(act: RoomAction) -> Self {
 91        IambAction::Room(act)
 92    }
 93}
 94
 95impl ApplicationAction for IambAction {
 96    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
 97        match self {
 98            IambAction::Room(..) => SequenceStatus::Break,
 99            IambAction::SendMessage(..) => SequenceStatus::Break,
100            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
101            IambAction::Verify(..) => SequenceStatus::Break,
102            IambAction::VerifyRequest(..) => SequenceStatus::Break,
103        }
104    }
105
106    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
107        match self {
108            IambAction::Room(..) => SequenceStatus::Atom,
109            IambAction::SendMessage(..) => SequenceStatus::Atom,
110            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
111            IambAction::Verify(..) => SequenceStatus::Atom,
112            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
113        }
114    }
115
116    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
117        match self {
118            IambAction::Room(..) => SequenceStatus::Ignore,
119            IambAction::SendMessage(..) => SequenceStatus::Ignore,
120            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
121            IambAction::Verify(..) => SequenceStatus::Ignore,
122            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
123        }
124    }
125
126    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
127        match self {
128            IambAction::Room(..) => false,
129            IambAction::SendMessage(..) => false,
130            IambAction::ToggleScrollbackFocus => false,
131            IambAction::Verify(..) => false,
132            IambAction::VerifyRequest(..) => false,
133        }
134    }
135}
136
137impl From<IambAction> for ProgramAction {
138    fn from(act: IambAction) -> Self {
139        Action::Application(act)
140    }
141}
142
143pub type ProgramAction = Action<IambInfo>;
144pub type ProgramContext = VimContext<IambInfo>;
145pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
146pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
147pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
148pub type ProgramStore = Store<IambInfo>;
149pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
150
151pub type IambResult<T> = UIResult<T, IambInfo>;
152
153#[derive(thiserror::Error, Debug)]
154pub enum IambError {
155    #[error("Unknown room identifier: {0}")]
156    InvalidUserId(String),
157
158    #[error("Invalid verification user/device pair: {0}")]
159    InvalidVerificationId(String),
160
161    #[error("Cryptographic storage error: {0}")]
162    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
163
164    #[error("HTTP client error: {0}")]
165    Http(#[from] matrix_sdk::HttpError),
166
167    #[error("Matrix client error: {0}")]
168    Matrix(#[from] matrix_sdk::Error),
169
170    #[error("Matrix client storage error: {0}")]
171    Store(#[from] matrix_sdk::StoreError),
172
173    #[error("Serialization/deserialization error: {0}")]
174    Serde(#[from] serde_json::Error),
175
176    #[error("Unknown room identifier: {0}")]
177    UnknownRoom(OwnedRoomId),
178
179    #[error("Verification request error: {0}")]
180    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
181}
182
183impl From<IambError> for UIError<IambInfo> {
184    fn from(err: IambError) -> Self {
185        UIError::Application(err)
186    }
187}
188
189impl ApplicationError for IambError {}
190
191#[derive(Default)]
192pub enum RoomFetchStatus {
193    Done,
194    HaveMore(String),
195    #[default]
196    NotStarted,
197}
198
199#[derive(Default)]
200pub struct RoomInfo {
201    pub name: Option<String>,
202    pub messages: Messages,
203    pub fetch_id: RoomFetchStatus,
204    pub fetch_last: Option<Instant>,
205    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
206}
207
208impl RoomInfo {
209    fn recently_fetched(&self) -> bool {
210        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
211    }
212
213    fn get_typers(&self) -> &[OwnedUserId] {
214        if let Some((t, users)) = &self.users_typing {
215            if t.elapsed() < Duration::from_secs(4) {
216                return users.as_ref();
217            } else {
218                return &[];
219            }
220        } else {
221            return &[];
222        }
223    }
224
225    fn get_typing_spans(&self) -> Spans {
226        let typers = self.get_typers();
227        let n = typers.len();
228
229        match n {
230            0 => Spans(vec![]),
231            1 => {
232                let user = typers[0].as_str();
233                let user = Span::styled(user, user_style(user));
234
235                Spans(vec![user, Span::from(" is typing...")])
236            },
237            2 => {
238                let user1 = typers[0].as_str();
239                let user1 = Span::styled(user1, user_style(user1));
240
241                let user2 = typers[1].as_str();
242                let user2 = Span::styled(user2, user_style(user2));
243
244                Spans(vec![
245                    user1,
246                    Span::raw(" and "),
247                    user2,
248                    Span::from(" are typing..."),
249                ])
250            },
251            n if n < 5 => Spans::from("Several people are typing..."),
252            _ => Spans::from("Many people are typing..."),
253        }
254    }
255
256    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
257        self.users_typing = (Instant::now(), user_ids).into();
258    }
259
260    pub fn render_typing(
261        &mut self,
262        area: Rect,
263        buf: &mut Buffer,
264        settings: &ApplicationSettings,
265    ) -> Rect {
266        if area.height <= 2 || area.width <= 20 {
267            return area;
268        }
269
270        if !settings.tunables.typing_notice_display {
271            return area;
272        }
273
274        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
275        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
276
277        Paragraph::new(self.get_typing_spans())
278            .alignment(Alignment::Center)
279            .render(bar, buf);
280
281        return top;
282    }
283}
284
285pub struct ChatStore {
286    pub worker: Requester,
287    pub rooms: HashMap<OwnedRoomId, RoomInfo>,
288    pub names: HashMap<String, OwnedRoomId>,
289    pub verifications: HashMap<String, SasVerification>,
290    pub settings: ApplicationSettings,
291    pub need_load: HashSet<OwnedRoomId>,
292}
293
294impl ChatStore {
295    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
296        ChatStore {
297            worker,
298            settings,
299
300            names: Default::default(),
301            rooms: Default::default(),
302            verifications: Default::default(),
303            need_load: Default::default(),
304        }
305    }
306
307    pub fn get_room_title(&self, room_id: &RoomId) -> String {
308        self.rooms
309            .get(room_id)
310            .and_then(|i| i.name.as_ref())
311            .map(String::from)
312            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
313    }
314
315    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
316        self.need_load.insert(room_id);
317    }
318
319    pub fn load_older(&mut self, limit: u32) {
320        let ChatStore { need_load, rooms, worker, .. } = self;
321
322        for room_id in std::mem::take(need_load).into_iter() {
323            let info = rooms.entry(room_id.clone()).or_default();
324
325            if info.recently_fetched() {
326                need_load.insert(room_id);
327                continue;
328            } else {
329                info.fetch_last = Instant::now().into();
330            }
331
332            let fetch_id = match &info.fetch_id {
333                RoomFetchStatus::Done => continue,
334                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
335                RoomFetchStatus::NotStarted => None,
336            };
337
338            let res = worker.load_older(room_id.clone(), fetch_id, limit);
339
340            match res {
341                Ok((fetch_id, msgs)) => {
342                    for msg in msgs.into_iter() {
343                        let key = (msg.origin_server_ts().into(), msg.event_id().to_owned());
344
345                        info.messages.insert(key, Message::from(msg));
346                    }
347
348                    info.fetch_id =
349                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
350                },
351                Err(e) => {
352                    warn!(
353                        room_id = room_id.as_str(),
354                        err = e.to_string(),
355                        "Failed to load older messages"
356                    );
357
358                    // Wait and try again.
359                    need_load.insert(room_id);
360                },
361            }
362        }
363    }
364
365    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
366        self.rooms.entry(room_id).or_default()
367    }
368
369    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
370        self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
371    }
372
373    pub fn insert_sas(&mut self, sas: SasVerification) {
374        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
375
376        self.verifications.insert(key, sas);
377    }
378}
379
380impl ApplicationStore for ChatStore {}
381
382#[derive(Clone, Debug, Eq, Hash, PartialEq)]
383pub enum IambId {
384    Room(OwnedRoomId),
385    DirectList,
386    MemberList(OwnedRoomId),
387    RoomList,
388    SpaceList,
389    VerifyList,
390    Welcome,
391}
392
393impl ApplicationWindowId for IambId {}
394
395#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
396pub enum RoomFocus {
397    Scrollback,
398    MessageBar,
399}
400
401impl RoomFocus {
402    pub fn is_scrollback(&self) -> bool {
403        matches!(self, RoomFocus::Scrollback)
404    }
405
406    pub fn is_msgbar(&self) -> bool {
407        matches!(self, RoomFocus::MessageBar)
408    }
409}
410
411#[derive(Clone, Debug, Eq, Hash, PartialEq)]
412pub enum IambBufferId {
413    Command,
414    Room(OwnedRoomId, RoomFocus),
415    DirectList,
416    MemberList(OwnedRoomId),
417    RoomList,
418    SpaceList,
419    VerifyList,
420    Welcome,
421}
422
423impl IambBufferId {
424    pub fn to_window(&self) -> Option<IambId> {
425        match self {
426            IambBufferId::Command => None,
427            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
428            IambBufferId::DirectList => Some(IambId::DirectList),
429            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
430            IambBufferId::RoomList => Some(IambId::RoomList),
431            IambBufferId::SpaceList => Some(IambId::SpaceList),
432            IambBufferId::VerifyList => Some(IambId::VerifyList),
433            IambBufferId::Welcome => Some(IambId::Welcome),
434        }
435    }
436}
437
438impl ApplicationContentId for IambBufferId {}
439
440impl ApplicationInfo for IambInfo {
441    type Error = IambError;
442    type Store = ChatStore;
443    type Action = IambAction;
444    type WindowId = IambId;
445    type ContentId = IambBufferId;
446}
447
448#[cfg(test)]
449pub mod tests {
450    use super::*;
451    use crate::tests::*;
452
453    #[test]
454    fn test_typing_spans() {
455        let mut info = RoomInfo::default();
456
457        let users0 = vec![];
458        let users1 = vec![TEST_USER1.clone()];
459        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
460        let users4 = vec![
461            TEST_USER1.clone(),
462            TEST_USER2.clone(),
463            TEST_USER3.clone(),
464            TEST_USER4.clone(),
465        ];
466        let users5 = vec![
467            TEST_USER1.clone(),
468            TEST_USER2.clone(),
469            TEST_USER3.clone(),
470            TEST_USER4.clone(),
471            TEST_USER5.clone(),
472        ];
473
474        // Nothing set.
475        assert_eq!(info.users_typing, None);
476        assert_eq!(info.get_typing_spans(), Spans(vec![]));
477
478        // Empty typing list.
479        info.set_typing(users0);
480        assert!(info.users_typing.is_some());
481        assert_eq!(info.get_typing_spans(), Spans(vec![]));
482
483        // Single user typing.
484        info.set_typing(users1);
485        assert!(info.users_typing.is_some());
486        assert_eq!(
487            info.get_typing_spans(),
488            Spans(vec![
489                Span::styled("@user1:example.com", user_style("@user1:example.com")),
490                Span::from(" is typing...")
491            ])
492        );
493
494        // Two users typing.
495        info.set_typing(users2);
496        assert!(info.users_typing.is_some());
497        assert_eq!(
498            info.get_typing_spans(),
499            Spans(vec![
500                Span::styled("@user1:example.com", user_style("@user1:example.com")),
501                Span::raw(" and "),
502                Span::styled("@user2:example.com", user_style("@user2:example.com")),
503                Span::raw(" are typing...")
504            ])
505        );
506
507        // Four users typing.
508        info.set_typing(users4);
509        assert!(info.users_typing.is_some());
510        assert_eq!(info.get_typing_spans(), Spans::from("Several people are typing..."));
511
512        // Five users typing.
513        info.set_typing(users5);
514        assert!(info.users_typing.is_some());
515        assert_eq!(info.get_typing_spans(), Spans::from("Many people are typing..."));
516    }
517}