src/main.rs
1240 lines · 41279 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#![recursion_limit = "256"]
15#![allow(clippy::manual_range_contains)]
16#![allow(clippy::needless_return)]
17#![allow(clippy::result_large_err)]
18#![allow(clippy::bool_assert_comparison)]
19use std::collections::VecDeque;
20use std::convert::TryFrom;
21use std::fmt::Display;
22use std::fs::{File, create_dir_all};
23use std::io::{BufWriter, Stdout, Write, stdout};
24use std::ops::DerefMut;
25use std::process;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::time::{Duration, Instant};
29
30use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::UserId;
32use matrix_sdk::ruma::api::error::ErrorKind;
33use matrix_sdk::ruma::profile::{ProfileFieldName, ProfileFieldValue};
34use matrix_sdk_crypto::encrypt_room_key_export;
35use modalkit::keybindings::InputBindings;
36use rand::RngExt as _;
37use rand::distr::Alphanumeric;
38use temp_dir::TempDir;
39use tokio::sync::Mutex as AsyncMutex;
40use tracing::Level;
41use tracing_subscriber::{EnvFilter, FmtSubscriber};
42
43use modalkit::crossterm::{
44 self,
45 cursor::{SetCursorStyle, Show as CursorShow},
46 event::{
47 DisableBracketedPaste,
48 DisableFocusChange,
49 DisableMouseCapture,
50 EnableBracketedPaste,
51 EnableFocusChange,
52 EnableMouseCapture,
53 Event,
54 KeyEventKind,
55 KeyboardEnhancementFlags,
56 MouseEventKind,
57 PopKeyboardEnhancementFlags,
58 PushKeyboardEnhancementFlags,
59 poll,
60 read,
61 },
62 execute,
63 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
64};
65
66use ratatui::{
67 Terminal,
68 backend::CrosstermBackend,
69 layout::Rect,
70 style::{Color, Modifier, Style},
71 text::Span,
72 widgets::Paragraph,
73};
74
75mod base;
76mod commands;
77mod completions;
78mod config;
79mod keybindings;
80mod message;
81mod notifications;
82mod preview;
83mod sled_export;
84mod util;
85mod windows;
86mod worker;
87
88#[cfg(test)]
89mod tests;
90mod verifications;
91
92use crate::{
93 base::{
94 AsyncProgramStore,
95 ChatStore,
96 HomeserverAction,
97 IambAction,
98 IambError,
99 IambId,
100 IambInfo,
101 IambResult,
102 KeysAction,
103 ProgramAction,
104 ProgramContext,
105 ProgramStore,
106 },
107 completions::IambCompleter,
108 config::{ApplicationSettings, Iamb},
109 windows::IambWindow,
110 worker::{ClientWorker, LoginStyle, Requester, create_room},
111};
112
113use modalkit::{
114 actions::{
115 Action,
116 Commandable,
117 Editable,
118 EditorAction,
119 InsertTextAction,
120 Jumpable,
121 Promptable,
122 Scrollable,
123 TabAction,
124 TabContainer,
125 TabCount,
126 WindowAction,
127 WindowContainer,
128 },
129 editing::{context::Resolve, key::KeyManager, store::Store},
130 errors::{EditError, UIError},
131 key::TerminalKey,
132 keybindings::{
133 BindingMachine,
134 dialog::{Pager, PromptYesNo},
135 },
136 prelude::*,
137 ui::FocusList,
138};
139
140use modalkit_ratatui::{
141 TerminalCursor,
142 TerminalExtOps,
143 Window,
144 cmdbar::CommandBarState,
145 screen::{Screen, ScreenState, TabbedLayoutDescription},
146 windows::{WindowLayoutDescription, WindowLayoutState},
147};
148
149fn config_tab_to_desc(
150 layout: config::WindowLayout,
151 store: &mut ProgramStore,
152) -> IambResult<WindowLayoutDescription<IambInfo>> {
153 let desc = match layout {
154 config::WindowLayout::Window { window } => {
155 let ChatStore { names, worker, .. } = &mut store.application;
156
157 let window = match window {
158 config::WindowPath::UserId(user_id) => {
159 let name = user_id.to_string();
160 let room_id = worker.join_room(name.clone())?;
161 names.insert(name, room_id.clone());
162 IambId::Room(room_id, None)
163 },
164 config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
165 config::WindowPath::AliasId(alias) => {
166 let name = alias.to_string();
167 let room_id = worker.join_room(name.clone())?;
168 names.insert(name, room_id.clone());
169 IambId::Room(room_id, None)
170 },
171 config::WindowPath::Window(id) => id,
172 };
173
174 WindowLayoutDescription::Window { window, length: None }
175 },
176 config::WindowLayout::Split { split } => {
177 let children = split
178 .into_iter()
179 .map(|child| config_tab_to_desc(child, store))
180 .collect::<IambResult<Vec<_>>>()?;
181
182 WindowLayoutDescription::Split { children, length: None }
183 },
184 };
185
186 Ok(desc)
187}
188
189fn restore_layout(
190 area: Rect,
191 settings: &ApplicationSettings,
192 store: &mut ProgramStore,
193) -> IambResult<FocusList<WindowLayoutState<IambWindow, IambInfo>>> {
194 let layout = std::fs::read(&settings.layout_json)?;
195 let tabs: TabbedLayoutDescription<IambInfo> =
196 serde_json::from_slice(&layout).map_err(IambError::from)?;
197 tabs.to_layout(area.into(), store)
198}
199
200fn setup_screen(
201 settings: ApplicationSettings,
202 store: &mut ProgramStore,
203) -> IambResult<ScreenState<IambWindow, IambInfo>> {
204 let cmd = CommandBarState::new(store);
205 let dims = crossterm::terminal::size()?;
206 let area = Rect::new(0, 0, dims.0, dims.1);
207
208 match settings.layout {
209 config::Layout::Restore => {
210 match restore_layout(area, &settings, store) {
211 Ok(tabs) => {
212 return Ok(ScreenState::from_list(tabs, cmd));
213 },
214 Err(e) => {
215 // Log the issue with restoring and then continue.
216 tracing::warn!(err = %e, "Failed to restore layout from disk");
217 },
218 }
219 },
220 config::Layout::New => {},
221 config::Layout::Config { tabs } => {
222 let mut list = FocusList::default();
223
224 for tab in tabs.into_iter() {
225 let tab = config_tab_to_desc(tab, store)?;
226 let tab = tab.to_layout(area.into(), store)?;
227 list.push(tab);
228 }
229
230 return Ok(ScreenState::from_list(list, cmd));
231 },
232 }
233
234 let win = settings
235 .tunables
236 .default_room
237 .and_then(|room| IambWindow::find(room, store).ok())
238 .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
239 .unwrap();
240
241 return Ok(ScreenState::new(win, cmd));
242}
243
244/// The main application state and event loop.
245struct Application {
246 /// Terminal backend.
247 terminal: Terminal<CrosstermBackend<Stdout>>,
248
249 /// State for the Matrix client, editing, etc.
250 store: AsyncProgramStore,
251
252 /// UI state (open tabs, command bar, etc.) to use when rendering.
253 screen: ScreenState<IambWindow, IambInfo>,
254
255 /// Handle to communicate synchronously with the Matrix worker task.
256 worker: Requester,
257
258 /// Mapped keybindings.
259 bindings: KeyManager<TerminalKey, ProgramAction, RepeatType>,
260
261 /// Pending actions to run.
262 actstack: VecDeque<(ProgramAction, ProgramContext)>,
263
264 /// Whether or not the terminal is currently focused.
265 focused: bool,
266
267 /// The tab layout before the last executed [TabAction].
268 last_layout: Option<TabbedLayoutDescription<IambInfo>>,
269
270 /// Whether we need to do a full redraw (e.g., after running a subprocess).
271 dirty: bool,
272}
273
274impl Application {
275 pub async fn new(
276 settings: ApplicationSettings,
277 store: AsyncProgramStore,
278 ) -> IambResult<Application> {
279 let backend = CrosstermBackend::new(stdout());
280 let terminal = Terminal::new(backend)?;
281
282 let mut bindings = crate::keybindings::setup_keybindings();
283 settings.setup(&mut bindings);
284 let bindings = KeyManager::new(bindings);
285
286 let mut locked = store.lock().await;
287 let screen = setup_screen(settings, locked.deref_mut())?;
288
289 let worker = locked.application.worker.clone();
290
291 drop(locked);
292
293 let actstack = VecDeque::new();
294
295 Ok(Application {
296 store,
297 worker,
298 terminal,
299 bindings,
300 actstack,
301 screen,
302 focused: true,
303 last_layout: None,
304 dirty: true,
305 })
306 }
307
308 fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
309 let bindings = &mut self.bindings;
310 let focused = self.focused;
311 let sstate = &mut self.screen;
312 let term = &mut self.terminal;
313
314 if store.application.ring_bell {
315 store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err();
316 }
317
318 if full {
319 term.clear()?;
320 }
321
322 term.draw(|f| {
323 let area = f.area();
324
325 let modestr = bindings.show_mode();
326 let cursor = bindings.get_cursor_hint();
327 let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
328
329 // Don't show terminal cursor when we show a dialog.
330 let hide_cursor = !dialogstr.is_empty();
331
332 store.application.draw_curr = Some(Instant::now());
333 let screen = Screen::new(store)
334 .show_dialog(dialogstr)
335 .show_mode(modestr)
336 .borders(true)
337 .border_style(Style::default().add_modifier(Modifier::DIM))
338 .tab_style(Style::default().add_modifier(Modifier::DIM))
339 .tab_style_focused(Style::default().remove_modifier(Modifier::DIM))
340 .focus(focused);
341 f.render_stateful_widget(screen, area, sstate);
342
343 if hide_cursor {
344 return;
345 }
346
347 if let Some((cx, cy)) = sstate.get_term_cursor() {
348 if let Some(c) = cursor.get_indicator() {
349 let style = Style::default().fg(Color::Green);
350 let span = Span::styled(c.to_string(), style);
351 let para = Paragraph::new(span);
352 let inner = Rect::new(cx, cy, 1, 1);
353 f.render_widget(para, inner)
354 }
355 f.set_cursor_position((cx, cy));
356 }
357 })?;
358 if sstate.hide_term_cursor() {
359 term.hide_cursor()?;
360 }
361
362 Ok(())
363 }
364
365 async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
366 loop {
367 self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?;
368 self.dirty = false;
369
370 if !poll(Duration::from_secs(1))? {
371 // Redraw in case there's new messages to show.
372 continue;
373 }
374
375 match read()? {
376 Event::Key(ke) => {
377 if ke.kind == KeyEventKind::Release {
378 continue;
379 }
380
381 return Ok(ke.into());
382 },
383 Event::Mouse(me) => {
384 let dir = match me.kind {
385 MouseEventKind::ScrollUp => MoveDir2D::Up,
386 MouseEventKind::ScrollDown => MoveDir2D::Down,
387 MouseEventKind::ScrollLeft => MoveDir2D::Left,
388 MouseEventKind::ScrollRight => MoveDir2D::Right,
389 _ => continue,
390 };
391
392 let size = ScrollSize::Cell;
393 let style = ScrollStyle::Direction2D(dir, size, 1.into());
394 let ctx = ProgramContext::default();
395 let mut store = self.store.lock().await;
396
397 match self.screen.scroll(&style, &ctx, store.deref_mut()) {
398 Ok(None) => {},
399 Ok(Some(info)) => {
400 drop(store);
401 self.handle_info(info);
402 },
403 Err(e) => {
404 self.screen.push_error(e);
405 },
406 }
407 },
408 Event::FocusGained => {
409 let mut store = self.store.lock().await;
410 store.application.focused = true;
411 self.focused = true;
412 },
413 Event::FocusLost => {
414 let mut store = self.store.lock().await;
415 store.application.focused = false;
416 self.focused = false;
417 },
418 Event::Resize(_, _) => {
419 // We'll redraw for the new size next time step() is called.
420 },
421 Event::Paste(s) => {
422 let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
423 let act = EditorAction::from(act);
424 let ctx = ProgramContext::default();
425 let mut store = self.store.lock().await;
426
427 match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
428 Ok(None) => {},
429 Ok(Some(info)) => {
430 drop(store);
431 self.handle_info(info);
432 },
433 Err(e) => {
434 self.screen.push_error(e);
435 },
436 }
437 },
438 }
439 }
440 }
441
442 fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
443 let mut acts = VecDeque::from(acts);
444 acts.append(&mut self.actstack);
445 self.actstack = acts;
446 }
447
448 fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
449 if let res @ Some(_) = self.actstack.pop_front() {
450 return res;
451 }
452
453 if keyskip {
454 return None;
455 } else {
456 return self.bindings.pop();
457 }
458 }
459
460 async fn action_run(
461 &mut self,
462 action: ProgramAction,
463 ctx: ProgramContext,
464 store: &mut ProgramStore,
465 ) -> IambResult<EditInfo> {
466 let info = match action {
467 // Do nothing.
468 Action::NoOp => None,
469
470 Action::Editor(act) => {
471 match self.screen.editor_command(&act, &ctx, store) {
472 Ok(info) => info,
473 Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
474 // Switch to the right window.
475 if let Some(winid) = content.to_window() {
476 let open = OpenTarget::Application(winid);
477 let open = WindowAction::Switch(open);
478 let _ = self.screen.window_command(&open, &ctx, store)?;
479
480 // Run command again.
481 self.screen.editor_command(&act, &ctx, store)?
482 } else {
483 return Err(EditError::WrongBuffer(content).into());
484 }
485 },
486 Err(err) => return Err(err.into()),
487 }
488 },
489
490 // Simple delegations.
491 Action::Application(act) => self.iamb_run(act, ctx, store).await?,
492 Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
493 Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
494 Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
495 Action::ShowInfoMessage(info) => Some(info),
496 Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
497
498 Action::Jump(l, dir, count) => {
499 let count = ctx.resolve(&count);
500 let _ = self.screen.jump(l, dir, count, &ctx)?;
501
502 None
503 },
504 Action::Suspend => {
505 self.terminal.program_suspend()?;
506
507 None
508 },
509
510 // UI actions.
511 Action::Tab(cmd) => {
512 if let TabAction::Close(_, _) = &cmd {
513 self.last_layout = self.screen.as_description().into();
514 }
515
516 self.screen.tab_command(&cmd, &ctx, store)?
517 },
518 Action::RedrawScreen => {
519 self.screen.clear_message();
520 self.redraw(true, store)?;
521
522 None
523 },
524
525 // Actions that create more Actions.
526 Action::Prompt(act) => {
527 let acts = self.screen.prompt(&act, &ctx, store)?;
528 self.action_prepend(acts);
529
530 None
531 },
532 Action::Command(act) => {
533 let acts = store.application.cmds.command(&act, &ctx, &mut store.registers)?;
534 self.action_prepend(acts);
535
536 None
537 },
538 Action::Repeat(rt) => {
539 self.bindings.repeat(rt, Some(ctx));
540
541 None
542 },
543
544 // Unimplemented.
545 Action::KeywordLookup(_) => {
546 // XXX: implement
547 None
548 },
549
550 _ => {
551 // XXX: log unhandled actions? print message?
552 None
553 },
554 };
555
556 return Ok(info);
557 }
558
559 async fn iamb_run(
560 &mut self,
561 action: IambAction,
562 ctx: ProgramContext,
563 store: &mut ProgramStore,
564 ) -> IambResult<EditInfo> {
565 if action.scribbles() {
566 self.dirty = true;
567 }
568
569 let info = match action {
570 IambAction::ClearUnreads => {
571 let user_id = &store.application.settings.profile.user_id;
572
573 // Clear any notifications we displayed:
574 store.application.open_notifications.clear();
575
576 for room_id in store.application.sync_info.chats() {
577 if let Some(room) = store.application.rooms.get_mut(room_id) {
578 room.fully_read_all(user_id);
579 }
580 }
581
582 None
583 },
584
585 IambAction::ToggleScrollbackFocus => {
586 self.screen.current_window_mut()?.focus_toggle();
587
588 None
589 },
590
591 IambAction::Homeserver(act) => {
592 let acts = self.homeserver_command(act, ctx, store).await?;
593 self.action_prepend(acts);
594
595 None
596 },
597 IambAction::Keys(act) => self.keys_command(act, ctx, store).await?,
598 IambAction::Message(act) => {
599 self.screen.current_window_mut()?.message_command(act, ctx, store).await?
600 },
601 IambAction::Space(act) => {
602 self.screen.current_window_mut()?.space_command(act, ctx, store).await?
603 },
604 IambAction::Room(act) => {
605 let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
606 self.action_prepend(acts);
607
608 None
609 },
610 IambAction::Send(act) => {
611 if store.application.settings.tunables.normal_after_send {
612 self.bindings.reset_mode();
613 }
614 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
615 },
616
617 IambAction::OpenLink(url) => {
618 tokio::task::spawn_blocking(move || {
619 return open::that(url);
620 });
621
622 None
623 },
624
625 IambAction::Verify(act, flow_id) => {
626 return verifications::iamb_verify(act, flow_id, store).await;
627 },
628 IambAction::VerifyRequest(user_id) => {
629 let Ok(user_id) = <&UserId>::try_from(user_id.as_str()) else {
630 return Err(IambError::InvalidUserId(user_id).into());
631 };
632
633 return verifications::iamb_verify_request(user_id, store).await;
634 },
635 };
636
637 Ok(info)
638 }
639
640 async fn homeserver_command(
641 &mut self,
642 action: HomeserverAction,
643 ctx: ProgramContext,
644 store: &mut ProgramStore,
645 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
646 match action {
647 HomeserverAction::CreateRoom(alias, vis, flags) => {
648 let client = &store.application.worker.client;
649 let room_id = create_room(client, alias, vis, flags).await?;
650 let room = IambId::Room(room_id, None);
651 let target = OpenTarget::Application(room);
652 let action = WindowAction::Switch(target);
653
654 Ok(vec![(action.into(), ctx)])
655 },
656 HomeserverAction::KnockSend(alias, reason) => {
657 let _ = self
658 .worker
659 .client
660 .knock(alias, reason, vec![])
661 .await
662 .map_err(IambError::from)?;
663 Ok(vec![])
664 },
665 HomeserverAction::Logout(user, true) => {
666 self.worker.logout(user)?;
667 let flags = CloseFlags::QUIT | CloseFlags::FORCE;
668 let act = TabAction::Close(TabTarget::All, flags);
669
670 Ok(vec![(act.into(), ctx)])
671 },
672 HomeserverAction::Logout(user, false) => {
673 let msg = "Would you like to logout?";
674 let act = IambAction::from(HomeserverAction::Logout(user, true));
675 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
676 let prompt = Box::new(prompt);
677
678 Err(UIError::NeedConfirm(prompt))
679 },
680 HomeserverAction::Forget => {
681 let client = &store.application.worker.client;
682 for room in client.left_rooms() {
683 room.forget().await.map_err(IambError::from)?;
684 }
685 Ok(vec![])
686 },
687 HomeserverAction::ProfileFieldSet(value) => {
688 let client = &store.application.worker.client;
689 let account = client.account();
690 account.set_profile_field(value).await.map_err(IambError::from)?;
691 Ok(vec![])
692 },
693 HomeserverAction::ProfileFieldUnset(field) => {
694 let client = &store.application.worker.client;
695 let account = client.account();
696 account.delete_profile_field(field).await.map_err(IambError::from)?;
697 Ok(vec![])
698 },
699 HomeserverAction::ProfileFieldShow(field) => {
700 let client = &store.application.worker.client;
701 let user_id = store.application.settings.profile.user_id.clone();
702 let account = client.account();
703 let value = account
704 .fetch_profile_field_of(user_id, field.clone())
705 .await
706 .map_err(IambError::from)?;
707
708 let msg = match (field, value) {
709 (_, Some(ProfileFieldValue::DisplayName(s))) => {
710 format!("Your profile's display name is set to: {s}")
711 },
712 (_, Some(ProfileFieldValue::TimeZone(s))) => {
713 format!("Your profile's timezone is set to: {s}")
714 },
715 (_, Some(ProfileFieldValue::AvatarUrl(s))) => {
716 format!("Your profile's avatar URL is set to: {s}")
717 },
718 (ProfileFieldName::DisplayName, None) => {
719 "Your profile's display name is currently unset".into()
720 },
721 (ProfileFieldName::TimeZone, None) => {
722 "Your profile's timezone is currently unset".into()
723 },
724 (ProfileFieldName::AvatarUrl, None) => {
725 "Your profile's avatar URL is currently unset".into()
726 },
727 (f, None) => {
728 format!("Your profile's {f:?} is currently unset")
729 },
730 (f, Some(s)) => {
731 format!("Your profile's {f:?} is set to {s:?}")
732 },
733 };
734
735 Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)])
736 },
737 }
738 }
739
740 async fn keys_command(
741 &mut self,
742 action: KeysAction,
743 _: ProgramContext,
744 store: &mut ProgramStore,
745 ) -> IambResult<EditInfo> {
746 let encryption = store.application.worker.client.encryption();
747
748 match action {
749 KeysAction::Export(path, passphrase) => {
750 encryption
751 .export_room_keys(path.into(), &passphrase, |_| true)
752 .await
753 .map_err(IambError::from)?;
754
755 Ok(Some("Successfully exported room keys".into()))
756 },
757 KeysAction::Import(path, passphrase) => {
758 let res = encryption
759 .import_room_keys(path.into(), &passphrase)
760 .await
761 .map_err(IambError::from)?;
762
763 let msg = format!("Imported {} of {} keys", res.imported_count, res.total_count);
764
765 Ok(Some(msg.into()))
766 },
767 }
768 }
769
770 fn handle_info(&mut self, info: InfoMessage) {
771 match info {
772 InfoMessage::Message(info) => {
773 self.screen.push_info(info);
774 },
775 InfoMessage::Pager(text) => {
776 let pager = Box::new(Pager::new(text, vec![]));
777 self.bindings.run_dialog(pager);
778 },
779 }
780 }
781
782 pub async fn run(&mut self) -> Result<(), std::io::Error> {
783 self.terminal.clear()?;
784
785 let store = self.store.clone();
786
787 while self.screen.tabs() != 0 {
788 let key = self.step().await?;
789
790 self.bindings.input_key(key);
791
792 let mut locked = store.lock().await;
793 let mut keyskip = false;
794
795 while let Some((action, ctx)) = self.action_pop(keyskip) {
796 match self.action_run(action, ctx, locked.deref_mut()).await {
797 Ok(None) => {
798 // Continue processing.
799 continue;
800 },
801 Ok(Some(info)) => {
802 self.handle_info(info);
803
804 // Continue processing; we'll redraw later.
805 continue;
806 },
807 Err(
808 UIError::NeedConfirm(dialog) |
809 UIError::EditingFailure(EditError::NeedConfirm(dialog)),
810 ) => {
811 self.bindings.run_dialog(dialog);
812 continue;
813 },
814 Err(e) => {
815 self.screen.push_error(e);
816
817 // Skip processing any more keypress Actions until the next key.
818 keyskip = true;
819 continue;
820 },
821 }
822 }
823 }
824
825 if let Some(ref layout) = self.last_layout {
826 let locked = self.store.lock().await;
827 let path = locked.application.settings.layout_json.as_path();
828 path.parent().map(create_dir_all).transpose()?;
829
830 let file = File::create(path)?;
831 let writer = BufWriter::new(file);
832
833 if let Err(e) = serde_json::to_writer(writer, layout) {
834 tracing::error!("Failed to save window layout while exiting: {}", e);
835 }
836 }
837
838 crossterm::terminal::disable_raw_mode()?;
839 execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
840 self.terminal.show_cursor()?;
841
842 return Ok(());
843 }
844}
845
846fn gen_passphrase() -> String {
847 rand::rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect()
848}
849
850fn read_response(question: &str) -> String {
851 println!("{question}");
852 let mut input = String::new();
853 let _ = std::io::stdin().read_line(&mut input);
854 input
855}
856
857fn read_yesno(question: &str) -> Option<char> {
858 read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
859}
860
861async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
862 if settings.session_json.is_file() {
863 let session = settings.read_session(&settings.session_json)?;
864 worker.login(LoginStyle::SessionRestore(session.into()))?;
865
866 return Ok(());
867 }
868
869 if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
870 let session = settings.read_session(&settings.session_json_old)?;
871 worker.login(LoginStyle::SessionRestore(session.into()))?;
872
873 return Ok(());
874 }
875
876 if let Some(ref password_file) = settings.profile.password_file {
877 if let Err(e) = std::fs::read_to_string(password_file)
878 .map(|password| worker.login(LoginStyle::Password(password)))
879 {
880 println!("Failed to log in using password file {password_file:?}: {e}");
881 println!("Continuing on to interactive login");
882 } else {
883 return Ok(());
884 }
885 }
886
887 loop {
888 let login_style =
889 match read_response("Please select login type: [p]assword / [s]ingle sign on")
890 .chars()
891 .next()
892 .map(|c| c.to_ascii_lowercase())
893 {
894 None | Some('p') => {
895 let password = rpassword::prompt_password("Password: ")?;
896 LoginStyle::Password(password)
897 },
898 Some('s') => LoginStyle::SingleSignOn,
899 Some(_) => {
900 println!("Failed to login. Please enter 'p' or 's'");
901 continue;
902 },
903 };
904
905 match worker.login(login_style) {
906 Ok(info) => {
907 if let Some(msg) = info {
908 println!("{msg}");
909 }
910
911 break;
912 },
913 Err(err) => {
914 println!("Failed to login: {err}");
915 continue;
916 },
917 }
918 }
919
920 Ok(())
921}
922
923fn print_exit<T: Display, N>(v: T) -> N {
924 eprintln!("{v}");
925 process::exit(2);
926}
927
928// We can't access the OlmMachine directly, so write the keys to a temporary
929// file first, and then import them later.
930async fn check_import_keys(
931 settings: &ApplicationSettings,
932) -> IambResult<Option<(temp_dir::TempDir, String)>> {
933 let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
934
935 if !do_import {
936 return Ok(None);
937 }
938
939 let question = format!(
940 "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
941 settings.sled_dir.display()
942 );
943
944 loop {
945 match read_yesno(&question) {
946 Some('y') => {
947 break;
948 },
949 Some('n') => {
950 return Ok(None);
951 },
952 Some(_) | None => {
953 continue;
954 },
955 }
956 }
957
958 let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
959 let passphrase = gen_passphrase();
960
961 println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
962
963 let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
964 Ok(encrypted) => encrypted,
965 Err(e) => {
966 eprintln!("* Failed to encrypt room keys during export: {e}");
967 process::exit(2);
968 },
969 };
970
971 let tmpdir = TempDir::new()?;
972 let exported = tmpdir.child("keys");
973
974 println!("* Writing encrypted room keys to {}...", exported.display());
975 tokio::fs::write(&exported, &encrypted).await?;
976
977 Ok(Some((tmpdir, passphrase)))
978}
979
980async fn login_upgrade(
981 keydir: TempDir,
982 passphrase: String,
983 worker: &Requester,
984 settings: &ApplicationSettings,
985 store: &AsyncProgramStore,
986) -> IambResult<()> {
987 println!(
988 "Please log in for {} to import the room keys into a new session",
989 settings.profile.user_id
990 );
991
992 login(worker, settings).await?;
993
994 println!("* Importing room keys...");
995
996 let exported = keydir.child("keys");
997 let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
998
999 match imported {
1000 Ok(res) => {
1001 println!(
1002 "* Successfully imported {} out of {} keys",
1003 res.imported_count, res.total_count
1004 );
1005 let _ = keydir.cleanup();
1006 },
1007 Err(e) => {
1008 println!(
1009 "Failed to import room keys from {}/keys: {e}\n\n\
1010 They have been encrypted with the passphrase {passphrase:?}.\
1011 Please save them and try importing them manually instead\n",
1012 keydir.path().display()
1013 );
1014
1015 loop {
1016 match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
1017 Some('y') => break,
1018 Some('n') => print_exit("* Exiting..."),
1019 Some(_) | None => continue,
1020 }
1021 }
1022 },
1023 }
1024
1025 println!("* Syncing...");
1026 worker::do_first_sync(&worker.client, store)
1027 .await
1028 .map_err(IambError::from)?;
1029
1030 Ok(())
1031}
1032
1033async fn login_normal(
1034 worker: &Requester,
1035 settings: &ApplicationSettings,
1036 store: &AsyncProgramStore,
1037) -> IambResult<()> {
1038 println!("* Logging in for {}...", settings.profile.user_id);
1039 login(worker, settings).await?;
1040 println!("* Syncing...");
1041 worker::do_first_sync(&worker.client, store)
1042 .await
1043 .map_err(IambError::from)?;
1044 Ok(())
1045}
1046
1047/// Set up the terminal for drawing the TUI, and getting additional info.
1048fn setup_tty(settings: &ApplicationSettings, enable_enhanced_keys: bool) -> std::io::Result<()> {
1049 // Enable raw mode and enter the alternate screen.
1050 crossterm::terminal::enable_raw_mode()?;
1051 crossterm::execute!(stdout(), EnterAlternateScreen)?;
1052
1053 if enable_enhanced_keys {
1054 // Enable the Kitty keyboard enhancement protocol for improved keypresses.
1055 crossterm::queue!(
1056 stdout(),
1057 PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
1058 )?;
1059 }
1060
1061 if settings.tunables.mouse.enabled {
1062 crossterm::execute!(stdout(), EnableMouseCapture)?;
1063 }
1064
1065 if settings.tunables.terminal.enable_title {
1066 let title = format!("iamb ({})", settings.profile.user_id.as_str());
1067 crossterm::execute!(stdout(), SetTitle(title))?;
1068 }
1069
1070 let cursor_shape = SetCursorStyle::from(settings.tunables.terminal.cursor_shape);
1071
1072 crossterm::execute!(stdout(), EnableBracketedPaste, EnableFocusChange, cursor_shape)
1073}
1074
1075// Do our best to reverse what we did in setup_tty() when we exit or crash.
1076fn restore_tty(enable_enhanced_keys: bool, enable_mouse: bool) {
1077 if enable_enhanced_keys {
1078 let _ = crossterm::queue!(stdout(), PopKeyboardEnhancementFlags);
1079 }
1080
1081 if enable_mouse {
1082 let _ = crossterm::queue!(stdout(), DisableMouseCapture);
1083 }
1084
1085 let _ = crossterm::execute!(
1086 stdout(),
1087 DisableBracketedPaste,
1088 DisableFocusChange,
1089 SetCursorStyle::DefaultUserShape,
1090 LeaveAlternateScreen,
1091 CursorShow,
1092 );
1093
1094 let _ = crossterm::terminal::disable_raw_mode();
1095}
1096
1097async fn run(settings: ApplicationSettings) -> IambResult<()> {
1098 // Get old keys the first time we run w/ the upgraded SDK.
1099 let import_keys = check_import_keys(&settings).await?;
1100
1101 // Set up client state.
1102 create_dir_all(settings.sqlite_dir.as_path())?;
1103 let client = worker::create_client(&settings).await;
1104
1105 // Set up the async worker thread and global store.
1106 let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
1107 let store = ChatStore::new(worker.clone(), settings.clone());
1108 let mut store = Store::new(store);
1109 store.completer = Box::new(IambCompleter);
1110
1111 let store = Arc::new(AsyncMutex::new(store));
1112 worker.init(store.clone());
1113
1114 let res = if let Some((keydir, pass)) = import_keys {
1115 login_upgrade(keydir, pass, &worker, &settings, &store).await
1116 } else {
1117 login_normal(&worker, &settings, &store).await
1118 };
1119
1120 match res {
1121 Err(UIError::Application(IambError::Matrix(e))) => {
1122 if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
1123 print_exit(format!(
1124 "Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.",
1125 settings.session_json.display()
1126 ))
1127 } else {
1128 print_exit(e)
1129 }
1130 },
1131 Err(e) => print_exit(e),
1132 Ok(()) => (),
1133 }
1134
1135 // Set up the terminal for drawing, and cleanup properly on panics.
1136 let enable_enhanced_keys =
1137 settings.tunables.terminal.enable_extended_keys.unwrap_or_else(|| {
1138 crossterm::terminal::supports_keyboard_enhancement()
1139 .inspect_err(|e| tracing::warn!(
1140 err = %e,
1141 "Failed to determine whether the terminal supports keyboard enhancements"
1142 ))
1143 .unwrap_or_default()
1144 });
1145 setup_tty(&settings, enable_enhanced_keys)?;
1146
1147 let orig_hook = std::panic::take_hook();
1148 let enable_mouse = settings.tunables.mouse.enabled;
1149 std::panic::set_hook(Box::new(move |panic_info| {
1150 restore_tty(enable_enhanced_keys, enable_mouse);
1151 orig_hook(panic_info);
1152 process::exit(1);
1153 }));
1154
1155 // And finally, start running the terminal UI.
1156 let mut application = Application::new(settings, store).await?;
1157 application.run().await?;
1158
1159 // Clean up the terminal on exit.
1160 restore_tty(enable_enhanced_keys, enable_mouse);
1161
1162 Ok(())
1163}
1164
1165fn setup_logging(settings: &ApplicationSettings) -> tracing_appender::non_blocking::WorkerGuard {
1166 let log_prefix = format!("iamb-log-{}", settings.profile_name);
1167 let log_dir = settings.dirs.logs.as_path();
1168 let max_log_files = settings.tunables.max_log_files;
1169 let log_level = &settings.tunables.log_level;
1170
1171 let appender = tracing_appender::rolling::Builder::new()
1172 .rotation(tracing_appender::rolling::Rotation::DAILY)
1173 .filename_prefix(log_prefix)
1174 .max_log_files(max_log_files)
1175 .build(log_dir)
1176 .expect("can build appending tracing logger");
1177 let (appender, guard) = tracing_appender::non_blocking(appender);
1178
1179 let filter = if let Ok(dirs) = std::env::var(EnvFilter::DEFAULT_ENV) {
1180 EnvFilter::builder()
1181 .with_default_directive(Level::WARN.into())
1182 .parse(dirs)
1183 .map_err(|err| format!("Unable to parse {}: {err}", EnvFilter::DEFAULT_ENV))
1184 .unwrap_or_else(print_exit)
1185 } else {
1186 EnvFilter::builder()
1187 .with_default_directive(Level::WARN.into())
1188 .parse(log_level)
1189 .map_err(|err| format!("Unable to parse `log_level`: {err}"))
1190 .unwrap_or_else(print_exit)
1191 };
1192
1193 let subscriber = FmtSubscriber::builder()
1194 .with_writer(appender)
1195 .with_env_filter(filter)
1196 .finish();
1197
1198 tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
1199
1200 guard
1201}
1202
1203fn main() {
1204 // Parse command-line flags.
1205 let iamb = Iamb::parse();
1206
1207 if let Some(shell) = iamb.completions {
1208 clap_complete::generate(shell, &mut Iamb::command(), "iamb", &mut std::io::stdout());
1209 return;
1210 }
1211
1212 // Load configuration and set up the Matrix SDK.
1213 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1214
1215 // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
1216 #[cfg(unix)]
1217 unsafe {
1218 libc::umask(0o077);
1219 };
1220
1221 let guard = setup_logging(&settings);
1222
1223 let rt = tokio::runtime::Builder::new_multi_thread()
1224 .enable_all()
1225 .worker_threads(2)
1226 .thread_name_fn(|| {
1227 static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1228 let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
1229 format!("iamb-worker-{id}")
1230 })
1231 .build()
1232 .unwrap();
1233
1234 if let Err(err) = rt.block_on(async move { run(settings).await }) {
1235 eprintln!("\n{err}\n");
1236 process::exit(2);
1237 }
1238
1239 drop(guard);
1240}