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 {
172172 let operation = session
173173 .section
174174 .restore_version_async(page, version, &self.author);
175 self.section_edit(operation, move |state, _| {
175 self.section_edit(vec![page], operation, move |state, _| {
176176 if let Some(session) = &mut state.session {
177177 session.refresh_history(&mut state.pane.showing)?;
178178 }
179 state.edited(vec![page]);
180179 state.commands.push(Command::OpenPage(page));
181180 Ok(())
182181 })
......@@ -191,7 +190,7 @@ impl State {
191190 let operation = session
192191 .section
193192 .delete_versions_async(&[(page, vec![version])]);
194 self.section_edit(operation, move |state, _| {
193 self.section_edit(Vec::new(), operation, move |state, _| {
195194 if let Some(session) = &mut state.session {
196195 session.refresh_history(&mut state.pane.showing)?;
197196 }
......@@ -244,6 +243,11 @@ impl State {
244243 };
245244 let operation = clear(&session.section);
246245 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();
247251 let proxy = self.proxy.clone();
248252 let operation = async move {
249253 operation.await?;
......@@ -254,11 +258,18 @@ impl State {
254258 String::new()
255259 };
256260 crate::spawn_async(move || async move {
261 let mut reached = Vec::new();
257262 for path in sections(&library, &folder) {
258263 if path == open {
259264 continue;
260265 }
266 let at = held.iter().position(|(held, _)| *held == path);
261267 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 }
262273 let section = library.open_async(&path, notify(proxy.clone())).await?;
263274 clear(&section).await?;
264275 Ok(section.close_async().await?)
......@@ -268,11 +279,17 @@ impl State {
268279 eprintln!("Deleting the versions in {path} failed: {error}");
269280 }
270281 }
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 })));
271288 });
272289 }
273290 Ok(())
274291 };
275 self.section_edit(operation, move |state, ()| {
292 self.section_edit(Vec::new(), operation, move |state, ()| {
276293 if let Some(session) = &mut state.session {
277294 session.refresh_history(&mut state.pane.showing)?;
278295 if state.pane.showing.version.is_some() {
crates/snowbound/src/live.rs+3-5
......@@ -464,11 +464,9 @@ impl State {
464464 if let Some(background) = joined.background.get().and_then(Weak::upgrade) {
465465 background.wake();
466466 }
467 if let Some(session) = &self.session
468 && Arc::ptr_eq(&session.library, library)
469 {
470 session.section.wake();
471 }
467 (self.session.iter().chain(&self.shelved))
468 .filter(|session| Arc::ptr_eq(&session.library, library))
469 .for_each(|session| session.section.wake());
472470 }
473471 }
474472 }
crates/snowbound/src/main.rs+296-151
......@@ -79,6 +79,7 @@ mod sidebar;
7979#[cfg_attr(windows, path = "spell_windows.rs")]
8080#[cfg_attr(target_arch = "wasm32", path = "spell_web.rs")]
8181mod spell;
82mod split;
8283#[cfg_attr(not(feature = "wgpu"), path = "surface_gl.rs")]
8384#[cfg_attr(all(target_os = "macos", feature = "wgpu"), path = "surface_macos.rs")]
8485#[cfg_attr(windows, path = "surface_windows.rs")]
......@@ -545,6 +546,8 @@ struct Pane {
545546 showing: Showing,
546547 /// The newest read requested; older ones are dropped when they finish.
547548 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>,
548551 opening: Option<Opening>,
549552 /// The section tab, if another, that the newest read opens, and when it was asked for.
550553 switching: Option<(Option<usize>, Instant)>,
......@@ -718,6 +721,8 @@ enum Loaded {
718721 /// A section just created, whose name opens for renaming as OneNote's New Section does.
719722 Created(Box<Session>, ExGuid, Page),
720723 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),
721726 /// A page's version, by the page's space and the version's context.
722727 Version(ExGuid, ExGuid, Page),
723728 /// A notebook read again after a change, at the section that stays open, if any.
......@@ -729,6 +734,7 @@ enum Shown {
729734 Section(Box<Session>, ExGuid),
730735 Created(Box<Session>, ExGuid),
731736 Page(ExGuid),
737 Held(Arc<Library>, String, ExGuid),
732738 Version(ExGuid, ExGuid),
733739}
734740
......@@ -754,6 +760,19 @@ struct Opening {
754760/// How long an opening page waits for its pictures before showing without them.
755761const 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
757776/// Work the interface asked for, done after the frame is built.
758777enum Command {
759778 /// Opens a notebook's section by catalog path, at the page it showed last.
......@@ -877,12 +896,19 @@ struct State {
877896 /// Backends that failed to start this run, and why.
878897 unavailable: Vec<(settings::Backend, String)>,
879898 ui: Ui,
880 /// The page view the window shows.
899 /// The focused pane, which the chrome around the page area follows.
881900 pane: Pane,
901 parked: Vec<split::Parked>,
882902 /// The open notebooks in the sidebar's order.
883903 notebooks: Vec<Arc<Library>>,
884 /// The open section, the one the pane shows.
904 /// The section the focused pane shows.
885905 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)>,
886912 /// A page not kept in any notebook, from a text file or `--page`.
887913 temporary: bool,
888914 /// Where the settings are saved; `None` leaves them as they were read.
......@@ -1378,6 +1404,7 @@ impl State {
13781404 ),
13791405 showing,
13801406 loading: 0,
1407 refused: Arc::default(),
13811408 opening: None,
13821409 switching: None,
13831410 trail: navigation::Trail::default(),
......@@ -1386,8 +1413,12 @@ impl State {
13861413 sectionless,
13871414 locked,
13881415 },
1416 parked: Vec::new(),
13891417 notebooks,
13901418 session,
1419 shelved: Vec::new(),
1420 requests: 0,
1421 opening_files: Vec::new(),
13911422 temporary,
13921423 settings,
13931424 cache,
......@@ -1607,10 +1638,7 @@ impl State {
16071638 lap("drawn", start);
16081639 self.sync_index(false, Vec::new());
16091640 let commands = std::mem::take(&mut self.commands);
1610 let follow = !commands.is_empty()
1611 || self.ui.wants_frame()
1612 || self.pane.opening.is_some()
1613 || self.pane.switching.is_some();
1641 let follow = !commands.is_empty() || self.ui.wants_frame() || !self.still();
16141642 for command in commands {
16151643 self.apply(command)?;
16161644 }
......@@ -3630,8 +3658,37 @@ impl State {
36303658 _ => None,
36313659 };
36323660 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 }
36333691 let notify = notify(self.proxy.clone());
3634 let last = self.last_pages.get(&library.key(&path)).copied();
36353692 self.load_async(move || async move {
36363693 let start = Instant::now();
36373694 let section = library.open_async(&path, notify).await?;
......@@ -3639,6 +3696,7 @@ impl State {
36393696 let (session, space, page) = read_session(section, library, path, last)?;
36403697 Ok(Loaded::Section(Box::new(session), space, page))
36413698 });
3699 self.opening_files.push((self.pane.loading, key));
36423700 }
36433701 Command::OpenPage(space) => {
36443702 let session = self.session.as_ref().ok_or("No section is open")?;
......@@ -3666,7 +3724,7 @@ impl State {
36663724 Command::DeleteVersion { page, version } => {
36673725 let session = self.session.as_mut().ok_or("No section is open")?;
36683726 let operation = session.section.delete_pages_async(&[version]);
3669 self.section_edit(operation, move |state, _| {
3727 self.section_edit(Vec::new(), operation, move |state, _| {
36703728 if let Some(session) = &mut state.session {
36713729 session.refresh_conflicts(&mut state.pane.showing)?;
36723730 }
......@@ -3682,13 +3740,16 @@ impl State {
36823740 }
36833741 _ => session.section.page(version)?,
36843742 };
3743 let key = session.library.key(&session.tabs[tab].path);
36853744 if tab == session.tab {
36863745 let operation = session.section.import_page_async(&page, &self.author);
3687 self.section_edit(operation, |state, _| {
3688 if let Some(session) = &mut state.session {
3689 session.pages = session.section.pages()?;
3690 }
3691 state.edited(Vec::new());
3746 self.section_edit(Vec::new(), operation, |_, _| Ok(()))?;
3747 } else if let Some(held) = self.shelved.iter().find(|held| held.key() == key) {
3748 // A section a parked pane shows is open already.
3749 let operation = held.section.import_page_async(&page, &self.author);
3750 self.complete_async(operation, move |state, copied| {
3751 copied?;
3752 state.edited_sections(&key, Vec::new(), |shown| shown == key);
36923753 Ok(())
36933754 })?;
36943755 } else {
......@@ -3746,10 +3807,7 @@ impl State {
37463807 self.restructure(library, change);
37473808 }
37483809 // The index follows the section's page list.
3749 Command::NewPage { under, title } => {
3750 self.new_page(under, &title)?;
3751 self.edited(Vec::new());
3752 }
3810 Command::NewPage { under, title } => self.new_page(under, &title)?,
37533811 Command::DeletePages(pages) => {
37543812 self.delete_pages(pages)?;
37553813 self.edited(Vec::new());
......@@ -3788,7 +3846,7 @@ impl State {
37883846 &mut self,
37893847 read: impl FnOnce() -> F + Send + 'static,
37903848 ) {
3791 self.pane.loading += 1;
3849 self.pane.loading = self.request();
37923850 let (id, sender, redraw) = (self.pane.loading, self.loads.0.clone(), self.redraw.clone());
37933851 let layouts = Arc::clone(&self.layouts);
37943852 let requested = Instant::now();
......@@ -3801,6 +3859,9 @@ impl State {
38013859 Loaded::Section(session, space, page) => (Shown::Section(session, space), page),
38023860 Loaded::Created(session, space, page) => (Shown::Created(session, space), page),
38033861 Loaded::Page(space, page) => (Shown::Page(space), page),
3862 Loaded::Held(library, path, space, page) => {
3863 (Shown::Held(library, path, space), page)
3864 }
38043865 Loaded::Version(space, version, page) => (Shown::Version(space, version), page),
38053866 Loaded::Library(library, path) => return Ok(Laid::Library(library, path)),
38063867 };
......@@ -3811,6 +3872,7 @@ impl State {
38113872 Some((session.key(), *space))
38123873 }
38133874 Shown::Page(space) => open.map(|open| (open, *space)),
3875 Shown::Held(library, path, space) => Some((library.key(path), *space)),
38143876 Shown::Version(..) => None,
38153877 };
38163878 // A page shown or prepared lately keeps the pictures it drew.
......@@ -3857,17 +3919,22 @@ impl State {
38573919 }
38583920 }
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.
38603925 fn section_edit<
38613926 T: Send + 'static,
38623927 F: Future<Output = Result<T, notebook::Error>> + Send + 'static,
38633928 >(
38643929 &mut self,
3930 spaces: Vec<ExGuid>,
38653931 operation: F,
38663932 then: impl FnOnce(&mut State, T) -> Result<(), Box<dyn Error>> + Send + 'static,
38673933 ) -> Result<(), Box<dyn Error>> {
38683934 let key = self.session.as_ref().ok_or("No section is open")?.key();
38693935 self.complete_async(operation, move |state, result| {
38703936 let value = result?;
3937 state.edited_sections(&key, spaces, |shown| shown == key);
38713938 if state
38723939 .session
38733940 .as_ref()
......@@ -3880,19 +3947,28 @@ impl State {
38803947 })
38813948 }
38823949
3883 /// Shows the newest page read once the pictures it shows first are drawn, or after
3884 /// `HOLD`.
3950 /// Shows the newest page each pane read once the pictures it shows first are drawn, or
3951 /// after `HOLD`.
38853952 fn open_loaded(&mut self) -> Result<(), Box<dyn Error>> {
38863953 let reads: Vec<Read> = self.loads.1.try_iter().collect();
38873954 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 };
38883961 match loaded {
38893962 // A later load supersedes what this one shows, but not its failure.
3890 Ok(_) if id != self.pane.loading => {}
3891 Ok(Laid::Page(opening)) => self.pane.opening = Some(*opening),
3892 Ok(Laid::Library(library, path)) => self.adopt(library, path.as_deref())?,
3963 Ok(_) if id != pane.loading => {}
3964 Ok(Laid::Page(opening)) => pane.opening = Some(*opening),
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 },
38933969 Err(error) => {
3894 if id == self.pane.loading {
3895 self.pane.switching = None;
3970 if id == pane.loading {
3971 pane.switching = None;
38963972 }
38973973 platform::alert("Couldn't open", &error);
38983974 }
......@@ -3903,25 +3979,27 @@ impl State {
39033979 ink: self.ui.theme.paper_ink,
39043980 };
39053981 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 {
39073988 return Ok(());
39083989 };
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 }
39193990 lap("switch pictures", opening.since);
39203991 self.show_page(opening)
39213992 }
39223993
39233994 fn show_page(&mut self, mut opening: Opening) -> Result<(), Box<dyn Error>> {
39243995 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 }
39254003 if let Shown::Section(session, _) | Shown::Created(session, _) = &mut opening.loaded
39264004 && let Some(library) = self
39274005 .notebooks
......@@ -3955,10 +4033,14 @@ impl State {
39554033 self.stop_recording(true)?;
39564034 // The page shown so far keeps what was typed while the next one loaded.
39574035 self.persist()?;
4036 // A page another pane still shows keeps that pane's history.
39584037 let mut leaving = self
39594038 .session
39604039 .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 })
39624044 .map(|_| self.pane.showing.space);
39634045 if let Some(session) = &self.session {
39644046 let key = session.key();
......@@ -3985,7 +4067,8 @@ impl State {
39854067 // The section left stays open a while for coming back to; the notebook's
39864068 // background sync takes it over once it is closed.
39874069 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)) {
39894072 let path = &previous.tabs[previous.tab].path;
39904073 let locked = self.leave(&previous.library, path);
39914074 let library = &previous.library;
......@@ -4009,6 +4092,7 @@ impl State {
40094092 self.save_settings();
40104093 }
40114094 }
4095 Shown::Held(..) => unreachable!("A held section is taken off the shelf"),
40124096 Shown::Page(space) | Shown::Version(space, _) => {
40134097 let session = self.session.as_mut().ok_or("No section is open")?;
40144098 let pages = session.section.pages()?;
......@@ -4080,6 +4164,12 @@ impl State {
40804164 self.list(&library);
40814165 let shown = |shown: &Library| shown.location == library.location;
40824166 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 }
40834173 if self.pane.sectionless.as_deref().is_some_and(shown)
40844174 || self
40854175 .session
......@@ -4106,7 +4196,12 @@ impl State {
41064196 if !shown(&session.library) {
41074197 return Ok(());
41084198 }
4199 let old = Some(session.key());
41094200 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 }
41104205 self.title();
41114206 self.save_settings();
41124207 Ok(())
......@@ -4119,6 +4214,7 @@ impl State {
41194214 Some(open) => *open = Arc::clone(library),
41204215 None => self.notebooks.push(Arc::clone(library)),
41214216 }
4217 self.follow_shelved(library);
41224218 if library.in_icloud() && library.downloading() {
41234219 self.fetch(Arc::clone(library), None);
41244220 }
......@@ -4308,21 +4404,17 @@ impl State {
43084404 Ok(())
43094405 }
43104406
4311 /// Publishes the open section's stored edits now, rather than after a pause in typing,
4312 /// and waits up to `wait` for them to reach the file.
4407 /// Publishes the open sections' stored edits now, rather than after a pause in typing,
4408 /// and waits up to `wait` for them to reach their files.
43134409 fn publish_now(&self, wait: std::time::Duration) {
4314 let Some(session) = &self.session else {
4315 return;
4316 };
43174410 let deadline = Instant::now() + wait;
43184411 loop {
4319 session.section.wake();
4320 if Instant::now() >= deadline
4321 || session
4322 .section
4323 .pending()
4324 .is_ok_and(|pending| pending.is_empty())
4325 {
4412 let mut pending = false;
4413 for session in self.sessions() {
4414 session.section.wake();
4415 pending |= !(session.section.pending()).is_ok_and(|pending| pending.is_empty());
4416 }
4417 if !pending || Instant::now() >= deadline {
43264418 return;
43274419 }
43284420 std::thread::sleep(std::time::Duration::from_millis(50));
......@@ -4348,16 +4440,14 @@ impl State {
43484440 return Ok(());
43494441 }
43504442 let space = self.pane.showing.space;
4351 session.section.apply(
4352 &self.author,
4353 onestore::op::Edit {
4354 at: filetime(),
4355 ops: ops
4356 .into_iter()
4357 .map(|op| onestore::op::Op::Page { space, op })
4358 .collect(),
4359 },
4443 self.store(
4444 ops.into_iter()
4445 .map(|op| onestore::op::Op::Page { space, op })
4446 .collect(),
43604447 )?;
4448 let Some(session) = &mut self.session else {
4449 return Ok(());
4450 };
43614451 // The page list shows the title as it is typed, even when the caret left it since.
43624452 let editor = &self.pane.view.editor;
43634453 let title = (editor.outlines().iter())
......@@ -4371,13 +4461,39 @@ impl State {
43714461 {
43724462 session.pages = session.section.pages()?;
43734463 }
4374 self.edited(vec![space]);
43754464 let editor = &self.pane.view.editor;
43764465 self.undo
43774466 .edited(space, editor.history_depth(), editor.typing().is_some());
43784467 Ok(())
43794468 }
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
43814497 /// Shows the page as stored after a change made elsewhere, in place: the caret,
43824498 /// selection, scroll and drawn pictures stay. Waits for marked text to end.
43834499 fn refresh(&mut self) -> Result<(), Box<dyn Error>> {
......@@ -4390,7 +4506,11 @@ impl State {
43904506 let Some(session) = &self.session else {
43914507 return Ok(());
43924508 };
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 };
43944514 let response = self.pane.view.refresh(page)?;
43954515 self.respond(response);
43964516 self.title();
......@@ -4409,7 +4529,10 @@ impl State {
44094529 .view
44104530 .editor
44114531 .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 }
44134536 self.refresh()?;
44144537 platform::alert(
44154538 "Change not saved",
......@@ -4418,7 +4541,7 @@ impl State {
44184541 Ok(())
44194542 }
44204543
4421 /// Applies what the section, and each notebook's closed sections, reported since the
4544 /// Applies what the open sections, and each notebook's closed ones, reported since the
44224545 /// last poll.
44234546 fn synced(&mut self) -> Result<(), Box<dyn Error>> {
44244547 self.wear_theme(false)?;
......@@ -4457,87 +4580,7 @@ impl State {
44574580 }
44584581 // Reports are rare: a status changed, or a section did.
44594582 self.window.request_redraw();
4460 let Some(session) = &mut self.session else {
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 }
4583 self.hear_sections();
45414584 Ok(())
45424585 }
45434586
......@@ -6554,7 +6597,7 @@ impl State {
65546597 // Quiet still when the mark sent on finding it quiet arrives, what a thread sent
65556598 // as it ended has been taken, however many frames wait in the queue before it.
65566599 let quiet = self.settled()
6557 && self.pane.opening.is_none()
6600 && self.still()
65586601 && RUNNING.load(Ordering::Acquire) == 0
65596602 && self.search.pending.load(Ordering::Relaxed) == 0;
65606603 if let Some((path, settled, sent)) = self.replay_settle.take() {
......@@ -6914,9 +6957,11 @@ impl ApplicationHandler<UserEvent> for App {
69146957 let deadline = Instant::now() + QUIT;
69156958 state.publish_now(QUIT);
69166959 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();
69186963 let libraries: Vec<_> = (state.notebooks.iter())
6919 .chain(session.as_ref().map(|session| &session.library))
6964 .chain(sessions.iter().map(|session| &session.library))
69206965 .cloned()
69216966 .collect();
69226967 // Dropped sections and backgrounds stop without waiting, so the process could end first.
......@@ -6929,10 +6974,10 @@ impl ApplicationHandler<UserEvent> for App {
69296974 {
69306975 background.stop();
69316976 }
6932 if let Some(session) = session
6933 && let Err(error) = session.section.close()
6934 {
6935 eprintln!("Synchronization stopped: {error}");
6977 for session in sessions {
6978 if let Err(error) = session.section.close() {
6979 eprintln!("Synchronization stopped: {error}");
6980 }
69366981 }
69376982 libraries.iter().for_each(|library| library.close_kept());
69386983 drop(closed);
......@@ -7585,6 +7630,106 @@ mod tests {
75857630 notebook::fs::remove_dir_all(&directory).unwrap();
75867631 }
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
75887733 /// Times opening each section of a notebook and each of its pages, phase by phase, as a
75897734 /// switch does: `SNOWBOUND_SWITCH_NOTEBOOK=FOLDER`, or a share through `ONESTORE_SMB_LAB`
75907735 /// (`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;
66use notebook::session::Notebook;
77use onestore::{
88 ExGuid, PageCreation, PageEdit,
9 op::{Edit, Op, PageOp, SectionOp},
9 op::{Op, PageOp, SectionOp},
1010 page::{Image, Page, PageObject},
1111};
1212use std::{error::Error, path::Path, sync::Arc};
......@@ -218,16 +218,19 @@ impl State {
218218 space, before, level,
219219 )?])));
220220 }
221 let session = self.session.as_ref().ok_or("No section is open")?;
222 let edit = Edit {
223 at: crate::filetime(),
224 ops,
225 };
226221 // A section being rebuilt answers reads from before the page was made.
227222 #[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 }
229232 #[cfg(target_arch = "wasm32")]
230 session.section.apply(&self.author, edit)?;
233 self.store(ops)?;
231234 let shown = self.pane.showing.space;
232235 self.made(Change::Delete {
233236 pages: vec![space],
......@@ -319,16 +322,8 @@ impl State {
319322 if ops.is_empty() {
320323 return Ok(());
321324 }
322 let session = self.session.as_ref().ok_or("No section is open")?;
323325 let space = self.pane.showing.space;
324 session.section.apply(
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]);
326 self.store(ops.into_iter().map(|op| Op::Page { space, op }).collect())?;
332327 self.refresh()
333328 }
334329
......@@ -579,8 +574,8 @@ impl State {
579574 }
580575
581576 /// 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 also
583 /// exported as a recovery archive; signing in again and reopening publishes them.
577 /// folders go with the account. Replicas holding edits stay, the open sections' also
578 /// exported as recovery archives; signing in again and reopening publishes them.
584579 pub(crate) fn icloud_account_changed(&mut self) {
585580 let closing: Vec<Arc<Library>> = self
586581 .notebooks
......@@ -588,16 +583,18 @@ impl State {
588583 .filter(|library| library.in_icloud())
589584 .cloned()
590585 .collect();
591 if let Some(session) = &self.session
592 && session.library.in_icloud()
593 && session
594 .section
595 .pending()
596 .is_ok_and(|pending| !pending.is_empty())
597 && let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery"))
598 {
586 let waiting = (self.sessions()).filter(|session| {
587 session.library.in_icloud()
588 && (session.section.pending()).is_ok_and(|pending| !pending.is_empty())
589 });
590 for session in waiting {
591 let Some(folder) = platform::settings_dir().map(|folder| folder.join("Recovery"))
592 else {
593 break;
594 };
595 let section = &session.tabs[session.tab].name;
599596 let archive = folder.join(format!(
600 "{}-{}.sqlite",
597 "{}-{section}-{}.sqlite",
601598 session.library.name,
602599 crate::filetime()
603600 ));
......@@ -617,6 +614,7 @@ impl State {
617614 /// Closes `library`: its files stay, its offline copies go unless edits wait in them,
618615 /// and the sidebar and the next launch leave it out.
619616 pub(crate) fn close_notebook(&mut self, library: &Arc<Library>) {
617 self.close_parked_in(library);
620618 self.notebooks.retain(|open| !Arc::ptr_eq(open, library));
621619 self.undo.close(&library.location);
622620 if let Some(background) = &library.background {
......@@ -737,6 +735,8 @@ impl State {
737735 let Some(to) = library.renamed_location(&name) else {
738736 return;
739737 };
738 // Their sections hold files in the folder.
739 self.close_parked_in(&library);
740740 let ours = |shown: &Arc<Library>| Arc::ptr_eq(shown, &library);
741741 let shown = self
742742 .session
......@@ -892,6 +892,13 @@ impl State {
892892 .as_ref()
893893 .filter(|session| Arc::ptr_eq(&session.library, &library))
894894 .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();
895902 let notify = notify(self.proxy.clone());
896903 let (proxy, requested) = (self.proxy.clone(), self.pane.loading);
897904 let showing = self.pane.switching.is_none() && self.pane.opening.is_none();
......@@ -1025,6 +1032,11 @@ impl State {
10251032 if followed.as_deref() == Some(path.as_str()) {
10261033 return Ok(Loaded::Library(library, Some(path)));
10271034 }
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 }
10281040 let section = library.open_async(&path, notify).await?;
10291041 let (session, space, page) = read_session(section, library, path, None)?;
10301042 Ok(if fresh {
......@@ -1051,6 +1063,7 @@ impl State {
10511063 Loaded::Section(session, ..) | Loaded::Created(session, ..) => {
10521064 Arc::clone(&session.library)
10531065 }
1066 Loaded::Held(library, ..) => Arc::clone(library),
10541067 _ => unreachable!("A structure change returns its notebook"),
10551068 };
10561069 if !state
......@@ -1133,20 +1146,15 @@ impl State {
11331146 /// Moves or indents pages of the open section, in order.
11341147 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {
11351148 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")?;
11371150 let order = session
11381151 .pages
11391152 .iter()
11401153 .map(|(space, _, level)| (*space, *level))
11411154 .collect();
11421155 let moved = edits.iter().map(PageEdit::space).collect();
1143 session.section.apply(
1144 &self.author,
1145 Edit {
1146 at: crate::filetime(),
1147 ops: vec![Op::Section(SectionOp::Pages(edits))],
1148 },
1149 )?;
1156 self.store(vec![Op::Section(SectionOp::Pages(edits))])?;
1157 let session = self.session.as_mut().ok_or("No section is open")?;
11501158 session.pages = session.section.pages()?;
11511159 self.made(Change::Arrange { order, moved });
11521160 Ok(())
......@@ -1206,6 +1214,7 @@ fn art_ops(page: &Page, art: Vec<Image>) -> Vec<PageOp> {
12061214#[cfg(test)]
12071215mod tests {
12081216 use super::*;
1217 use onestore::op::Edit;
12091218 use std::path::Path;
12101219
12111220 const AUTHOR: &str = "Rust Author";
crates/snowbound/src/prefetch.rs+6-2
......@@ -293,7 +293,7 @@ impl State {
293293
294294 /// Leaves the page shown as it is, dropping whatever was opening in its place.
295295 pub fn stop_loading(&mut self) {
296 self.pane.loading += 1;
296 self.pane.loading = self.request();
297297 self.pane.opening = None;
298298 self.pane.switching = None;
299299 }
......@@ -347,7 +347,11 @@ impl State {
347347 };
348348 let path = session.tabs[tab].path.clone();
349349 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 {
351355 return;
352356 }
353357 let _ = self.prefetch.jobs.send(Job::Section {
crates/snowbound/src/print.rs+13-6
......@@ -314,6 +314,8 @@ impl State {
314314 Arc::clone(&session.library),
315315 );
316316 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);
317319 let layouts = Arc::clone(&self.layouts);
318320 let proxy = self.proxy.clone();
319321 let paper = if setup.landscape {
......@@ -351,12 +353,17 @@ impl State {
351353 sections.push(open);
352354 continue;
353355 }
354 let section = library.open_async(&path, || {}).await?;
355 let pages = section
356 .pages()?
357 .into_iter()
358 .map(|(space, ..)| section.page(space))
359 .collect::<Result<Vec<_>, _>>()?;
356 let pages = match held.iter().find(|(held, _)| *held == path) {
357 Some((_, replica)) => (replica.pages()?.into_iter())
358 .map(|(space, ..)| replica.page(space))
359 .collect::<Result<Vec<_>, _>>()?,
360 None => {
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 };
360367 sections.push((name, printed(pages)));
361368 }
362369 sections
crates/snowbound/src/protection.rs+23-2
......@@ -81,7 +81,8 @@ impl State {
8181 ) -> Result<(), Box<dyn Error>> {
8282 self.stop_loading();
8383 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)) {
8586 let path = &previous.tabs[previous.tab].path;
8687 if self.leave(&previous.library, path) {
8788 previous.section.close()?;
......@@ -332,8 +333,18 @@ impl State {
332333 self.relock()
333334 }
334335
335 /// Shows the open section locked once its key is gone.
336 /// Shows each open section locked once its key is gone.
336337 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 );
337348 let Some(session) = &self.session else {
338349 return Ok(());
339350 };
......@@ -699,6 +710,16 @@ impl State {
699710 key: Option<onestore::protected::Key>,
700711 password: Option<Zeroizing<String>>,
701712 ) {
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 });
702723 let replica = self
703724 .session
704725 .as_ref()
crates/snowbound/src/recycle.rs+57-19
......@@ -5,7 +5,7 @@
55
66use crate::{Command, Library, Loaded, State, filetime, library, menus, notify, read_session};
77use onestore::{
8 ExGuid,
8 ExGuid, PageCreation,
99 op::{Edit, Op, SectionOp},
1010};
1111use std::{error::Error, sync::Arc};
......@@ -59,9 +59,14 @@ impl State {
5959 return;
6060 }
6161 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));
6363 self.load_async(move || async move {
6464 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 }
6570 let section = library.open_async(&path, notify(proxy.clone())).await?;
6671 if section.pages()?.is_empty() {
6772 section.close_async().await?;
......@@ -135,8 +140,24 @@ impl State {
135140 (spaces.clone().skip(at).find(kept)).or_else(|| spaces.take(at).rev().find(kept))
136141 });
137142 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()));
138154 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 })));
140161 if let Some(show) = if gone.contains(&shown) {
141162 after
142163 } else {
......@@ -148,6 +169,9 @@ impl State {
148169 let path = library
149170 .first_section()
150171 .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 }
151175 let section = library.open_async(&path, notify(proxy)).await?;
152176 let (session, space, page) = read_session(section, library, path, None)?;
153177 Ok(Loaded::Section(Box::new(session), space, page))
......@@ -191,33 +215,44 @@ impl State {
191215
192216/// Does `request` to the bin's section `replica` holds, in `library`, as `author`: a page
193217/// 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.
195220async fn carry_out(
196221 library: &Library,
197222 replica: &notebook::Replica,
198223 request: Request,
199224 author: &str,
225 held: Option<Arc<notebook::Replica>>,
200226) -> Result<(), Box<dyn Error>> {
201227 let gone = match request {
202228 Request::Restore { space, path, copy } => {
203229 let page = replica.page(space)?;
204 let section = library.open_async(&path, || {}).await?;
205 if copy {
206 section.import_page_async(&page, author).await?;
230 let opened = match held {
231 Some(_) => None,
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 })
207245 } else {
208 let ops = vec![notebook::session::moved(&page, author)?];
209 section
210 .replica()
211 .apply_async(
212 author,
213 Edit {
214 at: filetime(),
215 ops,
216 },
217 )
218 .await?;
246 notebook::session::moved(&page, author)?
247 };
248 let edit = Edit {
249 at: filetime(),
250 ops: vec![op],
251 };
252 target.apply_async(author, edit).await?;
253 if let Some(section) = opened {
254 section.close_async().await?;
219255 }
220 section.close_async().await?;
221256 (!copy).then_some(vec![space]).unwrap_or_default()
222257 }
223258 Request::Purge(spaces) => spaces,
......@@ -370,6 +405,7 @@ mod tests {
370405 bin.replica(),
371406 restore(back, false),
372407 AUTHOR,
408 None,
373409 ))
374410 .unwrap();
375411 pollster::block_on(carry_out(
......@@ -377,6 +413,7 @@ mod tests {
377413 bin.replica(),
378414 restore(copied, true),
379415 AUTHOR,
416 None,
380417 ))
381418 .unwrap();
382419 pollster::block_on(carry_out(
......@@ -384,6 +421,7 @@ mod tests {
384421 bin.replica(),
385422 Request::Purge(vec![purged]),
386423 AUTHOR,
424 None,
387425 ))
388426 .unwrap();
389427 bin.close().unwrap();
crates/snowbound/src/rename.rs+3-9
......@@ -5,7 +5,7 @@
55use crate::{Command, Library, State, manage::Structure};
66use onestore::{
77 ExGuid,
8 op::{Edit, Op, PageOp},
8 op::{Op, PageOp},
99 page::{Page, PageObject},
1010};
1111use std::{error::Error, sync::Arc};
......@@ -174,20 +174,14 @@ impl State {
174174 .find(|(page, ..)| *page == space)
175175 .map(|(_, title, _)| title.clone())
176176 .unwrap_or_default();
177 session.section.apply(
178 &self.author,
179 Edit {
180 at: crate::filetime(),
181 ops: vec![op],
182 },
183 )?;
177 self.store(vec![op])?;
178 let session = self.session.as_mut().ok_or("No section is open")?;
184179 session.pages = session.section.pages()?;
185180 self.made(crate::undo::Change::Retitle {
186181 page: space,
187182 from: name,
188183 to: old,
189184 });
190 self.edited(vec![space]);
191185 self.refresh()
192186 }
193187}
crates/snowbound/src/search.rs+9-6
......@@ -546,12 +546,15 @@ impl State {
546546 });
547547 }
548548
549 /// Tells the index an edit changed page `space` of the open section.
550 pub(crate) fn edited(&self, spaces: Vec<ExGuid>) {
551 if let Some(session) = &self.session {
552 self.search
553 .changed(session.key(), session.section.replica(), spaces);
554 }
549 /// Follows an edit made here of pages `spaces` of the open section, or of its page list
550 /// without any: the index reads them again, and so do the other panes showing them.
551 pub(crate) fn edited(&mut self, spaces: Vec<ExGuid>) {
552 let Some(session) = &self.session else {
553 return;
554 };
555 let key = session.key();
556 (self.search).changed(key.clone(), session.section.replica(), spaces.clone());
557 self.show_elsewhere(&key, &spaces);
555558 }
556559
557560 /// Whether `key` names a section the search's scope takes in.
crates/snowbound/src/sidebar.rs+5
......@@ -1453,6 +1453,7 @@ impl crate::State {
14531453 .and_then(|path| self.last_pages.get(&crate::library::key(&location, path)))
14541454 .copied();
14551455 let (cache, notify) = (self.cache.clone(), crate::notify(self.proxy.clone()));
1456 let held = self.held(&location);
14561457 self.load_async(move || async move {
14571458 let library = match open {
14581459 Some(library) => library,
......@@ -1476,6 +1477,10 @@ impl crate::State {
14761477 }
14771478 return Err("This folder holds no notebook sections.".into());
14781479 };
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 }
14791484 let section = library.open_async(&path, notify).await?;
14801485 let (session, space, page) = crate::read_session(section, library, path, left)?;
14811486 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 {
10601060 /// Builds the sync status popup while it is open: on the notebook its context menu
10611061 /// opened it for, or the open section's.
10621062 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);
10641064 let update = self.updates.status();
10651065 let Some(session) = &mut self.session else {
10661066 ui.close_popup(id());
......@@ -1126,6 +1126,7 @@ impl State {
11261126 if picked.offline {
11271127 library::set_offline(!offline);
11281128 session.section.set_offline(!offline);
1129 (shelved.iter()).for_each(|held| held.section.set_offline(!offline));
11291130 notebooks
11301131 .iter()
11311132 .for_each(|library| library.set_offline(!offline));
......@@ -1133,6 +1134,9 @@ impl State {
11331134 if own {
11341135 session.section.wake();
11351136 }
1137 (shelved.iter())
1138 .filter(|held| Arc::ptr_eq(&held.library, &library))
1139 .for_each(|held| held.section.wake());
11361140 backgrounds.for_each(|background| background.wake());
11371141 }
11381142 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 {
345345struct Site {
346346 replica: Arc<Replica>,
347347 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>)>,
348351 author: String,
349352 fresh: PageCreation,
350353}
......@@ -416,6 +419,19 @@ impl Site {
416419 entry_of(self.library.catalog()?, identity).map(|(_, path)| path)
417420 }
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
419435 /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be,
420436 /// keeps it open, where they are tried again until they are.
421437 async fn release(&self, path: &str, section: notebook::session::Section) {
......@@ -588,9 +604,8 @@ impl Site {
588604 let level = listed[from].2;
589605 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];
590606 let (show, added) = self.after(&listed, &[page], None, &mut ops);
591 let section = self.library.open_async(&path, || {}).await?;
592 section
593 .replica()
607 let (other, opened) = self.reach(&path).await?;
608 other
594609 .apply_async(
595610 &self.author,
596611 Edit {
......@@ -599,7 +614,9 @@ impl Site {
599614 },
600615 )
601616 .await?;
602 self.release(&path, section).await;
617 if let Some(section) = opened {
618 self.release(&path, section).await;
619 }
603620 let edit = Edit {
604621 at: crate::filetime(),
605622 ops,
......@@ -634,12 +651,14 @@ impl Site {
634651 let Some(path) = self.section_path(target) else {
635652 return Ok(None);
636653 };
637 let section = self.library.open_async(&path, || {}).await?;
638 if !(section.pages()?.iter()).any(|(listed, ..)| *listed == page) {
639 self.release(&path, section).await;
654 let (other, opened) = self.reach(&path).await?;
655 if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) {
656 if let Some(section) = opened {
657 self.release(&path, section).await;
658 }
640659 return Ok(None);
641660 }
642 let sent = section.replica().moving(page)?;
661 let sent = other.moving(page)?;
643662 let import = notebook::session::moved(sent.page(), &self.author)?;
644663 let back = imported(&import);
645664 let mut ops = vec![
......@@ -656,11 +675,10 @@ impl Site {
656675 at: crate::filetime(),
657676 ops: vec![Op::Section(SectionOp::Delete(vec![page]))],
658677 };
659 let retired = section
660 .replica()
661 .retire_async(&self.author, delete, sent)
662 .await;
663 self.release(&path, section).await;
678 let retired = other.retire_async(&self.author, delete, sent).await;
679 if let Some(section) = opened {
680 self.release(&path, section).await;
681 }
664682 Applied {
665683 undo: (retired.map(|_| Change::Send { page: back, target }))
666684 .map_err(|error| crate::plain(&error, "page")),
......@@ -1111,9 +1129,13 @@ impl State {
11111129 } else {
11121130 None
11131131 };
1132 let held = self.held(&session.library.location);
1133 let key = session.key();
1134 let notebook_key = session.library.key("");
11141135 let mut site = Site {
11151136 replica: Arc::clone(session.section.replica()),
11161137 library: Arc::clone(&session.library),
1138 held,
11171139 author: self.author.clone(),
11181140 fresh: self.dated_page(None, "")?,
11191141 };
......@@ -1181,7 +1203,8 @@ impl State {
11811203 }
11821204 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),
11831205 }
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));
11851208 Ok(())
11861209 })));
11871210 drop(changing);
......@@ -1464,6 +1487,7 @@ mod tests {
14641487 Site {
14651488 replica: Arc::clone(self.section().replica()),
14661489 library: Arc::clone(&self.library),
1490 held: Vec::new(),
14671491 author: AUTHOR.into(),
14681492 fresh: dated(),
14691493 }
crates/snowbound/src/unread.rs+2-5
......@@ -297,12 +297,9 @@ impl State {
297297 viewing.map(|(notebook, section, space)| (notebook, section, space, false));
298298 }
299299
300 /// Pages of the open section another client changed, as its sync reports them: those
300 /// Pages of an open section another client changed, as its sync reports them: those
301301 /// another author changed last are unread, once read on a thread of their own.
302 pub(crate) fn changed_elsewhere(&mut self, spaces: &[ExGuid]) {
303 let Some(session) = &self.session else {
304 return;
305 };
302 pub(crate) fn changed_elsewhere(&self, session: &crate::Session, spaces: &[ExGuid]) {
306303 let Some(section) = session
307304 .library
308305 .section_identity(&session.tabs[session.tab].path)
crates/snowbound/tests/replay.rs+25
......@@ -313,6 +313,31 @@ fn page_tabs(tree: &str) -> Vec<String> {
313313 .collect()
314314}
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
316341/// Undo walks back through two new pages and what was typed on each, crossing pages as
317342/// it goes: each page keeps its own history once left, and a new page goes once what was
318343/// typed on it has gone.