authoravatarclover caruso<git@paperclover.net>2026-10-19 11:26:27-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-19 18:07:46-07:00
log2479d36d4fec000481feba1adc0af26656079959
tree2428f6bf41a5f366b7366b025e95a77fa0900a67
parent5aee7da0e30d59f09659356bb7c230532f3a389f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat: restore split panes at launch

The settings keep how panes split the page area, beside the recent pages: the tree, its ratios, the page each pane shows and which pane has the focus. A layout is one person's, so it stays in the machine's settings and never in a notebook's folder, and one this build can't read is left out with the rest of the settings kept. At launch the focused pane returns to its page and the others open after it in the background, one at a time, so each section opens once; a pane focused while it waits opens next, a pane waiting or opening keeps its place in the settings saved meanwhile, and a focused page gone leaves its section as the launch opened it. A pane whose notebook is no longer open, or whose section is gone, is left out and its room goes to the pane beside it; a page gone shows its section's first, and a single pane left splits nothing. Renaming a notebook's folder keeps the panes on it, which open again from where it went. A new pane now takes Options' default font and Markdown typing from the focused pane, and its page wears its theme as any page opened does. A replay can write the settings it would save with the step settings PATH, as a screenshot's replay saves none, can start at launch rather than once the window settles, and logs the alerts its hidden window shows no one. Only replays split the page area yet. Assisted-by: claude-opus-5.5

6 files changed, 939 insertions(+), 107 deletions(-)

crates/snowbound/src/macos.rs+4
......@@ -1096,6 +1096,10 @@ pub fn symbol_fonts() -> Vec<String> {
10961096
10971097/// Tells the user something they asked for could not be done: `message`, then what to do.
10981098pub fn alert(message: &str, detail: &str) {
1099 // A replay's window is hidden, its sheets with it.
1100 if crate::automated() {
1101 eprintln!("Alert: {message} · {detail}");
1102 }
10991103 let mtm = MainThreadMarker::new().expect("Window events run on the main thread");
11001104 unsafe {
11011105 let alert = NSAlert::new(mtm);
crates/snowbound/src/main.rs+145-73
......@@ -430,6 +430,8 @@ enum Replay {
430430 Split(Axis),
431431 /// Closes the focused pane.
432432 ClosePane,
433 /// Writes the settings as they would be saved, as a screenshot's replay saves none.
434 Settings(PathBuf),
433435 Quit,
434436}
435437
......@@ -758,6 +760,8 @@ enum Laid {
758760/// are drawn, so it never appears without them.
759761struct Opening {
760762 loaded: Shown,
763 /// A page to show once this one does, as the pane taking the load over asked for.
764 then: Option<ExGuid>,
761765 scene: (PageScene, [f32; 2]),
762766 editor: CanvasEditor,
763767 since: Instant,
......@@ -921,6 +925,8 @@ struct State {
921925 parked: Vec<split::Parked>,
922926 /// How the panes divide the page area.
923927 split: split::Split,
928 /// Parked panes waiting to open at a place, by page box, in turn.
929 reopening: Vec<(Id, navigation::Place)>,
924930 /// The open notebooks in the sidebar's order.
925931 notebooks: Vec<Arc<Library>>,
926932 /// The section the focused pane shows.
......@@ -929,8 +935,9 @@ struct State {
929935 shelved: Vec<Session>,
930936 /// The last load request number given.
931937 requests: u64,
932 /// Sections loads are opening from their files, by request number.
933 opening_files: Vec<(u64, String)>,
938 /// Sections loads are opening from their files, by request number, with the page to show
939 /// after where a pane took the load over from the one that started it.
940 opening_files: Vec<(u64, String, Option<ExGuid>)>,
934941 /// A page not kept in any notebook, from a text file or `--page`.
935942 temporary: bool,
936943 /// Where the settings are saved; `None` leaves them as they were read.
......@@ -1433,6 +1440,7 @@ impl State {
14331440 },
14341441 parked: Vec::new(),
14351442 split: split::Split::Leaf(page),
1443 reopening: Vec::new(),
14361444 notebooks,
14371445 session,
14381446 shelved: Vec::new(),
......@@ -1544,6 +1552,11 @@ impl State {
15441552 state.commands.push(Command::OpenFromServer(Some(location)));
15451553 }
15461554 state.visited();
1555 if let Some(panes) = stored.panes
1556 && let Err(error) = state.restore_panes(panes)
1557 {
1558 eprintln!("Couldn't split the page area as it was: {error}");
1559 }
15471560 state.prefetch_around();
15481561 state.show_spelling();
15491562 state.title();
......@@ -1617,6 +1630,7 @@ impl State {
16171630 if let Err(error) = self.open_loaded() {
16181631 eprintln!("{error}");
16191632 }
1633 self.reopen_next();
16201634 if let Err(error) = self.take_waiting() {
16211635 eprintln!("{error}");
16221636 }
......@@ -1827,7 +1841,8 @@ impl State {
18271841 let welcome = self.session.is_none()
18281842 && !self.temporary
18291843 && self.pane.sectionless.is_none()
1830 && self.pane.locked.is_none();
1844 && self.pane.locked.is_none()
1845 && self.waiting(self.pane.id).is_none();
18311846 self.toolbar(&theme, !welcome)?;
18321847 if welcome {
18331848 self.welcome();
......@@ -2113,6 +2128,19 @@ impl State {
21132128 /// Builds the focused pane in the box open: its page, under the bars it shows above it,
21142129 /// or what it shows in place of one; whether that is a page.
21152130 fn pane_content(&mut self, theme: &Theme) -> Result<bool, Box<dyn Error>> {
2131 // A pane waiting to open shows bare paper.
2132 if self.session.is_none() && self.waiting(self.pane.id).is_some() {
2133 let paper = Some(theme.paper);
2134 self.ui.leaf(
2135 "waiting",
2136 Spec {
2137 size: [fill(), fill()],
2138 fill: paper,
2139 ..Spec::default()
2140 },
2141 );
2142 return Ok(false);
2143 }
21162144 if let Some(session) = &self.session
21172145 && let Some(bar) = session.bar(&self.pane.showing)
21182146 {
......@@ -3695,72 +3723,7 @@ impl State {
36953723
36963724 fn apply(&mut self, command: Command) -> Result<(), Box<dyn Error>> {
36973725 match command {
3698 Command::OpenSection(library, path) => {
3699 // Its files are on their way to the renamed folder.
3700 if self.folder_renaming(&library.location) {
3701 return Ok(());
3702 }
3703 if library.locked(&path) {
3704 return self.show_locked(library, path);
3705 }
3706 let tab = match &self.session {
3707 // Back to the open section before another one opened.
3708 Some(session)
3709 if self.pane.switching.is_some()
3710 && Arc::ptr_eq(&session.library, &library)
3711 && session.tabs[session.tab].path == path =>
3712 {
3713 self.stop_loading();
3714 return Ok(());
3715 }
3716 Some(session) if session.library.location == library.location => {
3717 session.tabs.iter().position(|tab| tab.path == path)
3718 }
3719 _ => None,
3720 };
3721 self.pane.switching = Some((tab, Instant::now()));
3722 let key = library.key(&path);
3723 let last = self.last_pages.get(&key).copied();
3724 // A section a parked pane shows is open already, and opens only once.
3725 if let Some(held) = self.shelved.iter().find(|held| held.key() == key) {
3726 let listed = |space: &ExGuid| held.pages.iter().any(|(page, ..)| page == space);
3727 let space = (last.filter(listed))
3728 .or(held.pages.first().map(|(page, ..)| *page))
3729 .ok_or("The section has no pages")?;
3730 let read = held.reader(space);
3731 self.load(move || Ok(Loaded::Held(library, path, space, read()?)));
3732 return Ok(());
3733 }
3734 // A section opens from its file once: a load already opening it shows it here,
3735 // and a parked pane that asked for it first, if any still waits, leaves it to
3736 // this one.
3737 let opening = (self.opening_files.iter())
3738 .rfind(|(_, opening)| *opening == key)
3739 .map(|(request, _)| *request);
3740 if let Some(request) = opening {
3741 if request != self.pane.loading {
3742 let fresh = self.request();
3743 let asked = (self.parked.iter_mut())
3744 .map(|parked| &mut parked.pane)
3745 .find(|pane| pane.loading == request);
3746 let opened = asked.and_then(|pane| {
3747 (pane.loading, pane.switching) = (fresh, None);
3748 pane.opening.take()
3749 });
3750 (self.pane.loading, self.pane.opening) = (request, opened);
3751 }
3752 return Ok(());
3753 }
3754 let notify = notify(self.proxy.clone());
3755 self.load_async(move || async move {
3756 let start = Instant::now();
3757 let section = library.open_async(&path, notify).await?;
3758 lap("switch section open", start);
3759 let (session, space, page) = read_session(section, library, path, last)?;
3760 Ok(Loaded::Section(Box::new(session), space, page))
3761 });
3762 self.opening_files.push((self.pane.loading, key));
3763 }
3726 Command::OpenSection(library, path) => self.open_section(library, path, None)?,
37643727 Command::OpenPage(space) => {
37653728 let session = self.session.as_ref().ok_or("No section is open")?;
37663729 if self.pane.switching.is_some()
......@@ -3901,6 +3864,85 @@ impl State {
39013864 Ok(())
39023865 }
39033866
3867 /// Opens `library`'s section at catalog `path` at page `page`, or the page it showed last,
3868 /// from its file where no pane holds it and no load is opening it already.
3869 pub(crate) fn open_section(
3870 &mut self,
3871 library: Arc<Library>,
3872 path: String,
3873 page: Option<ExGuid>,
3874 ) -> Result<(), Box<dyn Error>> {
3875 // Its files are on their way to the renamed folder.
3876 if self.folder_renaming(&library.location) {
3877 return Ok(());
3878 }
3879 if library.locked(&path) {
3880 return self.show_locked(library, path);
3881 }
3882 let tab = match &self.session {
3883 // Back to the open section before another one opened.
3884 Some(session)
3885 if self.pane.switching.is_some()
3886 && Arc::ptr_eq(&session.library, &library)
3887 && session.tabs[session.tab].path == path =>
3888 {
3889 self.stop_loading();
3890 return Ok(());
3891 }
3892 Some(session) if session.library.location == library.location => {
3893 session.tabs.iter().position(|tab| tab.path == path)
3894 }
3895 _ => None,
3896 };
3897 self.pane.switching = Some((tab, Instant::now()));
3898 let key = library.key(&path);
3899 let last = page.or_else(|| self.last_pages.get(&key).copied());
3900 // A section a parked pane shows is open already, and opens only once.
3901 if let Some(held) = self.shelved.iter().find(|held| held.key() == key) {
3902 let listed = |space: &ExGuid| held.pages.iter().any(|(page, ..)| page == space);
3903 let space = (last.filter(listed))
3904 .or(held.pages.first().map(|(page, ..)| *page))
3905 .ok_or("The section has no pages")?;
3906 let read = held.reader(space);
3907 self.load(move || Ok(Loaded::Held(library, path, space, read()?)));
3908 return Ok(());
3909 }
3910 // A section opens from its file once: a load already opening it shows it here,
3911 // and a parked pane that asked for it first, if any still waits, leaves it to
3912 // this one.
3913 let opening = (self.opening_files.iter_mut()).rfind(|(_, opening, _)| *opening == key);
3914 if let Some((request, _, then)) = opening {
3915 let request = *request;
3916 if request != self.pane.loading {
3917 // It shows this pane's page after the one it reads.
3918 *then = last;
3919 let fresh = self.request();
3920 let asked = (self.parked.iter_mut())
3921 .map(|parked| &mut parked.pane)
3922 .find(|pane| pane.loading == request);
3923 let mut opened = asked.and_then(|pane| {
3924 (pane.loading, pane.switching) = (fresh, None);
3925 pane.opening.take()
3926 });
3927 if let Some(opened) = &mut opened {
3928 opened.then = last;
3929 }
3930 (self.pane.loading, self.pane.opening) = (request, opened);
3931 }
3932 return Ok(());
3933 }
3934 let notify = notify(self.proxy.clone());
3935 self.load_async(move || async move {
3936 let start = Instant::now();
3937 let section = library.open_async(&path, notify).await?;
3938 lap("switch section open", start);
3939 let (session, space, page) = read_session(section, library, path, last)?;
3940 Ok(Loaded::Section(Box::new(session), space, page))
3941 });
3942 self.opening_files.push((self.pane.loading, key, None));
3943 Ok(())
3944 }
3945
39043946 /// Runs `read` on a thread of its own, which lays out the page it read; `open_loaded`
39053947 /// shows it unless a newer read was asked for meanwhile.
39063948 fn load(&mut self, read: impl FnOnce() -> Result<Loaded, Box<dyn Error>> + Send + 'static) {
......@@ -3955,6 +3997,7 @@ impl State {
39553997 Ok(Laid::Page(Box::new(Opening {
39563998 requested,
39573999 loaded: shown,
4000 then: None,
39584001 scene: (scene, [0.0; 2]),
39594002 editor,
39604003 since: Instant::now(),
......@@ -4021,7 +4064,10 @@ impl State {
40214064 fn open_loaded(&mut self) -> Result<(), Box<dyn Error>> {
40224065 let reads: Vec<Read> = self.loads.1.try_iter().collect();
40234066 for (id, loaded) in reads {
4024 self.opening_files.retain(|(request, _)| *request != id);
4067 let then = (self.opening_files.iter())
4068 .find(|(request, ..)| *request == id)
4069 .and_then(|(.., then)| *then);
4070 self.opening_files.retain(|(request, ..)| *request != id);
40254071 let parked = (self.parked.iter()).position(|parked| parked.pane.loading == id);
40264072 let pane = match parked {
40274073 Some(at) => &mut self.parked[at].pane,
......@@ -4030,16 +4076,26 @@ impl State {
40304076 match loaded {
40314077 // A later load supersedes what this one shows, but not its failure.
40324078 Ok(_) if id != pane.loading => {}
4033 Ok(Laid::Page(opening)) => pane.opening = Some(*opening),
4079 Ok(Laid::Page(opening)) => {
4080 pane.opening = Some(Opening { then, ..*opening });
4081 }
40344082 Ok(Laid::Library(library, path)) => match parked {
40354083 Some(at) => self.in_pane(at, |state| state.adopt(library, path.as_deref()))?,
40364084 None => self.adopt(library, path.as_deref())?,
40374085 },
40384086 Err(error) => {
4039 if id == pane.loading {
4087 let failed = (id == pane.loading).then_some(pane.id);
4088 if failed.is_some() {
40404089 pane.switching = None;
40414090 }
40424091 platform::alert("Couldn't open", &error);
4092 // A pane waiting to open, with nothing to show, closes.
4093 if let Some(failed) = failed
4094 && self.reopening.iter().any(|(waiting, _)| *waiting == failed)
4095 {
4096 self.reopening.retain(|(waiting, _)| *waiting != failed);
4097 self.close_pane(failed)?;
4098 }
40434099 }
40444100 }
40454101 }
......@@ -4061,7 +4117,7 @@ impl State {
40614117 }
40624118
40634119 fn show_page(&mut self, mut opening: Opening) -> Result<(), Box<dyn Error>> {
4064 let requested = opening.requested;
4120 let (requested, then) = (opening.requested, opening.then);
40654121 if let Shown::Held(library, path, space) = opening.loaded {
40664122 match self.unshelve(&library.key(&path)) {
40674123 Some(session) => opening.loaded = Shown::Section(Box::new(session), space),
......@@ -4134,6 +4190,7 @@ impl State {
41344190 .is_none_or(|open| open.library.location != session.library.location);
41354191 self.list(&session.library);
41364192 self.pane.locked = None;
4193 self.pane.view.tag_art = session.library.tag_art();
41374194 let previous = self.session.replace(*session);
41384195 if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) {
41394196 self.release(previous);
......@@ -4209,6 +4266,13 @@ impl State {
42094266 };
42104267 self.rename(target);
42114268 }
4269 let listed = |space: ExGuid| {
4270 (self.session.as_ref())
4271 .is_some_and(|session| session.pages.iter().any(|(page, ..)| *page == space))
4272 };
4273 if let Some(then) = then.filter(|then| *then != self.pane.showing.space && listed(*then)) {
4274 self.commands.push(Command::OpenPage(then));
4275 }
42124276 Ok(())
42134277 }
42144278
......@@ -6706,6 +6770,11 @@ impl State {
67066770 Replay::Renderer(_) => unreachable!("The app switches renderers"),
67076771 Replay::Split(axis) => self.commands.push(Command::Split(axis)),
67086772 Replay::ClosePane => self.commands.push(Command::ClosePane(self.pane.id)),
6773 Replay::Settings(path) => {
6774 if let Err(error) = self.kept_settings().save(&path) {
6775 eprintln!("{error}");
6776 }
6777 }
67096778 }
67106779 // A covered window gets no redraws, so each step draws its own frame.
67116780 if let Err(error) = self.frame() {
......@@ -7072,6 +7141,8 @@ impl ApplicationHandler<UserEvent> for App {
70727141 return;
70737142 };
70747143 let deadline = Instant::now() + QUIT;
7144 // Dividers dragged and pages shown in parked panes since.
7145 state.save_settings();
70757146 state.publish_now(QUIT);
70767147 self.restart = state.updates.restarting();
70777148 let sessions: Vec<_> = (state.session.take().into_iter())
......@@ -7225,6 +7296,7 @@ fn replay(script: String, proxy: EventLoopProxy<UserEvent>) -> Result<(), Box<dy
72257296 _ => return Err(format!("Unknown split {rest}").into()),
72267297 })),
72277298 "close" if rest == "pane" => Ok(Replay::ClosePane),
7299 "settings" => Ok(Replay::Settings(rest.into())),
72287300 "appearance" => Ok(Replay::Appearance(match rest {
72297301 "light" => winit::window::Theme::Light,
72307302 "dark" => winit::window::Theme::Dark,
crates/snowbound/src/manage.rs+7-2
......@@ -245,6 +245,7 @@ impl State {
245245 let now = crate::Instant::now();
246246 self.show_page(crate::Opening {
247247 loaded: crate::Shown::Page(space),
248 then: None,
248249 scene: (scene, [0.0; 2]),
249250 editor,
250251 since: now,
......@@ -727,8 +728,7 @@ impl State {
727728 let Some(to) = library.renamed_location(&name) else {
728729 return;
729730 };
730 // Their sections hold files in the folder.
731 self.close_parked_in(&library);
731 self.wait_out_rename(&library);
732732 let ours = |shown: &Arc<Library>| Arc::ptr_eq(shown, &library);
733733 let shown = self
734734 .session
......@@ -831,6 +831,11 @@ impl State {
831831 self.notebooks
832832 .retain(|open| open.location != to || !std::mem::replace(&mut listed, true));
833833 if from != to {
834 for (_, place) in &mut self.reopening {
835 if place.notebook == from {
836 place.notebook.clone_from(&to);
837 }
838 }
834839 self.undo.close(&from);
835840 self.pane.trail.moved(&from, &to);
836841 for place in self
crates/snowbound/src/settings.rs+195-4
......@@ -50,6 +50,11 @@ pub struct Settings {
5050 pub keys: std::collections::BTreeMap<String, Vec<String>>,
5151 /// Pages shown lately, latest first, which the palette lists first and a launch returns to.
5252 pub recent: Vec<crate::navigation::Place>,
53 /// The panes splitting the page area, each at the page it shows; none while one fills it.
54 /// A layout is one person's, so it stays here and never in a notebook. One another build
55 /// wrote that this one can't read is left out, and the rest of the settings kept.
56 #[serde(deserialize_with = "lenient")]
57 pub panes: Option<Panes>,
5358 pub passwords: Passwords,
5459 pub live: Live,
5560 /// Options' "Default for new notebooks": the built-in theme new notebooks take.
......@@ -58,6 +63,89 @@ pub struct Settings {
5863 pub renderer: Backend,
5964}
6065
66/// `T` as the settings keep it, or none where they keep what this build can't read.
67fn lenient<'de, D: serde::Deserializer<'de>, T: serde::de::DeserializeOwned>(
68 deserializer: D,
69) -> Result<Option<T>, D::Error> {
70 let value = serde_json::Value::deserialize(deserializer)?;
71 Ok(serde_json::from_value(value).ok())
72}
73
74/// How panes split the page area, as `split::Split` divides it, each at the page it shows.
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum Panes {
78 Pane {
79 place: crate::navigation::Place,
80 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
81 focused: bool,
82 },
83 /// Two parts, the second beside the first or `down` below it, `ratio` of the room going
84 /// to the first.
85 Split {
86 down: bool,
87 ratio: f32,
88 a: Box<Panes>,
89 b: Box<Panes>,
90 },
91}
92
93impl Panes {
94 /// The panes at places `kept` holds, a split losing a part giving its room to the other.
95 pub fn keep(self, kept: &impl Fn(&crate::navigation::Place) -> bool) -> Option<Self> {
96 match self {
97 Panes::Pane { ref place, .. } => kept(place).then_some(self),
98 Panes::Split { down, ratio, a, b } => match (a.keep(kept), b.keep(kept)) {
99 (Some(a), Some(b)) => Some(Panes::Split {
100 down,
101 ratio,
102 a: Box::new(a),
103 b: Box::new(b),
104 }),
105 (a, b) => a.or(b),
106 },
107 }
108 }
109
110 /// Leaves one pane focused: the first focused, or the first where none is.
111 pub fn focus_one(&mut self) {
112 fn each(panes: &mut Panes, visit: &mut impl FnMut(&mut bool)) {
113 match panes {
114 Panes::Pane { focused, .. } => visit(focused),
115 Panes::Split { a, b, .. } => {
116 each(a, visit);
117 each(b, visit);
118 }
119 }
120 }
121 let mut any = false;
122 each(self, &mut |focused| any |= *focused);
123 let mut taken = false;
124 each(self, &mut |focused| {
125 *focused = !taken && (*focused || !any);
126 taken |= *focused;
127 });
128 }
129
130 /// The place of the pane focused, or of the first.
131 pub fn focused(&self) -> &crate::navigation::Place {
132 fn find(panes: &Panes) -> Option<&crate::navigation::Place> {
133 match panes {
134 Panes::Pane { place, focused } => focused.then_some(place),
135 Panes::Split { a, b, .. } => find(a).or_else(|| find(b)),
136 }
137 }
138 let mut first = self;
139 while let Panes::Split { a, .. } = first {
140 first = a;
141 }
142 let Panes::Pane { place, .. } = first else {
143 unreachable!("a split's first part ends in a pane")
144 };
145 find(self).unwrap_or(place)
146 }
147}
148
61149/// What the window draws with: one of the platform's backends, or the first of them that
62150/// starts.
63151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
......@@ -285,9 +373,16 @@ impl crate::State {
285373 let Some(path) = &self.settings else {
286374 return;
287375 };
376 if let Err(error) = self.kept_settings().save(path) {
377 eprintln!("Cannot save the settings in {}: {error}", path.display());
378 }
379 }
380
381 /// What the settings keep of the window as it is.
382 pub(crate) fn kept_settings(&self) -> Settings {
288383 let kept =
289384 |library: &&std::sync::Arc<crate::Library>| !matches!(library.notebook, Ok(None));
290 let settings = Settings {
385 Settings {
291386 notebooks: self
292387 .notebooks
293388 .iter()
......@@ -319,13 +414,11 @@ impl crate::State {
319414 servers: self.servers.clone(),
320415 keys: crate::commands::Keymap::current().saved(),
321416 recent: self.recent.clone(),
417 panes: self.saved_panes(),
322418 passwords: self.passwords,
323419 notebook_theme: NotebookTheme(self.notebook_theme.clone()),
324420 live: self.live_options.clone(),
325421 renderer: self.renderer_choice,
326 };
327 if let Err(error) = settings.save(path) {
328 eprintln!("Cannot save the settings in {}: {error}", path.display());
329422 }
330423 }
331424}
......@@ -405,6 +498,47 @@ mod tests {
405498 n: 1,
406499 },
407500 }],
501 panes: Some(Panes::Split {
502 down: false,
503 ratio: 0.4,
504 a: Box::new(Panes::Pane {
505 place: crate::navigation::Place {
506 notebook: "/notebooks/Personal".into(),
507 section: "To Do.one".into(),
508 page: onestore::ExGuid {
509 guid: [7; 16],
510 n: 1,
511 },
512 },
513 focused: false,
514 }),
515 b: Box::new(Panes::Split {
516 down: true,
517 ratio: 0.5,
518 a: Box::new(Panes::Pane {
519 place: crate::navigation::Place {
520 notebook: "/notebooks/Personal".into(),
521 section: "Work/Plans.one".into(),
522 page: onestore::ExGuid {
523 guid: [8; 16],
524 n: 1,
525 },
526 },
527 focused: true,
528 }),
529 b: Box::new(Panes::Pane {
530 place: crate::navigation::Place {
531 notebook: "smb://server/share/Work".into(),
532 section: "Notes.one".into(),
533 page: onestore::ExGuid {
534 guid: [9; 16],
535 n: 1,
536 },
537 },
538 focused: false,
539 }),
540 }),
541 }),
408542 passwords: Passwords {
409543 lock_after: None,
410544 lock_on_leave: true,
......@@ -435,6 +569,10 @@ mod tests {
435569 // New notebooks take Modern until another theme, or none, is picked.
436570 let theme = Settings::load(&path).notebook_theme;
437571 assert_eq!(theme.0.as_deref(), Some(notebook::sidecar::themes::DEFAULT));
572 // A layout another build wrote keeps the other settings.
573 notebook::fs::write(&path, br#"{"sidebar": true, "panes": {"grid": [1, 2]}}"#).unwrap();
574 let settings = Settings::load(&path);
575 assert!(settings.sidebar && settings.panes.is_none());
438576 // A renderer this platform lacks keeps the other settings and draws with the default.
439577 notebook::fs::write(&path, br#"{"sidebar": true, "renderer": "glide"}"#).unwrap();
440578 let settings = Settings::load(&path);
......@@ -442,4 +580,57 @@ mod tests {
442580 assert_eq!(settings.renderer, Backend::Default);
443581 notebook::fs::remove_dir_all(&directory).unwrap();
444582 }
583
584 /// A layout losing panes gives their room to the parts beside them, down to one pane, and
585 /// keeps the focus where it was, or else on the first pane.
586 #[test]
587 fn panes_lost_give_their_room_away() {
588 let place = |section: &str| crate::navigation::Place {
589 notebook: "/notebooks/Personal".into(),
590 section: section.into(),
591 page: onestore::ExGuid::default(),
592 };
593 let pane = |section: &str, focused| {
594 Box::new(Panes::Pane {
595 place: place(section),
596 focused,
597 })
598 };
599 let split = |down, a, b| Panes::Split {
600 down,
601 ratio: 0.3,
602 a,
603 b,
604 };
605 let layout = split(
606 false,
607 pane("A.one", false),
608 Box::new(split(true, pane("B.one", true), pane("C.one", false))),
609 );
610 assert_eq!(layout.focused(), &place("B.one"));
611 // Two panes on one place keep the focus where it was.
612 let mut twins = split(false, pane("B.one", false), pane("B.one", true));
613 twins.focus_one();
614 assert_eq!(
615 twins,
616 split(false, pane("B.one", false), pane("B.one", true))
617 );
618 let mut none = split(false, pane("A.one", false), pane("B.one", false));
619 none.focus_one();
620 assert_eq!(
621 none,
622 split(false, pane("A.one", true), pane("B.one", false))
623 );
624 let kept = layout
625 .clone()
626 .keep(&|place| place.section != "B.one")
627 .unwrap();
628 assert_eq!(
629 kept,
630 split(false, pane("A.one", false), pane("C.one", false))
631 );
632 assert_eq!(kept.focused(), &place("A.one"));
633 let one = layout.keep(&|place| place.section == "C.one");
634 assert_eq!(one, Some(*pane("C.one", false)));
635 }
445636}
crates/snowbound/src/split.rs+271-26
......@@ -3,11 +3,18 @@
33//! are parked. Panes on one section share its `Session`, since a section's replica opens
44//! once (`locking_mode=EXCLUSIVE`).
55
6use crate::{Command, FRAME, Library, Loaded, Pane, Session, State, art, name, navigation};
6use crate::navigation::{self, Place};
7use crate::settings::Panes;
8use crate::{Command, FRAME, Library, Loaded, Pane, Session, Showing, State, art, name};
9use canvas::{document::TextDocument, editor::CanvasEditor};
710use canvas::{gpu::page::PageScene, interaction::PageView};
811use draw::edit::SelectionUnit;
912use notebook::{Replica, session::Event};
10use onestore::ExGuid;
13use onestore::{
14 ExGuid,
15 document::Format,
16 page::{Page, text::Paragraph},
17};
1118use std::{
1219 error::Error,
1320 sync::{Arc, atomic::Ordering},
......@@ -155,7 +162,7 @@ impl State {
155162 }
156163
157164 /// Closes the parked panes `gone` picks, their room going to the parts beside them.
158 fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) {
165 pub(crate) fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) {
159166 let ids: Vec<Id> = (self.parked.iter())
160167 .filter(|parked| gone(parked))
161168 .map(|parked| parked.pane.id)
......@@ -469,6 +476,7 @@ impl State {
469476 self.accessibility.deactivate();
470477 self.page_grafted = false;
471478 self.title();
479 self.save_settings();
472480 self.window.request_redraw();
473481 Ok(())
474482 }
......@@ -479,31 +487,56 @@ impl State {
479487 let Some(session) = &self.session else {
480488 return Ok(());
481489 };
490 let showing = self.pane.showing;
491 let page = match showing.version {
492 Some(version) => session.version_reader(showing.space, version)()?,
493 None => session.reader(showing.space)()?,
494 };
495 let mut pane = self.new_pane(showing, Some(page))?;
496 pane.view.viewport = self.pane.view.viewport;
497 let id = pane.id;
498 let section = Some(session.key());
499 self.parked.push(Parked { pane, section });
500 self.split.divide(self.pane.id, axis, id);
501 self.focus_pane(self.parked.len() - 1)?;
502 self.wear_theme(true)?;
503 self.visited();
504 self.ui.set_focus(Some(self.pane.id));
505 Ok(())
506 }
507
508 /// A pane beside the focused one showing `page` as `showing` says, or bare paper without
509 /// one, with the focused one's view settings, under a page box id no pane has.
510 fn new_pane(&self, showing: Showing, page: Option<Page>) -> Result<Pane, Box<dyn Error>> {
482511 let taken =
483512 |id: &Id| *id == self.pane.id || self.parked.iter().any(|parked| parked.pane.id == *id);
484513 let id = (1..)
485514 .map(|count: u32| Id::ROOT.child(("page", count)))
486515 .find(|id| !taken(id))
487516 .ok_or("No pane is left to make")?;
488 let (showing, section) = (self.pane.showing, Some(session.key()));
489 let page = match showing.version {
490 Some(version) => session.version_reader(showing.space, version)()?,
491 None => session.reader(showing.space)()?,
492 };
493517 let shown = &self.pane.view;
494518 let mut engine = shown.engine.clone();
495 let (scene, editor) = PageScene::from_page(page, &mut engine)?;
496 let size = shown.viewport.size;
519 let (scene, mut editor) = match page {
520 Some(page) => {
521 let (scene, editor) = PageScene::from_page(page, &mut engine)?;
522 (Some((scene, [0.0; 2])), editor)
523 }
524 None => {
525 let blank = vec![Paragraph::new(String::new(), Format::default())];
526 let editor = CanvasEditor::new(&mut engine, TextDocument::new(blank)?, 480.0)?;
527 (None, editor)
528 }
529 };
530 editor.default_font.clone_from(&shown.editor.default_font);
531 editor.markdown.clone_from(&shown.editor.markdown);
497532 let double_click = crate::platform::double_click_interval();
498 let scene = Some((scene, [0.0; 2]));
499 let scale = self.ui.scale();
500 let mut view = PageView::new(editor, engine, scene, size, scale, double_click);
501 view.viewport = shown.viewport;
533 let size = shown.viewport.size;
534 let mut view = PageView::new(editor, engine, scene, size, self.ui.scale(), double_click);
502535 view.spelling.clone_from(&shown.spelling);
503536 view.snap_to_grid = shown.snap_to_grid;
504 view.editor.styles = shown.editor.styles.clone();
505537 view.tag_art = shown.tag_art.clone();
506 let pane = Pane {
538 let _ = view.focus_changed(false)?;
539 Ok(Pane {
507540 id,
508541 view,
509542 showing,
......@@ -516,15 +549,216 @@ impl State {
516549 sectionless: None,
517550 locked: None,
518551 refused: Arc::default(),
552 })
553 }
554
555 /// The panes as the settings keep them, each at its page; none while one pane fills the
556 /// page area, or panes without a page leave one.
557 pub(crate) fn saved_panes(&self) -> Option<Panes> {
558 match self.saved_part(&self.split)? {
559 Panes::Pane { .. } => None,
560 split => Some(split),
561 }
562 }
563
564 fn saved_part(&self, split: &Split) -> Option<Panes> {
565 match split {
566 // A pane waiting to open keeps the place it waits for.
567 Split::Leaf(id) if self.waiting(*id).is_some() => Some(Panes::Pane {
568 place: self.waiting(*id)?.clone(),
569 focused: *id == self.pane.id,
570 }),
571 Split::Leaf(id) => {
572 let (pane, session) = if *id == self.pane.id {
573 (&self.pane, self.session.as_ref()?)
574 } else {
575 let parked = self.parked.iter().find(|parked| parked.pane.id == *id)?;
576 let key = parked.section.as_ref()?;
577 let session = self.sessions().find(|session| session.key() == *key)?;
578 (&parked.pane, session)
579 };
580 Some(Panes::Pane {
581 place: Place {
582 notebook: session.library.location.clone(),
583 section: session.tabs[session.tab].path.clone(),
584 page: pane.showing.space,
585 },
586 focused: *id == self.pane.id,
587 })
588 }
589 Split::Pair { axis, ratio, a, b } => match (self.saved_part(a), self.saved_part(b)) {
590 (Some(a), Some(b)) => Some(Panes::Split {
591 down: *axis == Axis::Y,
592 ratio: *ratio,
593 a: Box::new(a),
594 b: Box::new(b),
595 }),
596 (a, b) => a.or(b),
597 },
598 }
599 }
600
601 /// Splits the page area as `saved` did at launch, keeping the panes on sections still
602 /// listed in notebooks still open; a page gone shows its section's first. The focused
603 /// pane goes where the one focused then was, and the others open after it, in turn.
604 pub(crate) fn restore_panes(&mut self, saved: Panes) -> Result<(), Box<dyn Error>> {
605 let library = |place: &Place| {
606 (self.notebooks.iter())
607 .find(|library| {
608 library.location == place.notebook
609 && library.contains(&place.section)
610 && !library.locked(&place.section)
611 })
612 .cloned()
519613 };
520 self.parked.push(Parked { pane, section });
521 self.split.divide(self.pane.id, axis, id);
522 self.focus_pane(self.parked.len() - 1)?;
523 self.visited();
524 self.ui.set_focus(Some(self.pane.id));
614 let Some(mut saved @ Panes::Split { .. }) = saved.keep(&|place| library(place).is_some())
615 else {
616 return Ok(());
617 };
618 saved.focus_one();
619 let focused = saved.focused().clone();
620 let shown = library(&focused).ok_or("The focused pane's notebook closed")?;
621 self.split = self.restored(saved)?;
622 // The section the launch opened shows its page, or stays as it is where that is gone.
623 let open =
624 (self.session.as_ref()).filter(|session| session.key() == shown.key(&focused.section));
625 match open {
626 Some(session) => {
627 if self.pane.showing.space != focused.page
628 && session.pages.iter().any(|(page, ..)| *page == focused.page)
629 {
630 self.commands.push(Command::OpenPage(focused.page));
631 }
632 }
633 None => self.open_section(shown, focused.section, Some(focused.page))?,
634 }
525635 Ok(())
526636 }
527637
638 /// The part `saved` restores: the focused pane where `saved` focuses, and a pane at bare
639 /// paper waiting to open anywhere else.
640 fn restored(&mut self, saved: Panes) -> Result<Split, Box<dyn Error>> {
641 Ok(match saved {
642 Panes::Pane { focused: true, .. } => Split::Leaf(self.pane.id),
643 Panes::Pane { place, .. } => {
644 let pane = self.new_pane(Showing::default(), None)?;
645 let id = pane.id;
646 self.parked.push(Parked {
647 pane,
648 section: None,
649 });
650 self.reopening.push((id, place));
651 Split::Leaf(id)
652 }
653 Panes::Split { down, ratio, a, b } => Split::Pair {
654 axis: if down { Axis::Y } else { Axis::X },
655 ratio: ratio.clamp(0.05, 0.95),
656 a: Box::new(self.restored(*a)?),
657 b: Box::new(self.restored(*b)?),
658 },
659 })
660 }
661
662 /// Leaves the parked panes on `library`, a notebook whose folder is renamed, waiting at
663 /// their places to open again from where it goes, their sections closed meanwhile as
664 /// those hold files in the folder.
665 pub(crate) fn wait_out_rename(&mut self, library: &Arc<Library>) {
666 let ours = |shown: &Library| shown.location == library.location;
667 let waiting: Vec<_> = (self.parked.iter())
668 .filter_map(|parked| {
669 let key = parked.section.as_ref()?;
670 let session = self.sessions().find(|session| session.key() == *key)?;
671 ours(&session.library).then(|| {
672 let place = Place {
673 notebook: library.location.clone(),
674 section: session.tabs[session.tab].path.clone(),
675 page: parked.pane.showing.space,
676 };
677 (parked.pane.id, place)
678 })
679 })
680 .collect();
681 self.reopening.extend(waiting);
682 self.leave_sections(|session| ours(&session.library), |_, _| {});
683 self.close_parked(|Parked { pane, .. }| {
684 pane.sectionless.as_deref().is_some_and(ours)
685 || (pane.locked.as_ref()).is_some_and(|locked| ours(&locked.library))
686 });
687 }
688
689 /// Whether pane `id` is one with nothing to show yet: no section, locked section or
690 /// sectionless notebook.
691 fn blank(&self, id: Id) -> bool {
692 let blank = |pane: &Pane| pane.sectionless.is_none() && pane.locked.is_none();
693 if id == self.pane.id {
694 return self.session.is_none() && blank(&self.pane);
695 }
696 (self.parked.iter())
697 .any(|parked| parked.pane.id == id && parked.section.is_none() && blank(&parked.pane))
698 }
699
700 /// Where pane `id` waits to open, if it does.
701 pub(crate) fn waiting(&self, id: Id) -> Option<&Place> {
702 (self.reopening.iter())
703 .find(|(waiting, _)| *waiting == id)
704 .map(|(_, place)| place)
705 }
706
707 /// Opens the next pane waiting to, the focused one first, once no pane has a page on its
708 /// way, so a section two of them show opens once and in the background; a notebook being
709 /// renamed keeps its panes waiting. A pane waits until its page arrives, or it closes.
710 pub(crate) fn reopen_next(&mut self) {
711 let blank: Vec<Id> = (self.reopening.iter())
712 .map(|(id, _)| *id)
713 .filter(|id| self.blank(*id))
714 .collect();
715 self.reopening.retain(|(id, _)| blank.contains(id));
716 if !self.still() || !self.commands.is_empty() {
717 return;
718 }
719 let renaming = |place: &Place| {
720 (self.folder_rename.as_ref()).is_some_and(|(from, _)| *from == place.notebook)
721 };
722 let ready = |(_, place): &&(Id, Place)| !renaming(place);
723 let next = (self.reopening.iter().filter(ready))
724 .find(|(id, _)| *id == self.pane.id)
725 .or(self.reopening.iter().find(ready))
726 .cloned();
727 let Some((id, place)) = next else {
728 return;
729 };
730 let library = (self.notebooks.iter())
731 .find(|library| library.location == place.notebook)
732 .cloned();
733 let Some(library) = library else {
734 self.reopening.retain(|(waiting, _)| *waiting != id);
735 if let Err(error) = self.close_pane(id) {
736 eprintln!("{error}");
737 }
738 return;
739 };
740 // Its own page, which the section's last page stays apart from.
741 let open = |state: &mut State| state.open_section(library, place.section, Some(place.page));
742 let opened = match self.parked.iter().position(|parked| parked.pane.id == id) {
743 Some(at) => self.in_pane(at, open),
744 None => open(self),
745 };
746 if let Err(error) = &opened {
747 eprintln!("{error}");
748 }
749 // A pane whose open never started waits no more.
750 let pane = std::iter::once(&self.pane)
751 .chain(self.parked.iter().map(|parked| &parked.pane))
752 .find(|pane| pane.id == id);
753 let idle = pane.is_some_and(|pane| pane.switching.is_none() && pane.opening.is_none());
754 if idle && self.blank(id) {
755 self.reopening.retain(|(waiting, _)| *waiting != id);
756 if let Err(error) = self.close_pane(id) {
757 eprintln!("{error}");
758 }
759 }
760 }
761
528762 /// Closes pane `id`, its room going to the part beside it; the first pane there takes the
529763 /// focus where the pane closed had it. The only pane stays.
530764 pub(crate) fn close_pane(&mut self, id: Id) -> Result<(), Box<dyn Error>> {
......@@ -565,6 +799,7 @@ impl State {
565799 {
566800 self.release(session);
567801 }
802 self.save_settings();
568803 Ok(())
569804 }
570805
......@@ -651,14 +886,18 @@ impl State {
651886 theme: &Theme,
652887 ) -> Result<bool, Box<dyn Error>> {
653888 let parked = (self.parked.iter()).position(|parked| parked.pane.id == id);
654 let (section, page) = match parked {
655 Some(at) => {
889 let (section, page) = match (parked, self.waiting(id)) {
890 (_, Some(place)) => {
891 let name = crate::protection::section_name(&place.section);
892 (name.to_owned(), String::new())
893 }
894 (Some(at), None) => {
656895 let parked = &self.parked[at];
657896 let key = parked.section.as_ref();
658897 let session = self.sessions().find(|session| Some(&session.key()) == key);
659898 label(&parked.pane, session)
660899 }
661 None => label(&self.pane, self.session.as_ref()),
900 (None, None) => label(&self.pane, self.session.as_ref()),
662901 };
663902 let leaf = self.ui.open(
664903 part,
......@@ -670,9 +909,15 @@ impl State {
670909 },
671910 );
672911 if let Some(node) = self.ui.access(leaf) {
673 node.set_label(format!("{section}, {page}"));
912 node.set_label(match page.is_empty() {
913 true => section.clone(),
914 false => format!("{section}, {page}"),
915 });
674916 }
675 let header = format!("{section} · {page}");
917 let header = match page.is_empty() {
918 true => section.clone(),
919 false => format!("{section} · {page}"),
920 };
676921 // The focused pane's header wears its section's accent, which the strip's colour
677922 // stands clear of in either appearance.
678923 let focused = parked.is_none();
crates/snowbound/tests/replay.rs+317-2
......@@ -50,7 +50,11 @@ fn replay_with(
5050 std::fs::copy(entry.path(), dir.join("notebook").join(entry.file_name())).unwrap();
5151 }
5252 }
53 let mut script = String::from("settle\n");
53 // Steps start once the window settles, unless the first asks to start at launch.
54 let (mut script, steps) = match steps.split_first() {
55 Some((&"launching", rest)) => (String::new(), rest),
56 _ => (String::from("settle\n"), steps),
57 };
5458 let mut trees = Vec::new();
5559 for step in steps {
5660 match step.strip_prefix("accessibility ") {
......@@ -79,7 +83,9 @@ fn replay_with(
7983 if dir.join("settings.json").exists() {
8084 command.args(["--settings".as_ref(), dir.join("settings.json").as_os_str()]);
8185 }
82 let status = command.status().unwrap();
86 // What the app logs, alerts included, which a hidden window shows no one.
87 let log = std::fs::File::create(dir.join("log")).unwrap();
88 let status = command.stderr(log).status().unwrap();
8389 assert!(status.success(), "the replay ended with {status}");
8490 trees
8591 .iter()
......@@ -1786,3 +1792,312 @@ fn closing_split_panes_leaves_the_window_as_it_was() {
17861792 after.display()
17871793 );
17881794}
1795
1796/// A layout of panes as the settings keep it, on pages of `notebook`'s sections: a pane on
1797/// the first, then a part below it, the second above the third. A page of `None` is gone.
1798fn layout(notebook: &Path, panes: [(&str, Option<&str>); 3]) -> serde_json::Value {
1799 let gone = "{00000000-0000-0000-0000-000000000001},1";
1800 let pane = |(section, page): (&str, Option<&str>), focused| {
1801 serde_json::json!({"pane": {
1802 "place": {"notebook": notebook, "section": section, "page": page.unwrap_or(gone)},
1803 "focused": focused,
1804 }})
1805 };
1806 let split =
1807 |down, a, b| serde_json::json!({"split": {"down": down, "ratio": 0.5, "a": a, "b": b}});
1808 split(
1809 false,
1810 pane(panes[0], true),
1811 split(true, pane(panes[1], false), pane(panes[2], false)),
1812 )
1813}
1814
1815/// Split panes kept in the settings split the page area again at the next launch, the
1816/// focused pane where it was.
1817#[test]
1818fn split_panes_return_at_the_next_launch() {
1819 let scratch = Scratch::new("split-saved");
1820 let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
1821 let saved = scratch.0.join("saved.json");
1822 let steps = [
1823 "split right".to_owned(),
1824 "settle".into(),
1825 // The Kitchen tab, which opens in the pane split off.
1826 "move 175 51".into(),
1827 "press".into(),
1828 "release".into(),
1829 "settle".into(),
1830 format!("settings {}", saved.display()),
1831 ];
1832 let steps: Vec<_> = steps.iter().map(String::as_str).collect();
1833 replay(&scratch, Some(&notebook), &steps);
1834 std::fs::copy(&saved, scratch.0.join("settings.json")).unwrap();
1835 let [tree] = replay(&scratch, None, &["accessibility tree"])
1836 .try_into()
1837 .unwrap();
1838 assert_eq!(
1839 pane_groups(&tree),
1840 [
1841 r#" Group "Garden, Spring planting plan""#,
1842 r#" Group "Kitchen, Sunday focaccia""#
1843 ],
1844 "{tree}"
1845 );
1846 assert_eq!(
1847 line(&tree, "Window"),
1848 r#"Window "Sunday focaccia · Kitchen.one""#
1849 );
1850}
1851
1852/// A saved pane on a section since deleted is left out, its room going to the pane beside it,
1853/// and a pane on a page since deleted shows its section's first.
1854#[test]
1855fn a_saved_pane_on_a_deleted_section_is_left_out() {
1856 let scratch = Scratch::new("split-deleted");
1857 let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
1858 let notebook = scratch.0.join("notebook");
1859 copy_notebook(&source, &notebook);
1860 std::fs::remove_file(notebook.join("Journal.one")).unwrap();
1861 let panes = layout(
1862 &notebook,
1863 [
1864 (
1865 "Garden.one",
1866 Some("{CF235667-138A-4E5D-B628-782140F5576D},1"),
1867 ),
1868 ("Kitchen.one", None),
1869 ("Journal.one", None),
1870 ],
1871 );
1872 let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes});
1873 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
1874 let [tree] = replay(&scratch, None, &["accessibility tree"])
1875 .try_into()
1876 .unwrap();
1877 assert_eq!(
1878 pane_groups(&tree),
1879 [
1880 r#" Group "Garden, Spring planting plan""#,
1881 r#" Group "Kitchen, Sunday focaccia""#
1882 ],
1883 "{tree}"
1884 );
1885 assert_eq!(
1886 line(&tree, "Window"),
1887 r#"Window "Spring planting plan · Garden.one""#
1888 );
1889}
1890
1891/// Saved panes in a notebook no longer open are left out; one pane left splits nothing.
1892#[test]
1893fn saved_panes_in_a_closed_notebook_are_left_out() {
1894 let scratch = Scratch::new("split-closed");
1895 let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
1896 let closed = scratch.0.join("closed");
1897 let mut panes = layout(
1898 &closed,
1899 [
1900 ("Garden.one", None),
1901 ("Kitchen.one", None),
1902 ("Trips.one", None),
1903 ],
1904 );
1905 // The first pane, in the notebook open.
1906 panes["split"]["a"]["pane"]["place"]["notebook"] =
1907 scratch.0.join("notebook").display().to_string().into();
1908 let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes});
1909 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
1910 let [tree] = replay(&scratch, Some(&notebook), &["accessibility tree"])
1911 .try_into()
1912 .unwrap();
1913 // One pane holds the page's own group alone.
1914 assert_eq!(pane_groups(&tree), [r#" Group "Page""#], "{tree}");
1915}
1916
1917/// Split panes on one page come back with the focus on the pane that had it.
1918#[test]
1919fn split_panes_on_one_page_return_with_the_focus_where_it_was() {
1920 let scratch = Scratch::new("split-twins");
1921 let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
1922 let saved = scratch.0.join("saved.json");
1923 let steps = [
1924 "split right".to_owned(),
1925 "settle".into(),
1926 format!("settings {}", saved.display()),
1927 ];
1928 let steps: Vec<_> = steps.iter().map(String::as_str).collect();
1929 replay(&scratch, Some(&notebook), &steps);
1930 std::fs::copy(&saved, scratch.0.join("settings.json")).unwrap();
1931 let [tree] = replay(&scratch, None, &["accessibility tree"])
1932 .try_into()
1933 .unwrap();
1934 let lines: Vec<&str> = tree.lines().collect();
1935 let groups: Vec<usize> = (lines.iter().enumerate())
1936 .filter(|(_, line)| line.starts_with(" Group \"Garden"))
1937 .map(|(at, _)| at)
1938 .collect();
1939 let page = lines.iter().position(|line| *line == r#" Group "Page""#);
1940 assert!(
1941 groups.len() == 2 && page.is_some_and(|page| page > groups[1]),
1942 "the second pane has the focus:\n{tree}"
1943 );
1944}
1945
1946/// Renaming a notebook's folder while split keeps every pane on it, each back on its page.
1947#[test]
1948fn renaming_a_notebook_keeps_its_split_panes() {
1949 let scratch = Scratch::new("split-rename");
1950 let notebook =
1951 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate");
1952 let settings = r#"{"user_name": "Snowbound Test", "sidebar": true}"#;
1953 std::fs::write(scratch.0.join("settings.json"), settings).unwrap();
1954 let steps = [
1955 "split right",
1956 "settle",
1957 // A double click on the notebook's row renames its folder.
1958 "move 60 76",
1959 "press",
1960 "release",
1961 "press",
1962 "release",
1963 "settle",
1964 "type Projects",
1965 "key Enter",
1966 "settle",
1967 "wait 1000",
1968 "settle",
1969 "accessibility renamed",
1970 ];
1971 let [renamed] = replay(&scratch, Some(&notebook), &steps)
1972 .try_into()
1973 .unwrap();
1974 assert!(scratch.0.join("Projects").is_dir(), "{renamed}");
1975 assert_eq!(
1976 pane_groups(&renamed),
1977 [
1978 r#" Group "Cross, Delete into a table""#,
1979 r#" Group "Cross, Delete into a table""#
1980 ],
1981 "{renamed}"
1982 );
1983}
1984
1985/// The sections of the panes `settings`, as JSON, keeps, in order, each with whether it has
1986/// the focus.
1987fn saved_panes(settings: &Path) -> Vec<(String, bool)> {
1988 fn leaves(panes: &serde_json::Value, out: &mut Vec<(String, bool)>) {
1989 match (panes.get("pane"), panes.get("split")) {
1990 (Some(pane), _) => out.push((
1991 pane["place"]["section"]
1992 .as_str()
1993 .unwrap_or_default()
1994 .to_owned(),
1995 pane["focused"].as_bool().unwrap_or_default(),
1996 )),
1997 (None, Some(split)) => {
1998 leaves(&split["a"], out);
1999 leaves(&split["b"], out);
2000 }
2001 (None, None) => {}
2002 }
2003 }
2004 let settings: serde_json::Value =
2005 serde_json::from_str(&std::fs::read_to_string(settings).unwrap()).unwrap();
2006 let mut out = Vec::new();
2007 leaves(&settings["panes"], &mut out);
2008 out
2009}
2010
2011/// The alerts the scratch's last replay showed.
2012fn alerts(scratch: &Scratch) -> Vec<String> {
2013 (std::fs::read_to_string(scratch.0.join("log"))
2014 .unwrap()
2015 .lines())
2016 .filter(|line| line.starts_with("Alert:"))
2017 .map(str::to_owned)
2018 .collect()
2019}
2020
2021/// Writes a layout of three panes, on Garden, then Kitchen above Reading, into the scratch's
2022/// settings, Garden focused.
2023fn three_panes(scratch: &Scratch) {
2024 let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
2025 copy_notebook(&notebook, &scratch.0.join("notebook"));
2026 let panes = layout(
2027 &scratch.0.join("notebook"),
2028 [
2029 ("Garden.one", None),
2030 ("Kitchen.one", None),
2031 ("Reading.one", None),
2032 ],
2033 );
2034 let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes});
2035 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
2036}
2037
2038/// A restored pane clicked before it opens opens at once, takes the focus, and keeps its
2039/// place in the layout.
2040#[test]
2041fn a_restored_pane_clicked_before_it_opens_opens_there() {
2042 let scratch = Scratch::new("split-waiting-click");
2043 three_panes(&scratch);
2044 let saved = scratch.0.join("saved.json");
2045 let steps = [
2046 "launching".to_owned(),
2047 "wait 16".into(),
2048 // The pane on Reading, below Kitchen's.
2049 "move 600 600".into(),
2050 "press".into(),
2051 "release".into(),
2052 "settle".into(),
2053 "accessibility tree".into(),
2054 format!("settings {}", saved.display()),
2055 ];
2056 let steps: Vec<_> = steps.iter().map(String::as_str).collect();
2057 let [tree] = replay(&scratch, None, &steps).try_into().unwrap();
2058 assert!(alerts(&scratch).is_empty(), "{:?}", alerts(&scratch));
2059 assert_eq!(
2060 pane_groups(&tree),
2061 [
2062 r#" Group "Garden, Spring planting plan""#,
2063 r#" Group "Kitchen, Sunday focaccia""#,
2064 r#" Group "Reading, Reading now""#
2065 ],
2066 "{tree}"
2067 );
2068 assert_eq!(
2069 line(&tree, "Window"),
2070 r#"Window "Reading now · Reading.one""#
2071 );
2072 assert_eq!(
2073 saved_panes(&saved),
2074 [
2075 ("Garden.one".to_owned(), false),
2076 ("Kitchen.one".to_owned(), false),
2077 ("Reading.one".to_owned(), true)
2078 ]
2079 );
2080}
2081
2082/// Settings saved while restored panes still open keep every pane at its place.
2083#[test]
2084fn settings_saved_while_panes_open_keep_them_all() {
2085 let scratch = Scratch::new("split-saving-early");
2086 three_panes(&scratch);
2087 let saved = scratch.0.join("saved.json");
2088 let steps = [
2089 "launching".to_owned(),
2090 format!("settings {}", saved.display()),
2091 ];
2092 let steps: Vec<_> = steps.iter().map(String::as_str).collect();
2093 replay(&scratch, None, &steps);
2094 assert!(alerts(&scratch).is_empty(), "{:?}", alerts(&scratch));
2095 assert_eq!(
2096 saved_panes(&saved),
2097 [
2098 ("Garden.one".to_owned(), true),
2099 ("Kitchen.one".to_owned(), false),
2100 ("Reading.one".to_owned(), false)
2101 ]
2102 );
2103}