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