authoravatarclover caruso<git@paperclover.net>2026-10-16 13:52:19-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-19 16:50:39-07:00
log2793455970b9dbe108f5103c69802fc459b30298
tree96237c6fe5a3f5c8485a875e89da2ca043b83144
parent378fe60115f1ad1b1dd869b559da99c10ff95463
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

refactor: share open sections between panes

A section's replica opens once, so panes on one section share its Session. The focused pane's section stays State.session; parked panes name theirs by Library::key, and sections only they show wait on a shelf. Opening a section a parked pane holds takes it off the shelf instead of opening the file again, as do printing, Delete All Versions, copying a version, undoing a page sent to another section, the recycle bin, opening a notebook from the sidebar and a structure change; a section the focused pane leaves goes on the shelf while a parked pane still shows it, and a pane asking for a section another pane's load is opening from its file takes that load over. A section reports no event for its own edits, so every edit made here is shown in the other panes on its pages: those stored through State::store at once, and those done away from the frame (undo, versions, the recycle bin) in every pane on the section wherever the focus has gone, but a pane whose own page is on its way, and a pane showing a version keeps it as it was. Each section's events are taken once and answered in every pane on it, one pane failing to leaving the others to, and a refused edit is told of in the pane that stored it. Loads take request numbers from a counter, so a late read reaches only the pane that asked. Locking, emptying, moving, renaming and closing a notebook or section, working offline, Sync Now and the iCloud recovery export reach the sections parked panes show too, and a parked pane whose section leaves the notebook closes. Nothing visible changes: there is still one pane. Assisted-by: claude-opus-5.5

16 files changed, 940 insertions(+), 260 deletions(-)

crates/snowbound/src/history.rs+21-4
...@@ -172,11 +172,10 @@ impl State {...@@ -172,11 +172,10 @@ impl State {
172 let operation = session172 let operation = session
173 .section173 .section
174 .restore_version_async(page, version, &self.author);174 .restore_version_async(page, version, &self.author);
175 self.section_edit(operation, move |state, _| {175 self.section_edit(vec![page], operation, move |state, _| {
176 if let Some(session) = &mut state.session {176 if let Some(session) = &mut state.session {
177 session.refresh_history(&mut state.pane.showing)?;177 session.refresh_history(&mut state.pane.showing)?;
178 }178 }
179 state.edited(vec![page]);
180 state.commands.push(Command::OpenPage(page));179 state.commands.push(Command::OpenPage(page));
181 Ok(())180 Ok(())
182 })181 })
...@@ -191,7 +190,7 @@ impl State {...@@ -191,7 +190,7 @@ impl State {
191 let operation = session190 let operation = session
192 .section191 .section
193 .delete_versions_async(&[(page, vec![version])]);192 .delete_versions_async(&[(page, vec![version])]);
194 self.section_edit(operation, move |state, _| {193 self.section_edit(Vec::new(), operation, move |state, _| {
195 if let Some(session) = &mut state.session {194 if let Some(session) = &mut state.session {
196 session.refresh_history(&mut state.pane.showing)?;195 session.refresh_history(&mut state.pane.showing)?;
197 }196 }
...@@ -244,6 +243,11 @@ impl State {...@@ -244,6 +243,11 @@ impl State {
244 };243 };
245 let operation = clear(&session.section);244 let operation = clear(&session.section);
246 let library = Arc::clone(&session.library);245 let library = Arc::clone(&session.library);
246 // Sections parked panes show are open already, and cleared through their sessions.
247 let mut held: Vec<_> = (self.shelved.iter())
248 .filter(|held| scope != Scope::Section && Arc::ptr_eq(&held.library, &library))
249 .map(|held| (held.tabs[held.tab].path.clone(), clear(&held.section)))
250 .collect();
247 let proxy = self.proxy.clone();251 let proxy = self.proxy.clone();
248 let operation = async move {252 let operation = async move {
249 operation.await?;253 operation.await?;
...@@ -254,11 +258,18 @@ impl State {...@@ -254,11 +258,18 @@ impl State {
254 String::new()258 String::new()
255 };259 };
256 crate::spawn_async(move || async move {260 crate::spawn_async(move || async move {
261 let mut reached = Vec::new();
257 for path in sections(&library, &folder) {262 for path in sections(&library, &folder) {
258 if path == open {263 if path == open {
259 continue;264 continue;
260 }265 }
266 let at = held.iter().position(|(held, _)| *held == path);
261 let cleared: Result<(), Box<dyn Error>> = async {267 let cleared: Result<(), Box<dyn Error>> = async {
268 if let Some(at) = at {
269 held.swap_remove(at).1.await?;
270 reached.push(library.key(&path));
271 return Ok(());
272 }
262 let section = library.open_async(&path, notify(proxy.clone())).await?;273 let section = library.open_async(&path, notify(proxy.clone())).await?;
263 clear(&section).await?;274 clear(&section).await?;
264 Ok(section.close_async().await?)275 Ok(section.close_async().await?)
...@@ -268,11 +279,17 @@ impl State {...@@ -268,11 +279,17 @@ impl State {
268 eprintln!("Deleting the versions in {path} failed: {error}");279 eprintln!("Deleting the versions in {path} failed: {error}");
269 }280 }
270 }281 }
282 let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| {
283 for key in reached {
284 state.edited_sections(&key, Vec::new(), |shown| shown == key);
285 }
286 Ok(())
287 })));
271 });288 });
272 }289 }
273 Ok(())290 Ok(())
274 };291 };
275 self.section_edit(operation, move |state, ()| {292 self.section_edit(Vec::new(), operation, move |state, ()| {
276 if let Some(session) = &mut state.session {293 if let Some(session) = &mut state.session {
277 session.refresh_history(&mut state.pane.showing)?;294 session.refresh_history(&mut state.pane.showing)?;
278 if state.pane.showing.version.is_some() {295 if state.pane.showing.version.is_some() {
crates/snowbound/src/live.rs+3-5
...@@ -464,11 +464,9 @@ impl State {...@@ -464,11 +464,9 @@ impl State {
464 if let Some(background) = joined.background.get().and_then(Weak::upgrade) {464 if let Some(background) = joined.background.get().and_then(Weak::upgrade) {
465 background.wake();465 background.wake();
466 }466 }
467 if let Some(session) = &self.session467 (self.session.iter().chain(&self.shelved))
468 && Arc::ptr_eq(&session.library, library)468 .filter(|session| Arc::ptr_eq(&session.library, library))
469 {469 .for_each(|session| session.section.wake());
470 session.section.wake();
471 }
472 }470 }
473 }471 }
474 }472 }
crates/snowbound/src/main.rs+296-151
...@@ -79,6 +79,7 @@ mod sidebar;...@@ -79,6 +79,7 @@ mod sidebar;
79#[cfg_attr(windows, path = "spell_windows.rs")]79#[cfg_attr(windows, path = "spell_windows.rs")]
80#[cfg_attr(target_arch = "wasm32", path = "spell_web.rs")]80#[cfg_attr(target_arch = "wasm32", path = "spell_web.rs")]
81mod spell;81mod spell;
82mod split;
82#[cfg_attr(not(feature = "wgpu"), path = "surface_gl.rs")]83#[cfg_attr(not(feature = "wgpu"), path = "surface_gl.rs")]
83#[cfg_attr(all(target_os = "macos", feature = "wgpu"), path = "surface_macos.rs")]84#[cfg_attr(all(target_os = "macos", feature = "wgpu"), path = "surface_macos.rs")]
84#[cfg_attr(windows, path = "surface_windows.rs")]85#[cfg_attr(windows, path = "surface_windows.rs")]
...@@ -545,6 +546,8 @@ struct Pane {...@@ -545,6 +546,8 @@ struct Pane {
545 showing: Showing,546 showing: Showing,
546 /// The newest read requested; older ones are dropped when they finish.547 /// The newest read requested; older ones are dropped when they finish.
547 loading: u64,548 loading: u64,
549 /// Set when the section refuses an edit the pane stored, which the pane then tells of.
550 refused: Arc<std::sync::atomic::AtomicBool>,
548 opening: Option<Opening>,551 opening: Option<Opening>,
549 /// The section tab, if another, that the newest read opens, and when it was asked for.552 /// The section tab, if another, that the newest read opens, and when it was asked for.
550 switching: Option<(Option<usize>, Instant)>,553 switching: Option<(Option<usize>, Instant)>,
...@@ -718,6 +721,8 @@ enum Loaded {...@@ -718,6 +721,8 @@ enum Loaded {
718 /// A section just created, whose name opens for renaming as OneNote's New Section does.721 /// A section just created, whose name opens for renaming as OneNote's New Section does.
719 Created(Box<Session>, ExGuid, Page),722 Created(Box<Session>, ExGuid, Page),
720 Page(ExGuid, Page),723 Page(ExGuid, Page),
724 /// A page of a section a parked pane holds open, by its notebook and catalog path.
725 Held(Arc<Library>, String, ExGuid, Page),
721 /// A page's version, by the page's space and the version's context.726 /// A page's version, by the page's space and the version's context.
722 Version(ExGuid, ExGuid, Page),727 Version(ExGuid, ExGuid, Page),
723 /// A notebook read again after a change, at the section that stays open, if any.728 /// A notebook read again after a change, at the section that stays open, if any.
...@@ -729,6 +734,7 @@ enum Shown {...@@ -729,6 +734,7 @@ enum Shown {
729 Section(Box<Session>, ExGuid),734 Section(Box<Session>, ExGuid),
730 Created(Box<Session>, ExGuid),735 Created(Box<Session>, ExGuid),
731 Page(ExGuid),736 Page(ExGuid),
737 Held(Arc<Library>, String, ExGuid),
732 Version(ExGuid, ExGuid),738 Version(ExGuid, ExGuid),
733}739}
734740
...@@ -754,6 +760,19 @@ struct Opening {...@@ -754,6 +760,19 @@ struct Opening {
754/// How long an opening page waits for its pictures before showing without them.760/// How long an opening page waits for its pictures before showing without them.
755const HOLD: std::time::Duration = std::time::Duration::from_millis(200);761const HOLD: std::time::Duration = std::time::Duration::from_millis(200);
756762
763impl Pane {
764 /// The page opening here, once the pictures it shows first are drawn on `paper` or
765 /// `HOLD` has passed.
766 fn opened(&mut self, paper: canvas::gpu::Paper, redraw: &std::task::Waker) -> Option<Opening> {
767 let opening = self.opening.as_mut()?;
768 let paper = paper.colored(opening.editor.page_color());
769 let ready = (self.view).prepare(&mut opening.scene, &opening.editor, paper, redraw);
770 (ready || opening.since.elapsed() >= HOLD)
771 .then(|| self.opening.take())
772 .flatten()
773 }
774}
775
757/// Work the interface asked for, done after the frame is built.776/// Work the interface asked for, done after the frame is built.
758enum Command {777enum Command {
759 /// Opens a notebook's section by catalog path, at the page it showed last.778 /// Opens a notebook's section by catalog path, at the page it showed last.
...@@ -877,12 +896,19 @@ struct State {...@@ -877,12 +896,19 @@ struct State {
877 /// Backends that failed to start this run, and why.896 /// Backends that failed to start this run, and why.
878 unavailable: Vec<(settings::Backend, String)>,897 unavailable: Vec<(settings::Backend, String)>,
879 ui: Ui,898 ui: Ui,
880 /// The page view the window shows.899 /// The focused pane, which the chrome around the page area follows.
881 pane: Pane,900 pane: Pane,
901 parked: Vec<split::Parked>,
882 /// The open notebooks in the sidebar's order.902 /// The open notebooks in the sidebar's order.
883 notebooks: Vec<Arc<Library>>,903 notebooks: Vec<Arc<Library>>,
884 /// The open section, the one the pane shows.904 /// The section the focused pane shows.
885 session: Option<Session>,905 session: Option<Session>,
906 /// The sections only parked panes show.
907 shelved: Vec<Session>,
908 /// The last load request number given.
909 requests: u64,
910 /// Sections loads are opening from their files, by request number.
911 opening_files: Vec<(u64, String)>,
886 /// A page not kept in any notebook, from a text file or `--page`.912 /// A page not kept in any notebook, from a text file or `--page`.
887 temporary: bool,913 temporary: bool,
888 /// Where the settings are saved; `None` leaves them as they were read.914 /// Where the settings are saved; `None` leaves them as they were read.
...@@ -1378,6 +1404,7 @@ impl State {...@@ -1378,6 +1404,7 @@ impl State {
1378 ),1404 ),
1379 showing,1405 showing,
1380 loading: 0,1406 loading: 0,
1407 refused: Arc::default(),
1381 opening: None,1408 opening: None,
1382 switching: None,1409 switching: None,
1383 trail: navigation::Trail::default(),1410 trail: navigation::Trail::default(),
...@@ -1386,8 +1413,12 @@ impl State {...@@ -1386,8 +1413,12 @@ impl State {
1386 sectionless,1413 sectionless,
1387 locked,1414 locked,
1388 },1415 },
1416 parked: Vec::new(),
1389 notebooks,1417 notebooks,
1390 session,1418 session,
1419 shelved: Vec::new(),
1420 requests: 0,
1421 opening_files: Vec::new(),
1391 temporary,1422 temporary,
1392 settings,1423 settings,
1393 cache,1424 cache,
...@@ -1607,10 +1638,7 @@ impl State {...@@ -1607,10 +1638,7 @@ impl State {
1607 lap("drawn", start);1638 lap("drawn", start);
1608 self.sync_index(false, Vec::new());1639 self.sync_index(false, Vec::new());
1609 let commands = std::mem::take(&mut self.commands);1640 let commands = std::mem::take(&mut self.commands);
1610 let follow = !commands.is_empty()1641 let follow = !commands.is_empty() || self.ui.wants_frame() || !self.still();
1611 || self.ui.wants_frame()
1612 || self.pane.opening.is_some()
1613 || self.pane.switching.is_some();
1614 for command in commands {1642 for command in commands {
1615 self.apply(command)?;1643 self.apply(command)?;
1616 }1644 }
...@@ -3630,8 +3658,37 @@ impl State {...@@ -3630,8 +3658,37 @@ impl State {
3630 _ => None,3658 _ => None,
3631 };3659 };
3632 self.pane.switching = Some((tab, Instant::now()));3660 self.pane.switching = Some((tab, Instant::now()));
3661 let key = library.key(&path);
3662 let last = self.last_pages.get(&key).copied();
3663 // A section a parked pane shows is open already, and opens only once.
3664 if let Some(held) = self.shelved.iter().find(|held| held.key() == key) {
3665 let listed = |space: &ExGuid| held.pages.iter().any(|(page, ..)| page == space);
3666 let space = (last.filter(listed))
3667 .or(held.pages.first().map(|(page, ..)| *page))
3668 .ok_or("The section has no pages")?;
3669 let read = held.reader(space);
3670 self.load(move || Ok(Loaded::Held(library, path, space, read()?)));
3671 return Ok(());
3672 }
3673 // A section opens from its file once: a load already opening it shows it here,
3674 // and a parked pane that asked for it first leaves it to this one.
3675 let opening = (self.opening_files.iter())
3676 .find(|(_, opening)| *opening == key)
3677 .map(|(request, _)| *request);
3678 if opening == Some(self.pane.loading) {
3679 return Ok(());
3680 }
3681 let asked =
3682 (self.parked.iter()).position(|parked| Some(parked.pane.loading) == opening);
3683 if let Some(at) = asked {
3684 let fresh = self.request();
3685 let pane = &mut self.parked[at].pane;
3686 let (request, opened) = (pane.loading, pane.opening.take());
3687 (pane.loading, pane.switching) = (fresh, None);
3688 (self.pane.loading, self.pane.opening) = (request, opened);
3689 return Ok(());
3690 }
3633 let notify = notify(self.proxy.clone());3691 let notify = notify(self.proxy.clone());
3634 let last = self.last_pages.get(&library.key(&path)).copied();
3635 self.load_async(move || async move {3692 self.load_async(move || async move {
3636 let start = Instant::now();3693 let start = Instant::now();
3637 let section = library.open_async(&path, notify).await?;3694 let section = library.open_async(&path, notify).await?;
...@@ -3639,6 +3696,7 @@ impl State {...@@ -3639,6 +3696,7 @@ impl State {
3639 let (session, space, page) = read_session(section, library, path, last)?;3696 let (session, space, page) = read_session(section, library, path, last)?;
3640 Ok(Loaded::Section(Box::new(session), space, page))3697 Ok(Loaded::Section(Box::new(session), space, page))
3641 });3698 });
3699 self.opening_files.push((self.pane.loading, key));
3642 }3700 }
3643 Command::OpenPage(space) => {3701 Command::OpenPage(space) => {
3644 let session = self.session.as_ref().ok_or("No section is open")?;3702 let session = self.session.as_ref().ok_or("No section is open")?;
...@@ -3666,7 +3724,7 @@ impl State {...@@ -3666,7 +3724,7 @@ impl State {
3666 Command::DeleteVersion { page, version } => {3724 Command::DeleteVersion { page, version } => {
3667 let session = self.session.as_mut().ok_or("No section is open")?;3725 let session = self.session.as_mut().ok_or("No section is open")?;
3668 let operation = session.section.delete_pages_async(&[version]);3726 let operation = session.section.delete_pages_async(&[version]);
3669 self.section_edit(operation, move |state, _| {3727 self.section_edit(Vec::new(), operation, move |state, _| {
3670 if let Some(session) = &mut state.session {3728 if let Some(session) = &mut state.session {
3671 session.refresh_conflicts(&mut state.pane.showing)?;3729 session.refresh_conflicts(&mut state.pane.showing)?;
3672 }3730 }
...@@ -3682,13 +3740,16 @@ impl State {...@@ -3682,13 +3740,16 @@ impl State {
3682 }3740 }
3683 _ => session.section.page(version)?,3741 _ => session.section.page(version)?,
3684 };3742 };
3743 let key = session.library.key(&session.tabs[tab].path);
3685 if tab == session.tab {3744 if tab == session.tab {
3686 let operation = session.section.import_page_async(&page, &self.author);3745 let operation = session.section.import_page_async(&page, &self.author);
3687 self.section_edit(operation, |state, _| {3746 self.section_edit(Vec::new(), operation, |_, _| Ok(()))?;
3688 if let Some(session) = &mut state.session {3747 } else if let Some(held) = self.shelved.iter().find(|held| held.key() == key) {
3689 session.pages = session.section.pages()?;3748 // A section a parked pane shows is open already.
3690 }3749 let operation = held.section.import_page_async(&page, &self.author);
3691 state.edited(Vec::new());3750 self.complete_async(operation, move |state, copied| {
3751 copied?;
3752 state.edited_sections(&key, Vec::new(), |shown| shown == key);
3692 Ok(())3753 Ok(())
3693 })?;3754 })?;
3694 } else {3755 } else {
...@@ -3746,10 +3807,7 @@ impl State {...@@ -3746,10 +3807,7 @@ impl State {
3746 self.restructure(library, change);3807 self.restructure(library, change);
3747 }3808 }
3748 // The index follows the section's page list.3809 // The index follows the section's page list.
3749 Command::NewPage { under, title } => {3810 Command::NewPage { under, title } => self.new_page(under, &title)?,
3750 self.new_page(under, &title)?;
3751 self.edited(Vec::new());
3752 }
3753 Command::DeletePages(pages) => {3811 Command::DeletePages(pages) => {
3754 self.delete_pages(pages)?;3812 self.delete_pages(pages)?;
3755 self.edited(Vec::new());3813 self.edited(Vec::new());
...@@ -3788,7 +3846,7 @@ impl State {...@@ -3788,7 +3846,7 @@ impl State {
3788 &mut self,3846 &mut self,
3789 read: impl FnOnce() -> F + Send + 'static,3847 read: impl FnOnce() -> F + Send + 'static,
3790 ) {3848 ) {
3791 self.pane.loading += 1;3849 self.pane.loading = self.request();
3792 let (id, sender, redraw) = (self.pane.loading, self.loads.0.clone(), self.redraw.clone());3850 let (id, sender, redraw) = (self.pane.loading, self.loads.0.clone(), self.redraw.clone());
3793 let layouts = Arc::clone(&self.layouts);3851 let layouts = Arc::clone(&self.layouts);
3794 let requested = Instant::now();3852 let requested = Instant::now();
...@@ -3801,6 +3859,9 @@ impl State {...@@ -3801,6 +3859,9 @@ impl State {
3801 Loaded::Section(session, space, page) => (Shown::Section(session, space), page),3859 Loaded::Section(session, space, page) => (Shown::Section(session, space), page),
3802 Loaded::Created(session, space, page) => (Shown::Created(session, space), page),3860 Loaded::Created(session, space, page) => (Shown::Created(session, space), page),
3803 Loaded::Page(space, page) => (Shown::Page(space), page),3861 Loaded::Page(space, page) => (Shown::Page(space), page),
3862 Loaded::Held(library, path, space, page) => {
3863 (Shown::Held(library, path, space), page)
3864 }
3804 Loaded::Version(space, version, page) => (Shown::Version(space, version), page),3865 Loaded::Version(space, version, page) => (Shown::Version(space, version), page),
3805 Loaded::Library(library, path) => return Ok(Laid::Library(library, path)),3866 Loaded::Library(library, path) => return Ok(Laid::Library(library, path)),
3806 };3867 };
...@@ -3811,6 +3872,7 @@ impl State {...@@ -3811,6 +3872,7 @@ impl State {
3811 Some((session.key(), *space))3872 Some((session.key(), *space))
3812 }3873 }
3813 Shown::Page(space) => open.map(|open| (open, *space)),3874 Shown::Page(space) => open.map(|open| (open, *space)),
3875 Shown::Held(library, path, space) => Some((library.key(path), *space)),
3814 Shown::Version(..) => None,3876 Shown::Version(..) => None,
3815 };3877 };
3816 // A page shown or prepared lately keeps the pictures it drew.3878 // A page shown or prepared lately keeps the pictures it drew.
...@@ -3857,17 +3919,22 @@ impl State {...@@ -3857,17 +3919,22 @@ impl State {
3857 }3919 }
3858 }3920 }
38593921
3922 /// Does `operation`, an edit of the open section's pages `spaces` or its list without
3923 /// any, then shows it in every pane on the section and runs `then` if that is still the
3924 /// open one.
3860 fn section_edit<3925 fn section_edit<
3861 T: Send + 'static,3926 T: Send + 'static,
3862 F: Future<Output = Result<T, notebook::Error>> + Send + 'static,3927 F: Future<Output = Result<T, notebook::Error>> + Send + 'static,
3863 >(3928 >(
3864 &mut self,3929 &mut self,
3930 spaces: Vec<ExGuid>,
3865 operation: F,3931 operation: F,
3866 then: impl FnOnce(&mut State, T) -> Result<(), Box<dyn Error>> + Send + 'static,3932 then: impl FnOnce(&mut State, T) -> Result<(), Box<dyn Error>> + Send + 'static,
3867 ) -> Result<(), Box<dyn Error>> {3933 ) -> Result<(), Box<dyn Error>> {
3868 let key = self.session.as_ref().ok_or("No section is open")?.key();3934 let key = self.session.as_ref().ok_or("No section is open")?.key();
3869 self.complete_async(operation, move |state, result| {3935 self.complete_async(operation, move |state, result| {
3870 let value = result?;3936 let value = result?;
3937 state.edited_sections(&key, spaces, |shown| shown == key);
3871 if state3938 if state
3872 .session3939 .session
3873 .as_ref()3940 .as_ref()
...@@ -3880,19 +3947,28 @@ impl State {...@@ -3880,19 +3947,28 @@ impl State {
3880 })3947 })
3881 }3948 }
38823949
3883 /// Shows the newest page read once the pictures it shows first are drawn, or after3950 /// Shows the newest page each pane read once the pictures it shows first are drawn, or
3884 /// `HOLD`.3951 /// after `HOLD`.
3885 fn open_loaded(&mut self) -> Result<(), Box<dyn Error>> {3952 fn open_loaded(&mut self) -> Result<(), Box<dyn Error>> {
3886 let reads: Vec<Read> = self.loads.1.try_iter().collect();3953 let reads: Vec<Read> = self.loads.1.try_iter().collect();
3887 for (id, loaded) in reads {3954 for (id, loaded) in reads {
3955 self.opening_files.retain(|(request, _)| *request != id);
3956 let parked = (self.parked.iter()).position(|parked| parked.pane.loading == id);
3957 let pane = match parked {
3958 Some(at) => &mut self.parked[at].pane,
3959 None => &mut self.pane,
3960 };
3888 match loaded {3961 match loaded {
3889 // A later load supersedes what this one shows, but not its failure.3962 // A later load supersedes what this one shows, but not its failure.
3890 Ok(_) if id != self.pane.loading => {}3963 Ok(_) if id != pane.loading => {}
3891 Ok(Laid::Page(opening)) => self.pane.opening = Some(*opening),3964 Ok(Laid::Page(opening)) => pane.opening = Some(*opening),
3892 Ok(Laid::Library(library, path)) => self.adopt(library, path.as_deref())?,3965 Ok(Laid::Library(library, path)) => match parked {
3966 Some(at) => self.in_pane(at, |state| state.adopt(library, path.as_deref()))?,
3967 None => self.adopt(library, path.as_deref())?,
3968 },
3893 Err(error) => {3969 Err(error) => {
3894 if id == self.pane.loading {3970 if id == pane.loading {
3895 self.pane.switching = None;3971 pane.switching = None;
3896 }3972 }
3897 platform::alert("Couldn't open", &error);3973 platform::alert("Couldn't open", &error);
3898 }3974 }
...@@ -3903,25 +3979,27 @@ impl State {...@@ -3903,25 +3979,27 @@ impl State {
3903 ink: self.ui.theme.paper_ink,3979 ink: self.ui.theme.paper_ink,
3904 };3980 };
3905 self.prefetch.draw(&self.pane.view, paper, &self.redraw);3981 self.prefetch.draw(&self.pane.view, paper, &self.redraw);
3906 let Some(mut opening) = self.pane.opening.take() else {3982 for at in 0..self.parked.len() {
3983 if let Some(opening) = self.parked[at].pane.opened(paper, &self.redraw) {
3984 self.in_pane(at, |state| state.show_page(opening))?;
3985 }
3986 }
3987 let Some(opening) = self.pane.opened(paper, &self.redraw) else {
3907 return Ok(());3988 return Ok(());
3908 };3989 };
3909 let paper = paper.colored(opening.editor.page_color());
3910 if !self
3911 .pane
3912 .view
3913 .prepare(&mut opening.scene, &opening.editor, paper, &self.redraw)
3914 && opening.since.elapsed() < HOLD
3915 {
3916 self.pane.opening = Some(opening);
3917 return Ok(());
3918 }
3919 lap("switch pictures", opening.since);3990 lap("switch pictures", opening.since);
3920 self.show_page(opening)3991 self.show_page(opening)
3921 }3992 }
39223993
3923 fn show_page(&mut self, mut opening: Opening) -> Result<(), Box<dyn Error>> {3994 fn show_page(&mut self, mut opening: Opening) -> Result<(), Box<dyn Error>> {
3924 let requested = opening.requested;3995 let requested = opening.requested;
3996 if let Shown::Held(library, path, space) = opening.loaded {
3997 match self.unshelve(&library.key(&path)) {
3998 Some(session) => opening.loaded = Shown::Section(Box::new(session), space),
3999 // The panes holding it closed meanwhile, and the section went with them.
4000 None => return self.apply(Command::OpenSection(library, path)),
4001 }
4002 }
3925 if let Shown::Section(session, _) | Shown::Created(session, _) = &mut opening.loaded4003 if let Shown::Section(session, _) | Shown::Created(session, _) = &mut opening.loaded
3926 && let Some(library) = self4004 && let Some(library) = self
3927 .notebooks4005 .notebooks
...@@ -3955,10 +4033,14 @@ impl State {...@@ -3955,10 +4033,14 @@ impl State {
3955 self.stop_recording(true)?;4033 self.stop_recording(true)?;
3956 // The page shown so far keeps what was typed while the next one loaded.4034 // The page shown so far keeps what was typed while the next one loaded.
3957 self.persist()?;4035 self.persist()?;
4036 // A page another pane still shows keeps that pane's history.
3958 let mut leaving = self4037 let mut leaving = self
3959 .session4038 .session
3960 .as_ref()4039 .as_ref()
3961 .filter(|session| !session.read_only(&self.pane.showing))4040 .filter(|session| {
4041 !session.read_only(&self.pane.showing)
4042 && !self.shown_parked(&session.key(), self.pane.showing.space)
4043 })
3962 .map(|_| self.pane.showing.space);4044 .map(|_| self.pane.showing.space);
3963 if let Some(session) = &self.session {4045 if let Some(session) = &self.session {
3964 let key = session.key();4046 let key = session.key();
...@@ -3985,7 +4067,8 @@ impl State {...@@ -3985,7 +4067,8 @@ impl State {
3985 // The section left stays open a while for coming back to; the notebook's4067 // The section left stays open a while for coming back to; the notebook's
3986 // background sync takes it over once it is closed.4068 // background sync takes it over once it is closed.
3987 self.pane.locked = None;4069 self.pane.locked = None;
3988 if let Some(previous) = self.session.replace(*session) {4070 let previous = self.session.replace(*session);
4071 if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) {
3989 let path = &previous.tabs[previous.tab].path;4072 let path = &previous.tabs[previous.tab].path;
3990 let locked = self.leave(&previous.library, path);4073 let locked = self.leave(&previous.library, path);
3991 let library = &previous.library;4074 let library = &previous.library;
...@@ -4009,6 +4092,7 @@ impl State {...@@ -4009,6 +4092,7 @@ impl State {
4009 self.save_settings();4092 self.save_settings();
4010 }4093 }
4011 }4094 }
4095 Shown::Held(..) => unreachable!("A held section is taken off the shelf"),
4012 Shown::Page(space) | Shown::Version(space, _) => {4096 Shown::Page(space) | Shown::Version(space, _) => {
4013 let session = self.session.as_mut().ok_or("No section is open")?;4097 let session = self.session.as_mut().ok_or("No section is open")?;
4014 let pages = session.section.pages()?;4098 let pages = session.section.pages()?;
...@@ -4080,6 +4164,12 @@ impl State {...@@ -4080,6 +4164,12 @@ impl State {
4080 self.list(&library);4164 self.list(&library);
4081 let shown = |shown: &Library| shown.location == library.location;4165 let shown = |shown: &Library| shown.location == library.location;
4082 let Some(path) = path else {4166 let Some(path) = path else {
4167 if library.first_section().is_none() {
4168 self.leave_sections(
4169 |session| shown(&session.library),
4170 |_, pane| pane.sectionless = Some(Arc::clone(&library)),
4171 );
4172 }
4083 if self.pane.sectionless.as_deref().is_some_and(shown)4173 if self.pane.sectionless.as_deref().is_some_and(shown)
4084 || self4174 || self
4085 .session4175 .session
...@@ -4106,7 +4196,12 @@ impl State {...@@ -4106,7 +4196,12 @@ impl State {
4106 if !shown(&session.library) {4196 if !shown(&session.library) {
4107 return Ok(());4197 return Ok(());
4108 }4198 }
4199 let old = Some(session.key());
4109 session.follow(library, path)?;4200 session.follow(library, path)?;
4201 let new = Some(session.key());
4202 for parked in (self.parked.iter_mut()).filter(|parked| parked.section == old) {
4203 parked.section.clone_from(&new);
4204 }
4110 self.title();4205 self.title();
4111 self.save_settings();4206 self.save_settings();
4112 Ok(())4207 Ok(())
...@@ -4119,6 +4214,7 @@ impl State {...@@ -4119,6 +4214,7 @@ impl State {
4119 Some(open) => *open = Arc::clone(library),4214 Some(open) => *open = Arc::clone(library),
4120 None => self.notebooks.push(Arc::clone(library)),4215 None => self.notebooks.push(Arc::clone(library)),
4121 }4216 }
4217 self.follow_shelved(library);
4122 if library.in_icloud() && library.downloading() {4218 if library.in_icloud() && library.downloading() {
4123 self.fetch(Arc::clone(library), None);4219 self.fetch(Arc::clone(library), None);
4124 }4220 }
...@@ -4308,21 +4404,17 @@ impl State {...@@ -4308,21 +4404,17 @@ impl State {
4308 Ok(())4404 Ok(())
4309 }4405 }
43104406
4311 /// Publishes the open section's stored edits now, rather than after a pause in typing,4407 /// Publishes the open sections' stored edits now, rather than after a pause in typing,
4312 /// and waits up to `wait` for them to reach the file.4408 /// and waits up to `wait` for them to reach their files.
4313 fn publish_now(&self, wait: std::time::Duration) {4409 fn publish_now(&self, wait: std::time::Duration) {
4314 let Some(session) = &self.session else {
4315 return;
4316 };
4317 let deadline = Instant::now() + wait;4410 let deadline = Instant::now() + wait;
4318 loop {4411 loop {
4319 session.section.wake();4412 let mut pending = false;
4320 if Instant::now() >= deadline4413 for session in self.sessions() {
4321 || session4414 session.section.wake();
4322 .section4415 pending |= !(session.section.pending()).is_ok_and(|pending| pending.is_empty());
4323 .pending()4416 }
4324 .is_ok_and(|pending| pending.is_empty())4417 if !pending || Instant::now() >= deadline {
4325 {
4326 return;4418 return;
4327 }4419 }
4328 std::thread::sleep(std::time::Duration::from_millis(50));4420 std::thread::sleep(std::time::Duration::from_millis(50));
...@@ -4348,16 +4440,14 @@ impl State {...@@ -4348,16 +4440,14 @@ impl State {
4348 return Ok(());4440 return Ok(());
4349 }4441 }
4350 let space = self.pane.showing.space;4442 let space = self.pane.showing.space;
4351 session.section.apply(4443 self.store(
4352 &self.author,4444 ops.into_iter()
4353 onestore::op::Edit {4445 .map(|op| onestore::op::Op::Page { space, op })
4354 at: filetime(),4446 .collect(),
4355 ops: ops
4356 .into_iter()
4357 .map(|op| onestore::op::Op::Page { space, op })
4358 .collect(),
4359 },
4360 )?;4447 )?;
4448 let Some(session) = &mut self.session else {
4449 return Ok(());
4450 };
4361 // The page list shows the title as it is typed, even when the caret left it since.4451 // The page list shows the title as it is typed, even when the caret left it since.
4362 let editor = &self.pane.view.editor;4452 let editor = &self.pane.view.editor;
4363 let title = (editor.outlines().iter())4453 let title = (editor.outlines().iter())
...@@ -4371,13 +4461,39 @@ impl State {...@@ -4371,13 +4461,39 @@ impl State {
4371 {4461 {
4372 session.pages = session.section.pages()?;4462 session.pages = session.section.pages()?;
4373 }4463 }
4374 self.edited(vec![space]);
4375 let editor = &self.pane.view.editor;4464 let editor = &self.pane.view.editor;
4376 self.undo4465 self.undo
4377 .edited(space, editor.history_depth(), editor.typing().is_some());4466 .edited(space, editor.history_depth(), editor.typing().is_some());
4378 Ok(())4467 Ok(())
4379 }4468 }
43804469
4470 /// Stores `ops` in the open section as one edit, as every edit made here is stored, and
4471 /// shows it in the other panes on the pages it changed.
4472 fn store(&mut self, ops: Vec<onestore::op::Op>) -> Result<(), Box<dyn Error>> {
4473 let session = self.session.as_ref().ok_or("No section is open")?;
4474 let mut spaces: Vec<ExGuid> = (ops.iter())
4475 .filter_map(|op| match op {
4476 onestore::op::Op::Page { space, .. } => Some(*space),
4477 _ => None,
4478 })
4479 .collect();
4480 spaces.dedup();
4481 let edit = onestore::op::Edit {
4482 at: filetime(),
4483 ops,
4484 };
4485 let refused = Arc::clone(&self.pane.refused);
4486 session
4487 .section
4488 .apply_with(&self.author, edit, move |result| {
4489 if let Err(notebook::Error::Rejected(_)) = result {
4490 refused.store(true, Ordering::Release);
4491 }
4492 })?;
4493 self.edited(spaces);
4494 Ok(())
4495 }
4496
4381 /// Shows the page as stored after a change made elsewhere, in place: the caret,4497 /// Shows the page as stored after a change made elsewhere, in place: the caret,
4382 /// selection, scroll and drawn pictures stay. Waits for marked text to end.4498 /// selection, scroll and drawn pictures stay. Waits for marked text to end.
4383 fn refresh(&mut self) -> Result<(), Box<dyn Error>> {4499 fn refresh(&mut self) -> Result<(), Box<dyn Error>> {
...@@ -4390,7 +4506,11 @@ impl State {...@@ -4390,7 +4506,11 @@ impl State {
4390 let Some(session) = &self.session else {4506 let Some(session) = &self.session else {
4391 return Ok(());4507 return Ok(());
4392 };4508 };
4393 let page = session.reader(self.pane.showing.space)()?;4509 let (space, version) = (self.pane.showing.space, self.pane.showing.version);
4510 let page = match version {
4511 Some(version) => session.version_reader(space, version)()?,
4512 None => session.reader(space)()?,
4513 };
4394 let response = self.pane.view.refresh(page)?;4514 let response = self.pane.view.refresh(page)?;
4395 self.respond(response);4515 self.respond(response);
4396 self.title();4516 self.title();
...@@ -4409,7 +4529,10 @@ impl State {...@@ -4409,7 +4529,10 @@ impl State {
4409 .view4529 .view
4410 .editor4530 .editor
4411 .cancel_composition(&mut self.pane.view.engine)?;4531 .cancel_composition(&mut self.pane.view.engine)?;
4412 platform::clear_marked_text(&self.window);4532 // The input method's marked text is the page's with the keyboard, if any.
4533 if self.pane.page_focused {
4534 platform::clear_marked_text(&self.window);
4535 }
4413 self.refresh()?;4536 self.refresh()?;
4414 platform::alert(4537 platform::alert(
4415 "Change not saved",4538 "Change not saved",
...@@ -4418,7 +4541,7 @@ impl State {...@@ -4418,7 +4541,7 @@ impl State {
4418 Ok(())4541 Ok(())
4419 }4542 }
44204543
4421 /// Applies what the section, and each notebook's closed sections, reported since the4544 /// Applies what the open sections, and each notebook's closed ones, reported since the
4422 /// last poll.4545 /// last poll.
4423 fn synced(&mut self) -> Result<(), Box<dyn Error>> {4546 fn synced(&mut self) -> Result<(), Box<dyn Error>> {
4424 self.wear_theme(false)?;4547 self.wear_theme(false)?;
...@@ -4457,87 +4580,7 @@ impl State {...@@ -4457,87 +4580,7 @@ impl State {
4457 }4580 }
4458 // Reports are rare: a status changed, or a section did.4581 // Reports are rare: a status changed, or a section did.
4459 self.window.request_redraw();4582 self.window.request_redraw();
4460 let Some(session) = &mut self.session else {4583 self.hear_sections();
4461 return Ok(());
4462 };
4463 let mut listed = false;
4464 let mut changed = false;
4465 let mut rejected = None;
4466 let mut elsewhere = Vec::new();
4467 for event in session.section.events() {
4468 use notebook::session::Event;
4469 match event {
4470 Event::Changed(spaces) => {
4471 listed = true;
4472 changed |= spaces.contains(&self.pane.showing.space);
4473 elsewhere.extend_from_slice(&spaces);
4474 self.search
4475 .changed(session.key(), session.section.replica(), spaces);
4476 }
4477 Event::Rejected { spaces, error } => {
4478 if spaces.contains(&self.pane.showing.space) {
4479 rejected = Some(error);
4480 } else {
4481 eprintln!("Saving failed: {error}");
4482 }
4483 }
4484 Event::Failed(error) => eprintln!("Not saving: {error}"),
4485 // Its guests hear of it sooner than the folder's watch would tell them.
4486 #[cfg(feature = "live")]
4487 Event::Attempt {
4488 status: notebook::EditStatus::Published { .. },
4489 ..
4490 } => {
4491 if let Some(host) = self.peers.hosts.get(&session.library.location) {
4492 host.touched(&[session.tabs[session.tab].path.clone()]);
4493 }
4494 }
4495 Event::Attempt { .. } | Event::Unreachable(_) => {}
4496 }
4497 }
4498 session.sync = session.section.sync_status()?;
4499 if !elsewhere.is_empty() {
4500 self.changed_elsewhere(&elsewhere);
4501 }
4502 let Some(session) = &mut self.session else {
4503 return Ok(());
4504 };
4505 if listed {
4506 let back = self.pane.showing.shown;
4507 session.pages = session.section.pages()?;
4508 session.refresh_conflicts(&mut self.pane.showing)?;
4509 session.refresh_history(&mut self.pane.showing)?;
4510 let listed = |space: ExGuid| session.pages.iter().any(|(page, ..)| *page == space);
4511 let gone = self.pane.showing.version.is_some_and(|version| {
4512 !session
4513 .page_versions(self.pane.showing.space)
4514 .iter()
4515 .any(|listed| listed.context == version)
4516 });
4517 if gone && listed(self.pane.showing.space) {
4518 // A version deleted elsewhere returns to its page.
4519 self.commands
4520 .push(Command::OpenPage(self.pane.showing.space));
4521 return Ok(());
4522 }
4523 if !listed(self.pane.showing.space)
4524 && session.conflict(self.pane.showing.space).is_none()
4525 {
4526 // A page removed elsewhere, or a conflict page deleted elsewhere, which
4527 // returns to its page.
4528 let open = back
4529 .filter(|page| listed(*page))
4530 .or(session.pages.first().map(|(page, ..)| *page))
4531 .ok_or("The section has no pages")?;
4532 self.commands.push(Command::OpenPage(open));
4533 return Ok(());
4534 }
4535 }
4536 if let Some(error) = rejected {
4537 self.refused(&error)?;
4538 } else if changed {
4539 self.refresh()?;
4540 }
4541 Ok(())4584 Ok(())
4542 }4585 }
45434586
...@@ -6554,7 +6597,7 @@ impl State {...@@ -6554,7 +6597,7 @@ impl State {
6554 // Quiet still when the mark sent on finding it quiet arrives, what a thread sent6597 // Quiet still when the mark sent on finding it quiet arrives, what a thread sent
6555 // as it ended has been taken, however many frames wait in the queue before it.6598 // as it ended has been taken, however many frames wait in the queue before it.
6556 let quiet = self.settled()6599 let quiet = self.settled()
6557 && self.pane.opening.is_none()6600 && self.still()
6558 && RUNNING.load(Ordering::Acquire) == 06601 && RUNNING.load(Ordering::Acquire) == 0
6559 && self.search.pending.load(Ordering::Relaxed) == 0;6602 && self.search.pending.load(Ordering::Relaxed) == 0;
6560 if let Some((path, settled, sent)) = self.replay_settle.take() {6603 if let Some((path, settled, sent)) = self.replay_settle.take() {
...@@ -6914,9 +6957,11 @@ impl ApplicationHandler<UserEvent> for App {...@@ -6914,9 +6957,11 @@ impl ApplicationHandler<UserEvent> for App {
6914 let deadline = Instant::now() + QUIT;6957 let deadline = Instant::now() + QUIT;
6915 state.publish_now(QUIT);6958 state.publish_now(QUIT);
6916 self.restart = state.updates.restarting();6959 self.restart = state.updates.restarting();
6917 let session = state.session.take();6960 let sessions: Vec<_> = (state.session.take().into_iter())
6961 .chain(state.shelved.drain(..))
6962 .collect();
6918 let libraries: Vec<_> = (state.notebooks.iter())6963 let libraries: Vec<_> = (state.notebooks.iter())
6919 .chain(session.as_ref().map(|session| &session.library))6964 .chain(sessions.iter().map(|session| &session.library))
6920 .cloned()6965 .cloned()
6921 .collect();6966 .collect();
6922 // Dropped sections and backgrounds stop without waiting, so the process could end first.6967 // Dropped sections and backgrounds stop without waiting, so the process could end first.
...@@ -6929,10 +6974,10 @@ impl ApplicationHandler<UserEvent> for App {...@@ -6929,10 +6974,10 @@ impl ApplicationHandler<UserEvent> for App {
6929 {6974 {
6930 background.stop();6975 background.stop();
6931 }6976 }
6932 if let Some(session) = session6977 for session in sessions {
6933 && let Err(error) = session.section.close()6978 if let Err(error) = session.section.close() {
6934 {6979 eprintln!("Synchronization stopped: {error}");
6935 eprintln!("Synchronization stopped: {error}");6980 }
6936 }6981 }
6937 libraries.iter().for_each(|library| library.close_kept());6982 libraries.iter().for_each(|library| library.close_kept());
6938 drop(closed);6983 drop(closed);
...@@ -7585,6 +7630,106 @@ mod tests {...@@ -7585,6 +7630,106 @@ mod tests {
7585 notebook::fs::remove_dir_all(&directory).unwrap();7630 notebook::fs::remove_dir_all(&directory).unwrap();
7586 }7631 }
75877632
7633 /// Each function of the app's sources outside tests: its file, its name, and its code
7634 /// without whitespace, a line each.
7635 fn functions() -> Vec<(String, String, Vec<String>)> {
7636 let mut functions = Vec::new();
7637 let sources = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
7638 for entry in notebook::fs::read_dir(sources).unwrap() {
7639 let path = entry.unwrap().path();
7640 if path.extension().is_none_or(|extension| extension != "rs") {
7641 continue;
7642 }
7643 let file = path.file_name().unwrap().to_string_lossy().into_owned();
7644 // A module only tests build is a test's.
7645 let declared = format!("mod {};", file.trim_end_matches(".rs"));
7646 let main = include_str!("main.rs").lines().collect::<Vec<_>>();
7647 if (main.windows(2)).any(|lines| {
7648 lines[1] == declared && lines[0].starts_with("#[cfg(") && lines[0].contains("test")
7649 }) {
7650 continue;
7651 }
7652 let source = notebook::fs::read_to_string(&path).unwrap();
7653 let source = source.split("#[cfg(test)]\nmod tests").next().unwrap();
7654 for line in source.lines() {
7655 let declared = line.strip_prefix(" ").unwrap_or(line);
7656 let declared = (declared.strip_prefix("pub(crate) "))
7657 .or(declared.strip_prefix("pub "))
7658 .unwrap_or(declared);
7659 let declared = declared.strip_prefix("async ").unwrap_or(declared);
7660 if let Some(name) = declared.strip_prefix("fn ") {
7661 let name = name.split(['(', '<']).next().unwrap_or(name);
7662 functions.push((file.clone(), name.to_owned(), Vec::new()));
7663 }
7664 if let Some((.., code)) = functions.last_mut() {
7665 code.push(line.split_whitespace().collect());
7666 }
7667 }
7668 }
7669 functions
7670 }
7671
7672 /// The functions of `functions()`, as `file::name`, holding code with one of `does` but
7673 /// none of `follows`, but those `excused` names.
7674 fn unfollowed(does: &[&str], follows: &[&str], excused: &[&str]) -> Vec<String> {
7675 let holds = |code: &[String], parts: &[&str]| {
7676 (code.iter()).any(|line| parts.iter().any(|part| line.contains(part)))
7677 };
7678 (functions().into_iter())
7679 .map(|(file, name, code)| (format!("{file}::{name}"), code))
7680 .filter(|(named, code)| {
7681 holds(code, does) && !holds(code, follows) && !excused.contains(&named.as_str())
7682 })
7683 .map(|(named, _)| named)
7684 .collect()
7685 }
7686
7687 /// Every edit made here reaches the other panes on the pages it changed, as a section
7688 /// reports no event for its own edits: a function writing to a section stores through
7689 /// `State::store`, or follows the write with `edited`, `edited_sections` or `section_edit`,
7690 /// or is one whose callers do.
7691 #[test]
7692 fn every_edit_made_here_reaches_the_other_panes() {
7693 let writes = [
7694 ".section.apply(",
7695 ".section.apply_with(",
7696 "replica().apply(",
7697 ".apply_async(",
7698 "restore_version_async(",
7699 "delete_pages_async(",
7700 "import_page_async(",
7701 "delete_versions_async(",
7702 "retire_async(",
7703 ];
7704 let follows = [".store(", ".edited(", ".edited_sections(", ".section_edit("];
7705 // Their callers follow them: `perform` the undo site's, `recycle_now` the bin's, and
7706 // Delete All Versions the versions `clear` deletes.
7707 let called = [
7708 "undo.rs::apply",
7709 "undo.rs::change",
7710 "recycle.rs::carry_out",
7711 "history.rs::clear",
7712 ];
7713 let unfollowed = unfollowed(&writes, &follows, &called);
7714 assert!(unfollowed.is_empty(), "{unfollowed:#?}");
7715 }
7716
7717 /// A section opens once, as its replica is `locking_mode=EXCLUSIVE`: a function opening
7718 /// one from its file first looks for it among those panes hold.
7719 #[test]
7720 fn a_section_a_pane_holds_never_opens_again() {
7721 let opens = [
7722 "library.open_async(",
7723 "library.open(",
7724 ".library.open_async(",
7725 ];
7726 let looks = [".held", "held:", "held_page(", "shelved", ".sessions()"];
7727 // Launch opens a section before any pane is parked, and a new notebook's is new.
7728 let first = ["main.rs::new", "manage.rs::create_notebook"];
7729 let unfollowed = unfollowed(&opens, &looks, &first);
7730 assert!(unfollowed.is_empty(), "{unfollowed:#?}");
7731 }
7732
7588 /// Times opening each section of a notebook and each of its pages, phase by phase, as a7733 /// Times opening each section of a notebook and each of its pages, phase by phase, as a
7589 /// switch does: `SNOWBOUND_SWITCH_NOTEBOOK=FOLDER`, or a share through `ONESTORE_SMB_LAB`7734 /// switch does: `SNOWBOUND_SWITCH_NOTEBOOK=FOLDER`, or a share through `ONESTORE_SMB_LAB`
7590 /// (`HOST:PORT`, share `agent`) at `ONESTORE_SMB_LAB_ROOT` with `ONESTORE_SMB_LAB_USER`7735 /// (`HOST:PORT`, share `agent`) at `ONESTORE_SMB_LAB_ROOT` with `ONESTORE_SMB_LAB_USER`
crates/snowbound/src/manage.rs+45-36
...@@ -6,7 +6,7 @@ use canvas::template::Template;...@@ -6,7 +6,7 @@ use canvas::template::Template;
6use notebook::session::Notebook;6use notebook::session::Notebook;
7use onestore::{7use onestore::{
8 ExGuid, PageCreation, PageEdit,8 ExGuid, PageCreation, PageEdit,
9 op::{Edit, Op, PageOp, SectionOp},9 op::{Op, PageOp, SectionOp},
10 page::{Image, Page, PageObject},10 page::{Image, Page, PageObject},
11};11};
12use std::{error::Error, path::Path, sync::Arc};12use std::{error::Error, path::Path, sync::Arc};
...@@ -218,16 +218,19 @@ impl State {...@@ -218,16 +218,19 @@ impl State {
218 space, before, level,218 space, before, level,
219 )?])));219 )?])));
220 }220 }
221 let session = self.session.as_ref().ok_or("No section is open")?;
222 let edit = Edit {
223 at: crate::filetime(),
224 ops,
225 };
226 // A section being rebuilt answers reads from before the page was made.221 // A section being rebuilt answers reads from before the page was made.
227 #[cfg(not(target_arch = "wasm32"))]222 #[cfg(not(target_arch = "wasm32"))]
228 session.section.replica().apply(&self.author, edit)?;223 {
224 let session = self.session.as_ref().ok_or("No section is open")?;
225 let edit = onestore::op::Edit {
226 at: crate::filetime(),
227 ops,
228 };
229 session.section.replica().apply(&self.author, edit)?;
230 self.edited(Vec::new());
231 }
229 #[cfg(target_arch = "wasm32")]232 #[cfg(target_arch = "wasm32")]
230 session.section.apply(&self.author, edit)?;233 self.store(ops)?;
231 let shown = self.pane.showing.space;234 let shown = self.pane.showing.space;
232 self.made(Change::Delete {235 self.made(Change::Delete {
233 pages: vec![space],236 pages: vec![space],
...@@ -319,16 +322,8 @@ impl State {...@@ -319,16 +322,8 @@ impl State {
319 if ops.is_empty() {322 if ops.is_empty() {
320 return Ok(());323 return Ok(());
321 }324 }
322 let session = self.session.as_ref().ok_or("No section is open")?;
323 let space = self.pane.showing.space;325 let space = self.pane.showing.space;
324 session.section.apply(326 self.store(ops.into_iter().map(|op| Op::Page { space, op }).collect())?;
325 &self.author,
326 Edit {
327 at: crate::filetime(),
328 ops: ops.into_iter().map(|op| Op::Page { space, op }).collect(),
329 },
330 )?;
331 self.edited(vec![space]);
332 self.refresh()327 self.refresh()
333 }328 }
334329
...@@ -579,8 +574,8 @@ impl State {...@@ -579,8 +574,8 @@ impl State {
579 }574 }
580575
581 /// Closes the notebooks in iCloud Drive once its account signs out or changes: their576 /// Closes the notebooks in iCloud Drive once its account signs out or changes: their
582 /// folders go with the account. Replicas holding edits stay, the open section's also577 /// folders go with the account. Replicas holding edits stay, the open sections' also
583 /// exported as a recovery archive; signing in again and reopening publishes them.578 /// exported as recovery archives; signing in again and reopening publishes them.
584 pub(crate) fn icloud_account_changed(&mut self) {579 pub(crate) fn icloud_account_changed(&mut self) {
585 let closing: Vec<Arc<Library>> = self580 let closing: Vec<Arc<Library>> = self
586 .notebooks581 .notebooks
...@@ -588,16 +583,18 @@ impl State {...@@ -588,16 +583,18 @@ impl State {
588 .filter(|library| library.in_icloud())583 .filter(|library| library.in_icloud())
589 .cloned()584 .cloned()
590 .collect();585 .collect();
591 if let Some(session) = &self.session586 let waiting = (self.sessions()).filter(|session| {
592 && session.library.in_icloud()587 session.library.in_icloud()
593 && session588 && (session.section.pending()).is_ok_and(|pending| !pending.is_empty())
594 .section589 });
595 .pending()590 for session in waiting {
596 .is_ok_and(|pending| !pending.is_empty())591 let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery"))
597 && let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery"))592 else {
598 {593 break;
594 };
595 let section = &session.tabs[session.tab].name;
599 let archive = folder.join(format!(596 let archive = folder.join(format!(
600 "{}-{}.sqlite",597 "{}-{section}-{}.sqlite",
601 session.library.name,598 session.library.name,
602 crate::filetime()599 crate::filetime()
603 ));600 ));
...@@ -617,6 +614,7 @@ impl State {...@@ -617,6 +614,7 @@ impl State {
617 /// Closes `library`: its files stay, its offline copies go unless edits wait in them,614 /// Closes `library`: its files stay, its offline copies go unless edits wait in them,
618 /// and the sidebar and the next launch leave it out.615 /// and the sidebar and the next launch leave it out.
619 pub(crate) fn close_notebook(&mut self, library: &Arc<Library>) {616 pub(crate) fn close_notebook(&mut self, library: &Arc<Library>) {
617 self.close_parked_in(library);
620 self.notebooks.retain(|open| !Arc::ptr_eq(open, library));618 self.notebooks.retain(|open| !Arc::ptr_eq(open, library));
621 self.undo.close(&library.location);619 self.undo.close(&library.location);
622 if let Some(background) = &library.background {620 if let Some(background) = &library.background {
...@@ -737,6 +735,8 @@ impl State {...@@ -737,6 +735,8 @@ impl State {
737 let Some(to) = library.renamed_location(&name) else {735 let Some(to) = library.renamed_location(&name) else {
738 return;736 return;
739 };737 };
738 // Their sections hold files in the folder.
739 self.close_parked_in(&library);
740 let ours = |shown: &Arc<Library>| Arc::ptr_eq(shown, &library);740 let ours = |shown: &Arc<Library>| Arc::ptr_eq(shown, &library);
741 let shown = self741 let shown = self
742 .session742 .session
...@@ -892,6 +892,13 @@ impl State {...@@ -892,6 +892,13 @@ impl State {
892 .as_ref()892 .as_ref()
893 .filter(|session| Arc::ptr_eq(&session.library, &library))893 .filter(|session| Arc::ptr_eq(&session.library, &library))
894 .map(|session| session.tabs[session.tab].path.clone());894 .map(|session| session.tabs[session.tab].path.clone());
895 let held: Vec<_> = (self.shelved.iter())
896 .filter(|held| held.library.location == library.location)
897 .filter_map(|held| {
898 let identity = held.library.section_identity(&held.tabs[held.tab].path)?;
899 Some((identity, Arc::clone(held.section.replica())))
900 })
901 .collect();
895 let notify = notify(self.proxy.clone());902 let notify = notify(self.proxy.clone());
896 let (proxy, requested) = (self.proxy.clone(), self.pane.loading);903 let (proxy, requested) = (self.proxy.clone(), self.pane.loading);
897 let showing = self.pane.switching.is_none() && self.pane.opening.is_none();904 let showing = self.pane.switching.is_none() && self.pane.opening.is_none();
...@@ -1025,6 +1032,11 @@ impl State {...@@ -1025,6 +1032,11 @@ impl State {
1025 if followed.as_deref() == Some(path.as_str()) {1032 if followed.as_deref() == Some(path.as_str()) {
1026 return Ok(Loaded::Library(library, Some(path)));1033 return Ok(Loaded::Library(library, Some(path)));
1027 }1034 }
1035 // As does a section a parked pane shows.
1036 let identity = library.section_identity(&path);
1037 if let Some((_, replica)) = held.iter().find(|(held, _)| Some(*held) == identity) {
1038 return crate::split::held_page(library, path, replica, None);
1039 }
1028 let section = library.open_async(&path, notify).await?;1040 let section = library.open_async(&path, notify).await?;
1029 let (session, space, page) = read_session(section, library, path, None)?;1041 let (session, space, page) = read_session(section, library, path, None)?;
1030 Ok(if fresh {1042 Ok(if fresh {
...@@ -1051,6 +1063,7 @@ impl State {...@@ -1051,6 +1063,7 @@ impl State {
1051 Loaded::Section(session, ..) | Loaded::Created(session, ..) => {1063 Loaded::Section(session, ..) | Loaded::Created(session, ..) => {
1052 Arc::clone(&session.library)1064 Arc::clone(&session.library)
1053 }1065 }
1066 Loaded::Held(library, ..) => Arc::clone(library),
1054 _ => unreachable!("A structure change returns its notebook"),1067 _ => unreachable!("A structure change returns its notebook"),
1055 };1068 };
1056 if !state1069 if !state
...@@ -1133,20 +1146,15 @@ impl State {...@@ -1133,20 +1146,15 @@ impl State {
1133 /// Moves or indents pages of the open section, in order.1146 /// Moves or indents pages of the open section, in order.
1134 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {1147 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {
1135 self.persist()?;1148 self.persist()?;
1136 let session = self.session.as_mut().ok_or("No section is open")?;1149 let session = self.session.as_ref().ok_or("No section is open")?;
1137 let order = session1150 let order = session
1138 .pages1151 .pages
1139 .iter()1152 .iter()
1140 .map(|(space, _, level)| (*space, *level))1153 .map(|(space, _, level)| (*space, *level))
1141 .collect();1154 .collect();
1142 let moved = edits.iter().map(PageEdit::space).collect();1155 let moved = edits.iter().map(PageEdit::space).collect();
1143 session.section.apply(1156 self.store(vec![Op::Section(SectionOp::Pages(edits))])?;
1144 &self.author,1157 let session = self.session.as_mut().ok_or("No section is open")?;
1145 Edit {
1146 at: crate::filetime(),
1147 ops: vec![Op::Section(SectionOp::Pages(edits))],
1148 },
1149 )?;
1150 session.pages = session.section.pages()?;1158 session.pages = session.section.pages()?;
1151 self.made(Change::Arrange { order, moved });1159 self.made(Change::Arrange { order, moved });
1152 Ok(())1160 Ok(())
...@@ -1206,6 +1214,7 @@ fn art_ops(page: &Page, art: Vec<Image>) -> Vec<PageOp> {...@@ -1206,6 +1214,7 @@ fn art_ops(page: &Page, art: Vec<Image>) -> Vec<PageOp> {
1206#[cfg(test)]1214#[cfg(test)]
1207mod tests {1215mod tests {
1208 use super::*;1216 use super::*;
1217 use onestore::op::Edit;
1209 use std::path::Path;1218 use std::path::Path;
12101219
1211 const AUTHOR: &str = "Rust Author";1220 const AUTHOR: &str = "Rust Author";
crates/snowbound/src/prefetch.rs+6-2
...@@ -293,7 +293,7 @@ impl State {...@@ -293,7 +293,7 @@ impl State {
293293
294 /// Leaves the page shown as it is, dropping whatever was opening in its place.294 /// Leaves the page shown as it is, dropping whatever was opening in its place.
295 pub fn stop_loading(&mut self) {295 pub fn stop_loading(&mut self) {
296 self.pane.loading += 1;296 self.pane.loading = self.request();
297 self.pane.opening = None;297 self.pane.opening = None;
298 self.pane.switching = None;298 self.pane.switching = None;
299 }299 }
...@@ -347,7 +347,11 @@ impl State {...@@ -347,7 +347,11 @@ impl State {
347 };347 };
348 let path = session.tabs[tab].path.clone();348 let path = session.tabs[tab].path.clone();
349 let key = session.library.key(&path);349 let key = session.library.key(&path);
350 if tab == session.tab || !self.prefetch.ask((key.clone(), None)) {350 // A section a parked pane holds is open already.
351 if tab == session.tab
352 || self.shelved.iter().any(|held| held.key() == key)
353 || !self.prefetch.ask((key.clone(), None))
354 {
351 return;355 return;
352 }356 }
353 let _ = self.prefetch.jobs.send(Job::Section {357 let _ = self.prefetch.jobs.send(Job::Section {
crates/snowbound/src/print.rs+13-6
...@@ -314,6 +314,8 @@ impl State {...@@ -314,6 +314,8 @@ impl State {
314 Arc::clone(&session.library),314 Arc::clone(&session.library),
315 );315 );
316 let replica = Arc::clone(session.section.replica());316 let replica = Arc::clone(session.section.replica());
317 // Sections parked panes show are open already, and read from their replicas.
318 let held = self.held(&library.location);
317 let layouts = Arc::clone(&self.layouts);319 let layouts = Arc::clone(&self.layouts);
318 let proxy = self.proxy.clone();320 let proxy = self.proxy.clone();
319 let paper = if setup.landscape {321 let paper = if setup.landscape {
...@@ -351,12 +353,17 @@ impl State {...@@ -351,12 +353,17 @@ impl State {
351 sections.push(open);353 sections.push(open);
352 continue;354 continue;
353 }355 }
354 let section = library.open_async(&path, || {}).await?;356 let pages = match held.iter().find(|(held, _)| *held == path) {
355 let pages = section357 Some((_, replica)) => (replica.pages()?.into_iter())
356 .pages()?358 .map(|(space, ..)| replica.page(space))
357 .into_iter()359 .collect::<Result<Vec<_>, _>>()?,
358 .map(|(space, ..)| section.page(space))360 None => {
359 .collect::<Result<Vec<_>, _>>()?;361 let section = library.open_async(&path, || {}).await?;
362 (section.pages()?.into_iter())
363 .map(|(space, ..)| section.page(space))
364 .collect::<Result<Vec<_>, _>>()?
365 }
366 };
360 sections.push((name, printed(pages)));367 sections.push((name, printed(pages)));
361 }368 }
362 sections369 sections
crates/snowbound/src/protection.rs+23-2
...@@ -81,7 +81,8 @@ impl State {...@@ -81,7 +81,8 @@ impl State {
81 ) -> Result<(), Box<dyn Error>> {81 ) -> Result<(), Box<dyn Error>> {
82 self.stop_loading();82 self.stop_loading();
83 self.persist()?;83 self.persist()?;
84 if let Some(previous) = self.session.take() {84 let previous = self.session.take();
85 if let Some(previous) = previous.and_then(|previous| self.shelve(previous)) {
85 let path = &previous.tabs[previous.tab].path;86 let path = &previous.tabs[previous.tab].path;
86 if self.leave(&previous.library, path) {87 if self.leave(&previous.library, path) {
87 previous.section.close()?;88 previous.section.close()?;
...@@ -332,8 +333,18 @@ impl State {...@@ -332,8 +333,18 @@ impl State {
332 self.relock()333 self.relock()
333 }334 }
334335
335 /// Shows the open section locked once its key is gone.336 /// Shows each open section locked once its key is gone.
336 fn relock(&mut self) -> Result<(), Box<dyn Error>> {337 fn relock(&mut self) -> Result<(), Box<dyn Error>> {
338 let path = |session: &crate::Session| session.tabs[session.tab].path.clone();
339 self.leave_sections(
340 |session| session.library.locked(&path(session)),
341 |session, pane| {
342 pane.locked = Some(Locked {
343 library: Arc::clone(&session.library),
344 path: path(session),
345 });
346 },
347 );
337 let Some(session) = &self.session else {348 let Some(session) = &self.session else {
338 return Ok(());349 return Ok(());
339 };350 };
...@@ -699,6 +710,16 @@ impl State {...@@ -699,6 +710,16 @@ impl State {
699 key: Option<onestore::protected::Key>,710 key: Option<onestore::protected::Key>,
700 password: Option<Zeroizing<String>>,711 password: Option<Zeroizing<String>>,
701 ) {712 ) {
713 // Its file is written anew, so a parked pane on it lets it go and shows it locked.
714 let ours = |session: &crate::Session| {
715 session.library.location == library.location && session.tabs[session.tab].path == path
716 };
717 self.leave_sections(ours, |session, pane| {
718 pane.locked = Some(Locked {
719 library: Arc::clone(&session.library),
720 path: path.clone(),
721 });
722 });
702 let replica = self723 let replica = self
703 .session724 .session
704 .as_ref()725 .as_ref()
crates/snowbound/src/recycle.rs+57-19
...@@ -5,7 +5,7 @@...@@ -5,7 +5,7 @@
55
6use crate::{Command, Library, Loaded, State, filetime, library, menus, notify, read_session};6use crate::{Command, Library, Loaded, State, filetime, library, menus, notify, read_session};
7use onestore::{7use onestore::{
8 ExGuid,8 ExGuid, PageCreation,
9 op::{Edit, Op, SectionOp},9 op::{Edit, Op, SectionOp},
10};10};
11use std::{error::Error, sync::Arc};11use std::{error::Error, sync::Arc};
...@@ -59,9 +59,14 @@ impl State {...@@ -59,9 +59,14 @@ impl State {
59 return;59 return;
60 }60 }
61 let paths: Vec<String> = library.tabs(BIN).into_iter().map(|tab| tab.path).collect();61 let paths: Vec<String> = library.tabs(BIN).into_iter().map(|tab| tab.path).collect();
62 let proxy = self.proxy.clone();62 let (proxy, held) = (self.proxy.clone(), self.held(&library.location));
63 self.load_async(move || async move {63 self.load_async(move || async move {
64 for path in paths {64 for path in paths {
65 if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path)
66 && !replica.pages()?.is_empty()
67 {
68 return crate::split::held_page(library, path, replica, None);
69 }
65 let section = library.open_async(&path, notify(proxy.clone())).await?;70 let section = library.open_async(&path, notify(proxy.clone())).await?;
66 if section.pages()?.is_empty() {71 if section.pages()?.is_empty() {
67 section.close_async().await?;72 section.close_async().await?;
...@@ -135,8 +140,24 @@ impl State {...@@ -135,8 +140,24 @@ impl State {
135 (spaces.clone().skip(at).find(kept)).or_else(|| spaces.take(at).rev().find(kept))140 (spaces.clone().skip(at).find(kept)).or_else(|| spaces.take(at).rev().find(kept))
136 });141 });
137 let (author, proxy) = (self.author.clone(), self.proxy.clone());142 let (author, proxy) = (self.author.clone(), self.proxy.clone());
143 // Sections parked panes show are open already.
144 let held = self.held(&library.location);
145 let target = match &request {
146 Request::Restore { path, .. } => (held.iter())
147 .find(|(held, _)| held == path)
148 .map(|(_, replica)| Arc::clone(replica)),
149 Request::Purge(_) => None,
150 };
151 let (key, notebook_key) = (session.key(), library.key(""));
152 // The page it shows is on its way, so the panes hearing of it leave this one be.
153 self.pane.switching = Some((None, crate::Instant::now()));
138 self.load_async(move || async move {154 self.load_async(move || async move {
139 carry_out(&library, &replica, request, &author).await?;155 carry_out(&library, &replica, request, &author, target).await?;
156 let spaces = gone.clone();
157 let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| {
158 state.edited_sections(&key, spaces, |shown| shown.starts_with(&notebook_key));
159 Ok(())
160 })));
140 if let Some(show) = if gone.contains(&shown) {161 if let Some(show) = if gone.contains(&shown) {
141 after162 after
142 } else {163 } else {
...@@ -148,6 +169,9 @@ impl State {...@@ -148,6 +169,9 @@ impl State {
148 let path = library169 let path = library
149 .first_section()170 .first_section()
150 .ok_or("The notebook has no sections")?;171 .ok_or("The notebook has no sections")?;
172 if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path) {
173 return crate::split::held_page(library, path, replica, None);
174 }
151 let section = library.open_async(&path, notify(proxy)).await?;175 let section = library.open_async(&path, notify(proxy)).await?;
152 let (session, space, page) = read_session(section, library, path, None)?;176 let (session, space, page) = read_session(section, library, path, None)?;
153 Ok(Loaded::Section(Box::new(session), space, page))177 Ok(Loaded::Section(Box::new(session), space, page))
...@@ -191,33 +215,44 @@ impl State {...@@ -191,33 +215,44 @@ impl State {
191215
192/// Does `request` to the bin's section `replica` holds, in `library`, as `author`: a page216/// Does `request` to the bin's section `replica` holds, in `library`, as `author`: a page
193/// restored goes to its section as one op, keeping its identity, a copy under a new one, and217/// restored goes to its section as one op, keeping its identity, a copy under a new one, and
194/// what leaves the bin goes from it as another.218/// what leaves the bin goes from it as another. A section a pane shows is reached through
219/// its replica in `held`, as it is open already.
195async fn carry_out(220async fn carry_out(
196 library: &Library,221 library: &Library,
197 replica: &notebook::Replica,222 replica: &notebook::Replica,
198 request: Request,223 request: Request,
199 author: &str,224 author: &str,
225 held: Option<Arc<notebook::Replica>>,
200) -> Result<(), Box<dyn Error>> {226) -> Result<(), Box<dyn Error>> {
201 let gone = match request {227 let gone = match request {
202 Request::Restore { space, path, copy } => {228 Request::Restore { space, path, copy } => {
203 let page = replica.page(space)?;229 let page = replica.page(space)?;
204 let section = library.open_async(&path, || {}).await?;230 let opened = match held {
205 if copy {231 Some(_) => None,
206 section.import_page_async(&page, author).await?;232 None => Some(library.open_async(&path, || {}).await?),
233 };
234 let target = match (&held, &opened) {
235 (Some(held), _) => Arc::clone(held),
236 (None, Some(section)) => Arc::clone(section.replica()),
237 (None, None) => unreachable!("a section is held or opened"),
238 };
239 let op = if copy {
240 let creation = PageCreation::new(None, Some(&page.title), author)?;
241 Op::Section(SectionOp::Import {
242 creation,
243 page: page.copy()?,
244 })
207 } else {245 } else {
208 let ops = vec![notebook::session::moved(&page, author)?];246 notebook::session::moved(&page, author)?
209 section247 };
210 .replica()248 let edit = Edit {
211 .apply_async(249 at: filetime(),
212 author,250 ops: vec![op],
213 Edit {251 };
214 at: filetime(),252 target.apply_async(author, edit).await?;
215 ops,253 if let Some(section) = opened {
216 },254 section.close_async().await?;
217 )
218 .await?;
219 }255 }
220 section.close_async().await?;
221 (!copy).then_some(vec![space]).unwrap_or_default()256 (!copy).then_some(vec![space]).unwrap_or_default()
222 }257 }
223 Request::Purge(spaces) => spaces,258 Request::Purge(spaces) => spaces,
...@@ -370,6 +405,7 @@ mod tests {...@@ -370,6 +405,7 @@ mod tests {
370 bin.replica(),405 bin.replica(),
371 restore(back, false),406 restore(back, false),
372 AUTHOR,407 AUTHOR,
408 None,
373 ))409 ))
374 .unwrap();410 .unwrap();
375 pollster::block_on(carry_out(411 pollster::block_on(carry_out(
...@@ -377,6 +413,7 @@ mod tests {...@@ -377,6 +413,7 @@ mod tests {
377 bin.replica(),413 bin.replica(),
378 restore(copied, true),414 restore(copied, true),
379 AUTHOR,415 AUTHOR,
416 None,
380 ))417 ))
381 .unwrap();418 .unwrap();
382 pollster::block_on(carry_out(419 pollster::block_on(carry_out(
...@@ -384,6 +421,7 @@ mod tests {...@@ -384,6 +421,7 @@ mod tests {
384 bin.replica(),421 bin.replica(),
385 Request::Purge(vec![purged]),422 Request::Purge(vec![purged]),
386 AUTHOR,423 AUTHOR,
424 None,
387 ))425 ))
388 .unwrap();426 .unwrap();
389 bin.close().unwrap();427 bin.close().unwrap();
crates/snowbound/src/rename.rs+3-9
...@@ -5,7 +5,7 @@...@@ -5,7 +5,7 @@
5use crate::{Command, Library, State, manage::Structure};5use crate::{Command, Library, State, manage::Structure};
6use onestore::{6use onestore::{
7 ExGuid,7 ExGuid,
8 op::{Edit, Op, PageOp},8 op::{Op, PageOp},
9 page::{Page, PageObject},9 page::{Page, PageObject},
10};10};
11use std::{error::Error, sync::Arc};11use std::{error::Error, sync::Arc};
...@@ -174,20 +174,14 @@ impl State {...@@ -174,20 +174,14 @@ impl State {
174 .find(|(page, ..)| *page == space)174 .find(|(page, ..)| *page == space)
175 .map(|(_, title, _)| title.clone())175 .map(|(_, title, _)| title.clone())
176 .unwrap_or_default();176 .unwrap_or_default();
177 session.section.apply(177 self.store(vec![op])?;
178 &self.author,178 let session = self.session.as_mut().ok_or("No section is open")?;
179 Edit {
180 at: crate::filetime(),
181 ops: vec![op],
182 },
183 )?;
184 session.pages = session.section.pages()?;179 session.pages = session.section.pages()?;
185 self.made(crate::undo::Change::Retitle {180 self.made(crate::undo::Change::Retitle {
186 page: space,181 page: space,
187 from: name,182 from: name,
188 to: old,183 to: old,
189 });184 });
190 self.edited(vec![space]);
191 self.refresh()185 self.refresh()
192 }186 }
193}187}
crates/snowbound/src/search.rs+9-6
...@@ -546,12 +546,15 @@ impl State {...@@ -546,12 +546,15 @@ impl State {
546 });546 });
547 }547 }
548548
549 /// Tells the index an edit changed page `space` of the open section.549 /// Follows an edit made here of pages `spaces` of the open section, or of its page list
550 pub(crate) fn edited(&self, spaces: Vec<ExGuid>) {550 /// without any: the index reads them again, and so do the other panes showing them.
551 if let Some(session) = &self.session {551 pub(crate) fn edited(&mut self, spaces: Vec<ExGuid>) {
552 self.search552 let Some(session) = &self.session else {
553 .changed(session.key(), session.section.replica(), spaces);553 return;
554 }554 };
555 let key = session.key();
556 (self.search).changed(key.clone(), session.section.replica(), spaces.clone());
557 self.show_elsewhere(&key, &spaces);
555 }558 }
556559
557 /// Whether `key` names a section the search's scope takes in.560 /// Whether `key` names a section the search's scope takes in.
crates/snowbound/src/sidebar.rs+5
...@@ -1453,6 +1453,7 @@ impl crate::State {...@@ -1453,6 +1453,7 @@ impl crate::State {
1453 .and_then(|path| self.last_pages.get(&crate::library::key(&location, path)))1453 .and_then(|path| self.last_pages.get(&crate::library::key(&location, path)))
1454 .copied();1454 .copied();
1455 let (cache, notify) = (self.cache.clone(), crate::notify(self.proxy.clone()));1455 let (cache, notify) = (self.cache.clone(), crate::notify(self.proxy.clone()));
1456 let held = self.held(&location);
1456 self.load_async(move || async move {1457 self.load_async(move || async move {
1457 let library = match open {1458 let library = match open {
1458 Some(library) => library,1459 Some(library) => library,
...@@ -1476,6 +1477,10 @@ impl crate::State {...@@ -1476,6 +1477,10 @@ impl crate::State {
1476 }1477 }
1477 return Err("This folder holds no notebook sections.".into());1478 return Err("This folder holds no notebook sections.".into());
1478 };1479 };
1480 // A section a parked pane shows is open already.
1481 if let Some((_, replica)) = held.iter().find(|(held, _)| *held == path) {
1482 return crate::split::held_page(library, path, replica, left);
1483 }
1479 let section = library.open_async(&path, notify).await?;1484 let section = library.open_async(&path, notify).await?;
1480 let (session, space, page) = crate::read_session(section, library, path, left)?;1485 let (session, space, page) = crate::read_session(section, library, path, left)?;
1481 Ok(crate::Loaded::Section(Box::new(session), space, page))1486 Ok(crate::Loaded::Section(Box::new(session), space, page))
crates/snowbound/src/split.rs created+389
...@@ -0,0 +1,389 @@
1//! The page area split into panes, each a page view of its own, as Word's View > Split and an
2//! editor's groups split theirs. One pane has the focus and the chrome around it; the others
3//! are parked. Panes on one section share its `Session`, since a section's replica opens
4//! once (`locking_mode=EXCLUSIVE`).
5
6use crate::{Command, Library, Loaded, Pane, Session, State};
7use notebook::{Replica, session::Event};
8use onestore::ExGuid;
9use std::{
10 error::Error,
11 sync::{Arc, atomic::Ordering},
12};
13
14/// A pane out of focus, and the section it shows by `Library::key`; the focused pane's is
15/// `State::session`.
16pub struct Parked {
17 pub pane: Pane,
18 pub section: Option<String>,
19}
20
21impl State {
22 /// The open sections: the focused pane's, then those only parked panes show.
23 pub(crate) fn sessions(&self) -> impl Iterator<Item = &Session> {
24 self.session.iter().chain(&self.shelved)
25 }
26
27 /// Shelves `session`, a section the focused pane left, while a parked pane shows it, or
28 /// gives it back to be kept or closed.
29 pub(crate) fn shelve(&mut self, session: Session) -> Option<Session> {
30 let key = Some(session.key());
31 if !(self.parked.iter()).any(|parked| parked.section == key) {
32 return Some(session);
33 }
34 self.shelved.push(session);
35 None
36 }
37
38 /// The replicas of sections of the notebook at `location` that parked panes hold, by
39 /// catalog path: a section opens once, so what opens one reads these instead.
40 pub(crate) fn held(&self, location: &str) -> Vec<(String, Arc<Replica>)> {
41 (self.shelved.iter())
42 .filter(|held| held.library.location == location)
43 .map(|held| {
44 let path = held.tabs[held.tab].path.clone();
45 (path, Arc::clone(held.section.replica()))
46 })
47 .collect()
48 }
49
50 /// Takes the section `key` from the shelf, as the focused pane opens it.
51 pub(crate) fn unshelve(&mut self, key: &str) -> Option<Session> {
52 let at = (self.shelved.iter()).position(|session| session.key() == key)?;
53 Some(self.shelved.swap_remove(at))
54 }
55
56 /// Shows what `instead` makes of each open section `gone` picks in the parked panes on
57 /// it, and closes those only they showed; the focused pane's is the caller's to close.
58 pub(crate) fn leave_sections(
59 &mut self,
60 gone: impl Fn(&Session) -> bool,
61 instead: impl Fn(&Session, &mut Pane),
62 ) {
63 let (closing, kept) = std::mem::take(&mut self.shelved)
64 .into_iter()
65 .partition::<Vec<_>, _>(|session| gone(session));
66 self.shelved = kept;
67 for session in (self.session.iter().filter(|session| gone(session))).chain(&closing) {
68 let key = Some(session.key());
69 for parked in (self.parked.iter_mut()).filter(|parked| parked.section == key) {
70 parked.section = None;
71 instead(session, &mut parked.pane);
72 }
73 }
74 for session in closing {
75 if let Err(error) = session.section.close() {
76 eprintln!("Synchronization stopped: {error}");
77 }
78 }
79 }
80
81 /// Closes the parked panes on notebook `library`, and the sections only they showed.
82 pub(crate) fn close_parked_in(&mut self, library: &Arc<Library>) {
83 let ours = |shown: &Library| shown.location == library.location;
84 self.leave_sections(
85 |session| ours(&session.library),
86 |_, pane| pane.sectionless = Some(Arc::clone(library)),
87 );
88 self.close_parked(|Parked { pane, .. }| {
89 pane.sectionless.as_deref().is_some_and(ours)
90 || (pane.locked.as_ref()).is_some_and(|locked| ours(&locked.library))
91 });
92 }
93
94 /// Closes the parked panes `gone` picks.
95 fn close_parked(&mut self, gone: impl Fn(&Parked) -> bool) {
96 self.parked.retain(|parked| !gone(parked));
97 }
98
99 /// Moves the sections only parked panes show in `library`, a notebook read again, to
100 /// where it keeps them now; a pane on one it no longer has closes.
101 pub(crate) fn follow_shelved(&mut self, library: &Arc<Library>) {
102 let mut gone = Vec::new();
103 for session in &mut self.shelved {
104 if session.library.location != library.location
105 || Arc::ptr_eq(&session.library, library)
106 {
107 continue;
108 }
109 let old = Some(session.key());
110 let identity = (session.library).section_identity(&session.tabs[session.tab].path);
111 let path = library.catalog().and_then(|catalog| {
112 (catalog.sections())
113 .find(|section| Some(section.file_id) == identity)
114 .map(|section| section.path.clone())
115 });
116 match path.map(|path| session.follow(Arc::clone(library), &path)) {
117 Some(Ok(())) => {
118 let new = Some(session.key());
119 for parked in (self.parked.iter_mut()).filter(|parked| parked.section == old) {
120 parked.section.clone_from(&new);
121 }
122 }
123 _ => gone.extend(old),
124 }
125 }
126 if !gone.is_empty() {
127 self.close_parked(|parked| {
128 parked
129 .section
130 .as_ref()
131 .is_some_and(|key| gone.contains(key))
132 });
133 self.leave_sections(|session| gone.contains(&session.key()), |_, _| {});
134 }
135 }
136
137 /// Whether a parked pane shows page `space` of section `key`.
138 pub(crate) fn shown_parked(&self, key: &str, space: ExGuid) -> bool {
139 self.parked.iter().any(|parked| {
140 parked.section.as_deref() == Some(key) && parked.pane.showing.space == space
141 })
142 }
143
144 /// Swaps parked pane `index` and the focused one, and their sections with them.
145 pub(crate) fn swap_pane(&mut self, index: usize) {
146 let parked = &mut self.parked[index];
147 std::mem::swap(&mut self.pane, &mut parked.pane);
148 let left = self.session.as_ref().map(Session::key);
149 let wanted = std::mem::replace(&mut parked.section, left);
150 if wanted != parked.section {
151 let taken = wanted.and_then(|key| self.unshelve(&key));
152 if let Some(left) = std::mem::replace(&mut self.session, taken) {
153 self.shelved.push(left);
154 }
155 }
156 }
157
158 /// Runs `then` in parked pane `index` as though it had the focus, which stays where it
159 /// was, with the keyboard and any recording. What `then` asks for after the frame is done
160 /// in that pane too.
161 pub(crate) fn in_pane(
162 &mut self,
163 index: usize,
164 then: impl FnOnce(&mut State) -> Result<(), Box<dyn Error>>,
165 ) -> Result<(), Box<dyn Error>> {
166 let (focus, queued) = (self.ui.focused(), self.commands.len());
167 let media = std::mem::take(&mut self.media);
168 self.swap_pane(index);
169 let mut done = then(self);
170 for command in self.commands.split_off(queued) {
171 done = done.and_then(|()| self.apply(command));
172 }
173 self.swap_pane(index);
174 self.media = media;
175 self.ui.set_focus(focus);
176 self.title();
177 done.and_then(|()| self.update_accessibility(true))
178 }
179
180 /// Whether no pane has a page on its way.
181 pub(crate) fn still(&self) -> bool {
182 std::iter::once(&self.pane)
183 .chain(self.parked.iter().map(|parked| &parked.pane))
184 .all(|pane| pane.opening.is_none() && pane.switching.is_none())
185 }
186
187 /// A request number no load has had, so a late read reaches only the pane that asked.
188 pub(crate) fn request(&mut self) -> u64 {
189 self.requests += 1;
190 self.requests
191 }
192
193 /// Shows an edit of the focused pane's section, `key`, in the parked panes on it, as its
194 /// own edits come back as no event: a pane on a page in `spaces` reads it again, and,
195 /// where the edit changed the page list without any, a pane whose page left opens another.
196 pub(crate) fn show_elsewhere(&mut self, key: &str, spaces: &[ExGuid]) {
197 for index in 0..self.parked.len() {
198 let parked = &self.parked[index];
199 let showing = &parked.pane.showing;
200 // A version of a page stays as it was.
201 let changed = showing.version.is_none() && spaces.contains(&showing.space);
202 if parked.section.as_deref() != Some(key) || !(spaces.is_empty() || changed) {
203 continue;
204 }
205 let shown = self.in_pane(index, |state| {
206 if spaces.is_empty() {
207 state.relist().map(drop)
208 } else {
209 state.refresh()
210 }
211 });
212 if let Err(error) = shown {
213 eprintln!("{error}");
214 }
215 }
216 }
217
218 /// Follows an edit made here away from the frame to section `key`, and to any others of
219 /// its notebook `touched` picks, which comes back as no event and may land after the
220 /// focus moved: the index reads pages `spaces` of `key` again, and each pane on a section
221 /// touched reads its page list and page again.
222 pub(crate) fn edited_sections(
223 &mut self,
224 key: &str,
225 spaces: Vec<ExGuid>,
226 touched: impl Fn(&str) -> bool,
227 ) {
228 if let Some(session) = self.sessions().find(|session| session.key() == key) {
229 let replica = session.section.replica();
230 (self.search).changed(key.to_owned(), replica, spaces);
231 }
232 // A pane with a page on its way, as the one that did this has, shows it on arrival.
233 let reread = |state: &mut State| {
234 if state.pane.switching.is_none() && !state.relist()? {
235 state.refresh()?;
236 }
237 Ok(())
238 };
239 if (self.session.as_ref()).is_some_and(|session| touched(&session.key()))
240 && let Err(error) = reread(self)
241 {
242 eprintln!("{error}");
243 }
244 for index in 0..self.parked.len() {
245 if self.parked[index].section.as_deref().is_some_and(&touched)
246 && let Err(error) = self.in_pane(index, reread)
247 {
248 eprintln!("{error}");
249 }
250 }
251 }
252
253 /// Takes what each open section reported since the last poll once, and answers it in
254 /// every pane on that section; a pane failing to leaves the others to.
255 pub(crate) fn hear_sections(&mut self) {
256 let mut heard = Vec::new();
257 for session in self.session.iter_mut().chain(&mut self.shelved) {
258 heard.push((session.key(), session.section.events()));
259 match session.section.sync_status() {
260 Ok(sync) => session.sync = sync,
261 Err(error) => eprintln!("{error}"),
262 }
263 }
264 for (session, (key, events)) in self.sessions().zip(&heard) {
265 let mut elsewhere = Vec::new();
266 for event in events {
267 match event {
268 Event::Changed(spaces) => {
269 elsewhere.extend_from_slice(spaces);
270 let replica = session.section.replica();
271 (self.search).changed(key.clone(), replica, spaces.clone());
272 }
273 Event::Rejected { error, .. } => eprintln!("Saving failed: {error}"),
274 Event::Failed(error) => eprintln!("Not saving: {error}"),
275 // Its guests hear of it sooner than the folder's watch would tell them.
276 #[cfg(feature = "live")]
277 Event::Attempt {
278 status: notebook::EditStatus::Published { .. },
279 ..
280 } => {
281 if let Some(host) = self.peers.hosts.get(&session.library.location) {
282 host.touched(&[session.tabs[session.tab].path.clone()]);
283 }
284 }
285 _ => {}
286 }
287 }
288 if !elsewhere.is_empty() {
289 self.changed_elsewhere(session, &elsewhere);
290 }
291 }
292 let events = |key: Option<&String>| {
293 (heard.iter())
294 .find(|(heard, _)| Some(heard) == key)
295 .map(|(_, events)| events)
296 };
297 if let Some(events) = events(self.session.as_ref().map(Session::key).as_ref())
298 && let Err(error) = self.hear(events)
299 {
300 eprintln!("{error}");
301 }
302 for index in 0..self.parked.len() {
303 if let Some(events) = events(self.parked[index].section.as_ref())
304 && let Err(error) = self.in_pane(index, |state| state.hear(events))
305 {
306 eprintln!("{error}");
307 }
308 }
309 }
310
311 /// Answers in the focused pane what its section reported: the page list read again, and
312 /// the page read again where another writer changed it or an edit of it was refused. The
313 /// pane that stored a refused edit tells of the refusal.
314 fn hear(&mut self, events: &[Event]) -> Result<(), Box<dyn Error>> {
315 let space = self.pane.showing.space;
316 let (mut listed, mut changed, mut rejected, mut refusals) = (false, false, None, false);
317 for event in events {
318 match event {
319 Event::Changed(spaces) => {
320 listed = true;
321 changed |= spaces.contains(&space);
322 }
323 Event::Rejected { spaces, error } => {
324 refusals = true;
325 if spaces.contains(&space) {
326 rejected = Some(error);
327 }
328 }
329 _ => {}
330 }
331 }
332 let made = refusals && self.pane.refused.swap(false, Ordering::AcqRel);
333 if listed && self.relist()? {
334 return Ok(());
335 }
336 match rejected {
337 Some(error) if made => self.refused(error),
338 _ if changed || rejected.is_some() => self.refresh(),
339 _ => Ok(()),
340 }
341 }
342
343 /// Reads the open section's page list again, and opens another page where the one
344 /// shown, or the version of it, left; whether it did.
345 pub(crate) fn relist(&mut self) -> Result<bool, Box<dyn Error>> {
346 let Some(session) = &mut self.session else {
347 return Ok(false);
348 };
349 let showing = &mut self.pane.showing;
350 let back = showing.shown;
351 session.pages = session.section.pages()?;
352 session.refresh_conflicts(showing)?;
353 session.refresh_history(showing)?;
354 let listed = |space: ExGuid| session.pages.iter().any(|(page, ..)| *page == space);
355 let gone = showing.version.is_some_and(|version| {
356 !(session.page_versions(showing.space).iter()).any(|listed| listed.context == version)
357 });
358 let open = if gone && listed(showing.space) {
359 // A version deleted elsewhere returns to its page.
360 showing.space
361 } else if !listed(showing.space) && session.conflict(showing.space).is_none() {
362 // A page removed elsewhere, or a conflict page deleted elsewhere, which returns to
363 // its page.
364 back.filter(|page| listed(*page))
365 .or(session.pages.first().map(|(page, ..)| *page))
366 .ok_or("The section has no pages")?
367 } else {
368 return Ok(false);
369 };
370 self.commands.push(Command::OpenPage(open));
371 Ok(true)
372 }
373}
374
375/// Shows `library`'s section at catalog `path`, which a parked pane holds open through
376/// `replica`, at page `space` where it lists it, else at its first.
377pub fn held_page(
378 library: Arc<Library>,
379 path: String,
380 replica: &Replica,
381 space: Option<ExGuid>,
382) -> Result<Loaded, Box<dyn Error>> {
383 let pages = replica.pages()?;
384 let space = space
385 .filter(|space| pages.iter().any(|(listed, ..)| listed == space))
386 .or(pages.first().map(|(space, ..)| *space))
387 .ok_or("The section has no pages")?;
388 Ok(Loaded::Held(library, path, space, replica.page(space)?))
389}
crates/snowbound/src/sync.rs+5-1
...@@ -1060,7 +1060,7 @@ impl State {...@@ -1060,7 +1060,7 @@ impl State {
1060 /// Builds the sync status popup while it is open: on the notebook its context menu1060 /// Builds the sync status popup while it is open: on the notebook its context menu
1061 /// opened it for, or the open section's.1061 /// opened it for, or the open section's.
1062 pub(crate) fn sync_popup(&mut self) -> Result<(), Box<dyn Error>> {1062 pub(crate) fn sync_popup(&mut self) -> Result<(), Box<dyn Error>> {
1063 let (ui, notebooks) = (&mut self.ui, &self.notebooks);1063 let (ui, notebooks, shelved) = (&mut self.ui, &self.notebooks, &self.shelved);
1064 let update = self.updates.status();1064 let update = self.updates.status();
1065 let Some(session) = &mut self.session else {1065 let Some(session) = &mut self.session else {
1066 ui.close_popup(id());1066 ui.close_popup(id());
...@@ -1126,6 +1126,7 @@ impl State {...@@ -1126,6 +1126,7 @@ impl State {
1126 if picked.offline {1126 if picked.offline {
1127 library::set_offline(!offline);1127 library::set_offline(!offline);
1128 session.section.set_offline(!offline);1128 session.section.set_offline(!offline);
1129 (shelved.iter()).for_each(|held| held.section.set_offline(!offline));
1129 notebooks1130 notebooks
1130 .iter()1131 .iter()
1131 .for_each(|library| library.set_offline(!offline));1132 .for_each(|library| library.set_offline(!offline));
...@@ -1133,6 +1134,9 @@ impl State {...@@ -1133,6 +1134,9 @@ impl State {
1133 if own {1134 if own {
1134 session.section.wake();1135 session.section.wake();
1135 }1136 }
1137 (shelved.iter())
1138 .filter(|held| Arc::ptr_eq(&held.library, &library))
1139 .for_each(|held| held.section.wake());
1136 backgrounds.for_each(|background| background.wake());1140 backgrounds.for_each(|background| background.wake());
1137 }1141 }
1138 if let Some(file) = file.filter(|_| picked.show_file) {1142 if let Some(file) = file.filter(|_| picked.show_file) {
crates/snowbound/src/undo.rs+38-14
...@@ -345,6 +345,9 @@ fn imported(op: &Op) -> ExGuid {...@@ -345,6 +345,9 @@ fn imported(op: &Op) -> ExGuid {
345struct Site {345struct Site {
346 replica: Arc<Replica>,346 replica: Arc<Replica>,
347 library: Arc<Library>,347 library: Arc<Library>,
348 /// The replicas of the notebook's sections parked panes show, open already, by catalog
349 /// path.
350 held: Vec<(String, Arc<Replica>)>,
348 author: String,351 author: String,
349 fresh: PageCreation,352 fresh: PageCreation,
350}353}
...@@ -416,6 +419,19 @@ impl Site {...@@ -416,6 +419,19 @@ impl Site {
416 entry_of(self.library.catalog()?, identity).map(|(_, path)| path)419 entry_of(self.library.catalog()?, identity).map(|(_, path)| path)
417 }420 }
418421
422 /// The replica of the notebook's section at catalog `path`, with the section where it
423 /// was opened for this, which `release` closes after.
424 async fn reach(
425 &self,
426 path: &str,
427 ) -> Result<(Arc<Replica>, Option<notebook::session::Section>), Box<dyn Error>> {
428 if let Some((_, replica)) = self.held.iter().find(|(held, _)| held == path) {
429 return Ok((Arc::clone(replica), None));
430 }
431 let section = self.library.open_async(path, || {}).await?;
432 Ok((Arc::clone(section.replica()), Some(section)))
433 }
434
419 /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be,435 /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be,
420 /// keeps it open, where they are tried again until they are.436 /// keeps it open, where they are tried again until they are.
421 async fn release(&self, path: &str, section: notebook::session::Section) {437 async fn release(&self, path: &str, section: notebook::session::Section) {
...@@ -588,9 +604,8 @@ impl Site {...@@ -588,9 +604,8 @@ impl Site {
588 let level = listed[from].2;604 let level = listed[from].2;
589 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];605 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];
590 let (show, added) = self.after(&listed, &[page], None, &mut ops);606 let (show, added) = self.after(&listed, &[page], None, &mut ops);
591 let section = self.library.open_async(&path, || {}).await?;607 let (other, opened) = self.reach(&path).await?;
592 section608 other
593 .replica()
594 .apply_async(609 .apply_async(
595 &self.author,610 &self.author,
596 Edit {611 Edit {
...@@ -599,7 +614,9 @@ impl Site {...@@ -599,7 +614,9 @@ impl Site {
599 },614 },
600 )615 )
601 .await?;616 .await?;
602 self.release(&path, section).await;617 if let Some(section) = opened {
618 self.release(&path, section).await;
619 }
603 let edit = Edit {620 let edit = Edit {
604 at: crate::filetime(),621 at: crate::filetime(),
605 ops,622 ops,
...@@ -634,12 +651,14 @@ impl Site {...@@ -634,12 +651,14 @@ impl Site {
634 let Some(path) = self.section_path(target) else {651 let Some(path) = self.section_path(target) else {
635 return Ok(None);652 return Ok(None);
636 };653 };
637 let section = self.library.open_async(&path, || {}).await?;654 let (other, opened) = self.reach(&path).await?;
638 if !(section.pages()?.iter()).any(|(listed, ..)| *listed == page) {655 if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) {
639 self.release(&path, section).await;656 if let Some(section) = opened {
657 self.release(&path, section).await;
658 }
640 return Ok(None);659 return Ok(None);
641 }660 }
642 let sent = section.replica().moving(page)?;661 let sent = other.moving(page)?;
643 let import = notebook::session::moved(sent.page(), &self.author)?;662 let import = notebook::session::moved(sent.page(), &self.author)?;
644 let back = imported(&import);663 let back = imported(&import);
645 let mut ops = vec![664 let mut ops = vec![
...@@ -656,11 +675,10 @@ impl Site {...@@ -656,11 +675,10 @@ impl Site {
656 at: crate::filetime(),675 at: crate::filetime(),
657 ops: vec![Op::Section(SectionOp::Delete(vec![page]))],676 ops: vec![Op::Section(SectionOp::Delete(vec![page]))],
658 };677 };
659 let retired = section678 let retired = other.retire_async(&self.author, delete, sent).await;
660 .replica()679 if let Some(section) = opened {
661 .retire_async(&self.author, delete, sent)680 self.release(&path, section).await;
662 .await;681 }
663 self.release(&path, section).await;
664 Applied {682 Applied {
665 undo: (retired.map(|_| Change::Send { page: back, target }))683 undo: (retired.map(|_| Change::Send { page: back, target }))
666 .map_err(|error| crate::plain(&error, "page")),684 .map_err(|error| crate::plain(&error, "page")),
...@@ -1111,9 +1129,13 @@ impl State {...@@ -1111,9 +1129,13 @@ impl State {
1111 } else {1129 } else {
1112 None1130 None
1113 };1131 };
1132 let held = self.held(&session.library.location);
1133 let key = session.key();
1134 let notebook_key = session.library.key("");
1114 let mut site = Site {1135 let mut site = Site {
1115 replica: Arc::clone(session.section.replica()),1136 replica: Arc::clone(session.section.replica()),
1116 library: Arc::clone(&session.library),1137 library: Arc::clone(&session.library),
1138 held,
1117 author: self.author.clone(),1139 author: self.author.clone(),
1118 fresh: self.dated_page(None, "")?,1140 fresh: self.dated_page(None, "")?,
1119 };1141 };
...@@ -1181,7 +1203,8 @@ impl State {...@@ -1181,7 +1203,8 @@ impl State {
1181 }1203 }
1182 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),1204 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),
1183 }1205 }
1184 state.edited(Vec::new());1206 // Its section, and the one a page went to or came from, wherever the focus is.
1207 state.edited_sections(&key, Vec::new(), |shown| shown.starts_with(&notebook_key));
1185 Ok(())1208 Ok(())
1186 })));1209 })));
1187 drop(changing);1210 drop(changing);
...@@ -1464,6 +1487,7 @@ mod tests {...@@ -1464,6 +1487,7 @@ mod tests {
1464 Site {1487 Site {
1465 replica: Arc::clone(self.section().replica()),1488 replica: Arc::clone(self.section().replica()),
1466 library: Arc::clone(&self.library),1489 library: Arc::clone(&self.library),
1490 held: Vec::new(),
1467 author: AUTHOR.into(),1491 author: AUTHOR.into(),
1468 fresh: dated(),1492 fresh: dated(),
1469 }1493 }
crates/snowbound/src/unread.rs+2-5
...@@ -297,12 +297,9 @@ impl State {...@@ -297,12 +297,9 @@ impl State {
297 viewing.map(|(notebook, section, space)| (notebook, section, space, false));297 viewing.map(|(notebook, section, space)| (notebook, section, space, false));
298 }298 }
299299
300 /// Pages of the open section another client changed, as its sync reports them: those300 /// Pages of an open section another client changed, as its sync reports them: those
301 /// another author changed last are unread, once read on a thread of their own.301 /// another author changed last are unread, once read on a thread of their own.
302 pub(crate) fn changed_elsewhere(&mut self, spaces: &[ExGuid]) {302 pub(crate) fn changed_elsewhere(&self, session: &crate::Session, spaces: &[ExGuid]) {
303 let Some(session) = &self.session else {
304 return;
305 };
306 let Some(section) = session303 let Some(section) = session
307 .library304 .library
308 .section_identity(&session.tabs[session.tab].path)305 .section_identity(&session.tabs[session.tab].path)
crates/snowbound/tests/replay.rs+25
...@@ -313,6 +313,31 @@ fn page_tabs(tree: &str) -> Vec<String> {...@@ -313,6 +313,31 @@ fn page_tabs(tree: &str) -> Vec<String> {
313 .collect()313 .collect()
314}314}
315315
316/// Undoing a new page shows the page it was made from, though the page shown hears of the
317/// undo before the page it shows arrives. Waits, unlike settling, leave that race open.
318#[test]
319fn undoing_a_new_page_returns_to_the_page_it_was_made_from() {
320 let scratch = Scratch::new("undo-new-page");
321 let notebook = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
322 let chord =
323 |modifiers: &'static str, key: &'static str| [modifiers, key, "modifiers", "wait 1000"];
324 // The Bed rotation tab, then a new page with a title.
325 let mut steps = vec!["move 1003 139", "press", "release", "wait 1000"];
326 steps.extend(chord("modifiers command", "key n"));
327 steps.extend(["type Hello", "wait 1000"]);
328 for _ in 0..2 {
329 steps.extend(chord("modifiers command", "key z"));
330 }
331 steps.push("accessibility undone");
332 let [undone] = replay(&scratch, Some(&notebook), &steps)
333 .try_into()
334 .unwrap();
335 assert!(
336 undone.starts_with(r#"Window "Bed rotation · Garden.one""#),
337 "{undone}"
338 );
339}
340
316/// Undo walks back through two new pages and what was typed on each, crossing pages as341/// Undo walks back through two new pages and what was typed on each, crossing pages as
317/// it goes: each page keeps its own history once left, and a new page goes once what was342/// it goes: each page keeps its own history once left, and a new page goes once what was
318/// typed on it has gone.343/// typed on it has gone.