diff --git a/crates/snowbound/src/history.rs b/crates/snowbound/src/history.rs index f448ef400564a281bc0198c8dafa1302d997abef..33766a21b1e33f013128b8fd7e20a2978eeb017f 100644 --- a/crates/snowbound/src/history.rs +++ b/crates/snowbound/src/history.rs @@ -172,11 +172,10 @@ impl State { let operation = session .section .restore_version_async(page, version, &self.author); - self.section_edit(operation, move |state, _| { + self.section_edit(vec![page], operation, move |state, _| { if let Some(session) = &mut state.session { session.refresh_history(&mut state.pane.showing)?; } - state.edited(vec![page]); state.commands.push(Command::OpenPage(page)); Ok(()) }) @@ -191,7 +190,7 @@ impl State { let operation = session .section .delete_versions_async(&[(page, vec![version])]); - self.section_edit(operation, move |state, _| { + self.section_edit(Vec::new(), operation, move |state, _| { if let Some(session) = &mut state.session { session.refresh_history(&mut state.pane.showing)?; } @@ -244,6 +243,11 @@ impl State { }; let operation = clear(&session.section); let library = Arc::clone(&session.library); + // Sections parked panes show are open already, and cleared through their sessions. + let mut held: Vec<_> = (self.shelved.iter()) + .filter(|held| scope != Scope::Section && Arc::ptr_eq(&held.library, &library)) + .map(|held| (held.tabs[held.tab].path.clone(), clear(&held.section))) + .collect(); let proxy = self.proxy.clone(); let operation = async move { operation.await?; @@ -254,11 +258,18 @@ impl State { String::new() }; crate::spawn_async(move || async move { + let mut reached = Vec::new(); for path in sections(&library, &folder) { if path == open { continue; } + let at = held.iter().position(|(held, _)| *held == path); let cleared: Result<(), Box> = async { + if let Some(at) = at { + held.swap_remove(at).1.await?; + reached.push(library.key(&path)); + return Ok(()); + } let section = library.open_async(&path, notify(proxy.clone())).await?; clear(§ion).await?; Ok(section.close_async().await?) @@ -268,11 +279,17 @@ impl State { eprintln!("Deleting the versions in {path} failed: {error}"); } } + let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| { + for key in reached { + state.edited_sections(&key, Vec::new(), |shown| shown == key); + } + Ok(()) + }))); }); } Ok(()) }; - self.section_edit(operation, move |state, ()| { + self.section_edit(Vec::new(), operation, move |state, ()| { if let Some(session) = &mut state.session { session.refresh_history(&mut state.pane.showing)?; if state.pane.showing.version.is_some() { diff --git a/crates/snowbound/src/live.rs b/crates/snowbound/src/live.rs index 246a2ef876da85f53ce339103e680ce782006a00..670d8aae1543232ef0662afa954a117402d62581 100644 --- a/crates/snowbound/src/live.rs +++ b/crates/snowbound/src/live.rs @@ -464,11 +464,9 @@ impl State { if let Some(background) = joined.background.get().and_then(Weak::upgrade) { background.wake(); } - if let Some(session) = &self.session - && Arc::ptr_eq(&session.library, library) - { - session.section.wake(); - } + (self.session.iter().chain(&self.shelved)) + .filter(|session| Arc::ptr_eq(&session.library, library)) + .for_each(|session| session.section.wake()); } } } diff --git a/crates/snowbound/src/main.rs b/crates/snowbound/src/main.rs index ec68bd8e73c810857a71820190b03d1ed67379e9..7d111c284c6a98a3713734ce6fe5142382042fa3 100644 --- a/crates/snowbound/src/main.rs +++ b/crates/snowbound/src/main.rs @@ -79,6 +79,7 @@ mod sidebar; #[cfg_attr(windows, path = "spell_windows.rs")] #[cfg_attr(target_arch = "wasm32", path = "spell_web.rs")] mod spell; +mod split; #[cfg_attr(not(feature = "wgpu"), path = "surface_gl.rs")] #[cfg_attr(all(target_os = "macos", feature = "wgpu"), path = "surface_macos.rs")] #[cfg_attr(windows, path = "surface_windows.rs")] @@ -545,6 +546,8 @@ struct Pane { showing: Showing, /// The newest read requested; older ones are dropped when they finish. loading: u64, + /// Set when the section refuses an edit the pane stored, which the pane then tells of. + refused: Arc, opening: Option, /// The section tab, if another, that the newest read opens, and when it was asked for. switching: Option<(Option, Instant)>, @@ -718,6 +721,8 @@ enum Loaded { /// A section just created, whose name opens for renaming as OneNote's New Section does. Created(Box, ExGuid, Page), Page(ExGuid, Page), + /// A page of a section a parked pane holds open, by its notebook and catalog path. + Held(Arc, String, ExGuid, Page), /// A page's version, by the page's space and the version's context. Version(ExGuid, ExGuid, Page), /// A notebook read again after a change, at the section that stays open, if any. @@ -729,6 +734,7 @@ enum Shown { Section(Box, ExGuid), Created(Box, ExGuid), Page(ExGuid), + Held(Arc, String, ExGuid), Version(ExGuid, ExGuid), } @@ -754,6 +760,19 @@ struct Opening { /// How long an opening page waits for its pictures before showing without them. const HOLD: std::time::Duration = std::time::Duration::from_millis(200); +impl Pane { + /// The page opening here, once the pictures it shows first are drawn on `paper` or + /// `HOLD` has passed. + fn opened(&mut self, paper: canvas::gpu::Paper, redraw: &std::task::Waker) -> Option { + let opening = self.opening.as_mut()?; + let paper = paper.colored(opening.editor.page_color()); + let ready = (self.view).prepare(&mut opening.scene, &opening.editor, paper, redraw); + (ready || opening.since.elapsed() >= HOLD) + .then(|| self.opening.take()) + .flatten() + } +} + /// Work the interface asked for, done after the frame is built. enum Command { /// Opens a notebook's section by catalog path, at the page it showed last. @@ -877,12 +896,19 @@ struct State { /// Backends that failed to start this run, and why. unavailable: Vec<(settings::Backend, String)>, ui: Ui, - /// The page view the window shows. + /// The focused pane, which the chrome around the page area follows. pane: Pane, + parked: Vec, /// The open notebooks in the sidebar's order. notebooks: Vec>, - /// The open section, the one the pane shows. + /// The section the focused pane shows. session: Option, + /// The sections only parked panes show. + 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)>, /// 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. @@ -1378,6 +1404,7 @@ impl State { ), showing, loading: 0, + refused: Arc::default(), opening: None, switching: None, trail: navigation::Trail::default(), @@ -1386,8 +1413,12 @@ impl State { sectionless, locked, }, + parked: Vec::new(), notebooks, session, + shelved: Vec::new(), + requests: 0, + opening_files: Vec::new(), temporary, settings, cache, @@ -1607,10 +1638,7 @@ impl State { lap("drawn", start); self.sync_index(false, Vec::new()); let commands = std::mem::take(&mut self.commands); - let follow = !commands.is_empty() - || self.ui.wants_frame() - || self.pane.opening.is_some() - || self.pane.switching.is_some(); + let follow = !commands.is_empty() || self.ui.wants_frame() || !self.still(); for command in commands { self.apply(command)?; } @@ -3630,8 +3658,37 @@ impl State { _ => 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 leaves it to this one. + let opening = (self.opening_files.iter()) + .find(|(_, opening)| *opening == key) + .map(|(request, _)| *request); + if opening == Some(self.pane.loading) { + return Ok(()); + } + let asked = + (self.parked.iter()).position(|parked| Some(parked.pane.loading) == opening); + if let Some(at) = asked { + let fresh = self.request(); + let pane = &mut self.parked[at].pane; + let (request, opened) = (pane.loading, pane.opening.take()); + (pane.loading, pane.switching) = (fresh, None); + (self.pane.loading, self.pane.opening) = (request, opened); + return Ok(()); + } let notify = notify(self.proxy.clone()); - let last = self.last_pages.get(&library.key(&path)).copied(); self.load_async(move || async move { let start = Instant::now(); let section = library.open_async(&path, notify).await?; @@ -3639,6 +3696,7 @@ impl State { 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::OpenPage(space) => { let session = self.session.as_ref().ok_or("No section is open")?; @@ -3666,7 +3724,7 @@ impl State { Command::DeleteVersion { page, version } => { let session = self.session.as_mut().ok_or("No section is open")?; let operation = session.section.delete_pages_async(&[version]); - self.section_edit(operation, move |state, _| { + self.section_edit(Vec::new(), operation, move |state, _| { if let Some(session) = &mut state.session { session.refresh_conflicts(&mut state.pane.showing)?; } @@ -3682,13 +3740,16 @@ impl State { } _ => session.section.page(version)?, }; + let key = session.library.key(&session.tabs[tab].path); if tab == session.tab { let operation = session.section.import_page_async(&page, &self.author); - self.section_edit(operation, |state, _| { - if let Some(session) = &mut state.session { - session.pages = session.section.pages()?; - } - state.edited(Vec::new()); + self.section_edit(Vec::new(), operation, |_, _| Ok(()))?; + } else if let Some(held) = self.shelved.iter().find(|held| held.key() == key) { + // A section a parked pane shows is open already. + let operation = held.section.import_page_async(&page, &self.author); + self.complete_async(operation, move |state, copied| { + copied?; + state.edited_sections(&key, Vec::new(), |shown| shown == key); Ok(()) })?; } else { @@ -3746,10 +3807,7 @@ impl State { self.restructure(library, change); } // The index follows the section's page list. - Command::NewPage { under, title } => { - self.new_page(under, &title)?; - self.edited(Vec::new()); - } + Command::NewPage { under, title } => self.new_page(under, &title)?, Command::DeletePages(pages) => { self.delete_pages(pages)?; self.edited(Vec::new()); @@ -3788,7 +3846,7 @@ impl State { &mut self, read: impl FnOnce() -> F + Send + 'static, ) { - self.pane.loading += 1; + self.pane.loading = self.request(); let (id, sender, redraw) = (self.pane.loading, self.loads.0.clone(), self.redraw.clone()); let layouts = Arc::clone(&self.layouts); let requested = Instant::now(); @@ -3801,6 +3859,9 @@ impl State { Loaded::Section(session, space, page) => (Shown::Section(session, space), page), Loaded::Created(session, space, page) => (Shown::Created(session, space), page), Loaded::Page(space, page) => (Shown::Page(space), page), + Loaded::Held(library, path, space, page) => { + (Shown::Held(library, path, space), page) + } Loaded::Version(space, version, page) => (Shown::Version(space, version), page), Loaded::Library(library, path) => return Ok(Laid::Library(library, path)), }; @@ -3811,6 +3872,7 @@ impl State { Some((session.key(), *space)) } Shown::Page(space) => open.map(|open| (open, *space)), + Shown::Held(library, path, space) => Some((library.key(path), *space)), Shown::Version(..) => None, }; // A page shown or prepared lately keeps the pictures it drew. @@ -3857,17 +3919,22 @@ impl State { } } + /// Does `operation`, an edit of the open section's pages `spaces` or its list without + /// any, then shows it in every pane on the section and runs `then` if that is still the + /// open one. fn section_edit< T: Send + 'static, F: Future> + Send + 'static, >( &mut self, + spaces: Vec, operation: F, then: impl FnOnce(&mut State, T) -> Result<(), Box> + Send + 'static, ) -> Result<(), Box> { let key = self.session.as_ref().ok_or("No section is open")?.key(); self.complete_async(operation, move |state, result| { let value = result?; + state.edited_sections(&key, spaces, |shown| shown == key); if state .session .as_ref() @@ -3880,19 +3947,28 @@ impl State { }) } - /// Shows the newest page read once the pictures it shows first are drawn, or after - /// `HOLD`. + /// Shows the newest page each pane read once the pictures it shows first are drawn, or + /// after `HOLD`. 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 parked = (self.parked.iter()).position(|parked| parked.pane.loading == id); + let pane = match parked { + Some(at) => &mut self.parked[at].pane, + None => &mut self.pane, + }; match loaded { // A later load supersedes what this one shows, but not its failure. - Ok(_) if id != self.pane.loading => {} - Ok(Laid::Page(opening)) => self.pane.opening = Some(*opening), - Ok(Laid::Library(library, path)) => self.adopt(library, path.as_deref())?, + Ok(_) if id != pane.loading => {} + Ok(Laid::Page(opening)) => pane.opening = Some(*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 == self.pane.loading { - self.pane.switching = None; + if id == pane.loading { + pane.switching = None; } platform::alert("Couldn't open", &error); } @@ -3903,25 +3979,27 @@ impl State { ink: self.ui.theme.paper_ink, }; self.prefetch.draw(&self.pane.view, paper, &self.redraw); - let Some(mut opening) = self.pane.opening.take() else { - return Ok(()); - }; - let paper = paper.colored(opening.editor.page_color()); - if !self - .pane - .view - .prepare(&mut opening.scene, &opening.editor, paper, &self.redraw) - && opening.since.elapsed() < HOLD - { - self.pane.opening = Some(opening); - return Ok(()); + for at in 0..self.parked.len() { + if let Some(opening) = self.parked[at].pane.opened(paper, &self.redraw) { + self.in_pane(at, |state| state.show_page(opening))?; + } } + let Some(opening) = self.pane.opened(paper, &self.redraw) else { + return Ok(()); + }; lap("switch pictures", opening.since); self.show_page(opening) } fn show_page(&mut self, mut opening: Opening) -> Result<(), Box> { let requested = opening.requested; + 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), + // The panes holding it closed meanwhile, and the section went with them. + None => return self.apply(Command::OpenSection(library, path)), + } + } if let Shown::Section(session, _) | Shown::Created(session, _) = &mut opening.loaded && let Some(library) = self .notebooks @@ -3955,10 +4033,14 @@ impl State { self.stop_recording(true)?; // The page shown so far keeps what was typed while the next one loaded. self.persist()?; + // A page another pane still shows keeps that pane's history. let mut leaving = self .session .as_ref() - .filter(|session| !session.read_only(&self.pane.showing)) + .filter(|session| { + !session.read_only(&self.pane.showing) + && !self.shown_parked(&session.key(), self.pane.showing.space) + }) .map(|_| self.pane.showing.space); if let Some(session) = &self.session { let key = session.key(); @@ -3985,7 +4067,8 @@ impl State { // The section left stays open a while for coming back to; the notebook's // background sync takes it over once it is closed. self.pane.locked = None; - if let Some(previous) = self.session.replace(*session) { + let previous = self.session.replace(*session); + if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) { let path = &previous.tabs[previous.tab].path; let locked = self.leave(&previous.library, path); let library = &previous.library; @@ -4009,6 +4092,7 @@ impl State { self.save_settings(); } } + Shown::Held(..) => unreachable!("A held section is taken off the shelf"), Shown::Page(space) | Shown::Version(space, _) => { let session = self.session.as_mut().ok_or("No section is open")?; let pages = session.section.pages()?; @@ -4080,6 +4164,12 @@ impl State { self.list(&library); let shown = |shown: &Library| shown.location == library.location; let Some(path) = path else { + if library.first_section().is_none() { + self.leave_sections( + |session| shown(&session.library), + |_, pane| pane.sectionless = Some(Arc::clone(&library)), + ); + } if self.pane.sectionless.as_deref().is_some_and(shown) || self .session @@ -4106,7 +4196,12 @@ impl State { if !shown(&session.library) { return Ok(()); } + let old = Some(session.key()); session.follow(library, path)?; + let new = Some(session.key()); + for parked in (self.parked.iter_mut()).filter(|parked| parked.section == old) { + parked.section.clone_from(&new); + } self.title(); self.save_settings(); Ok(()) @@ -4119,6 +4214,7 @@ impl State { Some(open) => *open = Arc::clone(library), None => self.notebooks.push(Arc::clone(library)), } + self.follow_shelved(library); if library.in_icloud() && library.downloading() { self.fetch(Arc::clone(library), None); } @@ -4308,21 +4404,17 @@ impl State { Ok(()) } - /// Publishes the open section's stored edits now, rather than after a pause in typing, - /// and waits up to `wait` for them to reach the file. + /// Publishes the open sections' stored edits now, rather than after a pause in typing, + /// and waits up to `wait` for them to reach their files. fn publish_now(&self, wait: std::time::Duration) { - let Some(session) = &self.session else { - return; - }; let deadline = Instant::now() + wait; loop { - session.section.wake(); - if Instant::now() >= deadline - || session - .section - .pending() - .is_ok_and(|pending| pending.is_empty()) - { + let mut pending = false; + for session in self.sessions() { + session.section.wake(); + pending |= !(session.section.pending()).is_ok_and(|pending| pending.is_empty()); + } + if !pending || Instant::now() >= deadline { return; } std::thread::sleep(std::time::Duration::from_millis(50)); @@ -4348,16 +4440,14 @@ impl State { return Ok(()); } let space = self.pane.showing.space; - session.section.apply( - &self.author, - onestore::op::Edit { - at: filetime(), - ops: ops - .into_iter() - .map(|op| onestore::op::Op::Page { space, op }) - .collect(), - }, + self.store( + ops.into_iter() + .map(|op| onestore::op::Op::Page { space, op }) + .collect(), )?; + let Some(session) = &mut self.session else { + return Ok(()); + }; // The page list shows the title as it is typed, even when the caret left it since. let editor = &self.pane.view.editor; let title = (editor.outlines().iter()) @@ -4371,13 +4461,39 @@ impl State { { session.pages = session.section.pages()?; } - self.edited(vec![space]); let editor = &self.pane.view.editor; self.undo .edited(space, editor.history_depth(), editor.typing().is_some()); Ok(()) } + /// Stores `ops` in the open section as one edit, as every edit made here is stored, and + /// shows it in the other panes on the pages it changed. + fn store(&mut self, ops: Vec) -> Result<(), Box> { + let session = self.session.as_ref().ok_or("No section is open")?; + let mut spaces: Vec = (ops.iter()) + .filter_map(|op| match op { + onestore::op::Op::Page { space, .. } => Some(*space), + _ => None, + }) + .collect(); + spaces.dedup(); + let edit = onestore::op::Edit { + at: filetime(), + ops, + }; + let refused = Arc::clone(&self.pane.refused); + session + .section + .apply_with(&self.author, edit, move |result| { + if let Err(notebook::Error::Rejected(_)) = result { + refused.store(true, Ordering::Release); + } + })?; + self.edited(spaces); + Ok(()) + } + /// Shows the page as stored after a change made elsewhere, in place: the caret, /// selection, scroll and drawn pictures stay. Waits for marked text to end. fn refresh(&mut self) -> Result<(), Box> { @@ -4390,7 +4506,11 @@ impl State { let Some(session) = &self.session else { return Ok(()); }; - let page = session.reader(self.pane.showing.space)()?; + let (space, version) = (self.pane.showing.space, self.pane.showing.version); + let page = match version { + Some(version) => session.version_reader(space, version)()?, + None => session.reader(space)()?, + }; let response = self.pane.view.refresh(page)?; self.respond(response); self.title(); @@ -4409,7 +4529,10 @@ impl State { .view .editor .cancel_composition(&mut self.pane.view.engine)?; - platform::clear_marked_text(&self.window); + // The input method's marked text is the page's with the keyboard, if any. + if self.pane.page_focused { + platform::clear_marked_text(&self.window); + } self.refresh()?; platform::alert( "Change not saved", @@ -4418,7 +4541,7 @@ impl State { Ok(()) } - /// Applies what the section, and each notebook's closed sections, reported since the + /// Applies what the open sections, and each notebook's closed ones, reported since the /// last poll. fn synced(&mut self) -> Result<(), Box> { self.wear_theme(false)?; @@ -4457,87 +4580,7 @@ impl State { } // Reports are rare: a status changed, or a section did. self.window.request_redraw(); - let Some(session) = &mut self.session else { - return Ok(()); - }; - let mut listed = false; - let mut changed = false; - let mut rejected = None; - let mut elsewhere = Vec::new(); - for event in session.section.events() { - use notebook::session::Event; - match event { - Event::Changed(spaces) => { - listed = true; - changed |= spaces.contains(&self.pane.showing.space); - elsewhere.extend_from_slice(&spaces); - self.search - .changed(session.key(), session.section.replica(), spaces); - } - Event::Rejected { spaces, error } => { - if spaces.contains(&self.pane.showing.space) { - rejected = Some(error); - } else { - eprintln!("Saving failed: {error}"); - } - } - Event::Failed(error) => eprintln!("Not saving: {error}"), - // Its guests hear of it sooner than the folder's watch would tell them. - #[cfg(feature = "live")] - Event::Attempt { - status: notebook::EditStatus::Published { .. }, - .. - } => { - if let Some(host) = self.peers.hosts.get(&session.library.location) { - host.touched(&[session.tabs[session.tab].path.clone()]); - } - } - Event::Attempt { .. } | Event::Unreachable(_) => {} - } - } - session.sync = session.section.sync_status()?; - if !elsewhere.is_empty() { - self.changed_elsewhere(&elsewhere); - } - let Some(session) = &mut self.session else { - return Ok(()); - }; - if listed { - let back = self.pane.showing.shown; - session.pages = session.section.pages()?; - session.refresh_conflicts(&mut self.pane.showing)?; - session.refresh_history(&mut self.pane.showing)?; - let listed = |space: ExGuid| session.pages.iter().any(|(page, ..)| *page == space); - let gone = self.pane.showing.version.is_some_and(|version| { - !session - .page_versions(self.pane.showing.space) - .iter() - .any(|listed| listed.context == version) - }); - if gone && listed(self.pane.showing.space) { - // A version deleted elsewhere returns to its page. - self.commands - .push(Command::OpenPage(self.pane.showing.space)); - return Ok(()); - } - if !listed(self.pane.showing.space) - && session.conflict(self.pane.showing.space).is_none() - { - // A page removed elsewhere, or a conflict page deleted elsewhere, which - // returns to its page. - let open = back - .filter(|page| listed(*page)) - .or(session.pages.first().map(|(page, ..)| *page)) - .ok_or("The section has no pages")?; - self.commands.push(Command::OpenPage(open)); - return Ok(()); - } - } - if let Some(error) = rejected { - self.refused(&error)?; - } else if changed { - self.refresh()?; - } + self.hear_sections(); Ok(()) } @@ -6554,7 +6597,7 @@ impl State { // Quiet still when the mark sent on finding it quiet arrives, what a thread sent // as it ended has been taken, however many frames wait in the queue before it. let quiet = self.settled() - && self.pane.opening.is_none() + && self.still() && RUNNING.load(Ordering::Acquire) == 0 && self.search.pending.load(Ordering::Relaxed) == 0; if let Some((path, settled, sent)) = self.replay_settle.take() { @@ -6914,9 +6957,11 @@ impl ApplicationHandler for App { let deadline = Instant::now() + QUIT; state.publish_now(QUIT); self.restart = state.updates.restarting(); - let session = state.session.take(); + let sessions: Vec<_> = (state.session.take().into_iter()) + .chain(state.shelved.drain(..)) + .collect(); let libraries: Vec<_> = (state.notebooks.iter()) - .chain(session.as_ref().map(|session| &session.library)) + .chain(sessions.iter().map(|session| &session.library)) .cloned() .collect(); // Dropped sections and backgrounds stop without waiting, so the process could end first. @@ -6929,10 +6974,10 @@ impl ApplicationHandler for App { { background.stop(); } - if let Some(session) = session - && let Err(error) = session.section.close() - { - eprintln!("Synchronization stopped: {error}"); + for session in sessions { + if let Err(error) = session.section.close() { + eprintln!("Synchronization stopped: {error}"); + } } libraries.iter().for_each(|library| library.close_kept()); drop(closed); @@ -7585,6 +7630,106 @@ mod tests { notebook::fs::remove_dir_all(&directory).unwrap(); } + /// Each function of the app's sources outside tests: its file, its name, and its code + /// without whitespace, a line each. + fn functions() -> Vec<(String, String, Vec)> { + let mut functions = Vec::new(); + let sources = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + for entry in notebook::fs::read_dir(sources).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_none_or(|extension| extension != "rs") { + continue; + } + let file = path.file_name().unwrap().to_string_lossy().into_owned(); + // A module only tests build is a test's. + let declared = format!("mod {};", file.trim_end_matches(".rs")); + let main = include_str!("main.rs").lines().collect::>(); + if (main.windows(2)).any(|lines| { + lines[1] == declared && lines[0].starts_with("#[cfg(") && lines[0].contains("test") + }) { + continue; + } + let source = notebook::fs::read_to_string(&path).unwrap(); + let source = source.split("#[cfg(test)]\nmod tests").next().unwrap(); + for line in source.lines() { + let declared = line.strip_prefix(" ").unwrap_or(line); + let declared = (declared.strip_prefix("pub(crate) ")) + .or(declared.strip_prefix("pub ")) + .unwrap_or(declared); + let declared = declared.strip_prefix("async ").unwrap_or(declared); + if let Some(name) = declared.strip_prefix("fn ") { + let name = name.split(['(', '<']).next().unwrap_or(name); + functions.push((file.clone(), name.to_owned(), Vec::new())); + } + if let Some((.., code)) = functions.last_mut() { + code.push(line.split_whitespace().collect()); + } + } + } + functions + } + + /// The functions of `functions()`, as `file::name`, holding code with one of `does` but + /// none of `follows`, but those `excused` names. + fn unfollowed(does: &[&str], follows: &[&str], excused: &[&str]) -> Vec { + let holds = |code: &[String], parts: &[&str]| { + (code.iter()).any(|line| parts.iter().any(|part| line.contains(part))) + }; + (functions().into_iter()) + .map(|(file, name, code)| (format!("{file}::{name}"), code)) + .filter(|(named, code)| { + holds(code, does) && !holds(code, follows) && !excused.contains(&named.as_str()) + }) + .map(|(named, _)| named) + .collect() + } + + /// Every edit made here reaches the other panes on the pages it changed, as a section + /// reports no event for its own edits: a function writing to a section stores through + /// `State::store`, or follows the write with `edited`, `edited_sections` or `section_edit`, + /// or is one whose callers do. + #[test] + fn every_edit_made_here_reaches_the_other_panes() { + let writes = [ + ".section.apply(", + ".section.apply_with(", + "replica().apply(", + ".apply_async(", + "restore_version_async(", + "delete_pages_async(", + "import_page_async(", + "delete_versions_async(", + "retire_async(", + ]; + let follows = [".store(", ".edited(", ".edited_sections(", ".section_edit("]; + // Their callers follow them: `perform` the undo site's, `recycle_now` the bin's, and + // Delete All Versions the versions `clear` deletes. + let called = [ + "undo.rs::apply", + "undo.rs::change", + "recycle.rs::carry_out", + "history.rs::clear", + ]; + let unfollowed = unfollowed(&writes, &follows, &called); + assert!(unfollowed.is_empty(), "{unfollowed:#?}"); + } + + /// A section opens once, as its replica is `locking_mode=EXCLUSIVE`: a function opening + /// one from its file first looks for it among those panes hold. + #[test] + fn a_section_a_pane_holds_never_opens_again() { + let opens = [ + "library.open_async(", + "library.open(", + ".library.open_async(", + ]; + let looks = [".held", "held:", "held_page(", "shelved", ".sessions()"]; + // Launch opens a section before any pane is parked, and a new notebook's is new. + let first = ["main.rs::new", "manage.rs::create_notebook"]; + let unfollowed = unfollowed(&opens, &looks, &first); + assert!(unfollowed.is_empty(), "{unfollowed:#?}"); + } + /// Times opening each section of a notebook and each of its pages, phase by phase, as a /// switch does: `SNOWBOUND_SWITCH_NOTEBOOK=FOLDER`, or a share through `ONESTORE_SMB_LAB` /// (`HOST:PORT`, share `agent`) at `ONESTORE_SMB_LAB_ROOT` with `ONESTORE_SMB_LAB_USER` diff --git a/crates/snowbound/src/manage.rs b/crates/snowbound/src/manage.rs index d9590fa96d38c22021cea1a44d43b96316644cca..b3b5fff55da94c338f61f2d24e4f5c994118557d 100644 --- a/crates/snowbound/src/manage.rs +++ b/crates/snowbound/src/manage.rs @@ -6,7 +6,7 @@ use canvas::template::Template; use notebook::session::Notebook; use onestore::{ ExGuid, PageCreation, PageEdit, - op::{Edit, Op, PageOp, SectionOp}, + op::{Op, PageOp, SectionOp}, page::{Image, Page, PageObject}, }; use std::{error::Error, path::Path, sync::Arc}; @@ -218,16 +218,19 @@ impl State { space, before, level, )?]))); } - let session = self.session.as_ref().ok_or("No section is open")?; - let edit = Edit { - at: crate::filetime(), - ops, - }; // A section being rebuilt answers reads from before the page was made. #[cfg(not(target_arch = "wasm32"))] - session.section.replica().apply(&self.author, edit)?; + { + let session = self.session.as_ref().ok_or("No section is open")?; + let edit = onestore::op::Edit { + at: crate::filetime(), + ops, + }; + session.section.replica().apply(&self.author, edit)?; + self.edited(Vec::new()); + } #[cfg(target_arch = "wasm32")] - session.section.apply(&self.author, edit)?; + self.store(ops)?; let shown = self.pane.showing.space; self.made(Change::Delete { pages: vec![space], @@ -319,16 +322,8 @@ impl State { if ops.is_empty() { return Ok(()); } - let session = self.session.as_ref().ok_or("No section is open")?; let space = self.pane.showing.space; - session.section.apply( - &self.author, - Edit { - at: crate::filetime(), - ops: ops.into_iter().map(|op| Op::Page { space, op }).collect(), - }, - )?; - self.edited(vec![space]); + self.store(ops.into_iter().map(|op| Op::Page { space, op }).collect())?; self.refresh() } @@ -579,8 +574,8 @@ impl State { } /// Closes the notebooks in iCloud Drive once its account signs out or changes: their - /// folders go with the account. Replicas holding edits stay, the open section's also - /// exported as a recovery archive; signing in again and reopening publishes them. + /// folders go with the account. Replicas holding edits stay, the open sections' also + /// exported as recovery archives; signing in again and reopening publishes them. pub(crate) fn icloud_account_changed(&mut self) { let closing: Vec> = self .notebooks @@ -588,16 +583,18 @@ impl State { .filter(|library| library.in_icloud()) .cloned() .collect(); - if let Some(session) = &self.session - && session.library.in_icloud() - && session - .section - .pending() - .is_ok_and(|pending| !pending.is_empty()) - && let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery")) - { + let waiting = (self.sessions()).filter(|session| { + session.library.in_icloud() + && (session.section.pending()).is_ok_and(|pending| !pending.is_empty()) + }); + for session in waiting { + let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery")) + else { + break; + }; + let section = &session.tabs[session.tab].name; let archive = folder.join(format!( - "{}-{}.sqlite", + "{}-{section}-{}.sqlite", session.library.name, crate::filetime() )); @@ -617,6 +614,7 @@ impl State { /// Closes `library`: its files stay, its offline copies go unless edits wait in them, /// and the sidebar and the next launch leave it out. pub(crate) fn close_notebook(&mut self, library: &Arc) { + self.close_parked_in(library); self.notebooks.retain(|open| !Arc::ptr_eq(open, library)); self.undo.close(&library.location); if let Some(background) = &library.background { @@ -737,6 +735,8 @@ impl State { let Some(to) = library.renamed_location(&name) else { return; }; + // Their sections hold files in the folder. + self.close_parked_in(&library); let ours = |shown: &Arc| Arc::ptr_eq(shown, &library); let shown = self .session @@ -892,6 +892,13 @@ impl State { .as_ref() .filter(|session| Arc::ptr_eq(&session.library, &library)) .map(|session| session.tabs[session.tab].path.clone()); + let held: Vec<_> = (self.shelved.iter()) + .filter(|held| held.library.location == library.location) + .filter_map(|held| { + let identity = held.library.section_identity(&held.tabs[held.tab].path)?; + Some((identity, Arc::clone(held.section.replica()))) + }) + .collect(); let notify = notify(self.proxy.clone()); let (proxy, requested) = (self.proxy.clone(), self.pane.loading); let showing = self.pane.switching.is_none() && self.pane.opening.is_none(); @@ -1025,6 +1032,11 @@ impl State { if followed.as_deref() == Some(path.as_str()) { return Ok(Loaded::Library(library, Some(path))); } + // As does a section a parked pane shows. + let identity = library.section_identity(&path); + if let Some((_, replica)) = held.iter().find(|(held, _)| Some(*held) == identity) { + return crate::split::held_page(library, path, replica, None); + } let section = library.open_async(&path, notify).await?; let (session, space, page) = read_session(section, library, path, None)?; Ok(if fresh { @@ -1051,6 +1063,7 @@ impl State { Loaded::Section(session, ..) | Loaded::Created(session, ..) => { Arc::clone(&session.library) } + Loaded::Held(library, ..) => Arc::clone(library), _ => unreachable!("A structure change returns its notebook"), }; if !state @@ -1133,20 +1146,15 @@ impl State { /// Moves or indents pages of the open section, in order. pub(crate) fn edit_pages(&mut self, edits: Vec) -> Result<(), Box> { self.persist()?; - let session = self.session.as_mut().ok_or("No section is open")?; + let session = self.session.as_ref().ok_or("No section is open")?; let order = session .pages .iter() .map(|(space, _, level)| (*space, *level)) .collect(); let moved = edits.iter().map(PageEdit::space).collect(); - session.section.apply( - &self.author, - Edit { - at: crate::filetime(), - ops: vec![Op::Section(SectionOp::Pages(edits))], - }, - )?; + self.store(vec![Op::Section(SectionOp::Pages(edits))])?; + let session = self.session.as_mut().ok_or("No section is open")?; session.pages = session.section.pages()?; self.made(Change::Arrange { order, moved }); Ok(()) @@ -1206,6 +1214,7 @@ fn art_ops(page: &Page, art: Vec) -> Vec { #[cfg(test)] mod tests { use super::*; + use onestore::op::Edit; use std::path::Path; const AUTHOR: &str = "Rust Author"; diff --git a/crates/snowbound/src/prefetch.rs b/crates/snowbound/src/prefetch.rs index 377d26fb8bf243be1055cc7ded6bf3d91e8655be..a5d8d95969d7d87e9ec70b181e4f5aa8da477215 100644 --- a/crates/snowbound/src/prefetch.rs +++ b/crates/snowbound/src/prefetch.rs @@ -293,7 +293,7 @@ impl State { /// Leaves the page shown as it is, dropping whatever was opening in its place. pub fn stop_loading(&mut self) { - self.pane.loading += 1; + self.pane.loading = self.request(); self.pane.opening = None; self.pane.switching = None; } @@ -347,7 +347,11 @@ impl State { }; let path = session.tabs[tab].path.clone(); let key = session.library.key(&path); - if tab == session.tab || !self.prefetch.ask((key.clone(), None)) { + // A section a parked pane holds is open already. + if tab == session.tab + || self.shelved.iter().any(|held| held.key() == key) + || !self.prefetch.ask((key.clone(), None)) + { return; } let _ = self.prefetch.jobs.send(Job::Section { diff --git a/crates/snowbound/src/print.rs b/crates/snowbound/src/print.rs index 23c0c6e19e39185289ea33843242be9f12893825..e496b28fe0910a7b3bddcc58d7285a8cac5896d8 100644 --- a/crates/snowbound/src/print.rs +++ b/crates/snowbound/src/print.rs @@ -314,6 +314,8 @@ impl State { Arc::clone(&session.library), ); let replica = Arc::clone(session.section.replica()); + // Sections parked panes show are open already, and read from their replicas. + let held = self.held(&library.location); let layouts = Arc::clone(&self.layouts); let proxy = self.proxy.clone(); let paper = if setup.landscape { @@ -351,12 +353,17 @@ impl State { sections.push(open); continue; } - let section = library.open_async(&path, || {}).await?; - let pages = section - .pages()? - .into_iter() - .map(|(space, ..)| section.page(space)) - .collect::, _>>()?; + let pages = match held.iter().find(|(held, _)| *held == path) { + Some((_, replica)) => (replica.pages()?.into_iter()) + .map(|(space, ..)| replica.page(space)) + .collect::, _>>()?, + None => { + let section = library.open_async(&path, || {}).await?; + (section.pages()?.into_iter()) + .map(|(space, ..)| section.page(space)) + .collect::, _>>()? + } + }; sections.push((name, printed(pages))); } sections diff --git a/crates/snowbound/src/protection.rs b/crates/snowbound/src/protection.rs index 11cd31eba964a919c93a42e5b4fd72ebc1131ea6..46ee0b0fd796e341d95fa14f6b9d38e3313d8fe8 100644 --- a/crates/snowbound/src/protection.rs +++ b/crates/snowbound/src/protection.rs @@ -81,7 +81,8 @@ impl State { ) -> Result<(), Box> { self.stop_loading(); self.persist()?; - if let Some(previous) = self.session.take() { + let previous = self.session.take(); + if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) { let path = &previous.tabs[previous.tab].path; if self.leave(&previous.library, path) { previous.section.close()?; @@ -332,8 +333,18 @@ impl State { self.relock() } - /// Shows the open section locked once its key is gone. + /// Shows each open section locked once its key is gone. fn relock(&mut self) -> Result<(), Box> { + let path = |session: &crate::Session| session.tabs[session.tab].path.clone(); + self.leave_sections( + |session| session.library.locked(&path(session)), + |session, pane| { + pane.locked = Some(Locked { + library: Arc::clone(&session.library), + path: path(session), + }); + }, + ); let Some(session) = &self.session else { return Ok(()); }; @@ -699,6 +710,16 @@ impl State { key: Option, password: Option>, ) { + // Its file is written anew, so a parked pane on it lets it go and shows it locked. + let ours = |session: &crate::Session| { + session.library.location == library.location && session.tabs[session.tab].path == path + }; + self.leave_sections(ours, |session, pane| { + pane.locked = Some(Locked { + library: Arc::clone(&session.library), + path: path.clone(), + }); + }); let replica = self .session .as_ref() diff --git a/crates/snowbound/src/recycle.rs b/crates/snowbound/src/recycle.rs index 9d0788f59e3c461ae2f8350913e524b8a6279cdd..74589433cb2243cdcf117fcf097f9e45fe38f641 100644 --- a/crates/snowbound/src/recycle.rs +++ b/crates/snowbound/src/recycle.rs @@ -5,7 +5,7 @@ use crate::{Command, Library, Loaded, State, filetime, library, menus, notify, read_session}; use onestore::{ - ExGuid, + ExGuid, PageCreation, op::{Edit, Op, SectionOp}, }; use std::{error::Error, sync::Arc}; @@ -59,9 +59,14 @@ impl State { return; } let paths: Vec = library.tabs(BIN).into_iter().map(|tab| tab.path).collect(); - let proxy = self.proxy.clone(); + let (proxy, held) = (self.proxy.clone(), self.held(&library.location)); self.load_async(move || async move { for path in paths { + if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path) + && !replica.pages()?.is_empty() + { + return crate::split::held_page(library, path, replica, None); + } let section = library.open_async(&path, notify(proxy.clone())).await?; if section.pages()?.is_empty() { section.close_async().await?; @@ -135,8 +140,24 @@ impl State { (spaces.clone().skip(at).find(kept)).or_else(|| spaces.take(at).rev().find(kept)) }); let (author, proxy) = (self.author.clone(), self.proxy.clone()); + // Sections parked panes show are open already. + let held = self.held(&library.location); + let target = match &request { + Request::Restore { path, .. } => (held.iter()) + .find(|(held, _)| held == path) + .map(|(_, replica)| Arc::clone(replica)), + Request::Purge(_) => None, + }; + let (key, notebook_key) = (session.key(), library.key("")); + // The page it shows is on its way, so the panes hearing of it leave this one be. + self.pane.switching = Some((None, crate::Instant::now())); self.load_async(move || async move { - carry_out(&library, &replica, request, &author).await?; + carry_out(&library, &replica, request, &author, target).await?; + let spaces = gone.clone(); + let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| { + state.edited_sections(&key, spaces, |shown| shown.starts_with(¬ebook_key)); + Ok(()) + }))); if let Some(show) = if gone.contains(&shown) { after } else { @@ -148,6 +169,9 @@ impl State { let path = library .first_section() .ok_or("The notebook has no sections")?; + if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path) { + return crate::split::held_page(library, path, replica, None); + } let section = library.open_async(&path, notify(proxy)).await?; let (session, space, page) = read_session(section, library, path, None)?; Ok(Loaded::Section(Box::new(session), space, page)) @@ -191,33 +215,44 @@ impl State { /// Does `request` to the bin's section `replica` holds, in `library`, as `author`: a page /// restored goes to its section as one op, keeping its identity, a copy under a new one, and -/// what leaves the bin goes from it as another. +/// what leaves the bin goes from it as another. A section a pane shows is reached through +/// its replica in `held`, as it is open already. async fn carry_out( library: &Library, replica: ¬ebook::Replica, request: Request, author: &str, + held: Option>, ) -> Result<(), Box> { let gone = match request { Request::Restore { space, path, copy } => { let page = replica.page(space)?; - let section = library.open_async(&path, || {}).await?; - if copy { - section.import_page_async(&page, author).await?; + let opened = match held { + Some(_) => None, + None => Some(library.open_async(&path, || {}).await?), + }; + let target = match (&held, &opened) { + (Some(held), _) => Arc::clone(held), + (None, Some(section)) => Arc::clone(section.replica()), + (None, None) => unreachable!("a section is held or opened"), + }; + let op = if copy { + let creation = PageCreation::new(None, Some(&page.title), author)?; + Op::Section(SectionOp::Import { + creation, + page: page.copy()?, + }) } else { - let ops = vec![notebook::session::moved(&page, author)?]; - section - .replica() - .apply_async( - author, - Edit { - at: filetime(), - ops, - }, - ) - .await?; + notebook::session::moved(&page, author)? + }; + let edit = Edit { + at: filetime(), + ops: vec![op], + }; + target.apply_async(author, edit).await?; + if let Some(section) = opened { + section.close_async().await?; } - section.close_async().await?; (!copy).then_some(vec![space]).unwrap_or_default() } Request::Purge(spaces) => spaces, @@ -370,6 +405,7 @@ mod tests { bin.replica(), restore(back, false), AUTHOR, + None, )) .unwrap(); pollster::block_on(carry_out( @@ -377,6 +413,7 @@ mod tests { bin.replica(), restore(copied, true), AUTHOR, + None, )) .unwrap(); pollster::block_on(carry_out( @@ -384,6 +421,7 @@ mod tests { bin.replica(), Request::Purge(vec![purged]), AUTHOR, + None, )) .unwrap(); bin.close().unwrap(); diff --git a/crates/snowbound/src/rename.rs b/crates/snowbound/src/rename.rs index 989500cb2d51a0c06b85a7802589aa1e8c935435..df200c649c095c16255ddaed1f6e6db073a79965 100644 --- a/crates/snowbound/src/rename.rs +++ b/crates/snowbound/src/rename.rs @@ -5,7 +5,7 @@ use crate::{Command, Library, State, manage::Structure}; use onestore::{ ExGuid, - op::{Edit, Op, PageOp}, + op::{Op, PageOp}, page::{Page, PageObject}, }; use std::{error::Error, sync::Arc}; @@ -174,20 +174,14 @@ impl State { .find(|(page, ..)| *page == space) .map(|(_, title, _)| title.clone()) .unwrap_or_default(); - session.section.apply( - &self.author, - Edit { - at: crate::filetime(), - ops: vec![op], - }, - )?; + self.store(vec![op])?; + let session = self.session.as_mut().ok_or("No section is open")?; session.pages = session.section.pages()?; self.made(crate::undo::Change::Retitle { page: space, from: name, to: old, }); - self.edited(vec![space]); self.refresh() } } diff --git a/crates/snowbound/src/search.rs b/crates/snowbound/src/search.rs index f979e9717b710ba77b4f1b92d7a5b5c06a6bf271..167ad40f325147b3ffa02a089896acf3172a3049 100644 --- a/crates/snowbound/src/search.rs +++ b/crates/snowbound/src/search.rs @@ -546,12 +546,15 @@ impl State { }); } - /// Tells the index an edit changed page `space` of the open section. - pub(crate) fn edited(&self, spaces: Vec) { - if let Some(session) = &self.session { - self.search - .changed(session.key(), session.section.replica(), spaces); - } + /// Follows an edit made here of pages `spaces` of the open section, or of its page list + /// without any: the index reads them again, and so do the other panes showing them. + pub(crate) fn edited(&mut self, spaces: Vec) { + let Some(session) = &self.session else { + return; + }; + let key = session.key(); + (self.search).changed(key.clone(), session.section.replica(), spaces.clone()); + self.show_elsewhere(&key, &spaces); } /// Whether `key` names a section the search's scope takes in. diff --git a/crates/snowbound/src/sidebar.rs b/crates/snowbound/src/sidebar.rs index 336aee0ef34e3f4c443599de71000220b8ed9c3b..2679f8c17309c84eb69a2979f4512fb11fdf83c0 100644 --- a/crates/snowbound/src/sidebar.rs +++ b/crates/snowbound/src/sidebar.rs @@ -1453,6 +1453,7 @@ impl crate::State { .and_then(|path| self.last_pages.get(&crate::library::key(&location, path))) .copied(); let (cache, notify) = (self.cache.clone(), crate::notify(self.proxy.clone())); + let held = self.held(&location); self.load_async(move || async move { let library = match open { Some(library) => library, @@ -1476,6 +1477,10 @@ impl crate::State { } return Err("This folder holds no notebook sections.".into()); }; + // A section a parked pane shows is open already. + if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path) { + return crate::split::held_page(library, path, replica, left); + } let section = library.open_async(&path, notify).await?; let (session, space, page) = crate::read_session(section, library, path, left)?; Ok(crate::Loaded::Section(Box::new(session), space, page)) diff --git a/crates/snowbound/src/split.rs b/crates/snowbound/src/split.rs new file mode 100644 index 0000000000000000000000000000000000000000..a652cba662c4afed60a72abd88a651810317c35b --- /dev/null +++ b/crates/snowbound/src/split.rs @@ -0,0 +1,389 @@ +//! The page area split into panes, each a page view of its own, as Word's View > Split and an +//! editor's groups split theirs. One pane has the focus and the chrome around it; the others +//! are parked. Panes on one section share its `Session`, since a section's replica opens +//! once (`locking_mode=EXCLUSIVE`). + +use crate::{Command, Library, Loaded, Pane, Session, State}; +use notebook::{Replica, session::Event}; +use onestore::ExGuid; +use std::{ + error::Error, + sync::{Arc, atomic::Ordering}, +}; + +/// A pane out of focus, and the section it shows by `Library::key`; the focused pane's is +/// `State::session`. +pub struct Parked { + pub pane: Pane, + pub section: Option, +} + +impl State { + /// The open sections: the focused pane's, then those only parked panes show. + pub(crate) fn sessions(&self) -> impl Iterator { + self.session.iter().chain(&self.shelved) + } + + /// Shelves `session`, a section the focused pane left, while a parked pane shows it, or + /// gives it back to be kept or closed. + pub(crate) fn shelve(&mut self, session: Session) -> Option { + let key = Some(session.key()); + if !(self.parked.iter()).any(|parked| parked.section == key) { + return Some(session); + } + self.shelved.push(session); + None + } + + /// The replicas of sections of the notebook at `location` that parked panes hold, by + /// catalog path: a section opens once, so what opens one reads these instead. + pub(crate) fn held(&self, location: &str) -> Vec<(String, Arc)> { + (self.shelved.iter()) + .filter(|held| held.library.location == location) + .map(|held| { + let path = held.tabs[held.tab].path.clone(); + (path, Arc::clone(held.section.replica())) + }) + .collect() + } + + /// Takes the section `key` from the shelf, as the focused pane opens it. + pub(crate) fn unshelve(&mut self, key: &str) -> Option { + let at = (self.shelved.iter()).position(|session| session.key() == key)?; + Some(self.shelved.swap_remove(at)) + } + + /// Shows what `instead` makes of each open section `gone` picks in the parked panes on + /// it, and closes those only they showed; the focused pane's is the caller's to close. + pub(crate) fn leave_sections( + &mut self, + gone: impl Fn(&Session) -> bool, + instead: impl Fn(&Session, &mut Pane), + ) { + let (closing, kept) = std::mem::take(&mut self.shelved) + .into_iter() + .partition::, _>(|session| gone(session)); + self.shelved = kept; + for session in (self.session.iter().filter(|session| gone(session))).chain(&closing) { + let key = Some(session.key()); + for parked in (self.parked.iter_mut()).filter(|parked| parked.section == key) { + parked.section = None; + instead(session, &mut parked.pane); + } + } + for session in closing { + if let Err(error) = session.section.close() { + eprintln!("Synchronization stopped: {error}"); + } + } + } + + /// Closes the parked panes on notebook `library`, and the sections only they showed. + pub(crate) fn close_parked_in(&mut self, library: &Arc) { + let ours = |shown: &Library| shown.location == library.location; + self.leave_sections( + |session| ours(&session.library), + |_, pane| pane.sectionless = Some(Arc::clone(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)) + }); + } + + /// Closes the parked panes `gone` picks. + fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) { + self.parked.retain(|parked| !gone(parked)); + } + + /// Moves the sections only parked panes show in `library`, a notebook read again, to + /// where it keeps them now; a pane on one it no longer has closes. + pub(crate) fn follow_shelved(&mut self, library: &Arc) { + let mut gone = Vec::new(); + for session in &mut self.shelved { + if session.library.location != library.location + || Arc::ptr_eq(&session.library, library) + { + continue; + } + let old = Some(session.key()); + let identity = (session.library).section_identity(&session.tabs[session.tab].path); + let path = library.catalog().and_then(|catalog| { + (catalog.sections()) + .find(|section| Some(section.file_id) == identity) + .map(|section| section.path.clone()) + }); + match path.map(|path| session.follow(Arc::clone(library), &path)) { + Some(Ok(())) => { + let new = Some(session.key()); + for parked in (self.parked.iter_mut()).filter(|parked| parked.section == old) { + parked.section.clone_from(&new); + } + } + _ => gone.extend(old), + } + } + if !gone.is_empty() { + self.close_parked(|parked| { + parked + .section + .as_ref() + .is_some_and(|key| gone.contains(key)) + }); + self.leave_sections(|session| gone.contains(&session.key()), |_, _| {}); + } + } + + /// Whether a parked pane shows page `space` of section `key`. + pub(crate) fn shown_parked(&self, key: &str, space: ExGuid) -> bool { + self.parked.iter().any(|parked| { + parked.section.as_deref() == Some(key) && parked.pane.showing.space == space + }) + } + + /// Swaps parked pane `index` and the focused one, and their sections with them. + pub(crate) fn swap_pane(&mut self, index: usize) { + let parked = &mut self.parked[index]; + std::mem::swap(&mut self.pane, &mut parked.pane); + let left = self.session.as_ref().map(Session::key); + let wanted = std::mem::replace(&mut parked.section, left); + if wanted != parked.section { + let taken = wanted.and_then(|key| self.unshelve(&key)); + if let Some(left) = std::mem::replace(&mut self.session, taken) { + self.shelved.push(left); + } + } + } + + /// Runs `then` in parked pane `index` as though it had the focus, which stays where it + /// was, with the keyboard and any recording. What `then` asks for after the frame is done + /// in that pane too. + pub(crate) fn in_pane( + &mut self, + index: usize, + then: impl FnOnce(&mut State) -> Result<(), Box>, + ) -> Result<(), Box> { + let (focus, queued) = (self.ui.focused(), self.commands.len()); + let media = std::mem::take(&mut self.media); + self.swap_pane(index); + let mut done = then(self); + for command in self.commands.split_off(queued) { + done = done.and_then(|()| self.apply(command)); + } + self.swap_pane(index); + self.media = media; + self.ui.set_focus(focus); + self.title(); + done.and_then(|()| self.update_accessibility(true)) + } + + /// Whether no pane has a page on its way. + pub(crate) fn still(&self) -> bool { + std::iter::once(&self.pane) + .chain(self.parked.iter().map(|parked| &parked.pane)) + .all(|pane| pane.opening.is_none() && pane.switching.is_none()) + } + + /// A request number no load has had, so a late read reaches only the pane that asked. + pub(crate) fn request(&mut self) -> u64 { + self.requests += 1; + self.requests + } + + /// Shows an edit of the focused pane's section, `key`, in the parked panes on it, as its + /// own edits come back as no event: a pane on a page in `spaces` reads it again, and, + /// where the edit changed the page list without any, a pane whose page left opens another. + pub(crate) fn show_elsewhere(&mut self, key: &str, spaces: &[ExGuid]) { + for index in 0..self.parked.len() { + let parked = &self.parked[index]; + let showing = &parked.pane.showing; + // A version of a page stays as it was. + let changed = showing.version.is_none() && spaces.contains(&showing.space); + if parked.section.as_deref() != Some(key) || !(spaces.is_empty() || changed) { + continue; + } + let shown = self.in_pane(index, |state| { + if spaces.is_empty() { + state.relist().map(drop) + } else { + state.refresh() + } + }); + if let Err(error) = shown { + eprintln!("{error}"); + } + } + } + + /// Follows an edit made here away from the frame to section `key`, and to any others of + /// its notebook `touched` picks, which comes back as no event and may land after the + /// focus moved: the index reads pages `spaces` of `key` again, and each pane on a section + /// touched reads its page list and page again. + pub(crate) fn edited_sections( + &mut self, + key: &str, + spaces: Vec, + touched: impl Fn(&str) -> bool, + ) { + if let Some(session) = self.sessions().find(|session| session.key() == key) { + let replica = session.section.replica(); + (self.search).changed(key.to_owned(), replica, spaces); + } + // A pane with a page on its way, as the one that did this has, shows it on arrival. + let reread = |state: &mut State| { + if state.pane.switching.is_none() && !state.relist()? { + state.refresh()?; + } + Ok(()) + }; + if (self.session.as_ref()).is_some_and(|session| touched(&session.key())) + && let Err(error) = reread(self) + { + eprintln!("{error}"); + } + for index in 0..self.parked.len() { + if self.parked[index].section.as_deref().is_some_and(&touched) + && let Err(error) = self.in_pane(index, reread) + { + eprintln!("{error}"); + } + } + } + + /// Takes what each open section reported since the last poll once, and answers it in + /// every pane on that section; a pane failing to leaves the others to. + pub(crate) fn hear_sections(&mut self) { + let mut heard = Vec::new(); + for session in self.session.iter_mut().chain(&mut self.shelved) { + heard.push((session.key(), session.section.events())); + match session.section.sync_status() { + Ok(sync) => session.sync = sync, + Err(error) => eprintln!("{error}"), + } + } + for (session, (key, events)) in self.sessions().zip(&heard) { + let mut elsewhere = Vec::new(); + for event in events { + match event { + Event::Changed(spaces) => { + elsewhere.extend_from_slice(spaces); + let replica = session.section.replica(); + (self.search).changed(key.clone(), replica, spaces.clone()); + } + Event::Rejected { error, .. } => eprintln!("Saving failed: {error}"), + Event::Failed(error) => eprintln!("Not saving: {error}"), + // Its guests hear of it sooner than the folder's watch would tell them. + #[cfg(feature = "live")] + Event::Attempt { + status: notebook::EditStatus::Published { .. }, + .. + } => { + if let Some(host) = self.peers.hosts.get(&session.library.location) { + host.touched(&[session.tabs[session.tab].path.clone()]); + } + } + _ => {} + } + } + if !elsewhere.is_empty() { + self.changed_elsewhere(session, &elsewhere); + } + } + let events = |key: Option<&String>| { + (heard.iter()) + .find(|(heard, _)| Some(heard) == key) + .map(|(_, events)| events) + }; + if let Some(events) = events(self.session.as_ref().map(Session::key).as_ref()) + && let Err(error) = self.hear(events) + { + eprintln!("{error}"); + } + for index in 0..self.parked.len() { + if let Some(events) = events(self.parked[index].section.as_ref()) + && let Err(error) = self.in_pane(index, |state| state.hear(events)) + { + eprintln!("{error}"); + } + } + } + + /// Answers in the focused pane what its section reported: the page list read again, and + /// the page read again where another writer changed it or an edit of it was refused. The + /// pane that stored a refused edit tells of the refusal. + fn hear(&mut self, events: &[Event]) -> Result<(), Box> { + let space = self.pane.showing.space; + let (mut listed, mut changed, mut rejected, mut refusals) = (false, false, None, false); + for event in events { + match event { + Event::Changed(spaces) => { + listed = true; + changed |= spaces.contains(&space); + } + Event::Rejected { spaces, error } => { + refusals = true; + if spaces.contains(&space) { + rejected = Some(error); + } + } + _ => {} + } + } + let made = refusals && self.pane.refused.swap(false, Ordering::AcqRel); + if listed && self.relist()? { + return Ok(()); + } + match rejected { + Some(error) if made => self.refused(error), + _ if changed || rejected.is_some() => self.refresh(), + _ => Ok(()), + } + } + + /// Reads the open section's page list again, and opens another page where the one + /// shown, or the version of it, left; whether it did. + pub(crate) fn relist(&mut self) -> Result> { + let Some(session) = &mut self.session else { + return Ok(false); + }; + let showing = &mut self.pane.showing; + let back = showing.shown; + session.pages = session.section.pages()?; + session.refresh_conflicts(showing)?; + session.refresh_history(showing)?; + let listed = |space: ExGuid| session.pages.iter().any(|(page, ..)| *page == space); + let gone = showing.version.is_some_and(|version| { + !(session.page_versions(showing.space).iter()).any(|listed| listed.context == version) + }); + let open = if gone && listed(showing.space) { + // A version deleted elsewhere returns to its page. + showing.space + } else if !listed(showing.space) && session.conflict(showing.space).is_none() { + // A page removed elsewhere, or a conflict page deleted elsewhere, which returns to + // its page. + back.filter(|page| listed(*page)) + .or(session.pages.first().map(|(page, ..)| *page)) + .ok_or("The section has no pages")? + } else { + return Ok(false); + }; + self.commands.push(Command::OpenPage(open)); + Ok(true) + } +} + +/// Shows `library`'s section at catalog `path`, which a parked pane holds open through +/// `replica`, at page `space` where it lists it, else at its first. +pub fn held_page( + library: Arc, + path: String, + replica: &Replica, + space: Option, +) -> Result> { + let pages = replica.pages()?; + let space = space + .filter(|space| pages.iter().any(|(listed, ..)| listed == space)) + .or(pages.first().map(|(space, ..)| *space)) + .ok_or("The section has no pages")?; + Ok(Loaded::Held(library, path, space, replica.page(space)?)) +} diff --git a/crates/snowbound/src/sync.rs b/crates/snowbound/src/sync.rs index e70f9b9e775e96c65c9ca91a7249395724d84872..3c9168fbcacec2a83b682b6131fd2537ffc77b71 100644 --- a/crates/snowbound/src/sync.rs +++ b/crates/snowbound/src/sync.rs @@ -1060,7 +1060,7 @@ impl State { /// Builds the sync status popup while it is open: on the notebook its context menu /// opened it for, or the open section's. pub(crate) fn sync_popup(&mut self) -> Result<(), Box> { - let (ui, notebooks) = (&mut self.ui, &self.notebooks); + let (ui, notebooks, shelved) = (&mut self.ui, &self.notebooks, &self.shelved); let update = self.updates.status(); let Some(session) = &mut self.session else { ui.close_popup(id()); @@ -1126,6 +1126,7 @@ impl State { if picked.offline { library::set_offline(!offline); session.section.set_offline(!offline); + (shelved.iter()).for_each(|held| held.section.set_offline(!offline)); notebooks .iter() .for_each(|library| library.set_offline(!offline)); @@ -1133,6 +1134,9 @@ impl State { if own { session.section.wake(); } + (shelved.iter()) + .filter(|held| Arc::ptr_eq(&held.library, &library)) + .for_each(|held| held.section.wake()); backgrounds.for_each(|background| background.wake()); } if let Some(file) = file.filter(|_| picked.show_file) { diff --git a/crates/snowbound/src/undo.rs b/crates/snowbound/src/undo.rs index da9b06e8c9b25d4b18a633b869a4e880adb07e5e..31137f0cc9d33a7c127796c6195527857c1a5ae4 100644 --- a/crates/snowbound/src/undo.rs +++ b/crates/snowbound/src/undo.rs @@ -345,6 +345,9 @@ fn imported(op: &Op) -> ExGuid { struct Site { replica: Arc, library: Arc, + /// The replicas of the notebook's sections parked panes show, open already, by catalog + /// path. + held: Vec<(String, Arc)>, author: String, fresh: PageCreation, } @@ -416,6 +419,19 @@ impl Site { entry_of(self.library.catalog()?, identity).map(|(_, path)| path) } + /// The replica of the notebook's section at catalog `path`, with the section where it + /// was opened for this, which `release` closes after. + async fn reach( + &self, + path: &str, + ) -> Result<(Arc, Option), Box> { + if let Some((_, replica)) = self.held.iter().find(|(held, _)| held == path) { + return Ok((Arc::clone(replica), None)); + } + let section = self.library.open_async(path, || {}).await?; + Ok((Arc::clone(section.replica()), Some(section))) + } + /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be, /// keeps it open, where they are tried again until they are. async fn release(&self, path: &str, section: notebook::session::Section) { @@ -588,9 +604,8 @@ impl Site { let level = listed[from].2; let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))]; let (show, added) = self.after(&listed, &[page], None, &mut ops); - let section = self.library.open_async(&path, || {}).await?; - section - .replica() + let (other, opened) = self.reach(&path).await?; + other .apply_async( &self.author, Edit { @@ -599,7 +614,9 @@ impl Site { }, ) .await?; - self.release(&path, section).await; + if let Some(section) = opened { + self.release(&path, section).await; + } let edit = Edit { at: crate::filetime(), ops, @@ -634,12 +651,14 @@ impl Site { let Some(path) = self.section_path(target) else { return Ok(None); }; - let section = self.library.open_async(&path, || {}).await?; - if !(section.pages()?.iter()).any(|(listed, ..)| *listed == page) { - self.release(&path, section).await; + let (other, opened) = self.reach(&path).await?; + if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) { + if let Some(section) = opened { + self.release(&path, section).await; + } return Ok(None); } - let sent = section.replica().moving(page)?; + let sent = other.moving(page)?; let import = notebook::session::moved(sent.page(), &self.author)?; let back = imported(&import); let mut ops = vec![ @@ -656,11 +675,10 @@ impl Site { at: crate::filetime(), ops: vec![Op::Section(SectionOp::Delete(vec![page]))], }; - let retired = section - .replica() - .retire_async(&self.author, delete, sent) - .await; - self.release(&path, section).await; + let retired = other.retire_async(&self.author, delete, sent).await; + if let Some(section) = opened { + self.release(&path, section).await; + } Applied { undo: (retired.map(|_| Change::Send { page: back, target })) .map_err(|error| crate::plain(&error, "page")), @@ -1111,9 +1129,13 @@ impl State { } else { None }; + let held = self.held(&session.library.location); + let key = session.key(); + let notebook_key = session.library.key(""); let mut site = Site { replica: Arc::clone(session.section.replica()), library: Arc::clone(&session.library), + held, author: self.author.clone(), fresh: self.dated_page(None, "")?, }; @@ -1181,7 +1203,8 @@ impl State { } Err(copied) => crate::platform::alert("Page kept in both sections", &copied), } - state.edited(Vec::new()); + // Its section, and the one a page went to or came from, wherever the focus is. + state.edited_sections(&key, Vec::new(), |shown| shown.starts_with(¬ebook_key)); Ok(()) }))); drop(changing); @@ -1464,6 +1487,7 @@ mod tests { Site { replica: Arc::clone(self.section().replica()), library: Arc::clone(&self.library), + held: Vec::new(), author: AUTHOR.into(), fresh: dated(), } diff --git a/crates/snowbound/src/unread.rs b/crates/snowbound/src/unread.rs index bfa61009fe681ddc0c4dbc07c75a142bf403fc55..972760b9a6aaa299894a4d18f54ebb746142a121 100644 --- a/crates/snowbound/src/unread.rs +++ b/crates/snowbound/src/unread.rs @@ -297,12 +297,9 @@ impl State { viewing.map(|(notebook, section, space)| (notebook, section, space, false)); } - /// Pages of the open section another client changed, as its sync reports them: those + /// Pages of an open section another client changed, as its sync reports them: those /// another author changed last are unread, once read on a thread of their own. - pub(crate) fn changed_elsewhere(&mut self, spaces: &[ExGuid]) { - let Some(session) = &self.session else { - return; - }; + pub(crate) fn changed_elsewhere(&self, session: &crate::Session, spaces: &[ExGuid]) { let Some(section) = session .library .section_identity(&session.tabs[session.tab].path) diff --git a/crates/snowbound/tests/replay.rs b/crates/snowbound/tests/replay.rs index 75fa85b5e7d9bf4b1ab99abb0e154f0f6d481faf..c8a098f7d351bc4b8ab420dd1e32c838b93c682f 100644 --- a/crates/snowbound/tests/replay.rs +++ b/crates/snowbound/tests/replay.rs @@ -313,6 +313,31 @@ fn page_tabs(tree: &str) -> Vec { .collect() } +/// Undoing a new page shows the page it was made from, though the page shown hears of the +/// undo before the page it shows arrives. Waits, unlike settling, leave that race open. +#[test] +fn undoing_a_new_page_returns_to_the_page_it_was_made_from() { + let scratch = Scratch::new("undo-new-page"); + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let chord = + |modifiers: &'static str, key: &'static str| [modifiers, key, "modifiers", "wait 1000"]; + // The Bed rotation tab, then a new page with a title. + let mut steps = vec!["move 1003 139", "press", "release", "wait 1000"]; + steps.extend(chord("modifiers command", "key n")); + steps.extend(["type Hello", "wait 1000"]); + for _ in 0..2 { + steps.extend(chord("modifiers command", "key z")); + } + steps.push("accessibility undone"); + let [undone] = replay(&scratch, Some(¬ebook), &steps) + .try_into() + .unwrap(); + assert!( + undone.starts_with(r#"Window "Bed rotation ยท Garden.one""#), + "{undone}" + ); +} + /// Undo walks back through two new pages and what was typed on each, crossing pages as /// it goes: each page keeps its own history once left, and a new page goes once what was /// typed on it has gone.