src/base.rs

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