Commit 7c39e88ba2

7c39e88ba28a22e4ada30047c461fd39298c9cec

parent: 758397eb5a

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-06-29 06:42 UTC

Restore opened tabs and windows upon restart (#72)

Layout: unified · split

Cargo.lock +4 −2
@@ -2136,8 +2136,9 @@ dependencies = [
21362136
21372137[[package]]
21382138name = "modalkit"
2139version = "0.0.15"
2140source = "git+https://github.com/ulyssa/modalkit?rev=f641162#f6411625caa1ddb764c91a3fc47e052cfdc405b5"
2139version = "0.0.16"
2140source = "registry+https://github.com/rust-lang/crates.io-index"
2141checksum = "3f38eef0b4f6377e73d1082d508cae1df4d99a94d25361538131d839f292aa49"
21412142dependencies = [
21422143 "anymap2",
21432144 "arboard",
@@ -2151,6 +2152,7 @@ dependencies = [
21512152 "ratatui",
21522153 "regex",
21532154 "ropey",
2155 "serde",
21542156 "textwrap",
21552157 "thiserror",
21562158 "unicode-segmentation",
Cargo.toml +1 −2
@@ -51,8 +51,7 @@ unicode-width = "0.1.10"
5151url = {version = "^2.2.2", features = ["serde"]}
5252
5353[dependencies.modalkit]
54git = "https://github.com/ulyssa/modalkit"
55rev = "f641162"
54version = "0.0.16"
5655
5756[dependencies.matrix-sdk]
5857version = "0.6"
docs/iamb.5.md +21
@@ -36,6 +36,10 @@ These options are configured as a map under the profiles name.
3636> Overwrite general settings for this account. The fields are identical to
3737> those in *TUNABLES*.
3838
39**layout** (type: startup layout object)
40> Overwrite general settings for this account. The fields are identical to
41> those in *STARTUP LAYOUT*.
42
3943**dirs** (type: XDG overrides object)
4044> Overwrite general settings for this account. The fields are identical to
4145> those in *DIRECTORIES*.
@@ -92,6 +96,23 @@ maps containing the following key value pairs.
9296> _light-cyan_, _light-green_, _light-magenta_, _light-red_,
9397> _light-yellow_, _magenta_, _none_, _red_, _white_, _yellow_
9498
99# STARTUP LAYOUT
100
101Specifies what initial set of tabs and windows to show when starting the
102client. Configured as an object under the key *layout*.
103
104**style** (type: string)
105> Specifies what window layout to load when starting. Valid values are
106> _restore_ to restore the layout from the last time the client was exited,
107> _new_ to open a single window (uses the value of _default\_room_ if set), or
108> _config_ to open the layout described under _tabs_.
109
110**tabs** (type: array of window objects)
111> If **style** is set to _config_, then this value will be used to open a set
112> of tabs and windows at startup. Each object can contain either a **window**
113> key specifying a username, room identifier or room alias to show, or a
114> **split** key specifying an array of window objects.
115
95116# DIRECTORIES
96117
97118Specifies the directories to save data in. Configured as a map under the key
src/base.rs +153
@@ -1,12 +1,23 @@
11use std::borrow::Cow;
22use std::collections::{HashMap, HashSet};
3use std::convert::TryFrom;
4use std::fmt::{self, Display};
35use std::hash::Hash;
46use std::str::FromStr;
57use std::sync::Arc;
68use std::time::{Duration, Instant};
79
810use emojis::Emoji;
11use serde::{
12 de::Error as SerdeError,
13 de::Visitor,
14 Deserialize,
15 Deserializer,
16 Serialize,
17 Serializer,
18};
919use tokio::sync::Mutex as AsyncMutex;
20use url::Url;
1021
1122use matrix_sdk::{
1223 encryption::verification::SasVerification,
@@ -715,17 +726,159 @@ impl ApplicationStore for ChatStore {}
715726
716727#[derive(Clone, Debug, Eq, Hash, PartialEq)]
717728pub enum IambId {
729 /// A Matrix room.
718730 Room(OwnedRoomId),
731
732 /// The `:rooms` window.
719733 DirectList,
734
735 /// The `:members` window for a given Matrix room.
720736 MemberList(OwnedRoomId),
737
738 /// The `:rooms` window.
721739 RoomList,
740
741 /// The `:spaces` window.
722742 SpaceList,
743
744 /// The `:verify` window.
723745 VerifyList,
746
747 /// The `:welcome` window.
724748 Welcome,
725749}
726750
751impl Display for IambId {
752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 match self {
754 IambId::Room(room_id) => {
755 write!(f, "iamb://room/{room_id}")
756 },
757 IambId::MemberList(room_id) => {
758 write!(f, "iamb://members/{room_id}")
759 },
760 IambId::DirectList => f.write_str("iamb://dms"),
761 IambId::RoomList => f.write_str("iamb://rooms"),
762 IambId::SpaceList => f.write_str("iamb://spaces"),
763 IambId::VerifyList => f.write_str("iamb://verify"),
764 IambId::Welcome => f.write_str("iamb://welcome"),
765 }
766 }
767}
768
727769impl ApplicationWindowId for IambId {}
728770
771impl Serialize for IambId {
772 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
773 where
774 S: Serializer,
775 {
776 serializer.serialize_str(&self.to_string())
777 }
778}
779
780impl<'de> Deserialize<'de> for IambId {
781 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
782 where
783 D: Deserializer<'de>,
784 {
785 deserializer.deserialize_str(IambIdVisitor)
786 }
787}
788
789struct IambIdVisitor;
790
791impl<'de> Visitor<'de> for IambIdVisitor {
792 type Value = IambId;
793
794 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
795 formatter.write_str("a valid window URL")
796 }
797
798 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
799 where
800 E: SerdeError,
801 {
802 let Ok(url) = Url::parse(value) else {
803 return Err(E::custom("Invalid iamb window URL"));
804 };
805
806 if url.scheme() != "iamb" {
807 return Err(E::custom("Invalid iamb window URL"));
808 }
809
810 match url.domain() {
811 Some("room") => {
812 let Some(path) = url.path_segments() else {
813 return Err(E::custom("Invalid members window URL"));
814 };
815
816 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
817 return Err(E::custom("Invalid members window URL"));
818 };
819
820 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
821 return Err(E::custom("Invalid room identifier"));
822 };
823
824 Ok(IambId::Room(room_id))
825 },
826 Some("members") => {
827 let Some(path) = url.path_segments() else {
828 return Err(E::custom( "Invalid members window URL"));
829 };
830
831 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
832 return Err(E::custom( "Invalid members window URL"));
833 };
834
835 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
836 return Err(E::custom("Invalid room identifier"));
837 };
838
839 Ok(IambId::MemberList(room_id))
840 },
841 Some("dms") => {
842 if url.path() != "" {
843 return Err(E::custom("iamb://dms takes no path"));
844 }
845
846 Ok(IambId::DirectList)
847 },
848 Some("rooms") => {
849 if url.path() != "" {
850 return Err(E::custom("iamb://rooms takes no path"));
851 }
852
853 Ok(IambId::RoomList)
854 },
855 Some("spaces") => {
856 if url.path() != "" {
857 return Err(E::custom("iamb://spaces takes no path"));
858 }
859
860 Ok(IambId::SpaceList)
861 },
862 Some("verify") => {
863 if url.path() != "" {
864 return Err(E::custom("iamb://verify takes no path"));
865 }
866
867 Ok(IambId::VerifyList)
868 },
869 Some("welcome") => {
870 if url.path() != "" {
871 return Err(E::custom("iamb://welcome takes no path"));
872 }
873
874 Ok(IambId::Welcome)
875 },
876 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
877 None => Err(E::custom("Invalid iamb window URL")),
878 }
879 }
880}
881
729882#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
730883pub enum RoomFocus {
731884 Scrollback,
src/config.rs +113 −4
@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};
99use std::process;
1010
1111use clap::Parser;
12use matrix_sdk::ruma::{OwnedUserId, UserId};
12use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
1313use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
1414use tracing::Level;
1515use url::Url;
@@ -19,6 +19,8 @@ use modalkit::tui::{
1919 text::Span,
2020};
2121
22use super::base::IambId;
23
2224macro_rules! usage {
2325 ( $($args: tt)* ) => {
2426 println!($($args)*);
@@ -339,12 +341,43 @@ impl Directories {
339341 }
340342}
341343
344#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
345#[serde(untagged)]
346pub enum WindowPath {
347 AliasId(OwnedRoomAliasId),
348 RoomId(OwnedRoomId),
349 UserId(OwnedUserId),
350 Window(IambId),
351}
352
353#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
354#[serde(untagged, deny_unknown_fields)]
355pub enum WindowLayout {
356 Window { window: WindowPath },
357 Split { split: Vec<WindowLayout> },
358}
359
360#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
361#[serde(rename_all = "lowercase", tag = "style")]
362pub enum Layout {
363 /// Restore the layout from the previous session.
364 #[default]
365 Restore,
366
367 /// Open a single window using the `default_room` value.
368 New,
369
370 /// Open the window layouts described under `tabs`.
371 Config { tabs: Vec<WindowLayout> },
372}
373
342374#[derive(Clone, Deserialize)]
343375pub struct ProfileConfig {
344376 pub user_id: OwnedUserId,
345377 pub url: Url,
346378 pub settings: Option<Tunables>,
347379 pub dirs: Option<Directories>,
380 pub layout: Option<Layout>,
348381}
349382
350383#[derive(Clone, Deserialize)]
@@ -353,6 +386,7 @@ pub struct IambConfig {
353386 pub default_profile: Option<String>,
354387 pub settings: Option<Tunables>,
355388 pub dirs: Option<Directories>,
389 pub layout: Option<Layout>,
356390}
357391
358392impl IambConfig {
@@ -376,11 +410,13 @@ impl IambConfig {
376410#[derive(Clone)]
377411pub struct ApplicationSettings {
378412 pub matrix_dir: PathBuf,
413 pub layout_json: PathBuf,
379414 pub session_json: PathBuf,
380415 pub profile_name: String,
381416 pub profile: ProfileConfig,
382417 pub tunables: TunableValues,
383418 pub dirs: DirectoryValues,
419 pub layout: Layout,
384420}
385421
386422impl ApplicationSettings {
@@ -401,6 +437,7 @@ impl ApplicationSettings {
401437 default_profile,
402438 dirs,
403439 settings: global,
440 layout,
404441 } = IambConfig::load(config_json.as_path())?;
405442
406443 validate_profile_names(&profiles);
@@ -424,10 +461,17 @@ impl ApplicationSettings {
424461 );
425462 };
426463
464 let layout = profile.layout.take().or(layout).unwrap_or_default();
465
427466 let tunables = global.unwrap_or_default();
428467 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
429468 let tunables = tunables.values();
430469
470 let dirs = dirs.unwrap_or_default();
471 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
472 let dirs = dirs.values();
473
474 // Set up paths that live inside the profile's data directory.
431475 let mut profile_dir = config_dir.clone();
432476 profile_dir.push("profiles");
433477 profile_dir.push(profile_name.as_str());
@@ -438,17 +482,23 @@ impl ApplicationSettings {
438482 let mut session_json = profile_dir;
439483 session_json.push("session.json");
440484
441 let dirs = dirs.unwrap_or_default();
442 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
443 let dirs = dirs.values();
485 // Set up paths that live inside the profile's cache directory.
486 let mut cache_dir = dirs.cache.clone();
487 cache_dir.push("profiles");
488 cache_dir.push(profile_name.as_str());
489
490 let mut layout_json = cache_dir.clone();
491 layout_json.push("layout.json");
444492
445493 let settings = ApplicationSettings {
446494 matrix_dir,
495 layout_json,
447496 session_json,
448497 profile_name,
449498 profile,
450499 tunables,
451500 dirs,
501 layout,
452502 };
453503
454504 Ok(settings)
@@ -496,6 +546,7 @@ impl ApplicationSettings {
496546mod tests {
497547 use super::*;
498548 use matrix_sdk::ruma::user_id;
549 use std::convert::TryFrom;
499550
500551 #[test]
501552 fn test_profile_name_invalid() {
@@ -589,4 +640,62 @@ mod tests {
589640 })];
590641 assert_eq!(res.users, Some(users.into_iter().collect()));
591642 }
643
644 #[test]
645 fn test_parse_layout() {
646 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
647 let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
648 let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
649 let dms = WindowPath::Window(IambId::DirectList);
650 let welcome = WindowPath::Window(IambId::Welcome);
651
652 let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
653 assert_eq!(res, Layout::Restore);
654
655 let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
656 assert_eq!(res, Layout::New);
657
658 let res: Layout = serde_json::from_str(
659 "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
660 )
661 .unwrap();
662 assert_eq!(res, Layout::Config {
663 tabs: vec![WindowLayout::Window { window: user.clone() }]
664 });
665
666 let res: Layout = serde_json::from_str(
667 "{\
668 \"style\": \"config\",\
669 \"tabs\": [\
670 {\"split\":[\
671 {\"window\":\"@user:example.com\"},\
672 {\"window\":\"#room:example.com\"}\
673 ]},\
674 {\"split\":[\
675 {\"window\":\"!room:example.com\"},\
676 {\"split\":[\
677 {\"window\":\"iamb://dms\"},\
678 {\"window\":\"iamb://welcome\"}\
679 ]}\
680 ]}\
681 ]}",
682 )
683 .unwrap();
684 let split1 = WindowLayout::Split {
685 split: vec![
686 WindowLayout::Window { window: user.clone() },
687 WindowLayout::Window { window: alias },
688 ],
689 };
690 let split2 = WindowLayout::Split {
691 split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
692 window: welcome,
693 }],
694 };
695 let split3 = WindowLayout::Split {
696 split: vec![WindowLayout::Window { window: room }, split2],
697 };
698 let tabs = vec![split1, split3];
699 assert_eq!(res, Layout::Config { tabs });
700 }
592701}
src/main.rs +126 −15
@@ -6,7 +6,7 @@ use std::collections::VecDeque;
66use std::convert::TryFrom;
77use std::fmt::Display;
88use std::fs::{create_dir_all, File};
9use std::io::{stdout, BufReader, Stdout};
9use std::io::{stdout, BufReader, BufWriter, Stdout};
1010use std::ops::DerefMut;
1111use std::process;
1212use std::sync::atomic::{AtomicUsize, Ordering};
@@ -89,6 +89,7 @@ use modalkit::{
8989 Jumpable,
9090 Promptable,
9191 Scrollable,
92 TabAction,
9293 TabContainer,
9394 TabCount,
9495 UIError,
@@ -103,21 +104,120 @@ use modalkit::{
103104 input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey},
104105 widgets::{
105106 cmdbar::CommandBarState,
106 screen::{Screen, ScreenState},
107 screen::{FocusList, Screen, ScreenState, TabLayoutDescription},
108 windows::WindowLayoutDescription,
107109 TerminalCursor,
108110 TerminalExtOps,
109111 Window,
110112 },
111113};
112114
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
113197struct Application {
198 /// Terminal backend.
199 terminal: Terminal<CrosstermBackend<Stdout>>,
200
201 /// State for the Matrix client, editing, etc.
114202 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.
115208 worker: Requester,
116 terminal: Terminal<CrosstermBackend<Stdout>>,
209
210 /// Mapped keybindings.
117211 bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
212
213 /// Pending actions to run.
118214 actstack: VecDeque<(ProgramAction, ProgramContext)>,
119 screen: ScreenState<IambWindow, IambInfo>,
215
216 /// Whether or not the terminal is currently focused.
120217 focused: bool,
218
219 /// The tab layout before the last executed [TabAction].
220 last_layout: Option<TabLayoutDescription<IambInfo>>,
121221}
122222
123223impl Application {
@@ -141,16 +241,7 @@ impl Application {
141241 let bindings = KeyManager::new(bindings);
142242
143243 let mut locked = store.lock().await;
144
145 let win = settings
146 .tunables
147 .default_room
148 .and_then(|room| IambWindow::find(room, locked.deref_mut()).ok())
149 .or_else(|| IambWindow::open(IambId::Welcome, locked.deref_mut()).ok())
150 .unwrap();
151
152 let cmd = CommandBarState::new(locked.deref_mut());
153 let screen = ScreenState::new(win, cmd);
244 let screen = setup_screen(settings, locked.deref_mut())?;
154245
155246 let worker = locked.application.worker.clone();
156247 drop(locked);
@@ -165,6 +256,7 @@ impl Application {
165256 actstack,
166257 screen,
167258 focused: true,
259 last_layout: None,
168260 })
169261 }
170262
@@ -312,7 +404,6 @@ impl Application {
312404 Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
313405 Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
314406 Action::ShowInfoMessage(info) => Some(info),
315 Action::Tab(cmd) => self.screen.tab_command(&cmd, &ctx, store)?,
316407 Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
317408
318409 Action::Jump(l, dir, count) => {
@@ -328,6 +419,13 @@ impl Application {
328419 },
329420
330421 // 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 },
331429 Action::RedrawScreen => {
332430 self.screen.clear_message();
333431 self.redraw(true, store)?;
@@ -494,6 +592,19 @@ impl Application {
494592 }
495593 }
496594
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
497608 crossterm::terminal::disable_raw_mode()?;
498609 execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
499610 self.terminal.show_cursor()?;
src/message/printer.rs +4
@@ -156,6 +156,10 @@ impl<'a> TextPrinter<'a> {
156156 pub fn push_str(&mut self, s: &'a str, style: Style) {
157157 let style = self.base_style.patch(style);
158158
159 if self.width == 0 {
160 return;
161 }
162
159163 for mut word in UnicodeSegmentation::split_word_bounds(s) {
160164 if let "\n" | "\r\n" = word {
161165 // Render embedded newlines as spaces.
src/tests.rs +4
@@ -195,16 +195,20 @@ pub fn mock_tunables() -> TunableValues {
195195pub fn mock_settings() -> ApplicationSettings {
196196 ApplicationSettings {
197197 matrix_dir: PathBuf::new(),
198 layout_json: PathBuf::new(),
198199 session_json: PathBuf::new(),
200
199201 profile_name: "test".into(),
200202 profile: ProfileConfig {
201203 user_id: user_id!("@user:example.com").to_owned(),
202204 url: Url::parse("https://example.com").unwrap(),
203205 settings: None,
204206 dirs: None,
207 layout: None,
205208 },
206209 tunables: mock_tunables(),
207210 dirs: mock_dirs(),
211 layout: Default::default(),
208212 }
209213}
210214