Commit 7c39e88ba2
Unregistered key
Layout: unified · split
Cargo.lock +4 −2
| @@ -2136,8 +2136,9 @@ dependencies = [ | |||
| 2136 | 2136 | ||
| 2137 | [[package]] | 2137 | [[package]] |
| 2138 | name = "modalkit" | 2138 | name = "modalkit" |
| 2139 | version = "0.0.15" | 2139 | version = "0.0.16" |
| 2140 | source = "git+https://github.com/ulyssa/modalkit?rev=f641162#f6411625caa1ddb764c91a3fc47e052cfdc405b5" | 2140 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2141 | checksum = "3f38eef0b4f6377e73d1082d508cae1df4d99a94d25361538131d839f292aa49" | ||
| 2141 | dependencies = [ | 2142 | dependencies = [ |
| 2142 | "anymap2", | 2143 | "anymap2", |
| 2143 | "arboard", | 2144 | "arboard", |
| @@ -2151,6 +2152,7 @@ dependencies = [ | |||
| 2151 | "ratatui", | 2152 | "ratatui", |
| 2152 | "regex", | 2153 | "regex", |
| 2153 | "ropey", | 2154 | "ropey", |
| 2155 | "serde", | ||
| 2154 | "textwrap", | 2156 | "textwrap", |
| 2155 | "thiserror", | 2157 | "thiserror", |
| 2156 | "unicode-segmentation", | 2158 | "unicode-segmentation", |
Cargo.toml +1 −2
| @@ -51,8 +51,7 @@ unicode-width = "0.1.10" | |||
| 51 | url = {version = "^2.2.2", features = ["serde"]} | 51 | url = {version = "^2.2.2", features = ["serde"]} |
| 52 | 52 | ||
| 53 | [dependencies.modalkit] | 53 | [dependencies.modalkit] |
| 54 | git = "https://github.com/ulyssa/modalkit" | 54 | version = "0.0.16" |
| 55 | rev = "f641162" | ||
| 56 | 55 | ||
| 57 | [dependencies.matrix-sdk] | 56 | [dependencies.matrix-sdk] |
| 58 | version = "0.6" | 57 | version = "0.6" |
docs/iamb.5.md +21
| @@ -36,6 +36,10 @@ These options are configured as a map under the profiles name. | |||
| 36 | > Overwrite general settings for this account. The fields are identical to | 36 | > Overwrite general settings for this account. The fields are identical to |
| 37 | > those in *TUNABLES*. | 37 | > those in *TUNABLES*. |
| 38 | 38 | ||
| 39 | **layout** (type: startup layout object) | ||
| 40 | > Overwrite general settings for this account. The fields are identical to | ||
| 41 | > those in *STARTUP LAYOUT*. | ||
| 42 | |||
| 39 | **dirs** (type: XDG overrides object) | 43 | **dirs** (type: XDG overrides object) |
| 40 | > Overwrite general settings for this account. The fields are identical to | 44 | > Overwrite general settings for this account. The fields are identical to |
| 41 | > those in *DIRECTORIES*. | 45 | > those in *DIRECTORIES*. |
| @@ -92,6 +96,23 @@ maps containing the following key value pairs. | |||
| 92 | > _light-cyan_, _light-green_, _light-magenta_, _light-red_, | 96 | > _light-cyan_, _light-green_, _light-magenta_, _light-red_, |
| 93 | > _light-yellow_, _magenta_, _none_, _red_, _white_, _yellow_ | 97 | > _light-yellow_, _magenta_, _none_, _red_, _white_, _yellow_ |
| 94 | 98 | ||
| 99 | # STARTUP LAYOUT | ||
| 100 | |||
| 101 | Specifies what initial set of tabs and windows to show when starting the | ||
| 102 | client. 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 | |||
| 95 | # DIRECTORIES | 116 | # DIRECTORIES |
| 96 | 117 | ||
| 97 | Specifies the directories to save data in. Configured as a map under the key | 118 | Specifies the directories to save data in. Configured as a map under the key |
src/base.rs +153
| @@ -1,12 +1,23 @@ | |||
| 1 | use std::borrow::Cow; | 1 | use std::borrow::Cow; |
| 2 | use std::collections::{HashMap, HashSet}; | 2 | use std::collections::{HashMap, HashSet}; |
| 3 | use std::convert::TryFrom; | ||
| 4 | use std::fmt::{self, Display}; | ||
| 3 | use std::hash::Hash; | 5 | use std::hash::Hash; |
| 4 | use std::str::FromStr; | 6 | use std::str::FromStr; |
| 5 | use std::sync::Arc; | 7 | use std::sync::Arc; |
| 6 | use std::time::{Duration, Instant}; | 8 | use std::time::{Duration, Instant}; |
| 7 | 9 | ||
| 8 | use emojis::Emoji; | 10 | use emojis::Emoji; |
| 11 | use serde::{ | ||
| 12 | de::Error as SerdeError, | ||
| 13 | de::Visitor, | ||
| 14 | Deserialize, | ||
| 15 | Deserializer, | ||
| 16 | Serialize, | ||
| 17 | Serializer, | ||
| 18 | }; | ||
| 9 | use tokio::sync::Mutex as AsyncMutex; | 19 | use tokio::sync::Mutex as AsyncMutex; |
| 20 | use url::Url; | ||
| 10 | 21 | ||
| 11 | use matrix_sdk::{ | 22 | use matrix_sdk::{ |
| 12 | encryption::verification::SasVerification, | 23 | encryption::verification::SasVerification, |
| @@ -715,17 +726,159 @@ impl ApplicationStore for ChatStore {} | |||
| 715 | 726 | ||
| 716 | #[derive(Clone, Debug, Eq, Hash, PartialEq)] | 727 | #[derive(Clone, Debug, Eq, Hash, PartialEq)] |
| 717 | pub enum IambId { | 728 | pub enum IambId { |
| 729 | /// A Matrix room. | ||
| 718 | Room(OwnedRoomId), | 730 | Room(OwnedRoomId), |
| 731 | |||
| 732 | /// The `:rooms` window. | ||
| 719 | DirectList, | 733 | DirectList, |
| 734 | |||
| 735 | /// The `:members` window for a given Matrix room. | ||
| 720 | MemberList(OwnedRoomId), | 736 | MemberList(OwnedRoomId), |
| 737 | |||
| 738 | /// The `:rooms` window. | ||
| 721 | RoomList, | 739 | RoomList, |
| 740 | |||
| 741 | /// The `:spaces` window. | ||
| 722 | SpaceList, | 742 | SpaceList, |
| 743 | |||
| 744 | /// The `:verify` window. | ||
| 723 | VerifyList, | 745 | VerifyList, |
| 746 | |||
| 747 | /// The `:welcome` window. | ||
| 724 | Welcome, | 748 | Welcome, |
| 725 | } | 749 | } |
| 726 | 750 | ||
| 751 | impl 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 | |||
| 727 | impl ApplicationWindowId for IambId {} | 769 | impl ApplicationWindowId for IambId {} |
| 728 | 770 | ||
| 771 | impl 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 | |||
| 780 | impl<'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 | |||
| 789 | struct IambIdVisitor; | ||
| 790 | |||
| 791 | impl<'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 | |||
| 729 | #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] | 882 | #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] |
| 730 | pub enum RoomFocus { | 883 | pub enum RoomFocus { |
| 731 | Scrollback, | 884 | Scrollback, |
src/config.rs +113 −4
| @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; | |||
| 9 | use std::process; | 9 | use std::process; |
| 10 | 10 | ||
| 11 | use clap::Parser; | 11 | use clap::Parser; |
| 12 | use matrix_sdk::ruma::{OwnedUserId, UserId}; | 12 | use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; |
| 13 | use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer}; | 13 | use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer}; |
| 14 | use tracing::Level; | 14 | use tracing::Level; |
| 15 | use url::Url; | 15 | use url::Url; |
| @@ -19,6 +19,8 @@ use modalkit::tui::{ | |||
| 19 | text::Span, | 19 | text::Span, |
| 20 | }; | 20 | }; |
| 21 | 21 | ||
| 22 | use super::base::IambId; | ||
| 23 | |||
| 22 | macro_rules! usage { | 24 | macro_rules! usage { |
| 23 | ( $($args: tt)* ) => { | 25 | ( $($args: tt)* ) => { |
| 24 | println!($($args)*); | 26 | println!($($args)*); |
| @@ -339,12 +341,43 @@ impl Directories { | |||
| 339 | } | 341 | } |
| 340 | } | 342 | } |
| 341 | 343 | ||
| 344 | #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] | ||
| 345 | #[serde(untagged)] | ||
| 346 | pub 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)] | ||
| 355 | pub 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")] | ||
| 362 | pub 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 | |||
| 342 | #[derive(Clone, Deserialize)] | 374 | #[derive(Clone, Deserialize)] |
| 343 | pub struct ProfileConfig { | 375 | pub struct ProfileConfig { |
| 344 | pub user_id: OwnedUserId, | 376 | pub user_id: OwnedUserId, |
| 345 | pub url: Url, | 377 | pub url: Url, |
| 346 | pub settings: Option<Tunables>, | 378 | pub settings: Option<Tunables>, |
| 347 | pub dirs: Option<Directories>, | 379 | pub dirs: Option<Directories>, |
| 380 | pub layout: Option<Layout>, | ||
| 348 | } | 381 | } |
| 349 | 382 | ||
| 350 | #[derive(Clone, Deserialize)] | 383 | #[derive(Clone, Deserialize)] |
| @@ -353,6 +386,7 @@ pub struct IambConfig { | |||
| 353 | pub default_profile: Option<String>, | 386 | pub default_profile: Option<String>, |
| 354 | pub settings: Option<Tunables>, | 387 | pub settings: Option<Tunables>, |
| 355 | pub dirs: Option<Directories>, | 388 | pub dirs: Option<Directories>, |
| 389 | pub layout: Option<Layout>, | ||
| 356 | } | 390 | } |
| 357 | 391 | ||
| 358 | impl IambConfig { | 392 | impl IambConfig { |
| @@ -376,11 +410,13 @@ impl IambConfig { | |||
| 376 | #[derive(Clone)] | 410 | #[derive(Clone)] |
| 377 | pub struct ApplicationSettings { | 411 | pub struct ApplicationSettings { |
| 378 | pub matrix_dir: PathBuf, | 412 | pub matrix_dir: PathBuf, |
| 413 | pub layout_json: PathBuf, | ||
| 379 | pub session_json: PathBuf, | 414 | pub session_json: PathBuf, |
| 380 | pub profile_name: String, | 415 | pub profile_name: String, |
| 381 | pub profile: ProfileConfig, | 416 | pub profile: ProfileConfig, |
| 382 | pub tunables: TunableValues, | 417 | pub tunables: TunableValues, |
| 383 | pub dirs: DirectoryValues, | 418 | pub dirs: DirectoryValues, |
| 419 | pub layout: Layout, | ||
| 384 | } | 420 | } |
| 385 | 421 | ||
| 386 | impl ApplicationSettings { | 422 | impl ApplicationSettings { |
| @@ -401,6 +437,7 @@ impl ApplicationSettings { | |||
| 401 | default_profile, | 437 | default_profile, |
| 402 | dirs, | 438 | dirs, |
| 403 | settings: global, | 439 | settings: global, |
| 440 | layout, | ||
| 404 | } = IambConfig::load(config_json.as_path())?; | 441 | } = IambConfig::load(config_json.as_path())?; |
| 405 | 442 | ||
| 406 | validate_profile_names(&profiles); | 443 | validate_profile_names(&profiles); |
| @@ -424,10 +461,17 @@ impl ApplicationSettings { | |||
| 424 | ); | 461 | ); |
| 425 | }; | 462 | }; |
| 426 | 463 | ||
| 464 | let layout = profile.layout.take().or(layout).unwrap_or_default(); | ||
| 465 | |||
| 427 | let tunables = global.unwrap_or_default(); | 466 | let tunables = global.unwrap_or_default(); |
| 428 | let tunables = profile.settings.take().unwrap_or_default().merge(tunables); | 467 | let tunables = profile.settings.take().unwrap_or_default().merge(tunables); |
| 429 | let tunables = tunables.values(); | 468 | let tunables = tunables.values(); |
| 430 | 469 | ||
| 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. | ||
| 431 | let mut profile_dir = config_dir.clone(); | 475 | let mut profile_dir = config_dir.clone(); |
| 432 | profile_dir.push("profiles"); | 476 | profile_dir.push("profiles"); |
| 433 | profile_dir.push(profile_name.as_str()); | 477 | profile_dir.push(profile_name.as_str()); |
| @@ -438,17 +482,23 @@ impl ApplicationSettings { | |||
| 438 | let mut session_json = profile_dir; | 482 | let mut session_json = profile_dir; |
| 439 | session_json.push("session.json"); | 483 | session_json.push("session.json"); |
| 440 | 484 | ||
| 441 | let dirs = dirs.unwrap_or_default(); | 485 | // Set up paths that live inside the profile's cache directory. |
| 442 | let dirs = profile.dirs.take().unwrap_or_default().merge(dirs); | 486 | let mut cache_dir = dirs.cache.clone(); |
| 443 | let dirs = dirs.values(); | 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"); | ||
| 444 | 492 | ||
| 445 | let settings = ApplicationSettings { | 493 | let settings = ApplicationSettings { |
| 446 | matrix_dir, | 494 | matrix_dir, |
| 495 | layout_json, | ||
| 447 | session_json, | 496 | session_json, |
| 448 | profile_name, | 497 | profile_name, |
| 449 | profile, | 498 | profile, |
| 450 | tunables, | 499 | tunables, |
| 451 | dirs, | 500 | dirs, |
| 501 | layout, | ||
| 452 | }; | 502 | }; |
| 453 | 503 | ||
| 454 | Ok(settings) | 504 | Ok(settings) |
| @@ -496,6 +546,7 @@ impl ApplicationSettings { | |||
| 496 | mod tests { | 546 | mod tests { |
| 497 | use super::*; | 547 | use super::*; |
| 498 | use matrix_sdk::ruma::user_id; | 548 | use matrix_sdk::ruma::user_id; |
| 549 | use std::convert::TryFrom; | ||
| 499 | 550 | ||
| 500 | #[test] | 551 | #[test] |
| 501 | fn test_profile_name_invalid() { | 552 | fn test_profile_name_invalid() { |
| @@ -589,4 +640,62 @@ mod tests { | |||
| 589 | })]; | 640 | })]; |
| 590 | assert_eq!(res.users, Some(users.into_iter().collect())); | 641 | assert_eq!(res.users, Some(users.into_iter().collect())); |
| 591 | } | 642 | } |
| 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 | } | ||
| 592 | } | 701 | } |
src/main.rs +126 −15
| @@ -6,7 +6,7 @@ use std::collections::VecDeque; | |||
| 6 | use std::convert::TryFrom; | 6 | use std::convert::TryFrom; |
| 7 | use std::fmt::Display; | 7 | use std::fmt::Display; |
| 8 | use std::fs::{create_dir_all, File}; | 8 | use std::fs::{create_dir_all, File}; |
| 9 | use std::io::{stdout, BufReader, Stdout}; | 9 | use std::io::{stdout, BufReader, BufWriter, Stdout}; |
| 10 | use std::ops::DerefMut; | 10 | use std::ops::DerefMut; |
| 11 | use std::process; | 11 | use std::process; |
| 12 | use std::sync::atomic::{AtomicUsize, Ordering}; | 12 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| @@ -89,6 +89,7 @@ use modalkit::{ | |||
| 89 | Jumpable, | 89 | Jumpable, |
| 90 | Promptable, | 90 | Promptable, |
| 91 | Scrollable, | 91 | Scrollable, |
| 92 | TabAction, | ||
| 92 | TabContainer, | 93 | TabContainer, |
| 93 | TabCount, | 94 | TabCount, |
| 94 | UIError, | 95 | UIError, |
| @@ -103,21 +104,120 @@ use modalkit::{ | |||
| 103 | input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey}, | 104 | input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey}, |
| 104 | widgets::{ | 105 | widgets::{ |
| 105 | cmdbar::CommandBarState, | 106 | cmdbar::CommandBarState, |
| 106 | screen::{Screen, ScreenState}, | 107 | screen::{FocusList, Screen, ScreenState, TabLayoutDescription}, |
| 108 | windows::WindowLayoutDescription, | ||
| 107 | TerminalCursor, | 109 | TerminalCursor, |
| 108 | TerminalExtOps, | 110 | TerminalExtOps, |
| 109 | Window, | 111 | Window, |
| 110 | }, | 112 | }, |
| 111 | }; | 113 | }; |
| 112 | 114 | ||
| 115 | fn 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 | |||
| 155 | fn 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 | |||
| 113 | struct Application { | 197 | struct Application { |
| 198 | /// Terminal backend. | ||
| 199 | terminal: Terminal<CrosstermBackend<Stdout>>, | ||
| 200 | |||
| 201 | /// State for the Matrix client, editing, etc. | ||
| 114 | store: AsyncProgramStore, | 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. | ||
| 115 | worker: Requester, | 208 | worker: Requester, |
| 116 | terminal: Terminal<CrosstermBackend<Stdout>>, | 209 | |
| 210 | /// Mapped keybindings. | ||
| 117 | bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>, | 211 | bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>, |
| 212 | |||
| 213 | /// Pending actions to run. | ||
| 118 | actstack: VecDeque<(ProgramAction, ProgramContext)>, | 214 | actstack: VecDeque<(ProgramAction, ProgramContext)>, |
| 119 | screen: ScreenState<IambWindow, IambInfo>, | 215 | |
| 216 | /// Whether or not the terminal is currently focused. | ||
| 120 | focused: bool, | 217 | focused: bool, |
| 218 | |||
| 219 | /// The tab layout before the last executed [TabAction]. | ||
| 220 | last_layout: Option<TabLayoutDescription<IambInfo>>, | ||
| 121 | } | 221 | } |
| 122 | 222 | ||
| 123 | impl Application { | 223 | impl Application { |
| @@ -141,16 +241,7 @@ impl Application { | |||
| 141 | let bindings = KeyManager::new(bindings); | 241 | let bindings = KeyManager::new(bindings); |
| 142 | 242 | ||
| 143 | let mut locked = store.lock().await; | 243 | let mut locked = store.lock().await; |
| 144 | 244 | let screen = setup_screen(settings, locked.deref_mut())?; | |
| 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); | ||
| 154 | 245 | ||
| 155 | let worker = locked.application.worker.clone(); | 246 | let worker = locked.application.worker.clone(); |
| 156 | drop(locked); | 247 | drop(locked); |
| @@ -165,6 +256,7 @@ impl Application { | |||
| 165 | actstack, | 256 | actstack, |
| 166 | screen, | 257 | screen, |
| 167 | focused: true, | 258 | focused: true, |
| 259 | last_layout: None, | ||
| 168 | }) | 260 | }) |
| 169 | } | 261 | } |
| 170 | 262 | ||
| @@ -312,7 +404,6 @@ impl Application { | |||
| 312 | Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?, | 404 | Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?, |
| 313 | Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?, | 405 | Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?, |
| 314 | Action::ShowInfoMessage(info) => Some(info), | 406 | Action::ShowInfoMessage(info) => Some(info), |
| 315 | Action::Tab(cmd) => self.screen.tab_command(&cmd, &ctx, store)?, | ||
| 316 | Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?, | 407 | Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?, |
| 317 | 408 | ||
| 318 | Action::Jump(l, dir, count) => { | 409 | Action::Jump(l, dir, count) => { |
| @@ -328,6 +419,13 @@ impl Application { | |||
| 328 | }, | 419 | }, |
| 329 | 420 | ||
| 330 | // UI actions. | 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 | }, | ||
| 331 | Action::RedrawScreen => { | 429 | Action::RedrawScreen => { |
| 332 | self.screen.clear_message(); | 430 | self.screen.clear_message(); |
| 333 | self.redraw(true, store)?; | 431 | self.redraw(true, store)?; |
| @@ -494,6 +592,19 @@ impl Application { | |||
| 494 | } | 592 | } |
| 495 | } | 593 | } |
| 496 | 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 | |||
| 497 | crossterm::terminal::disable_raw_mode()?; | 608 | crossterm::terminal::disable_raw_mode()?; |
| 498 | execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?; | 609 | execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?; |
| 499 | self.terminal.show_cursor()?; | 610 | self.terminal.show_cursor()?; |
src/message/printer.rs +4
| @@ -156,6 +156,10 @@ impl<'a> TextPrinter<'a> { | |||
| 156 | pub fn push_str(&mut self, s: &'a str, style: Style) { | 156 | pub fn push_str(&mut self, s: &'a str, style: Style) { |
| 157 | let style = self.base_style.patch(style); | 157 | let style = self.base_style.patch(style); |
| 158 | 158 | ||
| 159 | if self.width == 0 { | ||
| 160 | return; | ||
| 161 | } | ||
| 162 | |||
| 159 | for mut word in UnicodeSegmentation::split_word_bounds(s) { | 163 | for mut word in UnicodeSegmentation::split_word_bounds(s) { |
| 160 | if let "\n" | "\r\n" = word { | 164 | if let "\n" | "\r\n" = word { |
| 161 | // Render embedded newlines as spaces. | 165 | // Render embedded newlines as spaces. |
src/tests.rs +4
| @@ -195,16 +195,20 @@ pub fn mock_tunables() -> TunableValues { | |||
| 195 | pub fn mock_settings() -> ApplicationSettings { | 195 | pub fn mock_settings() -> ApplicationSettings { |
| 196 | ApplicationSettings { | 196 | ApplicationSettings { |
| 197 | matrix_dir: PathBuf::new(), | 197 | matrix_dir: PathBuf::new(), |
| 198 | layout_json: PathBuf::new(), | ||
| 198 | session_json: PathBuf::new(), | 199 | session_json: PathBuf::new(), |
| 200 | |||
| 199 | profile_name: "test".into(), | 201 | profile_name: "test".into(), |
| 200 | profile: ProfileConfig { | 202 | profile: ProfileConfig { |
| 201 | user_id: user_id!("@user:example.com").to_owned(), | 203 | user_id: user_id!("@user:example.com").to_owned(), |
| 202 | url: Url::parse("https://example.com").unwrap(), | 204 | url: Url::parse("https://example.com").unwrap(), |
| 203 | settings: None, | 205 | settings: None, |
| 204 | dirs: None, | 206 | dirs: None, |
| 207 | layout: None, | ||
| 205 | }, | 208 | }, |
| 206 | tunables: mock_tunables(), | 209 | tunables: mock_tunables(), |
| 207 | dirs: mock_dirs(), | 210 | dirs: mock_dirs(), |
| 211 | layout: Default::default(), | ||
| 208 | } | 212 | } |
| 209 | } | 213 | } |
| 210 | 214 | ||