src/main.rs
728 lines · 22885 bytes
1#![allow(clippy::manual_range_contains)]
2#![allow(clippy::needless_return)]
3#![allow(clippy::result_large_err)]
4#![allow(clippy::bool_assert_comparison)]
5use std::collections::VecDeque;
6use std::convert::TryFrom;
7use std::fmt::Display;
8use std::fs::{create_dir_all, File};
9use std::io::{stdout, BufReader, BufWriter, Stdout};
10use std::ops::DerefMut;
11use std::process;
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::sync::Arc;
14use std::time::Duration;
15
16use clap::Parser;
17use tokio::sync::Mutex as AsyncMutex;
18use tracing_subscriber::FmtSubscriber;
19
20use matrix_sdk::ruma::OwnedUserId;
21
22use modalkit::crossterm::{
23 self,
24 cursor::Show as CursorShow,
25 event::{
26 poll,
27 read,
28 DisableBracketedPaste,
29 DisableFocusChange,
30 EnableBracketedPaste,
31 EnableFocusChange,
32 Event,
33 },
34 execute,
35 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
36};
37
38use modalkit::tui::{
39 backend::CrosstermBackend,
40 layout::Rect,
41 style::{Color, Style},
42 text::Span,
43 widgets::Paragraph,
44 Terminal,
45};
46
47mod base;
48mod commands;
49mod config;
50mod keybindings;
51mod message;
52mod util;
53mod windows;
54mod worker;
55
56#[cfg(test)]
57mod tests;
58
59use crate::{
60 base::{
61 AsyncProgramStore,
62 ChatStore,
63 HomeserverAction,
64 IambAction,
65 IambError,
66 IambId,
67 IambInfo,
68 IambResult,
69 ProgramAction,
70 ProgramContext,
71 ProgramStore,
72 },
73 config::{ApplicationSettings, Iamb},
74 windows::IambWindow,
75 worker::{create_room, ClientWorker, LoginStyle, Requester},
76};
77
78use modalkit::{
79 editing::{
80 action::{
81 Action,
82 Commandable,
83 EditError,
84 EditInfo,
85 Editable,
86 EditorAction,
87 InfoMessage,
88 InsertTextAction,
89 Jumpable,
90 Promptable,
91 Scrollable,
92 TabAction,
93 TabContainer,
94 TabCount,
95 UIError,
96 WindowAction,
97 WindowContainer,
98 },
99 base::{MoveDir1D, OpenTarget, RepeatType},
100 context::Resolve,
101 key::KeyManager,
102 store::Store,
103 },
104 input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey},
105 widgets::{
106 cmdbar::CommandBarState,
107 screen::{FocusList, Screen, ScreenState, TabLayoutDescription},
108 windows::WindowLayoutDescription,
109 TerminalCursor,
110 TerminalExtOps,
111 Window,
112 },
113};
114
115fn config_tab_to_desc(
116 layout: config::WindowLayout,
117 store: &mut ProgramStore,
118) -> IambResult<WindowLayoutDescription<IambInfo>> {
119 let desc = match layout {
120 config::WindowLayout::Window { window } => {
121 let ChatStore { names, worker, .. } = &mut store.application;
122
123 let window = match window {
124 config::WindowPath::UserId(user_id) => {
125 let name = user_id.to_string();
126 let room_id = worker.join_room(name.clone())?;
127 names.insert(name, room_id.clone());
128 IambId::Room(room_id)
129 },
130 config::WindowPath::RoomId(room_id) => IambId::Room(room_id),
131 config::WindowPath::AliasId(alias) => {
132 let name = alias.to_string();
133 let room_id = worker.join_room(name.clone())?;
134 names.insert(name, room_id.clone());
135 IambId::Room(room_id)
136 },
137 config::WindowPath::Window(id) => id,
138 };
139
140 WindowLayoutDescription::Window { window, length: None }
141 },
142 config::WindowLayout::Split { split } => {
143 let children = split
144 .into_iter()
145 .map(|child| config_tab_to_desc(child, store))
146 .collect::<IambResult<Vec<_>>>()?;
147
148 WindowLayoutDescription::Split { children, length: None }
149 },
150 };
151
152 Ok(desc)
153}
154
155fn setup_screen(
156 settings: ApplicationSettings,
157 store: &mut ProgramStore,
158) -> IambResult<ScreenState<IambWindow, IambInfo>> {
159 let cmd = CommandBarState::new(store);
160 let dims = crossterm::terminal::size()?;
161 let area = Rect::new(0, 0, dims.0, dims.1);
162
163 match settings.layout {
164 config::Layout::Restore => {
165 if let Ok(layout) = std::fs::read(&settings.layout_json) {
166 let tabs: TabLayoutDescription<IambInfo> =
167 serde_json::from_slice(&layout).map_err(IambError::from)?;
168 let tabs = tabs.to_layout(area.into(), store)?;
169
170 return Ok(ScreenState::from_list(tabs, cmd));
171 }
172 },
173 config::Layout::New => {},
174 config::Layout::Config { tabs } => {
175 let mut list = FocusList::default();
176
177 for tab in tabs.into_iter() {
178 let tab = config_tab_to_desc(tab, store)?;
179 let tab = tab.to_layout(area.into(), store)?;
180 list.push(tab);
181 }
182
183 return Ok(ScreenState::from_list(list, cmd));
184 },
185 }
186
187 let win = settings
188 .tunables
189 .default_room
190 .and_then(|room| IambWindow::find(room, store).ok())
191 .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
192 .unwrap();
193
194 return Ok(ScreenState::new(win, cmd));
195}
196
197struct Application {
198 /// Terminal backend.
199 terminal: Terminal<CrosstermBackend<Stdout>>,
200
201 /// State for the Matrix client, editing, etc.
202 store: AsyncProgramStore,
203
204 /// UI state (open tabs, command bar, etc.) to use when rendering.
205 screen: ScreenState<IambWindow, IambInfo>,
206
207 /// Handle to communicate synchronously with the Matrix worker task.
208 worker: Requester,
209
210 /// Mapped keybindings.
211 bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
212
213 /// Pending actions to run.
214 actstack: VecDeque<(ProgramAction, ProgramContext)>,
215
216 /// Whether or not the terminal is currently focused.
217 focused: bool,
218
219 /// The tab layout before the last executed [TabAction].
220 last_layout: Option<TabLayoutDescription<IambInfo>>,
221}
222
223impl Application {
224 pub async fn new(
225 settings: ApplicationSettings,
226 store: AsyncProgramStore,
227 ) -> IambResult<Application> {
228 let mut stdout = stdout();
229 crossterm::terminal::enable_raw_mode()?;
230 crossterm::execute!(stdout, EnterAlternateScreen)?;
231 crossterm::execute!(stdout, EnableBracketedPaste)?;
232 crossterm::execute!(stdout, EnableFocusChange)?;
233
234 let title = format!("iamb ({})", settings.profile.user_id);
235 crossterm::execute!(stdout, SetTitle(title))?;
236
237 let backend = CrosstermBackend::new(stdout);
238 let terminal = Terminal::new(backend)?;
239
240 let bindings = crate::keybindings::setup_keybindings();
241 let bindings = KeyManager::new(bindings);
242
243 let mut locked = store.lock().await;
244 let screen = setup_screen(settings, locked.deref_mut())?;
245
246 let worker = locked.application.worker.clone();
247 drop(locked);
248
249 let actstack = VecDeque::new();
250
251 Ok(Application {
252 store,
253 worker,
254 terminal,
255 bindings,
256 actstack,
257 screen,
258 focused: true,
259 last_layout: None,
260 })
261 }
262
263 fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
264 let bindings = &mut self.bindings;
265 let focused = self.focused;
266 let sstate = &mut self.screen;
267 let term = &mut self.terminal;
268
269 if full {
270 term.clear()?;
271 }
272
273 term.draw(|f| {
274 let area = f.size();
275
276 let modestr = bindings.show_mode();
277 let cursor = bindings.get_cursor_indicator();
278 let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
279
280 // Don't show terminal cursor when we show a dialog.
281 let hide_cursor = !dialogstr.is_empty();
282
283 let screen = Screen::new(store)
284 .show_dialog(dialogstr)
285 .show_mode(modestr)
286 .borders(true)
287 .focus(focused);
288 f.render_stateful_widget(screen, area, sstate);
289
290 if hide_cursor {
291 return;
292 }
293
294 if let Some((cx, cy)) = sstate.get_term_cursor() {
295 if let Some(c) = cursor {
296 let style = Style::default().fg(Color::Green);
297 let span = Span::styled(c.to_string(), style);
298 let para = Paragraph::new(span);
299 let inner = Rect::new(cx, cy, 1, 1);
300 f.render_widget(para, inner)
301 }
302 f.set_cursor(cx, cy);
303 }
304 })?;
305
306 Ok(())
307 }
308
309 async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
310 loop {
311 self.redraw(false, self.store.clone().lock().await.deref_mut())?;
312
313 if !poll(Duration::from_secs(1))? {
314 // Redraw in case there's new messages to show.
315 continue;
316 }
317
318 match read()? {
319 Event::Key(ke) => return Ok(ke.into()),
320 Event::Mouse(_) => {
321 // Do nothing for now.
322 },
323 Event::FocusGained => {
324 self.focused = true;
325 },
326 Event::FocusLost => {
327 self.focused = false;
328 },
329 Event::Resize(_, _) => {
330 // We'll redraw for the new size next time step() is called.
331 },
332 Event::Paste(s) => {
333 let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
334 let act = EditorAction::from(act);
335 let ctx = ProgramContext::default();
336 let mut store = self.store.lock().await;
337
338 match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
339 Ok(None) => {},
340 Ok(Some(info)) => {
341 drop(store);
342 self.handle_info(info);
343 },
344 Err(e) => {
345 self.screen.push_error(e);
346 },
347 }
348 },
349 }
350 }
351 }
352
353 fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
354 let mut acts = VecDeque::from(acts);
355 acts.append(&mut self.actstack);
356 self.actstack = acts;
357 }
358
359 fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
360 if let res @ Some(_) = self.actstack.pop_front() {
361 return res;
362 }
363
364 if keyskip {
365 return None;
366 } else {
367 return self.bindings.pop();
368 }
369 }
370
371 async fn action_run(
372 &mut self,
373 action: ProgramAction,
374 ctx: ProgramContext,
375 store: &mut ProgramStore,
376 ) -> IambResult<EditInfo> {
377 let info = match action {
378 // Do nothing.
379 Action::NoOp => None,
380
381 Action::Editor(act) => {
382 match self.screen.editor_command(&act, &ctx, store) {
383 Ok(info) => info,
384 Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
385 // Switch to the right window.
386 if let Some(winid) = content.to_window() {
387 let open = OpenTarget::Application(winid);
388 let open = WindowAction::Switch(open);
389 let _ = self.screen.window_command(&open, &ctx, store)?;
390
391 // Run command again.
392 self.screen.editor_command(&act, &ctx, store)?
393 } else {
394 return Err(EditError::WrongBuffer(content).into());
395 }
396 },
397 Err(err) => return Err(err.into()),
398 }
399 },
400
401 // Simple delegations.
402 Action::Application(act) => self.iamb_run(act, ctx, store).await?,
403 Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
404 Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
405 Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
406 Action::ShowInfoMessage(info) => Some(info),
407 Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
408
409 Action::Jump(l, dir, count) => {
410 let count = ctx.resolve(&count);
411 let _ = self.screen.jump(l, dir, count, &ctx)?;
412
413 None
414 },
415 Action::Suspend => {
416 self.terminal.program_suspend()?;
417
418 None
419 },
420
421 // UI actions.
422 Action::Tab(cmd) => {
423 if let TabAction::Close(_, _) = &cmd {
424 self.last_layout = self.screen.as_description().into();
425 }
426
427 self.screen.tab_command(&cmd, &ctx, store)?
428 },
429 Action::RedrawScreen => {
430 self.screen.clear_message();
431 self.redraw(true, store)?;
432
433 None
434 },
435
436 // Actions that create more Actions.
437 Action::Prompt(act) => {
438 let acts = self.screen.prompt(&act, &ctx, store)?;
439 self.action_prepend(acts);
440
441 None
442 },
443 Action::Command(act) => {
444 let acts = store.application.cmds.command(&act, &ctx)?;
445 self.action_prepend(acts);
446
447 None
448 },
449 Action::Repeat(rt) => {
450 self.bindings.repeat(rt, Some(ctx));
451
452 None
453 },
454
455 // Unimplemented.
456 Action::KeywordLookup => {
457 // XXX: implement
458 None
459 },
460
461 _ => {
462 // XXX: log unhandled actions? print message?
463 None
464 },
465 };
466
467 return Ok(info);
468 }
469
470 async fn iamb_run(
471 &mut self,
472 action: IambAction,
473 ctx: ProgramContext,
474 store: &mut ProgramStore,
475 ) -> IambResult<EditInfo> {
476 let info = match action {
477 IambAction::ToggleScrollbackFocus => {
478 self.screen.current_window_mut()?.focus_toggle();
479
480 None
481 },
482
483 IambAction::Homeserver(act) => {
484 let acts = self.homeserver_command(act, ctx, store).await?;
485 self.action_prepend(acts);
486
487 None
488 },
489 IambAction::Message(act) => {
490 self.screen.current_window_mut()?.message_command(act, ctx, store).await?
491 },
492 IambAction::Room(act) => {
493 let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
494 self.action_prepend(acts);
495
496 None
497 },
498 IambAction::Send(act) => {
499 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
500 },
501
502 IambAction::Verify(act, user_dev) => {
503 if let Some(sas) = store.application.verifications.get(&user_dev) {
504 self.worker.verify(act, sas.clone())?
505 } else {
506 return Err(IambError::InvalidVerificationId(user_dev).into());
507 }
508 },
509 IambAction::VerifyRequest(user_id) => {
510 if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
511 self.worker.verify_request(user_id)?
512 } else {
513 return Err(IambError::InvalidUserId(user_id).into());
514 }
515 },
516 };
517
518 Ok(info)
519 }
520
521 async fn homeserver_command(
522 &mut self,
523 action: HomeserverAction,
524 ctx: ProgramContext,
525 store: &mut ProgramStore,
526 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
527 match action {
528 HomeserverAction::CreateRoom(alias, vis, flags) => {
529 let client = &store.application.worker.client;
530 let room_id = create_room(client, alias.as_deref(), vis, flags).await?;
531 let room = IambId::Room(room_id);
532 let target = OpenTarget::Application(room);
533 let action = WindowAction::Switch(target);
534
535 Ok(vec![(action.into(), ctx)])
536 },
537 }
538 }
539
540 fn handle_info(&mut self, info: InfoMessage) {
541 match info {
542 InfoMessage::Message(info) => {
543 self.screen.push_info(info);
544 },
545 InfoMessage::Pager(text) => {
546 let pager = Box::new(Pager::new(text, vec![]));
547 self.bindings.run_dialog(pager);
548 },
549 }
550 }
551
552 pub async fn run(&mut self) -> Result<(), std::io::Error> {
553 self.terminal.clear()?;
554
555 let store = self.store.clone();
556
557 while self.screen.tabs() != 0 {
558 let key = self.step().await?;
559
560 self.bindings.input_key(key);
561
562 let mut locked = store.lock().await;
563 let mut keyskip = false;
564
565 while let Some((action, ctx)) = self.action_pop(keyskip) {
566 match self.action_run(action, ctx, locked.deref_mut()).await {
567 Ok(None) => {
568 // Continue processing.
569 continue;
570 },
571 Ok(Some(info)) => {
572 self.handle_info(info);
573
574 // Continue processing; we'll redraw later.
575 continue;
576 },
577 Err(
578 UIError::NeedConfirm(dialog) |
579 UIError::EditingFailure(EditError::NeedConfirm(dialog)),
580 ) => {
581 self.bindings.run_dialog(dialog);
582 continue;
583 },
584 Err(e) => {
585 self.screen.push_error(e);
586
587 // Skip processing any more keypress Actions until the next key.
588 keyskip = true;
589 continue;
590 },
591 }
592 }
593 }
594
595 if let Some(ref layout) = self.last_layout {
596 let locked = self.store.lock().await;
597 let path = locked.application.settings.layout_json.as_path();
598 path.parent().map(create_dir_all).transpose()?;
599
600 let file = File::create(path)?;
601 let writer = BufWriter::new(file);
602
603 if let Err(e) = serde_json::to_writer(writer, layout) {
604 tracing::error!("Failed to save window layout while exiting: {}", e);
605 }
606 }
607
608 crossterm::terminal::disable_raw_mode()?;
609 execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
610 self.terminal.show_cursor()?;
611
612 return Ok(());
613 }
614}
615
616async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
617 println!("Logging in for {}...", settings.profile.user_id);
618
619 if settings.session_json.is_file() {
620 let file = File::open(settings.session_json.as_path())?;
621 let reader = BufReader::new(file);
622 let session = serde_json::from_reader(reader).map_err(IambError::from)?;
623
624 worker.login(LoginStyle::SessionRestore(session))?;
625
626 return Ok(());
627 }
628
629 loop {
630 let password = rpassword::prompt_password("Password: ")?;
631
632 match worker.login(LoginStyle::Password(password)) {
633 Ok(info) => {
634 if let Some(msg) = info {
635 println!("{msg}");
636 }
637
638 break;
639 },
640 Err(err) => {
641 println!("Failed to login: {err}");
642 continue;
643 },
644 }
645 }
646
647 Ok(())
648}
649
650fn print_exit<T: Display, N>(v: T) -> N {
651 println!("{v}");
652 process::exit(2);
653}
654
655async fn run(settings: ApplicationSettings) -> IambResult<()> {
656 // Set up the async worker thread and global store.
657 let worker = ClientWorker::spawn(settings.clone()).await;
658 let store = ChatStore::new(worker.clone(), settings.clone());
659 let store = Store::new(store);
660 let store = Arc::new(AsyncMutex::new(store));
661 worker.init(store.clone());
662
663 login(worker, &settings).await.unwrap_or_else(print_exit);
664
665 fn restore_tty() {
666 let _ = crossterm::terminal::disable_raw_mode();
667 let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
668 let _ = crossterm::execute!(stdout(), DisableFocusChange);
669 let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
670 let _ = crossterm::execute!(stdout(), CursorShow);
671 }
672
673 // Make sure panics clean up the terminal properly.
674 let orig_hook = std::panic::take_hook();
675 std::panic::set_hook(Box::new(move |panic_info| {
676 restore_tty();
677 orig_hook(panic_info);
678 process::exit(1);
679 }));
680
681 let mut application = Application::new(settings, store).await?;
682
683 // We can now run the application.
684 application.run().await?;
685 restore_tty();
686
687 Ok(())
688}
689
690fn main() -> IambResult<()> {
691 // Parse command-line flags.
692 let iamb = Iamb::parse();
693
694 // Load configuration and set up the Matrix SDK.
695 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
696
697 // Set up the tracing subscriber so we can log client messages.
698 let log_prefix = format!("iamb-log-{}", settings.profile_name);
699 let log_dir = settings.dirs.logs.as_path();
700
701 create_dir_all(settings.matrix_dir.as_path())?;
702 create_dir_all(log_dir)?;
703
704 let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
705 let (appender, guard) = tracing_appender::non_blocking(appender);
706
707 let subscriber = FmtSubscriber::builder()
708 .with_writer(appender)
709 .with_max_level(settings.tunables.log_level)
710 .finish();
711 tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
712
713 let rt = tokio::runtime::Builder::new_multi_thread()
714 .enable_all()
715 .worker_threads(2)
716 .thread_name_fn(|| {
717 static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
718 let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
719 format!("iamb-worker-{id}")
720 })
721 .build()
722 .unwrap();
723
724 rt.block_on(async move { run(settings).await })?;
725
726 drop(guard);
727 process::exit(0);
728}