src/base.rs

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