src/main.rs
800 lines · 25586 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::{CloseFlags, MoveDir1D, OpenTarget, RepeatType, TabTarget},
119 context::Resolve,
120 key::KeyManager,
121 store::Store,
122 },
123 input::{bindings::BindingMachine, dialog::Pager, dialog::PromptYesNo, 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 HomeserverAction::Logout(user, true) => {
575 self.worker.logout(user)?;
576 let flags = CloseFlags::QUIT | CloseFlags::FORCE;
577 let act = TabAction::Close(TabTarget::All, flags);
578
579 Ok(vec![(act.into(), ctx)])
580 },
581 HomeserverAction::Logout(user, false) => {
582 let msg = "Would you like to logout?";
583 let act = IambAction::from(HomeserverAction::Logout(user, true));
584 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
585 let prompt = Box::new(prompt);
586
587 Err(UIError::NeedConfirm(prompt))
588 },
589 }
590 }
591
592 fn handle_info(&mut self, info: InfoMessage) {
593 match info {
594 InfoMessage::Message(info) => {
595 self.screen.push_info(info);
596 },
597 InfoMessage::Pager(text) => {
598 let pager = Box::new(Pager::new(text, vec![]));
599 self.bindings.run_dialog(pager);
600 },
601 }
602 }
603
604 pub async fn run(&mut self) -> Result<(), std::io::Error> {
605 self.terminal.clear()?;
606
607 let store = self.store.clone();
608
609 while self.screen.tabs() != 0 {
610 let key = self.step().await?;
611
612 self.bindings.input_key(key);
613
614 let mut locked = store.lock().await;
615 let mut keyskip = false;
616
617 while let Some((action, ctx)) = self.action_pop(keyskip) {
618 match self.action_run(action, ctx, locked.deref_mut()).await {
619 Ok(None) => {
620 // Continue processing.
621 continue;
622 },
623 Ok(Some(info)) => {
624 self.handle_info(info);
625
626 // Continue processing; we'll redraw later.
627 continue;
628 },
629 Err(
630 UIError::NeedConfirm(dialog) |
631 UIError::EditingFailure(EditError::NeedConfirm(dialog)),
632 ) => {
633 self.bindings.run_dialog(dialog);
634 continue;
635 },
636 Err(e) => {
637 self.screen.push_error(e);
638
639 // Skip processing any more keypress Actions until the next key.
640 keyskip = true;
641 continue;
642 },
643 }
644 }
645 }
646
647 if let Some(ref layout) = self.last_layout {
648 let locked = self.store.lock().await;
649 let path = locked.application.settings.layout_json.as_path();
650 path.parent().map(create_dir_all).transpose()?;
651
652 let file = File::create(path)?;
653 let writer = BufWriter::new(file);
654
655 if let Err(e) = serde_json::to_writer(writer, layout) {
656 tracing::error!("Failed to save window layout while exiting: {}", e);
657 }
658 }
659
660 crossterm::terminal::disable_raw_mode()?;
661 execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
662 self.terminal.show_cursor()?;
663
664 return Ok(());
665 }
666}
667
668async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
669 println!("Logging in for {}...", settings.profile.user_id);
670
671 if settings.session_json.is_file() {
672 let file = File::open(settings.session_json.as_path())?;
673 let reader = BufReader::new(file);
674 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
675
676 worker.login(LoginStyle::SessionRestore(session))?;
677
678 return Ok(());
679 }
680
681 loop {
682 let password = rpassword::prompt_password("Password: ")?;
683
684 match worker.login(LoginStyle::Password(password)) {
685 Ok(info) => {
686 if let Some(msg) = info {
687 println!("{msg}");
688 }
689
690 break;
691 },
692 Err(err) => {
693 println!("Failed to login: {err}");
694 continue;
695 },
696 }
697 }
698
699 // Perform an initial, lazily-loaded sync.
700 let mut room = RoomEventFilter::default();
701 room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
702
703 let mut room_ev = RoomFilter::default();
704 room_ev.state = room;
705
706 let mut filter = FilterDefinition::default();
707 filter.room = room_ev;
708
709 let settings = SyncSettings::new().filter(filter.into());
710
711 worker.client.sync_once(settings).await.map_err(IambError::from)?;
712
713 Ok(())
714}
715
716fn print_exit<T: Display, N>(v: T) -> N {
717 println!("{v}");
718 process::exit(2);
719}
720
721async fn run(settings: ApplicationSettings) -> IambResult<()> {
722 // Set up the async worker thread and global store.
723 let worker = ClientWorker::spawn(settings.clone()).await;
724 let store = ChatStore::new(worker.clone(), settings.clone());
725 let store = Store::new(store);
726 let store = Arc::new(AsyncMutex::new(store));
727 worker.init(store.clone());
728
729 login(worker, &settings).await.unwrap_or_else(print_exit);
730
731 fn restore_tty() {
732 let _ = crossterm::terminal::disable_raw_mode();
733 let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
734 let _ = crossterm::execute!(stdout(), DisableFocusChange);
735 let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
736 let _ = crossterm::execute!(stdout(), CursorShow);
737 }
738
739 // Make sure panics clean up the terminal properly.
740 let orig_hook = std::panic::take_hook();
741 std::panic::set_hook(Box::new(move |panic_info| {
742 restore_tty();
743 orig_hook(panic_info);
744 process::exit(1);
745 }));
746
747 let mut application = Application::new(settings, store).await?;
748
749 // We can now run the application.
750 application.run().await?;
751 restore_tty();
752
753 Ok(())
754}
755
756fn main() -> IambResult<()> {
757 // Parse command-line flags.
758 let iamb = Iamb::parse();
759
760 // Load configuration and set up the Matrix SDK.
761 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
762
763 // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
764 #[cfg(unix)]
765 unsafe {
766 libc::umask(0o077);
767 };
768
769 // Set up the tracing subscriber so we can log client messages.
770 let log_prefix = format!("iamb-log-{}", settings.profile_name);
771 let log_dir = settings.dirs.logs.as_path();
772
773 create_dir_all(settings.matrix_dir.as_path())?;
774 create_dir_all(log_dir)?;
775
776 let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
777 let (appender, guard) = tracing_appender::non_blocking(appender);
778
779 let subscriber = FmtSubscriber::builder()
780 .with_writer(appender)
781 .with_max_level(settings.tunables.log_level)
782 .finish();
783 tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
784
785 let rt = tokio::runtime::Builder::new_multi_thread()
786 .enable_all()
787 .worker_threads(2)
788 .thread_name_fn(|| {
789 static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
790 let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
791 format!("iamb-worker-{id}")
792 })
793 .build()
794 .unwrap();
795
796 rt.block_on(async move { run(settings).await })?;
797
798 drop(guard);
799 process::exit(0);
800}