src/base.rs

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