src/base.rs

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