src/main.rs

785 lines · 24870 bytes

  1//! # iamb
  2//!
  3//! The iamb client loops over user input and commands, and turns them into actions, [some of
  4//! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When
  5//! adding new functionality, you will usually want to extend [IambAction] or one of its variants
  6//! (like [RoomAction][base::RoomAction]), and then add an appropriate [command][commands] or
  7//! [keybinding][keybindings].
  8//!
  9//! For more complicated changes, you may need to update [the async worker thread][worker], which
 10//! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk].
 11//!
 12//! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have
 13//! their own module.
 14#![allow(clippy::manual_range_contains)]
 15#![allow(clippy::needless_return)]
 16#![allow(clippy::result_large_err)]
 17#![allow(clippy::bool_assert_comparison)]
 18use std::collections::VecDeque;
 19use std::convert::TryFrom;
 20use std::fmt::Display;
 21use std::fs::{create_dir_all, File};
 22use std::io::{stdout, BufReader, BufWriter, Stdout};
 23use std::ops::DerefMut;
 24use std::process;
 25use std::sync::atomic::{AtomicUsize, Ordering};
 26use std::sync::Arc;
 27use std::time::Duration;
 28
 29use clap::Parser;
 30use tokio::sync::Mutex as AsyncMutex;
 31use tracing_subscriber::FmtSubscriber;
 32
 33use matrix_sdk::{
 34    config::SyncSettings,
 35    ruma::{
 36        api::client::filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
 37        OwnedUserId,
 38    },
 39};
 40
 41use modalkit::crossterm::{
 42    self,
 43    cursor::Show as CursorShow,
 44    event::{
 45        poll,
 46        read,
 47        DisableBracketedPaste,
 48        DisableFocusChange,
 49        EnableBracketedPaste,
 50        EnableFocusChange,
 51        Event,
 52    },
 53    execute,
 54    terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
 55};
 56
 57use modalkit::tui::{
 58    backend::CrosstermBackend,
 59    layout::Rect,
 60    style::{Color, Style},
 61    text::Span,
 62    widgets::Paragraph,
 63    Terminal,
 64};
 65
 66mod base;
 67mod commands;
 68mod config;
 69mod keybindings;
 70mod message;
 71mod util;
 72mod windows;
 73mod worker;
 74
 75#[cfg(test)]
 76mod tests;
 77
 78use crate::{
 79    base::{
 80        AsyncProgramStore,
 81        ChatStore,
 82        HomeserverAction,
 83        IambAction,
 84        IambError,
 85        IambId,
 86        IambInfo,
 87        IambResult,
 88        ProgramAction,
 89        ProgramContext,
 90        ProgramStore,
 91    },
 92    config::{ApplicationSettings, Iamb},
 93    windows::IambWindow,
 94    worker::{create_room, ClientWorker, LoginStyle, Requester},
 95};
 96
 97use modalkit::{
 98    editing::{
 99        action::{
100            Action,
101            Commandable,
102            EditError,
103            EditInfo,
104            Editable,
105            EditorAction,
106            InfoMessage,
107            InsertTextAction,
108            Jumpable,
109            Promptable,
110            Scrollable,
111            TabAction,
112            TabContainer,
113            TabCount,
114            UIError,
115            WindowAction,
116            WindowContainer,
117        },
118        base::{MoveDir1D, OpenTarget, RepeatType},
119        context::Resolve,
120        key::KeyManager,
121        store::Store,
122    },
123    input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey},
124    widgets::{
125        cmdbar::CommandBarState,
126        screen::{FocusList, Screen, ScreenState, TabLayoutDescription},
127        windows::WindowLayoutDescription,
128        TerminalCursor,
129        TerminalExtOps,
130        Window,
131    },
132};
133
134fn config_tab_to_desc(
135    layout: config::WindowLayout,
136    store: &mut ProgramStore,
137) -> IambResult<WindowLayoutDescription<IambInfo>> {
138    let desc = match layout {
139        config::WindowLayout::Window { window } => {
140            let ChatStore { names, worker, .. } = &mut store.application;
141
142            let window = match window {
143                config::WindowPath::UserId(user_id) => {
144                    let name = user_id.to_string();
145                    let room_id = worker.join_room(name.clone())?;
146                    names.insert(name, room_id.clone());
147                    IambId::Room(room_id)
148                },
149                config::WindowPath::RoomId(room_id) => IambId::Room(room_id),
150                config::WindowPath::AliasId(alias) => {
151                    let name = alias.to_string();
152                    let room_id = worker.join_room(name.clone())?;
153                    names.insert(name, room_id.clone());
154                    IambId::Room(room_id)
155                },
156                config::WindowPath::Window(id) => id,
157            };
158
159            WindowLayoutDescription::Window { window, length: None }
160        },
161        config::WindowLayout::Split { split } => {
162            let children = split
163                .into_iter()
164                .map(|child| config_tab_to_desc(child, store))
165                .collect::<IambResult<Vec<_>>>()?;
166
167            WindowLayoutDescription::Split { children, length: None }
168        },
169    };
170
171    Ok(desc)
172}
173
174fn setup_screen(
175    settings: ApplicationSettings,
176    store: &mut ProgramStore,
177) -> IambResult<ScreenState<IambWindow, IambInfo>> {
178    let cmd = CommandBarState::new(store);
179    let dims = crossterm::terminal::size()?;
180    let area = Rect::new(0, 0, dims.0, dims.1);
181
182    match settings.layout {
183        config::Layout::Restore => {
184            if let Ok(layout) = std::fs::read(&settings.layout_json) {
185                let tabs: TabLayoutDescription<IambInfo> =
186                    serde_json::from_slice(&layout).map_err(IambError::from)?;
187                let tabs = tabs.to_layout(area.into(), store)?;
188
189                return Ok(ScreenState::from_list(tabs, cmd));
190            }
191        },
192        config::Layout::New => {},
193        config::Layout::Config { tabs } => {
194            let mut list = FocusList::default();
195
196            for tab in tabs.into_iter() {
197                let tab = config_tab_to_desc(tab, store)?;
198                let tab = tab.to_layout(area.into(), store)?;
199                list.push(tab);
200            }
201
202            return Ok(ScreenState::from_list(list, cmd));
203        },
204    }
205
206    let win = settings
207        .tunables
208        .default_room
209        .and_then(|room| IambWindow::find(room, store).ok())
210        .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
211        .unwrap();
212
213    return Ok(ScreenState::new(win, cmd));
214}
215
216/// The main application state and event loop.
217struct Application {
218    /// Terminal backend.
219    terminal: Terminal<CrosstermBackend<Stdout>>,
220
221    /// State for the Matrix client, editing, etc.
222    store: AsyncProgramStore,
223
224    /// UI state (open tabs, command bar, etc.) to use when rendering.
225    screen: ScreenState<IambWindow, IambInfo>,
226
227    /// Handle to communicate synchronously with the Matrix worker task.
228    worker: Requester,
229
230    /// Mapped keybindings.
231    bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
232
233    /// Pending actions to run.
234    actstack: VecDeque<(ProgramAction, ProgramContext)>,
235
236    /// Whether or not the terminal is currently focused.
237    focused: bool,
238
239    /// The tab layout before the last executed [TabAction].
240    last_layout: Option<TabLayoutDescription<IambInfo>>,
241
242    /// Whether we need to do a full redraw (e.g., after running a subprocess).
243    dirty: bool,
244}
245
246impl Application {
247    pub async fn new(
248        settings: ApplicationSettings,
249        store: AsyncProgramStore,
250    ) -> IambResult<Application> {
251        let mut stdout = stdout();
252        crossterm::terminal::enable_raw_mode()?;
253        crossterm::execute!(stdout, EnterAlternateScreen)?;
254        crossterm::execute!(stdout, EnableBracketedPaste)?;
255        crossterm::execute!(stdout, EnableFocusChange)?;
256
257        let title = format!("iamb ({})", settings.profile.user_id);
258        crossterm::execute!(stdout, SetTitle(title))?;
259
260        let backend = CrosstermBackend::new(stdout);
261        let terminal = Terminal::new(backend)?;
262
263        let bindings = crate::keybindings::setup_keybindings();
264        let bindings = KeyManager::new(bindings);
265
266        let mut locked = store.lock().await;
267        let screen = setup_screen(settings, locked.deref_mut())?;
268
269        let worker = locked.application.worker.clone();
270        drop(locked);
271
272        let actstack = VecDeque::new();
273
274        Ok(Application {
275            store,
276            worker,
277            terminal,
278            bindings,
279            actstack,
280            screen,
281            focused: true,
282            last_layout: None,
283            dirty: true,
284        })
285    }
286
287    fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
288        let bindings = &mut self.bindings;
289        let focused = self.focused;
290        let sstate = &mut self.screen;
291        let term = &mut self.terminal;
292
293        if full {
294            term.clear()?;
295        }
296
297        term.draw(|f| {
298            let area = f.size();
299
300            let modestr = bindings.show_mode();
301            let cursor = bindings.get_cursor_indicator();
302            let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
303
304            // Don't show terminal cursor when we show a dialog.
305            let hide_cursor = !dialogstr.is_empty();
306
307            let screen = Screen::new(store)
308                .show_dialog(dialogstr)
309                .show_mode(modestr)
310                .borders(true)
311                .focus(focused);
312            f.render_stateful_widget(screen, area, sstate);
313
314            if hide_cursor {
315                return;
316            }
317
318            if let Some((cx, cy)) = sstate.get_term_cursor() {
319                if let Some(c) = cursor {
320                    let style = Style::default().fg(Color::Green);
321                    let span = Span::styled(c.to_string(), style);
322                    let para = Paragraph::new(span);
323                    let inner = Rect::new(cx, cy, 1, 1);
324                    f.render_widget(para, inner)
325                }
326                f.set_cursor(cx, cy);
327            }
328        })?;
329
330        Ok(())
331    }
332
333    async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
334        loop {
335            self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?;
336            self.dirty = false;
337
338            if !poll(Duration::from_secs(1))? {
339                // Redraw in case there's new messages to show.
340                continue;
341            }
342
343            match read()? {
344                Event::Key(ke) => return Ok(ke.into()),
345                Event::Mouse(_) => {
346                    // Do nothing for now.
347                },
348                Event::FocusGained => {
349                    self.focused = true;
350                },
351                Event::FocusLost => {
352                    self.focused = false;
353                },
354                Event::Resize(_, _) => {
355                    // We'll redraw for the new size next time step() is called.
356                },
357                Event::Paste(s) => {
358                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
359                    let act = EditorAction::from(act);
360                    let ctx = ProgramContext::default();
361                    let mut store = self.store.lock().await;
362
363                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
364                        Ok(None) => {},
365                        Ok(Some(info)) => {
366                            drop(store);
367                            self.handle_info(info);
368                        },
369                        Err(e) => {
370                            self.screen.push_error(e);
371                        },
372                    }
373                },
374            }
375        }
376    }
377
378    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
379        let mut acts = VecDeque::from(acts);
380        acts.append(&mut self.actstack);
381        self.actstack = acts;
382    }
383
384    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
385        if let res @ Some(_) = self.actstack.pop_front() {
386            return res;
387        }
388
389        if keyskip {
390            return None;
391        } else {
392            return self.bindings.pop();
393        }
394    }
395
396    async fn action_run(
397        &mut self,
398        action: ProgramAction,
399        ctx: ProgramContext,
400        store: &mut ProgramStore,
401    ) -> IambResult<EditInfo> {
402        let info = match action {
403            // Do nothing.
404            Action::NoOp => None,
405
406            Action::Editor(act) => {
407                match self.screen.editor_command(&act, &ctx, store) {
408                    Ok(info) => info,
409                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
410                        // Switch to the right window.
411                        if let Some(winid) = content.to_window() {
412                            let open = OpenTarget::Application(winid);
413                            let open = WindowAction::Switch(open);
414                            let _ = self.screen.window_command(&open, &ctx, store)?;
415
416                            // Run command again.
417                            self.screen.editor_command(&act, &ctx, store)?
418                        } else {
419                            return Err(EditError::WrongBuffer(content).into());
420                        }
421                    },
422                    Err(err) => return Err(err.into()),
423                }
424            },
425
426            // Simple delegations.
427            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
428            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
429            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
430            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
431            Action::ShowInfoMessage(info) => Some(info),
432            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
433
434            Action::Jump(l, dir, count) => {
435                let count = ctx.resolve(&count);
436                let _ = self.screen.jump(l, dir, count, &ctx)?;
437
438                None
439            },
440            Action::Suspend => {
441                self.terminal.program_suspend()?;
442
443                None
444            },
445
446            // UI actions.
447            Action::Tab(cmd) => {
448                if let TabAction::Close(_, _) = &cmd {
449                    self.last_layout = self.screen.as_description().into();
450                }
451
452                self.screen.tab_command(&cmd, &ctx, store)?
453            },
454            Action::RedrawScreen => {
455                self.screen.clear_message();
456                self.redraw(true, store)?;
457
458                None
459            },
460
461            // Actions that create more Actions.
462            Action::Prompt(act) => {
463                let acts = self.screen.prompt(&act, &ctx, store)?;
464                self.action_prepend(acts);
465
466                None
467            },
468            Action::Command(act) => {
469                let acts = store.application.cmds.command(&act, &ctx)?;
470                self.action_prepend(acts);
471
472                None
473            },
474            Action::Repeat(rt) => {
475                self.bindings.repeat(rt, Some(ctx));
476
477                None
478            },
479
480            // Unimplemented.
481            Action::KeywordLookup => {
482                // XXX: implement
483                None
484            },
485
486            _ => {
487                // XXX: log unhandled actions? print message?
488                None
489            },
490        };
491
492        return Ok(info);
493    }
494
495    async fn iamb_run(
496        &mut self,
497        action: IambAction,
498        ctx: ProgramContext,
499        store: &mut ProgramStore,
500    ) -> IambResult<EditInfo> {
501        if action.scribbles() {
502            self.dirty = true;
503        }
504
505        let info = match action {
506            IambAction::ToggleScrollbackFocus => {
507                self.screen.current_window_mut()?.focus_toggle();
508
509                None
510            },
511
512            IambAction::Homeserver(act) => {
513                let acts = self.homeserver_command(act, ctx, store).await?;
514                self.action_prepend(acts);
515
516                None
517            },
518            IambAction::Message(act) => {
519                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
520            },
521            IambAction::Room(act) => {
522                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
523                self.action_prepend(acts);
524
525                None
526            },
527            IambAction::Send(act) => {
528                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
529            },
530
531            IambAction::OpenLink(url) => {
532                tokio::task::spawn_blocking(move || {
533                    return open::that(url);
534                });
535
536                None
537            },
538
539            IambAction::Verify(act, user_dev) => {
540                if let Some(sas) = store.application.verifications.get(&user_dev) {
541                    self.worker.verify(act, sas.clone())?
542                } else {
543                    return Err(IambError::InvalidVerificationId(user_dev).into());
544                }
545            },
546            IambAction::VerifyRequest(user_id) => {
547                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
548                    self.worker.verify_request(user_id)?
549                } else {
550                    return Err(IambError::InvalidUserId(user_id).into());
551                }
552            },
553        };
554
555        Ok(info)
556    }
557
558    async fn homeserver_command(
559        &mut self,
560        action: HomeserverAction,
561        ctx: ProgramContext,
562        store: &mut ProgramStore,
563    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
564        match action {
565            HomeserverAction::CreateRoom(alias, vis, flags) => {
566                let client = &store.application.worker.client;
567                let room_id = create_room(client, alias.as_deref(), vis, flags).await?;
568                let room = IambId::Room(room_id);
569                let target = OpenTarget::Application(room);
570                let action = WindowAction::Switch(target);
571
572                Ok(vec![(action.into(), ctx)])
573            },
574        }
575    }
576
577    fn handle_info(&mut self, info: InfoMessage) {
578        match info {
579            InfoMessage::Message(info) => {
580                self.screen.push_info(info);
581            },
582            InfoMessage::Pager(text) => {
583                let pager = Box::new(Pager::new(text, vec![]));
584                self.bindings.run_dialog(pager);
585            },
586        }
587    }
588
589    pub async fn run(&mut self) -> Result<(), std::io::Error> {
590        self.terminal.clear()?;
591
592        let store = self.store.clone();
593
594        while self.screen.tabs() != 0 {
595            let key = self.step().await?;
596
597            self.bindings.input_key(key);
598
599            let mut locked = store.lock().await;
600            let mut keyskip = false;
601
602            while let Some((action, ctx)) = self.action_pop(keyskip) {
603                match self.action_run(action, ctx, locked.deref_mut()).await {
604                    Ok(None) => {
605                        // Continue processing.
606                        continue;
607                    },
608                    Ok(Some(info)) => {
609                        self.handle_info(info);
610
611                        // Continue processing; we'll redraw later.
612                        continue;
613                    },
614                    Err(
615                        UIError::NeedConfirm(dialog) |
616                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
617                    ) => {
618                        self.bindings.run_dialog(dialog);
619                        continue;
620                    },
621                    Err(e) => {
622                        self.screen.push_error(e);
623
624                        // Skip processing any more keypress Actions until the next key.
625                        keyskip = true;
626                        continue;
627                    },
628                }
629            }
630        }
631
632        if let Some(ref layout) = self.last_layout {
633            let locked = self.store.lock().await;
634            let path = locked.application.settings.layout_json.as_path();
635            path.parent().map(create_dir_all).transpose()?;
636
637            let file = File::create(path)?;
638            let writer = BufWriter::new(file);
639
640            if let Err(e) = serde_json::to_writer(writer, layout) {
641                tracing::error!("Failed to save window layout while exiting: {}", e);
642            }
643        }
644
645        crossterm::terminal::disable_raw_mode()?;
646        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
647        self.terminal.show_cursor()?;
648
649        return Ok(());
650    }
651}
652
653async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
654    println!("Logging in for {}...", settings.profile.user_id);
655
656    if settings.session_json.is_file() {
657        let file = File::open(settings.session_json.as_path())?;
658        let reader = BufReader::new(file);
659        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
660
661        worker.login(LoginStyle::SessionRestore(session))?;
662
663        return Ok(());
664    }
665
666    loop {
667        let password = rpassword::prompt_password("Password: ")?;
668
669        match worker.login(LoginStyle::Password(password)) {
670            Ok(info) => {
671                if let Some(msg) = info {
672                    println!("{msg}");
673                }
674
675                break;
676            },
677            Err(err) => {
678                println!("Failed to login: {err}");
679                continue;
680            },
681        }
682    }
683
684    // Perform an initial, lazily-loaded sync.
685    let mut room = RoomEventFilter::default();
686    room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
687
688    let mut room_ev = RoomFilter::default();
689    room_ev.state = room;
690
691    let mut filter = FilterDefinition::default();
692    filter.room = room_ev;
693
694    let settings = SyncSettings::new().filter(filter.into());
695
696    worker.client.sync_once(settings).await.map_err(IambError::from)?;
697
698    Ok(())
699}
700
701fn print_exit<T: Display, N>(v: T) -> N {
702    println!("{v}");
703    process::exit(2);
704}
705
706async fn run(settings: ApplicationSettings) -> IambResult<()> {
707    // Set up the async worker thread and global store.
708    let worker = ClientWorker::spawn(settings.clone()).await;
709    let store = ChatStore::new(worker.clone(), settings.clone());
710    let store = Store::new(store);
711    let store = Arc::new(AsyncMutex::new(store));
712    worker.init(store.clone());
713
714    login(worker, &settings).await.unwrap_or_else(print_exit);
715
716    fn restore_tty() {
717        let _ = crossterm::terminal::disable_raw_mode();
718        let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
719        let _ = crossterm::execute!(stdout(), DisableFocusChange);
720        let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
721        let _ = crossterm::execute!(stdout(), CursorShow);
722    }
723
724    // Make sure panics clean up the terminal properly.
725    let orig_hook = std::panic::take_hook();
726    std::panic::set_hook(Box::new(move |panic_info| {
727        restore_tty();
728        orig_hook(panic_info);
729        process::exit(1);
730    }));
731
732    let mut application = Application::new(settings, store).await?;
733
734    // We can now run the application.
735    application.run().await?;
736    restore_tty();
737
738    Ok(())
739}
740
741fn main() -> IambResult<()> {
742    // Parse command-line flags.
743    let iamb = Iamb::parse();
744
745    // Load configuration and set up the Matrix SDK.
746    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
747
748    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
749    #[cfg(unix)]
750    unsafe {
751        libc::umask(0o077);
752    };
753
754    // Set up the tracing subscriber so we can log client messages.
755    let log_prefix = format!("iamb-log-{}", settings.profile_name);
756    let log_dir = settings.dirs.logs.as_path();
757
758    create_dir_all(settings.matrix_dir.as_path())?;
759    create_dir_all(log_dir)?;
760
761    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
762    let (appender, guard) = tracing_appender::non_blocking(appender);
763
764    let subscriber = FmtSubscriber::builder()
765        .with_writer(appender)
766        .with_max_level(settings.tunables.log_level)
767        .finish();
768    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
769
770    let rt = tokio::runtime::Builder::new_multi_thread()
771        .enable_all()
772        .worker_threads(2)
773        .thread_name_fn(|| {
774            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
775            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
776            format!("iamb-worker-{id}")
777        })
778        .build()
779        .unwrap();
780
781    rt.block_on(async move { run(settings).await })?;
782
783    drop(guard);
784    process::exit(0);
785}