src/base.rs

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