diff --git a/crates/snowbound/src/macos.rs b/crates/snowbound/src/macos.rs index 105fd0955eb41ff976ea1e0729e96a739606c431..310a29ca2d1a2487de68d9f7da93929c86912d99 100644 --- a/crates/snowbound/src/macos.rs +++ b/crates/snowbound/src/macos.rs @@ -1096,6 +1096,10 @@ pub fn symbol_fonts() -> Vec { /// Tells the user something they asked for could not be done: `message`, then what to do. pub fn alert(message: &str, detail: &str) { + // A replay's window is hidden, its sheets with it. + if crate::automated() { + eprintln!("Alert: {message} · {detail}"); + } let mtm = MainThreadMarker::new().expect("Window events run on the main thread"); unsafe { let alert = NSAlert::new(mtm); diff --git a/crates/snowbound/src/main.rs b/crates/snowbound/src/main.rs index 9f2bb2cabf81c4a0efed2a253546f0042517d3b8..87c773956015cd841993a37ed9ff5fab615b58c4 100644 --- a/crates/snowbound/src/main.rs +++ b/crates/snowbound/src/main.rs @@ -430,6 +430,8 @@ enum Replay { Split(Axis), /// Closes the focused pane. ClosePane, + /// Writes the settings as they would be saved, as a screenshot's replay saves none. + Settings(PathBuf), Quit, } @@ -758,6 +760,8 @@ enum Laid { /// are drawn, so it never appears without them. struct Opening { loaded: Shown, + /// A page to show once this one does, as the pane taking the load over asked for. + then: Option, scene: (PageScene, [f32; 2]), editor: CanvasEditor, since: Instant, @@ -921,6 +925,8 @@ struct State { parked: Vec, /// How the panes divide the page area. split: split::Split, + /// Parked panes waiting to open at a place, by page box, in turn. + reopening: Vec<(Id, navigation::Place)>, /// The open notebooks in the sidebar's order. notebooks: Vec>, /// The section the focused pane shows. @@ -929,8 +935,9 @@ struct State { shelved: Vec, /// The last load request number given. requests: u64, - /// Sections loads are opening from their files, by request number. - opening_files: Vec<(u64, String)>, + /// Sections loads are opening from their files, by request number, with the page to show + /// after where a pane took the load over from the one that started it. + opening_files: Vec<(u64, String, Option)>, /// A page not kept in any notebook, from a text file or `--page`. temporary: bool, /// Where the settings are saved; `None` leaves them as they were read. @@ -1433,6 +1440,7 @@ impl State { }, parked: Vec::new(), split: split::Split::Leaf(page), + reopening: Vec::new(), notebooks, session, shelved: Vec::new(), @@ -1544,6 +1552,11 @@ impl State { state.commands.push(Command::OpenFromServer(Some(location))); } state.visited(); + if let Some(panes) = stored.panes + && let Err(error) = state.restore_panes(panes) + { + eprintln!("Couldn't split the page area as it was: {error}"); + } state.prefetch_around(); state.show_spelling(); state.title(); @@ -1617,6 +1630,7 @@ impl State { if let Err(error) = self.open_loaded() { eprintln!("{error}"); } + self.reopen_next(); if let Err(error) = self.take_waiting() { eprintln!("{error}"); } @@ -1827,7 +1841,8 @@ impl State { let welcome = self.session.is_none() && !self.temporary && self.pane.sectionless.is_none() - && self.pane.locked.is_none(); + && self.pane.locked.is_none() + && self.waiting(self.pane.id).is_none(); self.toolbar(&theme, !welcome)?; if welcome { self.welcome(); @@ -2113,6 +2128,19 @@ impl State { /// Builds the focused pane in the box open: its page, under the bars it shows above it, /// or what it shows in place of one; whether that is a page. fn pane_content(&mut self, theme: &Theme) -> Result> { + // A pane waiting to open shows bare paper. + if self.session.is_none() && self.waiting(self.pane.id).is_some() { + let paper = Some(theme.paper); + self.ui.leaf( + "waiting", + Spec { + size: [fill(), fill()], + fill: paper, + ..Spec::default() + }, + ); + return Ok(false); + } if let Some(session) = &self.session && let Some(bar) = session.bar(&self.pane.showing) { @@ -3695,72 +3723,7 @@ impl State { fn apply(&mut self, command: Command) -> Result<(), Box> { match command { - Command::OpenSection(library, path) => { - // Its files are on their way to the renamed folder. - if self.folder_renaming(&library.location) { - return Ok(()); - } - if library.locked(&path) { - return self.show_locked(library, path); - } - let tab = match &self.session { - // Back to the open section before another one opened. - Some(session) - if self.pane.switching.is_some() - && Arc::ptr_eq(&session.library, &library) - && session.tabs[session.tab].path == path => - { - self.stop_loading(); - return Ok(()); - } - Some(session) if session.library.location == library.location => { - session.tabs.iter().position(|tab| tab.path == path) - } - _ => None, - }; - self.pane.switching = Some((tab, Instant::now())); - let key = library.key(&path); - let last = self.last_pages.get(&key).copied(); - // A section a parked pane shows is open already, and opens only once. - if let Some(held) = self.shelved.iter().find(|held| held.key() == key) { - let listed = |space: &ExGuid| held.pages.iter().any(|(page, ..)| page == space); - let space = (last.filter(listed)) - .or(held.pages.first().map(|(page, ..)| *page)) - .ok_or("The section has no pages")?; - let read = held.reader(space); - self.load(move || Ok(Loaded::Held(library, path, space, read()?))); - return Ok(()); - } - // A section opens from its file once: a load already opening it shows it here, - // and a parked pane that asked for it first, if any still waits, leaves it to - // this one. - let opening = (self.opening_files.iter()) - .rfind(|(_, opening)| *opening == key) - .map(|(request, _)| *request); - if let Some(request) = opening { - if request != self.pane.loading { - let fresh = self.request(); - let asked = (self.parked.iter_mut()) - .map(|parked| &mut parked.pane) - .find(|pane| pane.loading == request); - let opened = asked.and_then(|pane| { - (pane.loading, pane.switching) = (fresh, None); - pane.opening.take() - }); - (self.pane.loading, self.pane.opening) = (request, opened); - } - return Ok(()); - } - let notify = notify(self.proxy.clone()); - self.load_async(move || async move { - let start = Instant::now(); - let section = library.open_async(&path, notify).await?; - lap("switch section open", start); - let (session, space, page) = read_session(section, library, path, last)?; - Ok(Loaded::Section(Box::new(session), space, page)) - }); - self.opening_files.push((self.pane.loading, key)); - } + Command::OpenSection(library, path) => self.open_section(library, path, None)?, Command::OpenPage(space) => { let session = self.session.as_ref().ok_or("No section is open")?; if self.pane.switching.is_some() @@ -3901,6 +3864,85 @@ impl State { Ok(()) } + /// Opens `library`'s section at catalog `path` at page `page`, or the page it showed last, + /// from its file where no pane holds it and no load is opening it already. + pub(crate) fn open_section( + &mut self, + library: Arc, + path: String, + page: Option, + ) -> Result<(), Box> { + // Its files are on their way to the renamed folder. + if self.folder_renaming(&library.location) { + return Ok(()); + } + if library.locked(&path) { + return self.show_locked(library, path); + } + let tab = match &self.session { + // Back to the open section before another one opened. + Some(session) + if self.pane.switching.is_some() + && Arc::ptr_eq(&session.library, &library) + && session.tabs[session.tab].path == path => + { + self.stop_loading(); + return Ok(()); + } + Some(session) if session.library.location == library.location => { + session.tabs.iter().position(|tab| tab.path == path) + } + _ => None, + }; + self.pane.switching = Some((tab, Instant::now())); + let key = library.key(&path); + let last = page.or_else(|| self.last_pages.get(&key).copied()); + // A section a parked pane shows is open already, and opens only once. + if let Some(held) = self.shelved.iter().find(|held| held.key() == key) { + let listed = |space: &ExGuid| held.pages.iter().any(|(page, ..)| page == space); + let space = (last.filter(listed)) + .or(held.pages.first().map(|(page, ..)| *page)) + .ok_or("The section has no pages")?; + let read = held.reader(space); + self.load(move || Ok(Loaded::Held(library, path, space, read()?))); + return Ok(()); + } + // A section opens from its file once: a load already opening it shows it here, + // and a parked pane that asked for it first, if any still waits, leaves it to + // this one. + let opening = (self.opening_files.iter_mut()).rfind(|(_, opening, _)| *opening == key); + if let Some((request, _, then)) = opening { + let request = *request; + if request != self.pane.loading { + // It shows this pane's page after the one it reads. + *then = last; + let fresh = self.request(); + let asked = (self.parked.iter_mut()) + .map(|parked| &mut parked.pane) + .find(|pane| pane.loading == request); + let mut opened = asked.and_then(|pane| { + (pane.loading, pane.switching) = (fresh, None); + pane.opening.take() + }); + if let Some(opened) = &mut opened { + opened.then = last; + } + (self.pane.loading, self.pane.opening) = (request, opened); + } + return Ok(()); + } + let notify = notify(self.proxy.clone()); + self.load_async(move || async move { + let start = Instant::now(); + let section = library.open_async(&path, notify).await?; + lap("switch section open", start); + let (session, space, page) = read_session(section, library, path, last)?; + Ok(Loaded::Section(Box::new(session), space, page)) + }); + self.opening_files.push((self.pane.loading, key, None)); + Ok(()) + } + /// Runs `read` on a thread of its own, which lays out the page it read; `open_loaded` /// shows it unless a newer read was asked for meanwhile. fn load(&mut self, read: impl FnOnce() -> Result> + Send + 'static) { @@ -3955,6 +3997,7 @@ impl State { Ok(Laid::Page(Box::new(Opening { requested, loaded: shown, + then: None, scene: (scene, [0.0; 2]), editor, since: Instant::now(), @@ -4021,7 +4064,10 @@ impl State { fn open_loaded(&mut self) -> Result<(), Box> { let reads: Vec = self.loads.1.try_iter().collect(); for (id, loaded) in reads { - self.opening_files.retain(|(request, _)| *request != id); + let then = (self.opening_files.iter()) + .find(|(request, ..)| *request == id) + .and_then(|(.., then)| *then); + self.opening_files.retain(|(request, ..)| *request != id); let parked = (self.parked.iter()).position(|parked| parked.pane.loading == id); let pane = match parked { Some(at) => &mut self.parked[at].pane, @@ -4030,16 +4076,26 @@ impl State { match loaded { // A later load supersedes what this one shows, but not its failure. Ok(_) if id != pane.loading => {} - Ok(Laid::Page(opening)) => pane.opening = Some(*opening), + Ok(Laid::Page(opening)) => { + pane.opening = Some(Opening { then, ..*opening }); + } Ok(Laid::Library(library, path)) => match parked { Some(at) => self.in_pane(at, |state| state.adopt(library, path.as_deref()))?, None => self.adopt(library, path.as_deref())?, }, Err(error) => { - if id == pane.loading { + let failed = (id == pane.loading).then_some(pane.id); + if failed.is_some() { pane.switching = None; } platform::alert("Couldn't open", &error); + // A pane waiting to open, with nothing to show, closes. + if let Some(failed) = failed + && self.reopening.iter().any(|(waiting, _)| *waiting == failed) + { + self.reopening.retain(|(waiting, _)| *waiting != failed); + self.close_pane(failed)?; + } } } } @@ -4061,7 +4117,7 @@ impl State { } fn show_page(&mut self, mut opening: Opening) -> Result<(), Box> { - let requested = opening.requested; + let (requested, then) = (opening.requested, opening.then); if let Shown::Held(library, path, space) = opening.loaded { match self.unshelve(&library.key(&path)) { Some(session) => opening.loaded = Shown::Section(Box::new(session), space), @@ -4134,6 +4190,7 @@ impl State { .is_none_or(|open| open.library.location != session.library.location); self.list(&session.library); self.pane.locked = None; + self.pane.view.tag_art = session.library.tag_art(); let previous = self.session.replace(*session); if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) { self.release(previous); @@ -4209,6 +4266,13 @@ impl State { }; self.rename(target); } + let listed = |space: ExGuid| { + (self.session.as_ref()) + .is_some_and(|session| session.pages.iter().any(|(page, ..)| *page == space)) + }; + if let Some(then) = then.filter(|then| *then != self.pane.showing.space && listed(*then)) { + self.commands.push(Command::OpenPage(then)); + } Ok(()) } @@ -6706,6 +6770,11 @@ impl State { Replay::Renderer(_) => unreachable!("The app switches renderers"), Replay::Split(axis) => self.commands.push(Command::Split(axis)), Replay::ClosePane => self.commands.push(Command::ClosePane(self.pane.id)), + Replay::Settings(path) => { + if let Err(error) = self.kept_settings().save(&path) { + eprintln!("{error}"); + } + } } // A covered window gets no redraws, so each step draws its own frame. if let Err(error) = self.frame() { @@ -7072,6 +7141,8 @@ impl ApplicationHandler for App { return; }; let deadline = Instant::now() + QUIT; + // Dividers dragged and pages shown in parked panes since. + state.save_settings(); state.publish_now(QUIT); self.restart = state.updates.restarting(); let sessions: Vec<_> = (state.session.take().into_iter()) @@ -7225,6 +7296,7 @@ fn replay(script: String, proxy: EventLoopProxy) -> Result<(), Box return Err(format!("Unknown split {rest}").into()), })), "close" if rest == "pane" => Ok(Replay::ClosePane), + "settings" => Ok(Replay::Settings(rest.into())), "appearance" => Ok(Replay::Appearance(match rest { "light" => winit::window::Theme::Light, "dark" => winit::window::Theme::Dark, diff --git a/crates/snowbound/src/manage.rs b/crates/snowbound/src/manage.rs index bd41c990c7b5a6de5aca8f5d27f0313111409331..62ada96c50e7ea4b91f3236e6fef64b1fe658e09 100644 --- a/crates/snowbound/src/manage.rs +++ b/crates/snowbound/src/manage.rs @@ -245,6 +245,7 @@ impl State { let now = crate::Instant::now(); self.show_page(crate::Opening { loaded: crate::Shown::Page(space), + then: None, scene: (scene, [0.0; 2]), editor, since: now, @@ -727,8 +728,7 @@ impl State { let Some(to) = library.renamed_location(&name) else { return; }; - // Their sections hold files in the folder. - self.close_parked_in(&library); + self.wait_out_rename(&library); let ours = |shown: &Arc| Arc::ptr_eq(shown, &library); let shown = self .session @@ -831,6 +831,11 @@ impl State { self.notebooks .retain(|open| open.location != to || !std::mem::replace(&mut listed, true)); if from != to { + for (_, place) in &mut self.reopening { + if place.notebook == from { + place.notebook.clone_from(&to); + } + } self.undo.close(&from); self.pane.trail.moved(&from, &to); for place in self diff --git a/crates/snowbound/src/settings.rs b/crates/snowbound/src/settings.rs index 2f8722eba8f7ecf32c74becdf4c21a2ee4cbc5dc..67d712510b501059e5fad3fd29d191059bbae9aa 100644 --- a/crates/snowbound/src/settings.rs +++ b/crates/snowbound/src/settings.rs @@ -50,6 +50,11 @@ pub struct Settings { pub keys: std::collections::BTreeMap>, /// Pages shown lately, latest first, which the palette lists first and a launch returns to. pub recent: Vec, + /// The panes splitting the page area, each at the page it shows; none while one fills it. + /// A layout is one person's, so it stays here and never in a notebook. One another build + /// wrote that this one can't read is left out, and the rest of the settings kept. + #[serde(deserialize_with = "lenient")] + pub panes: Option, pub passwords: Passwords, pub live: Live, /// Options' "Default for new notebooks": the built-in theme new notebooks take. @@ -58,6 +63,89 @@ pub struct Settings { pub renderer: Backend, } +/// `T` as the settings keep it, or none where they keep what this build can't read. +fn lenient<'de, D: serde::Deserializer<'de>, T: serde::de::DeserializeOwned>( + deserializer: D, +) -> Result, D::Error> { + let value = serde_json::Value::deserialize(deserializer)?; + Ok(serde_json::from_value(value).ok()) +} + +/// How panes split the page area, as `split::Split` divides it, each at the page it shows. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Panes { + Pane { + place: crate::navigation::Place, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + focused: bool, + }, + /// Two parts, the second beside the first or `down` below it, `ratio` of the room going + /// to the first. + Split { + down: bool, + ratio: f32, + a: Box, + b: Box, + }, +} + +impl Panes { + /// The panes at places `kept` holds, a split losing a part giving its room to the other. + pub fn keep(self, kept: &impl Fn(&crate::navigation::Place) -> bool) -> Option { + match self { + Panes::Pane { ref place, .. } => kept(place).then_some(self), + Panes::Split { down, ratio, a, b } => match (a.keep(kept), b.keep(kept)) { + (Some(a), Some(b)) => Some(Panes::Split { + down, + ratio, + a: Box::new(a), + b: Box::new(b), + }), + (a, b) => a.or(b), + }, + } + } + + /// Leaves one pane focused: the first focused, or the first where none is. + pub fn focus_one(&mut self) { + fn each(panes: &mut Panes, visit: &mut impl FnMut(&mut bool)) { + match panes { + Panes::Pane { focused, .. } => visit(focused), + Panes::Split { a, b, .. } => { + each(a, visit); + each(b, visit); + } + } + } + let mut any = false; + each(self, &mut |focused| any |= *focused); + let mut taken = false; + each(self, &mut |focused| { + *focused = !taken && (*focused || !any); + taken |= *focused; + }); + } + + /// The place of the pane focused, or of the first. + pub fn focused(&self) -> &crate::navigation::Place { + fn find(panes: &Panes) -> Option<&crate::navigation::Place> { + match panes { + Panes::Pane { place, focused } => focused.then_some(place), + Panes::Split { a, b, .. } => find(a).or_else(|| find(b)), + } + } + let mut first = self; + while let Panes::Split { a, .. } = first { + first = a; + } + let Panes::Pane { place, .. } = first else { + unreachable!("a split's first part ends in a pane") + }; + find(self).unwrap_or(place) + } +} + /// What the window draws with: one of the platform's backends, or the first of them that /// starts. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -285,9 +373,16 @@ impl crate::State { let Some(path) = &self.settings else { return; }; + if let Err(error) = self.kept_settings().save(path) { + eprintln!("Cannot save the settings in {}: {error}", path.display()); + } + } + + /// What the settings keep of the window as it is. + pub(crate) fn kept_settings(&self) -> Settings { let kept = |library: &&std::sync::Arc| !matches!(library.notebook, Ok(None)); - let settings = Settings { + Settings { notebooks: self .notebooks .iter() @@ -319,13 +414,11 @@ impl crate::State { servers: self.servers.clone(), keys: crate::commands::Keymap::current().saved(), recent: self.recent.clone(), + panes: self.saved_panes(), passwords: self.passwords, notebook_theme: NotebookTheme(self.notebook_theme.clone()), live: self.live_options.clone(), renderer: self.renderer_choice, - }; - if let Err(error) = settings.save(path) { - eprintln!("Cannot save the settings in {}: {error}", path.display()); } } } @@ -405,6 +498,47 @@ mod tests { n: 1, }, }], + panes: Some(Panes::Split { + down: false, + ratio: 0.4, + a: Box::new(Panes::Pane { + place: crate::navigation::Place { + notebook: "/notebooks/Personal".into(), + section: "To Do.one".into(), + page: onestore::ExGuid { + guid: [7; 16], + n: 1, + }, + }, + focused: false, + }), + b: Box::new(Panes::Split { + down: true, + ratio: 0.5, + a: Box::new(Panes::Pane { + place: crate::navigation::Place { + notebook: "/notebooks/Personal".into(), + section: "Work/Plans.one".into(), + page: onestore::ExGuid { + guid: [8; 16], + n: 1, + }, + }, + focused: true, + }), + b: Box::new(Panes::Pane { + place: crate::navigation::Place { + notebook: "smb://server/share/Work".into(), + section: "Notes.one".into(), + page: onestore::ExGuid { + guid: [9; 16], + n: 1, + }, + }, + focused: false, + }), + }), + }), passwords: Passwords { lock_after: None, lock_on_leave: true, @@ -435,6 +569,10 @@ mod tests { // New notebooks take Modern until another theme, or none, is picked. let theme = Settings::load(&path).notebook_theme; assert_eq!(theme.0.as_deref(), Some(notebook::sidecar::themes::DEFAULT)); + // A layout another build wrote keeps the other settings. + notebook::fs::write(&path, br#"{"sidebar": true, "panes": {"grid": [1, 2]}}"#).unwrap(); + let settings = Settings::load(&path); + assert!(settings.sidebar && settings.panes.is_none()); // A renderer this platform lacks keeps the other settings and draws with the default. notebook::fs::write(&path, br#"{"sidebar": true, "renderer": "glide"}"#).unwrap(); let settings = Settings::load(&path); @@ -442,4 +580,57 @@ mod tests { assert_eq!(settings.renderer, Backend::Default); notebook::fs::remove_dir_all(&directory).unwrap(); } + + /// A layout losing panes gives their room to the parts beside them, down to one pane, and + /// keeps the focus where it was, or else on the first pane. + #[test] + fn panes_lost_give_their_room_away() { + let place = |section: &str| crate::navigation::Place { + notebook: "/notebooks/Personal".into(), + section: section.into(), + page: onestore::ExGuid::default(), + }; + let pane = |section: &str, focused| { + Box::new(Panes::Pane { + place: place(section), + focused, + }) + }; + let split = |down, a, b| Panes::Split { + down, + ratio: 0.3, + a, + b, + }; + let layout = split( + false, + pane("A.one", false), + Box::new(split(true, pane("B.one", true), pane("C.one", false))), + ); + assert_eq!(layout.focused(), &place("B.one")); + // Two panes on one place keep the focus where it was. + let mut twins = split(false, pane("B.one", false), pane("B.one", true)); + twins.focus_one(); + assert_eq!( + twins, + split(false, pane("B.one", false), pane("B.one", true)) + ); + let mut none = split(false, pane("A.one", false), pane("B.one", false)); + none.focus_one(); + assert_eq!( + none, + split(false, pane("A.one", true), pane("B.one", false)) + ); + let kept = layout + .clone() + .keep(&|place| place.section != "B.one") + .unwrap(); + assert_eq!( + kept, + split(false, pane("A.one", false), pane("C.one", false)) + ); + assert_eq!(kept.focused(), &place("A.one")); + let one = layout.keep(&|place| place.section == "C.one"); + assert_eq!(one, Some(*pane("C.one", false))); + } } diff --git a/crates/snowbound/src/split.rs b/crates/snowbound/src/split.rs index 67458d6c1baf62346847fca3fde67b2cb6178527..842ba306e06346f8163c73edb7fd0117247ecda9 100644 --- a/crates/snowbound/src/split.rs +++ b/crates/snowbound/src/split.rs @@ -3,11 +3,18 @@ //! are parked. Panes on one section share its `Session`, since a section's replica opens //! once (`locking_mode=EXCLUSIVE`). -use crate::{Command, FRAME, Library, Loaded, Pane, Session, State, art, name, navigation}; +use crate::navigation::{self, Place}; +use crate::settings::Panes; +use crate::{Command, FRAME, Library, Loaded, Pane, Session, Showing, State, art, name}; +use canvas::{document::TextDocument, editor::CanvasEditor}; use canvas::{gpu::page::PageScene, interaction::PageView}; use draw::edit::SelectionUnit; use notebook::{Replica, session::Event}; -use onestore::ExGuid; +use onestore::{ + ExGuid, + document::Format, + page::{Page, text::Paragraph}, +}; use std::{ error::Error, sync::{Arc, atomic::Ordering}, @@ -155,7 +162,7 @@ impl State { } /// Closes the parked panes `gone` picks, their room going to the parts beside them. - fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) { + pub(crate) fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) { let ids: Vec = (self.parked.iter()) .filter(|parked| gone(parked)) .map(|parked| parked.pane.id) @@ -469,6 +476,7 @@ impl State { self.accessibility.deactivate(); self.page_grafted = false; self.title(); + self.save_settings(); self.window.request_redraw(); Ok(()) } @@ -479,31 +487,56 @@ impl State { let Some(session) = &self.session else { return Ok(()); }; + let showing = self.pane.showing; + let page = match showing.version { + Some(version) => session.version_reader(showing.space, version)()?, + None => session.reader(showing.space)()?, + }; + let mut pane = self.new_pane(showing, Some(page))?; + pane.view.viewport = self.pane.view.viewport; + let id = pane.id; + let section = Some(session.key()); + self.parked.push(Parked { pane, section }); + self.split.divide(self.pane.id, axis, id); + self.focus_pane(self.parked.len() - 1)?; + self.wear_theme(true)?; + self.visited(); + self.ui.set_focus(Some(self.pane.id)); + Ok(()) + } + + /// A pane beside the focused one showing `page` as `showing` says, or bare paper without + /// one, with the focused one's view settings, under a page box id no pane has. + fn new_pane(&self, showing: Showing, page: Option) -> Result> { let taken = |id: &Id| *id == self.pane.id || self.parked.iter().any(|parked| parked.pane.id == *id); let id = (1..) .map(|count: u32| Id::ROOT.child(("page", count))) .find(|id| !taken(id)) .ok_or("No pane is left to make")?; - let (showing, section) = (self.pane.showing, Some(session.key())); - let page = match showing.version { - Some(version) => session.version_reader(showing.space, version)()?, - None => session.reader(showing.space)()?, - }; let shown = &self.pane.view; let mut engine = shown.engine.clone(); - let (scene, editor) = PageScene::from_page(page, &mut engine)?; - let size = shown.viewport.size; + let (scene, mut editor) = match page { + Some(page) => { + let (scene, editor) = PageScene::from_page(page, &mut engine)?; + (Some((scene, [0.0; 2])), editor) + } + None => { + let blank = vec![Paragraph::new(String::new(), Format::default())]; + let editor = CanvasEditor::new(&mut engine, TextDocument::new(blank)?, 480.0)?; + (None, editor) + } + }; + editor.default_font.clone_from(&shown.editor.default_font); + editor.markdown.clone_from(&shown.editor.markdown); let double_click = crate::platform::double_click_interval(); - let scene = Some((scene, [0.0; 2])); - let scale = self.ui.scale(); - let mut view = PageView::new(editor, engine, scene, size, scale, double_click); - view.viewport = shown.viewport; + let size = shown.viewport.size; + let mut view = PageView::new(editor, engine, scene, size, self.ui.scale(), double_click); view.spelling.clone_from(&shown.spelling); view.snap_to_grid = shown.snap_to_grid; - view.editor.styles = shown.editor.styles.clone(); view.tag_art = shown.tag_art.clone(); - let pane = Pane { + let _ = view.focus_changed(false)?; + Ok(Pane { id, view, showing, @@ -516,15 +549,216 @@ impl State { sectionless: None, locked: None, refused: Arc::default(), + }) + } + + /// The panes as the settings keep them, each at its page; none while one pane fills the + /// page area, or panes without a page leave one. + pub(crate) fn saved_panes(&self) -> Option { + match self.saved_part(&self.split)? { + Panes::Pane { .. } => None, + split => Some(split), + } + } + + fn saved_part(&self, split: &Split) -> Option { + match split { + // A pane waiting to open keeps the place it waits for. + Split::Leaf(id) if self.waiting(*id).is_some() => Some(Panes::Pane { + place: self.waiting(*id)?.clone(), + focused: *id == self.pane.id, + }), + Split::Leaf(id) => { + let (pane, session) = if *id == self.pane.id { + (&self.pane, self.session.as_ref()?) + } else { + let parked = self.parked.iter().find(|parked| parked.pane.id == *id)?; + let key = parked.section.as_ref()?; + let session = self.sessions().find(|session| session.key() == *key)?; + (&parked.pane, session) + }; + Some(Panes::Pane { + place: Place { + notebook: session.library.location.clone(), + section: session.tabs[session.tab].path.clone(), + page: pane.showing.space, + }, + focused: *id == self.pane.id, + }) + } + Split::Pair { axis, ratio, a, b } => match (self.saved_part(a), self.saved_part(b)) { + (Some(a), Some(b)) => Some(Panes::Split { + down: *axis == Axis::Y, + ratio: *ratio, + a: Box::new(a), + b: Box::new(b), + }), + (a, b) => a.or(b), + }, + } + } + + /// Splits the page area as `saved` did at launch, keeping the panes on sections still + /// listed in notebooks still open; a page gone shows its section's first. The focused + /// pane goes where the one focused then was, and the others open after it, in turn. + pub(crate) fn restore_panes(&mut self, saved: Panes) -> Result<(), Box> { + let library = |place: &Place| { + (self.notebooks.iter()) + .find(|library| { + library.location == place.notebook + && library.contains(&place.section) + && !library.locked(&place.section) + }) + .cloned() }; - self.parked.push(Parked { pane, section }); - self.split.divide(self.pane.id, axis, id); - self.focus_pane(self.parked.len() - 1)?; - self.visited(); - self.ui.set_focus(Some(self.pane.id)); + let Some(mut saved @ Panes::Split { .. }) = saved.keep(&|place| library(place).is_some()) + else { + return Ok(()); + }; + saved.focus_one(); + let focused = saved.focused().clone(); + let shown = library(&focused).ok_or("The focused pane's notebook closed")?; + self.split = self.restored(saved)?; + // The section the launch opened shows its page, or stays as it is where that is gone. + let open = + (self.session.as_ref()).filter(|session| session.key() == shown.key(&focused.section)); + match open { + Some(session) => { + if self.pane.showing.space != focused.page + && session.pages.iter().any(|(page, ..)| *page == focused.page) + { + self.commands.push(Command::OpenPage(focused.page)); + } + } + None => self.open_section(shown, focused.section, Some(focused.page))?, + } Ok(()) } + /// The part `saved` restores: the focused pane where `saved` focuses, and a pane at bare + /// paper waiting to open anywhere else. + fn restored(&mut self, saved: Panes) -> Result> { + Ok(match saved { + Panes::Pane { focused: true, .. } => Split::Leaf(self.pane.id), + Panes::Pane { place, .. } => { + let pane = self.new_pane(Showing::default(), None)?; + let id = pane.id; + self.parked.push(Parked { + pane, + section: None, + }); + self.reopening.push((id, place)); + Split::Leaf(id) + } + Panes::Split { down, ratio, a, b } => Split::Pair { + axis: if down { Axis::Y } else { Axis::X }, + ratio: ratio.clamp(0.05, 0.95), + a: Box::new(self.restored(*a)?), + b: Box::new(self.restored(*b)?), + }, + }) + } + + /// Leaves the parked panes on `library`, a notebook whose folder is renamed, waiting at + /// their places to open again from where it goes, their sections closed meanwhile as + /// those hold files in the folder. + pub(crate) fn wait_out_rename(&mut self, library: &Arc) { + let ours = |shown: &Library| shown.location == library.location; + let waiting: Vec<_> = (self.parked.iter()) + .filter_map(|parked| { + let key = parked.section.as_ref()?; + let session = self.sessions().find(|session| session.key() == *key)?; + ours(&session.library).then(|| { + let place = Place { + notebook: library.location.clone(), + section: session.tabs[session.tab].path.clone(), + page: parked.pane.showing.space, + }; + (parked.pane.id, place) + }) + }) + .collect(); + self.reopening.extend(waiting); + self.leave_sections(|session| ours(&session.library), |_, _| {}); + self.close_parked(|Parked { pane, .. }| { + pane.sectionless.as_deref().is_some_and(ours) + || (pane.locked.as_ref()).is_some_and(|locked| ours(&locked.library)) + }); + } + + /// Whether pane `id` is one with nothing to show yet: no section, locked section or + /// sectionless notebook. + fn blank(&self, id: Id) -> bool { + let blank = |pane: &Pane| pane.sectionless.is_none() && pane.locked.is_none(); + if id == self.pane.id { + return self.session.is_none() && blank(&self.pane); + } + (self.parked.iter()) + .any(|parked| parked.pane.id == id && parked.section.is_none() && blank(&parked.pane)) + } + + /// Where pane `id` waits to open, if it does. + pub(crate) fn waiting(&self, id: Id) -> Option<&Place> { + (self.reopening.iter()) + .find(|(waiting, _)| *waiting == id) + .map(|(_, place)| place) + } + + /// Opens the next pane waiting to, the focused one first, once no pane has a page on its + /// way, so a section two of them show opens once and in the background; a notebook being + /// renamed keeps its panes waiting. A pane waits until its page arrives, or it closes. + pub(crate) fn reopen_next(&mut self) { + let blank: Vec = (self.reopening.iter()) + .map(|(id, _)| *id) + .filter(|id| self.blank(*id)) + .collect(); + self.reopening.retain(|(id, _)| blank.contains(id)); + if !self.still() || !self.commands.is_empty() { + return; + } + let renaming = |place: &Place| { + (self.folder_rename.as_ref()).is_some_and(|(from, _)| *from == place.notebook) + }; + let ready = |(_, place): &&(Id, Place)| !renaming(place); + let next = (self.reopening.iter().filter(ready)) + .find(|(id, _)| *id == self.pane.id) + .or(self.reopening.iter().find(ready)) + .cloned(); + let Some((id, place)) = next else { + return; + }; + let library = (self.notebooks.iter()) + .find(|library| library.location == place.notebook) + .cloned(); + let Some(library) = library else { + self.reopening.retain(|(waiting, _)| *waiting != id); + if let Err(error) = self.close_pane(id) { + eprintln!("{error}"); + } + return; + }; + // Its own page, which the section's last page stays apart from. + let open = |state: &mut State| state.open_section(library, place.section, Some(place.page)); + let opened = match self.parked.iter().position(|parked| parked.pane.id == id) { + Some(at) => self.in_pane(at, open), + None => open(self), + }; + if let Err(error) = &opened { + eprintln!("{error}"); + } + // A pane whose open never started waits no more. + let pane = std::iter::once(&self.pane) + .chain(self.parked.iter().map(|parked| &parked.pane)) + .find(|pane| pane.id == id); + let idle = pane.is_some_and(|pane| pane.switching.is_none() && pane.opening.is_none()); + if idle && self.blank(id) { + self.reopening.retain(|(waiting, _)| *waiting != id); + if let Err(error) = self.close_pane(id) { + eprintln!("{error}"); + } + } + } + /// Closes pane `id`, its room going to the part beside it; the first pane there takes the /// focus where the pane closed had it. The only pane stays. pub(crate) fn close_pane(&mut self, id: Id) -> Result<(), Box> { @@ -565,6 +799,7 @@ impl State { { self.release(session); } + self.save_settings(); Ok(()) } @@ -651,14 +886,18 @@ impl State { theme: &Theme, ) -> Result> { let parked = (self.parked.iter()).position(|parked| parked.pane.id == id); - let (section, page) = match parked { - Some(at) => { + let (section, page) = match (parked, self.waiting(id)) { + (_, Some(place)) => { + let name = crate::protection::section_name(&place.section); + (name.to_owned(), String::new()) + } + (Some(at), None) => { let parked = &self.parked[at]; let key = parked.section.as_ref(); let session = self.sessions().find(|session| Some(&session.key()) == key); label(&parked.pane, session) } - None => label(&self.pane, self.session.as_ref()), + (None, None) => label(&self.pane, self.session.as_ref()), }; let leaf = self.ui.open( part, @@ -670,9 +909,15 @@ impl State { }, ); if let Some(node) = self.ui.access(leaf) { - node.set_label(format!("{section}, {page}")); + node.set_label(match page.is_empty() { + true => section.clone(), + false => format!("{section}, {page}"), + }); } - let header = format!("{section} · {page}"); + let header = match page.is_empty() { + true => section.clone(), + false => format!("{section} · {page}"), + }; // The focused pane's header wears its section's accent, which the strip's colour // stands clear of in either appearance. let focused = parked.is_none(); diff --git a/crates/snowbound/tests/replay.rs b/crates/snowbound/tests/replay.rs index 4a64900aff6c2e2023390fafcea524ce2d9a837d..89d1db5638bdbf547a78d0047dba74f2c40e8f19 100644 --- a/crates/snowbound/tests/replay.rs +++ b/crates/snowbound/tests/replay.rs @@ -50,7 +50,11 @@ fn replay_with( std::fs::copy(entry.path(), dir.join("notebook").join(entry.file_name())).unwrap(); } } - let mut script = String::from("settle\n"); + // Steps start once the window settles, unless the first asks to start at launch. + let (mut script, steps) = match steps.split_first() { + Some((&"launching", rest)) => (String::new(), rest), + _ => (String::from("settle\n"), steps), + }; let mut trees = Vec::new(); for step in steps { match step.strip_prefix("accessibility ") { @@ -79,7 +83,9 @@ fn replay_with( if dir.join("settings.json").exists() { command.args(["--settings".as_ref(), dir.join("settings.json").as_os_str()]); } - let status = command.status().unwrap(); + // What the app logs, alerts included, which a hidden window shows no one. + let log = std::fs::File::create(dir.join("log")).unwrap(); + let status = command.stderr(log).status().unwrap(); assert!(status.success(), "the replay ended with {status}"); trees .iter() @@ -1786,3 +1792,312 @@ fn closing_split_panes_leaves_the_window_as_it_was() { after.display() ); } + +/// A layout of panes as the settings keep it, on pages of `notebook`'s sections: a pane on +/// the first, then a part below it, the second above the third. A page of `None` is gone. +fn layout(notebook: &Path, panes: [(&str, Option<&str>); 3]) -> serde_json::Value { + let gone = "{00000000-0000-0000-0000-000000000001},1"; + let pane = |(section, page): (&str, Option<&str>), focused| { + serde_json::json!({"pane": { + "place": {"notebook": notebook, "section": section, "page": page.unwrap_or(gone)}, + "focused": focused, + }}) + }; + let split = + |down, a, b| serde_json::json!({"split": {"down": down, "ratio": 0.5, "a": a, "b": b}}); + split( + false, + pane(panes[0], true), + split(true, pane(panes[1], false), pane(panes[2], false)), + ) +} + +/// Split panes kept in the settings split the page area again at the next launch, the +/// focused pane where it was. +#[test] +fn split_panes_return_at_the_next_launch() { + let scratch = Scratch::new("split-saved"); + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let saved = scratch.0.join("saved.json"); + let steps = [ + "split right".to_owned(), + "settle".into(), + // The Kitchen tab, which opens in the pane split off. + "move 175 51".into(), + "press".into(), + "release".into(), + "settle".into(), + format!("settings {}", saved.display()), + ]; + let steps: Vec<_> = steps.iter().map(String::as_str).collect(); + replay(&scratch, Some(¬ebook), &steps); + std::fs::copy(&saved, scratch.0.join("settings.json")).unwrap(); + let [tree] = replay(&scratch, None, &["accessibility tree"]) + .try_into() + .unwrap(); + assert_eq!( + pane_groups(&tree), + [ + r#" Group "Garden, Spring planting plan""#, + r#" Group "Kitchen, Sunday focaccia""# + ], + "{tree}" + ); + assert_eq!( + line(&tree, "Window"), + r#"Window "Sunday focaccia · Kitchen.one""# + ); +} + +/// A saved pane on a section since deleted is left out, its room going to the pane beside it, +/// and a pane on a page since deleted shows its section's first. +#[test] +fn a_saved_pane_on_a_deleted_section_is_left_out() { + let scratch = Scratch::new("split-deleted"); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let notebook = scratch.0.join("notebook"); + copy_notebook(&source, ¬ebook); + std::fs::remove_file(notebook.join("Journal.one")).unwrap(); + let panes = layout( + ¬ebook, + [ + ( + "Garden.one", + Some("{CF235667-138A-4E5D-B628-782140F5576D},1"), + ), + ("Kitchen.one", None), + ("Journal.one", None), + ], + ); + let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes}); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + let [tree] = replay(&scratch, None, &["accessibility tree"]) + .try_into() + .unwrap(); + assert_eq!( + pane_groups(&tree), + [ + r#" Group "Garden, Spring planting plan""#, + r#" Group "Kitchen, Sunday focaccia""# + ], + "{tree}" + ); + assert_eq!( + line(&tree, "Window"), + r#"Window "Spring planting plan · Garden.one""# + ); +} + +/// Saved panes in a notebook no longer open are left out; one pane left splits nothing. +#[test] +fn saved_panes_in_a_closed_notebook_are_left_out() { + let scratch = Scratch::new("split-closed"); + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let closed = scratch.0.join("closed"); + let mut panes = layout( + &closed, + [ + ("Garden.one", None), + ("Kitchen.one", None), + ("Trips.one", None), + ], + ); + // The first pane, in the notebook open. + panes["split"]["a"]["pane"]["place"]["notebook"] = + scratch.0.join("notebook").display().to_string().into(); + let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes}); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + let [tree] = replay(&scratch, Some(¬ebook), &["accessibility tree"]) + .try_into() + .unwrap(); + // One pane holds the page's own group alone. + assert_eq!(pane_groups(&tree), [r#" Group "Page""#], "{tree}"); +} + +/// Split panes on one page come back with the focus on the pane that had it. +#[test] +fn split_panes_on_one_page_return_with_the_focus_where_it_was() { + let scratch = Scratch::new("split-twins"); + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let saved = scratch.0.join("saved.json"); + let steps = [ + "split right".to_owned(), + "settle".into(), + format!("settings {}", saved.display()), + ]; + let steps: Vec<_> = steps.iter().map(String::as_str).collect(); + replay(&scratch, Some(¬ebook), &steps); + std::fs::copy(&saved, scratch.0.join("settings.json")).unwrap(); + let [tree] = replay(&scratch, None, &["accessibility tree"]) + .try_into() + .unwrap(); + let lines: Vec<&str> = tree.lines().collect(); + let groups: Vec = (lines.iter().enumerate()) + .filter(|(_, line)| line.starts_with(" Group \"Garden")) + .map(|(at, _)| at) + .collect(); + let page = lines.iter().position(|line| *line == r#" Group "Page""#); + assert!( + groups.len() == 2 && page.is_some_and(|page| page > groups[1]), + "the second pane has the focus:\n{tree}" + ); +} + +/// Renaming a notebook's folder while split keeps every pane on it, each back on its page. +#[test] +fn renaming_a_notebook_keeps_its_split_panes() { + let scratch = Scratch::new("split-rename"); + let notebook = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"); + let settings = r#"{"user_name": "Snowbound Test", "sidebar": true}"#; + std::fs::write(scratch.0.join("settings.json"), settings).unwrap(); + let steps = [ + "split right", + "settle", + // A double click on the notebook's row renames its folder. + "move 60 76", + "press", + "release", + "press", + "release", + "settle", + "type Projects", + "key Enter", + "settle", + "wait 1000", + "settle", + "accessibility renamed", + ]; + let [renamed] = replay(&scratch, Some(¬ebook), &steps) + .try_into() + .unwrap(); + assert!(scratch.0.join("Projects").is_dir(), "{renamed}"); + assert_eq!( + pane_groups(&renamed), + [ + r#" Group "Cross, Delete into a table""#, + r#" Group "Cross, Delete into a table""# + ], + "{renamed}" + ); +} + +/// The sections of the panes `settings`, as JSON, keeps, in order, each with whether it has +/// the focus. +fn saved_panes(settings: &Path) -> Vec<(String, bool)> { + fn leaves(panes: &serde_json::Value, out: &mut Vec<(String, bool)>) { + match (panes.get("pane"), panes.get("split")) { + (Some(pane), _) => out.push(( + pane["place"]["section"] + .as_str() + .unwrap_or_default() + .to_owned(), + pane["focused"].as_bool().unwrap_or_default(), + )), + (None, Some(split)) => { + leaves(&split["a"], out); + leaves(&split["b"], out); + } + (None, None) => {} + } + } + let settings: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(settings).unwrap()).unwrap(); + let mut out = Vec::new(); + leaves(&settings["panes"], &mut out); + out +} + +/// The alerts the scratch's last replay showed. +fn alerts(scratch: &Scratch) -> Vec { + (std::fs::read_to_string(scratch.0.join("log")) + .unwrap() + .lines()) + .filter(|line| line.starts_with("Alert:")) + .map(str::to_owned) + .collect() +} + +/// Writes a layout of three panes, on Garden, then Kitchen above Reading, into the scratch's +/// settings, Garden focused. +fn three_panes(scratch: &Scratch) { + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + copy_notebook(¬ebook, &scratch.0.join("notebook")); + let panes = layout( + &scratch.0.join("notebook"), + [ + ("Garden.one", None), + ("Kitchen.one", None), + ("Reading.one", None), + ], + ); + let settings = serde_json::json!({"user_name": "Snowbound Test", "panes": panes}); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); +} + +/// A restored pane clicked before it opens opens at once, takes the focus, and keeps its +/// place in the layout. +#[test] +fn a_restored_pane_clicked_before_it_opens_opens_there() { + let scratch = Scratch::new("split-waiting-click"); + three_panes(&scratch); + let saved = scratch.0.join("saved.json"); + let steps = [ + "launching".to_owned(), + "wait 16".into(), + // The pane on Reading, below Kitchen's. + "move 600 600".into(), + "press".into(), + "release".into(), + "settle".into(), + "accessibility tree".into(), + format!("settings {}", saved.display()), + ]; + let steps: Vec<_> = steps.iter().map(String::as_str).collect(); + let [tree] = replay(&scratch, None, &steps).try_into().unwrap(); + assert!(alerts(&scratch).is_empty(), "{:?}", alerts(&scratch)); + assert_eq!( + pane_groups(&tree), + [ + r#" Group "Garden, Spring planting plan""#, + r#" Group "Kitchen, Sunday focaccia""#, + r#" Group "Reading, Reading now""# + ], + "{tree}" + ); + assert_eq!( + line(&tree, "Window"), + r#"Window "Reading now · Reading.one""# + ); + assert_eq!( + saved_panes(&saved), + [ + ("Garden.one".to_owned(), false), + ("Kitchen.one".to_owned(), false), + ("Reading.one".to_owned(), true) + ] + ); +} + +/// Settings saved while restored panes still open keep every pane at its place. +#[test] +fn settings_saved_while_panes_open_keep_them_all() { + let scratch = Scratch::new("split-saving-early"); + three_panes(&scratch); + let saved = scratch.0.join("saved.json"); + let steps = [ + "launching".to_owned(), + format!("settings {}", saved.display()), + ]; + let steps: Vec<_> = steps.iter().map(String::as_str).collect(); + replay(&scratch, None, &steps); + assert!(alerts(&scratch).is_empty(), "{:?}", alerts(&scratch)); + assert_eq!( + saved_panes(&saved), + [ + ("Garden.one".to_owned(), true), + ("Kitchen.one".to_owned(), false), + ("Reading.one".to_owned(), false) + ] + ); +}