src/base.rs

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