src/main.rs

763 lines · 23897 bytes

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