src/base.rs

527 lines · 15360 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::{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, settings: &ApplicationSettings) -> 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 = settings.get_user_span(typers[0].as_ref());
233
234                Spans(vec![user, Span::from(" is typing...")])
235            },
236            2 => {
237                let user1 = settings.get_user_span(typers[0].as_ref());
238                let user2 = settings.get_user_span(typers[1].as_ref());
239
240                Spans(vec![
241                    user1,
242                    Span::raw(" and "),
243                    user2,
244                    Span::from(" are typing..."),
245                ])
246            },
247            n if n < 5 => Spans::from("Several people are typing..."),
248            _ => Spans::from("Many people are typing..."),
249        }
250    }
251
252    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
253        self.users_typing = (Instant::now(), user_ids).into();
254    }
255
256    pub fn render_typing(
257        &mut self,
258        area: Rect,
259        buf: &mut Buffer,
260        settings: &ApplicationSettings,
261    ) -> Rect {
262        if area.height <= 2 || area.width <= 20 {
263            return area;
264        }
265
266        if !settings.tunables.typing_notice_display {
267            return area;
268        }
269
270        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
271        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
272
273        Paragraph::new(self.get_typing_spans(settings))
274            .alignment(Alignment::Center)
275            .render(bar, buf);
276
277        return top;
278    }
279}
280
281pub struct ChatStore {
282    pub worker: Requester,
283    pub rooms: HashMap<OwnedRoomId, RoomInfo>,
284    pub names: HashMap<String, OwnedRoomId>,
285    pub verifications: HashMap<String, SasVerification>,
286    pub settings: ApplicationSettings,
287    pub need_load: HashSet<OwnedRoomId>,
288}
289
290impl ChatStore {
291    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
292        ChatStore {
293            worker,
294            settings,
295
296            names: Default::default(),
297            rooms: Default::default(),
298            verifications: Default::default(),
299            need_load: Default::default(),
300        }
301    }
302
303    pub fn get_room_title(&self, room_id: &RoomId) -> String {
304        self.rooms
305            .get(room_id)
306            .and_then(|i| i.name.as_ref())
307            .map(String::from)
308            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
309    }
310
311    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
312        self.need_load.insert(room_id);
313    }
314
315    pub fn load_older(&mut self, limit: u32) {
316        let ChatStore { need_load, rooms, worker, .. } = self;
317
318        for room_id in std::mem::take(need_load).into_iter() {
319            let info = rooms.entry(room_id.clone()).or_default();
320
321            if info.recently_fetched() {
322                need_load.insert(room_id);
323                continue;
324            } else {
325                info.fetch_last = Instant::now().into();
326            }
327
328            let fetch_id = match &info.fetch_id {
329                RoomFetchStatus::Done => continue,
330                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
331                RoomFetchStatus::NotStarted => None,
332            };
333
334            let res = worker.load_older(room_id.clone(), fetch_id, limit);
335
336            match res {
337                Ok((fetch_id, msgs)) => {
338                    for msg in msgs.into_iter() {
339                        let key = (msg.origin_server_ts().into(), msg.event_id().to_owned());
340
341                        info.messages.insert(key, Message::from(msg));
342                    }
343
344                    info.fetch_id =
345                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
346                },
347                Err(e) => {
348                    warn!(
349                        room_id = room_id.as_str(),
350                        err = e.to_string(),
351                        "Failed to load older messages"
352                    );
353
354                    // Wait and try again.
355                    need_load.insert(room_id);
356                },
357            }
358        }
359    }
360
361    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
362        self.rooms.entry(room_id).or_default()
363    }
364
365    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
366        self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
367    }
368
369    pub fn insert_sas(&mut self, sas: SasVerification) {
370        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
371
372        self.verifications.insert(key, sas);
373    }
374}
375
376impl ApplicationStore for ChatStore {}
377
378#[derive(Clone, Debug, Eq, Hash, PartialEq)]
379pub enum IambId {
380    Room(OwnedRoomId),
381    DirectList,
382    MemberList(OwnedRoomId),
383    RoomList,
384    SpaceList,
385    VerifyList,
386    Welcome,
387}
388
389impl ApplicationWindowId for IambId {}
390
391#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
392pub enum RoomFocus {
393    Scrollback,
394    MessageBar,
395}
396
397impl RoomFocus {
398    pub fn is_scrollback(&self) -> bool {
399        matches!(self, RoomFocus::Scrollback)
400    }
401
402    pub fn is_msgbar(&self) -> bool {
403        matches!(self, RoomFocus::MessageBar)
404    }
405}
406
407#[derive(Clone, Debug, Eq, Hash, PartialEq)]
408pub enum IambBufferId {
409    Command,
410    Room(OwnedRoomId, RoomFocus),
411    DirectList,
412    MemberList(OwnedRoomId),
413    RoomList,
414    SpaceList,
415    VerifyList,
416    Welcome,
417}
418
419impl IambBufferId {
420    pub fn to_window(&self) -> Option<IambId> {
421        match self {
422            IambBufferId::Command => None,
423            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
424            IambBufferId::DirectList => Some(IambId::DirectList),
425            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
426            IambBufferId::RoomList => Some(IambId::RoomList),
427            IambBufferId::SpaceList => Some(IambId::SpaceList),
428            IambBufferId::VerifyList => Some(IambId::VerifyList),
429            IambBufferId::Welcome => Some(IambId::Welcome),
430        }
431    }
432}
433
434impl ApplicationContentId for IambBufferId {}
435
436impl ApplicationInfo for IambInfo {
437    type Error = IambError;
438    type Store = ChatStore;
439    type Action = IambAction;
440    type WindowId = IambId;
441    type ContentId = IambBufferId;
442}
443
444#[cfg(test)]
445pub mod tests {
446    use super::*;
447    use crate::config::{user_style, user_style_from_color};
448    use crate::tests::*;
449    use modalkit::tui::style::Color;
450
451    #[test]
452    fn test_typing_spans() {
453        let mut info = RoomInfo::default();
454        let settings = mock_settings();
455
456        let users0 = vec![];
457        let users1 = vec![TEST_USER1.clone()];
458        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
459        let users4 = vec![
460            TEST_USER1.clone(),
461            TEST_USER2.clone(),
462            TEST_USER3.clone(),
463            TEST_USER4.clone(),
464        ];
465        let users5 = vec![
466            TEST_USER1.clone(),
467            TEST_USER2.clone(),
468            TEST_USER3.clone(),
469            TEST_USER4.clone(),
470            TEST_USER5.clone(),
471        ];
472
473        // Nothing set.
474        assert_eq!(info.users_typing, None);
475        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
476
477        // Empty typing list.
478        info.set_typing(users0);
479        assert!(info.users_typing.is_some());
480        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
481
482        // Single user typing.
483        info.set_typing(users1);
484        assert!(info.users_typing.is_some());
485        assert_eq!(
486            info.get_typing_spans(&settings),
487            Spans(vec![
488                Span::styled("@user1:example.com", user_style("@user1:example.com")),
489                Span::from(" is typing...")
490            ])
491        );
492
493        // Two users typing.
494        info.set_typing(users2);
495        assert!(info.users_typing.is_some());
496        assert_eq!(
497            info.get_typing_spans(&settings),
498            Spans(vec![
499                Span::styled("@user1:example.com", user_style("@user1:example.com")),
500                Span::raw(" and "),
501                Span::styled("@user2:example.com", user_style("@user2:example.com")),
502                Span::raw(" are typing...")
503            ])
504        );
505
506        // Four users typing.
507        info.set_typing(users4);
508        assert!(info.users_typing.is_some());
509        assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
510
511        // Five users typing.
512        info.set_typing(users5);
513        assert!(info.users_typing.is_some());
514        assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
515
516        // Test that USER5 gets rendered using the configured color and name.
517        info.set_typing(vec![TEST_USER5.clone()]);
518        assert!(info.users_typing.is_some());
519        assert_eq!(
520            info.get_typing_spans(&settings),
521            Spans(vec![
522                Span::styled("USER 5", user_style_from_color(Color::Black)),
523                Span::from(" is typing...")
524            ])
525        );
526    }
527}