src/base.rs

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