src/main.rs

754 lines · 23663 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
229impl Application {
230    pub async fn new(
231        settings: ApplicationSettings,
232        store: AsyncProgramStore,
233    ) -> IambResult<Application> {
234        let mut stdout = stdout();
235        crossterm::terminal::enable_raw_mode()?;
236        crossterm::execute!(stdout, EnterAlternateScreen)?;
237        crossterm::execute!(stdout, EnableBracketedPaste)?;
238        crossterm::execute!(stdout, EnableFocusChange)?;
239
240        let title = format!("iamb ({})", settings.profile.user_id);
241        crossterm::execute!(stdout, SetTitle(title))?;
242
243        let backend = CrosstermBackend::new(stdout);
244        let terminal = Terminal::new(backend)?;
245
246        let bindings = crate::keybindings::setup_keybindings();
247        let bindings = KeyManager::new(bindings);
248
249        let mut locked = store.lock().await;
250        let screen = setup_screen(settings, locked.deref_mut())?;
251
252        let worker = locked.application.worker.clone();
253        drop(locked);
254
255        let actstack = VecDeque::new();
256
257        Ok(Application {
258            store,
259            worker,
260            terminal,
261            bindings,
262            actstack,
263            screen,
264            focused: true,
265            last_layout: None,
266        })
267    }
268
269    fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
270        let bindings = &mut self.bindings;
271        let focused = self.focused;
272        let sstate = &mut self.screen;
273        let term = &mut self.terminal;
274
275        if full {
276            term.clear()?;
277        }
278
279        term.draw(|f| {
280            let area = f.size();
281
282            let modestr = bindings.show_mode();
283            let cursor = bindings.get_cursor_indicator();
284            let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
285
286            // Don't show terminal cursor when we show a dialog.
287            let hide_cursor = !dialogstr.is_empty();
288
289            let screen = Screen::new(store)
290                .show_dialog(dialogstr)
291                .show_mode(modestr)
292                .borders(true)
293                .focus(focused);
294            f.render_stateful_widget(screen, area, sstate);
295
296            if hide_cursor {
297                return;
298            }
299
300            if let Some((cx, cy)) = sstate.get_term_cursor() {
301                if let Some(c) = cursor {
302                    let style = Style::default().fg(Color::Green);
303                    let span = Span::styled(c.to_string(), style);
304                    let para = Paragraph::new(span);
305                    let inner = Rect::new(cx, cy, 1, 1);
306                    f.render_widget(para, inner)
307                }
308                f.set_cursor(cx, cy);
309            }
310        })?;
311
312        Ok(())
313    }
314
315    async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
316        loop {
317            self.redraw(false, self.store.clone().lock().await.deref_mut())?;
318
319            if !poll(Duration::from_secs(1))? {
320                // Redraw in case there's new messages to show.
321                continue;
322            }
323
324            match read()? {
325                Event::Key(ke) => return Ok(ke.into()),
326                Event::Mouse(_) => {
327                    // Do nothing for now.
328                },
329                Event::FocusGained => {
330                    self.focused = true;
331                },
332                Event::FocusLost => {
333                    self.focused = false;
334                },
335                Event::Resize(_, _) => {
336                    // We'll redraw for the new size next time step() is called.
337                },
338                Event::Paste(s) => {
339                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
340                    let act = EditorAction::from(act);
341                    let ctx = ProgramContext::default();
342                    let mut store = self.store.lock().await;
343
344                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
345                        Ok(None) => {},
346                        Ok(Some(info)) => {
347                            drop(store);
348                            self.handle_info(info);
349                        },
350                        Err(e) => {
351                            self.screen.push_error(e);
352                        },
353                    }
354                },
355            }
356        }
357    }
358
359    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
360        let mut acts = VecDeque::from(acts);
361        acts.append(&mut self.actstack);
362        self.actstack = acts;
363    }
364
365    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
366        if let res @ Some(_) = self.actstack.pop_front() {
367            return res;
368        }
369
370        if keyskip {
371            return None;
372        } else {
373            return self.bindings.pop();
374        }
375    }
376
377    async fn action_run(
378        &mut self,
379        action: ProgramAction,
380        ctx: ProgramContext,
381        store: &mut ProgramStore,
382    ) -> IambResult<EditInfo> {
383        let info = match action {
384            // Do nothing.
385            Action::NoOp => None,
386
387            Action::Editor(act) => {
388                match self.screen.editor_command(&act, &ctx, store) {
389                    Ok(info) => info,
390                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
391                        // Switch to the right window.
392                        if let Some(winid) = content.to_window() {
393                            let open = OpenTarget::Application(winid);
394                            let open = WindowAction::Switch(open);
395                            let _ = self.screen.window_command(&open, &ctx, store)?;
396
397                            // Run command again.
398                            self.screen.editor_command(&act, &ctx, store)?
399                        } else {
400                            return Err(EditError::WrongBuffer(content).into());
401                        }
402                    },
403                    Err(err) => return Err(err.into()),
404                }
405            },
406
407            // Simple delegations.
408            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
409            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
410            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
411            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
412            Action::ShowInfoMessage(info) => Some(info),
413            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
414
415            Action::Jump(l, dir, count) => {
416                let count = ctx.resolve(&count);
417                let _ = self.screen.jump(l, dir, count, &ctx)?;
418
419                None
420            },
421            Action::Suspend => {
422                self.terminal.program_suspend()?;
423
424                None
425            },
426
427            // UI actions.
428            Action::Tab(cmd) => {
429                if let TabAction::Close(_, _) = &cmd {
430                    self.last_layout = self.screen.as_description().into();
431                }
432
433                self.screen.tab_command(&cmd, &ctx, store)?
434            },
435            Action::RedrawScreen => {
436                self.screen.clear_message();
437                self.redraw(true, store)?;
438
439                None
440            },
441
442            // Actions that create more Actions.
443            Action::Prompt(act) => {
444                let acts = self.screen.prompt(&act, &ctx, store)?;
445                self.action_prepend(acts);
446
447                None
448            },
449            Action::Command(act) => {
450                let acts = store.application.cmds.command(&act, &ctx)?;
451                self.action_prepend(acts);
452
453                None
454            },
455            Action::Repeat(rt) => {
456                self.bindings.repeat(rt, Some(ctx));
457
458                None
459            },
460
461            // Unimplemented.
462            Action::KeywordLookup => {
463                // XXX: implement
464                None
465            },
466
467            _ => {
468                // XXX: log unhandled actions? print message?
469                None
470            },
471        };
472
473        return Ok(info);
474    }
475
476    async fn iamb_run(
477        &mut self,
478        action: IambAction,
479        ctx: ProgramContext,
480        store: &mut ProgramStore,
481    ) -> IambResult<EditInfo> {
482        let info = match action {
483            IambAction::ToggleScrollbackFocus => {
484                self.screen.current_window_mut()?.focus_toggle();
485
486                None
487            },
488
489            IambAction::Homeserver(act) => {
490                let acts = self.homeserver_command(act, ctx, store).await?;
491                self.action_prepend(acts);
492
493                None
494            },
495            IambAction::Message(act) => {
496                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
497            },
498            IambAction::Room(act) => {
499                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
500                self.action_prepend(acts);
501
502                None
503            },
504            IambAction::Send(act) => {
505                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
506            },
507
508            IambAction::Verify(act, user_dev) => {
509                if let Some(sas) = store.application.verifications.get(&user_dev) {
510                    self.worker.verify(act, sas.clone())?
511                } else {
512                    return Err(IambError::InvalidVerificationId(user_dev).into());
513                }
514            },
515            IambAction::VerifyRequest(user_id) => {
516                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
517                    self.worker.verify_request(user_id)?
518                } else {
519                    return Err(IambError::InvalidUserId(user_id).into());
520                }
521            },
522        };
523
524        Ok(info)
525    }
526
527    async fn homeserver_command(
528        &mut self,
529        action: HomeserverAction,
530        ctx: ProgramContext,
531        store: &mut ProgramStore,
532    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
533        match action {
534            HomeserverAction::CreateRoom(alias, vis, flags) => {
535                let client = &store.application.worker.client;
536                let room_id = create_room(client, alias.as_deref(), vis, flags).await?;
537                let room = IambId::Room(room_id);
538                let target = OpenTarget::Application(room);
539                let action = WindowAction::Switch(target);
540
541                Ok(vec![(action.into(), ctx)])
542            },
543        }
544    }
545
546    fn handle_info(&mut self, info: InfoMessage) {
547        match info {
548            InfoMessage::Message(info) => {
549                self.screen.push_info(info);
550            },
551            InfoMessage::Pager(text) => {
552                let pager = Box::new(Pager::new(text, vec![]));
553                self.bindings.run_dialog(pager);
554            },
555        }
556    }
557
558    pub async fn run(&mut self) -> Result<(), std::io::Error> {
559        self.terminal.clear()?;
560
561        let store = self.store.clone();
562
563        while self.screen.tabs() != 0 {
564            let key = self.step().await?;
565
566            self.bindings.input_key(key);
567
568            let mut locked = store.lock().await;
569            let mut keyskip = false;
570
571            while let Some((action, ctx)) = self.action_pop(keyskip) {
572                match self.action_run(action, ctx, locked.deref_mut()).await {
573                    Ok(None) => {
574                        // Continue processing.
575                        continue;
576                    },
577                    Ok(Some(info)) => {
578                        self.handle_info(info);
579
580                        // Continue processing; we'll redraw later.
581                        continue;
582                    },
583                    Err(
584                        UIError::NeedConfirm(dialog) |
585                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
586                    ) => {
587                        self.bindings.run_dialog(dialog);
588                        continue;
589                    },
590                    Err(e) => {
591                        self.screen.push_error(e);
592
593                        // Skip processing any more keypress Actions until the next key.
594                        keyskip = true;
595                        continue;
596                    },
597                }
598            }
599        }
600
601        if let Some(ref layout) = self.last_layout {
602            let locked = self.store.lock().await;
603            let path = locked.application.settings.layout_json.as_path();
604            path.parent().map(create_dir_all).transpose()?;
605
606            let file = File::create(path)?;
607            let writer = BufWriter::new(file);
608
609            if let Err(e) = serde_json::to_writer(writer, layout) {
610                tracing::error!("Failed to save window layout while exiting: {}", e);
611            }
612        }
613
614        crossterm::terminal::disable_raw_mode()?;
615        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
616        self.terminal.show_cursor()?;
617
618        return Ok(());
619    }
620}
621
622async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
623    println!("Logging in for {}...", settings.profile.user_id);
624
625    if settings.session_json.is_file() {
626        let file = File::open(settings.session_json.as_path())?;
627        let reader = BufReader::new(file);
628        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
629
630        worker.login(LoginStyle::SessionRestore(session))?;
631
632        return Ok(());
633    }
634
635    loop {
636        let password = rpassword::prompt_password("Password: ")?;
637
638        match worker.login(LoginStyle::Password(password)) {
639            Ok(info) => {
640                if let Some(msg) = info {
641                    println!("{msg}");
642                }
643
644                break;
645            },
646            Err(err) => {
647                println!("Failed to login: {err}");
648                continue;
649            },
650        }
651    }
652
653    // Perform an initial, lazily-loaded sync.
654    let mut room = RoomEventFilter::default();
655    room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
656
657    let mut room_ev = RoomFilter::default();
658    room_ev.state = room;
659
660    let mut filter = FilterDefinition::default();
661    filter.room = room_ev;
662
663    let settings = SyncSettings::new().filter(filter.into());
664
665    worker.client.sync_once(settings).await.map_err(IambError::from)?;
666
667    Ok(())
668}
669
670fn print_exit<T: Display, N>(v: T) -> N {
671    println!("{v}");
672    process::exit(2);
673}
674
675async fn run(settings: ApplicationSettings) -> IambResult<()> {
676    // Set up the async worker thread and global store.
677    let worker = ClientWorker::spawn(settings.clone()).await;
678    let store = ChatStore::new(worker.clone(), settings.clone());
679    let store = Store::new(store);
680    let store = Arc::new(AsyncMutex::new(store));
681    worker.init(store.clone());
682
683    login(worker, &settings).await.unwrap_or_else(print_exit);
684
685    fn restore_tty() {
686        let _ = crossterm::terminal::disable_raw_mode();
687        let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
688        let _ = crossterm::execute!(stdout(), DisableFocusChange);
689        let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
690        let _ = crossterm::execute!(stdout(), CursorShow);
691    }
692
693    // Make sure panics clean up the terminal properly.
694    let orig_hook = std::panic::take_hook();
695    std::panic::set_hook(Box::new(move |panic_info| {
696        restore_tty();
697        orig_hook(panic_info);
698        process::exit(1);
699    }));
700
701    let mut application = Application::new(settings, store).await?;
702
703    // We can now run the application.
704    application.run().await?;
705    restore_tty();
706
707    Ok(())
708}
709
710fn main() -> IambResult<()> {
711    // Parse command-line flags.
712    let iamb = Iamb::parse();
713
714    // Load configuration and set up the Matrix SDK.
715    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
716
717    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
718    #[cfg(unix)]
719    unsafe {
720        libc::umask(0o077);
721    };
722
723    // Set up the tracing subscriber so we can log client messages.
724    let log_prefix = format!("iamb-log-{}", settings.profile_name);
725    let log_dir = settings.dirs.logs.as_path();
726
727    create_dir_all(settings.matrix_dir.as_path())?;
728    create_dir_all(log_dir)?;
729
730    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
731    let (appender, guard) = tracing_appender::non_blocking(appender);
732
733    let subscriber = FmtSubscriber::builder()
734        .with_writer(appender)
735        .with_max_level(settings.tunables.log_level)
736        .finish();
737    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
738
739    let rt = tokio::runtime::Builder::new_multi_thread()
740        .enable_all()
741        .worker_threads(2)
742        .thread_name_fn(|| {
743            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
744            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
745            format!("iamb-worker-{id}")
746        })
747        .build()
748        .unwrap();
749
750    rt.block_on(async move { run(settings).await })?;
751
752    drop(guard);
753    process::exit(0);
754}