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