authoravatarclover caruso<git@paperclover.net>2026-10-19 11:52:00-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-19 23:31:22-07:00
log9ec5dfb963ad9d44a22beefd26d7382f9a45acc2
tree68e40914fc4dcc5928692caa747e712f93a9a85f
parent9dc3da1b71afbdef3136fa4bf9a3ab40933a6d5b
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat: Move or Copy takes sections and pages into any open notebook

A section's context menu offers Move or Copy in place of Move, and a page's in place of Move to Section, each opening OneNote 2010's dialog of the same name: every open notebook with its section groups and sections, a tree with levels for screen readers, a search by title that keeps each match's notebook and groups, and Move, Copy and Cancel in OneNote's order on Windows and the platform's elsewhere. A section goes into a notebook or group, last, or after a section; a page goes to the end of a section that isn't locked. Within its notebook a section moves as it did; into another, including one in iCloud Drive or on a server, it is written there anew, the original going to its notebook's recycle bin once the copy reads back whole. A section on its way opens nowhere until it has gone, and quitting meanwhile asks first, and a pane it was shown in says it is moving. Every pane that showed it, parked ones included, then shows its notebook's first section, or it again where it stayed; a section a pane holds is copied from, or a page copied into, without opening it twice, and a pane on the section a page went to or came back from lists it again. Pages move across notebooks as they moved between sections, Undo included; Undo says so when the notebook the page went to has closed. Move or Copy Page is in the palette and the menu bar, on Ctrl+Alt+M outside macOS. - Move or Copy moves or copies a section or a page into any open notebook, as OneNote 2010 does - Quitting while a notebook without sections is shown no longer asks to discard a page Fixes #105 Assisted-by: claude-opus-5.5

12 files changed, 1219 insertions(+), 83 deletions(-)

arc/sync.md+4
...@@ -347,6 +347,10 @@ pages to `OneNote_RecycleBin`, as OneNote does, and opening a notebook empties...@@ -347,6 +347,10 @@ pages to `OneNote_RecycleBin`, as OneNote does, and opening a notebook empties
347what the bin has held unchanged for 60 days, as OneNote prunes it: judged by the347what the bin has held unchanged for 60 days, as OneNote prunes it: judged by the
348content's last change, the pages in one revision, binned section files deleted348content's last change, the pages in one revision, binned section files deleted
349with their TOC entries left (`corpus/recycle-purge`).349with their TOC entries left (`corpus/recycle-purge`).
350Move or Copy puts a section in another notebook as OneNote 2010 does, written anew under new
351identities, taking the edits its replica still queues. Where OneNote deletes the original, a
352move sends it to the recycle bin, and only once the copy reads back whole and the original is
353as it was copied; otherwise the section stays in both notebooks and the move says so.
350354
351What only Snowbound reads lives in the notebook's `.snowbound` folder, which carries the355What only Snowbound reads lives in the notebook's `.snowbound` folder, which carries the
352Windows hidden attribute so that OneNote never makes a section group of it. Its files are356Windows hidden attribute so that OneNote never makes a section group of it. Its files are
crates/snowbound/src/commands.rs+15-2
...@@ -30,6 +30,8 @@ pub enum Id {...@@ -30,6 +30,8 @@ pub enum Id {
30 NewSubpage,30 NewSubpage,
31 PageVersions,31 PageVersions,
32 CopyPageLink,32 CopyPageLink,
33 /// Move or Copy on the page shown.
34 MoveOrCopyPage,
33 /// Password Protection on the section shown.35 /// Password Protection on the section shown.
34 PasswordProtect,36 PasswordProtect,
35 /// Locks every password-protected section unlocked.37 /// Locks every password-protected section unlocked.
...@@ -278,6 +280,13 @@ pub const COMMANDS: &[Command] = &[...@@ -278,6 +280,13 @@ pub const COMMANDS: &[Command] = &[
278 ),280 ),
279 row!(Id::PageVersions, "Page Versions", NONE, NONE),281 row!(Id::PageVersions, "Page Versions", NONE, NONE),
280 row!(Id::CopyPageLink, "Copy Link to Page", NONE, NONE),282 row!(Id::CopyPageLink, "Copy Link to Page", NONE, NONE),
283 // OneNote 2010's Ctrl+Alt+M; macOS keeps Option-Command-M for Minimize All.
284 row!(
285 Id::MoveOrCopyPage,
286 "Move or Copy Page",
287 NONE,
288 &[cmd('m').option()]
289 ),
281 row!(290 row!(
282 Id::PasswordProtect,291 Id::PasswordProtect,
283 "Password Protect This Section",292 "Password Protect This Section",
...@@ -1255,8 +1264,8 @@ impl State {...@@ -1255,8 +1264,8 @@ impl State {
1255 .notebook()1264 .notebook()
1256 .is_some_and(|library| library.catalog().is_some()),1265 .is_some_and(|library| library.catalog().is_some()),
1257 ),1266 ),
1258 // The recycle bin takes no new pages.1267 // The recycle bin takes no new pages, and moves its own by Restore To.
1259 Id::NewPage | Id::NewSubpage => {1268 Id::NewPage | Id::NewSubpage | Id::MoveOrCopyPage => {
1260 enabled(!modal && session.is_some() && !self.in_recycle_bin())1269 enabled(!modal && session.is_some() && !self.in_recycle_bin())
1261 }1270 }
1262 Id::CopyPageLink | Id::Find | Id::Search | Id::ExportPdf | Id::Print => {1271 Id::CopyPageLink | Id::Find | Id::Search | Id::ExportPdf | Id::Print => {
...@@ -1555,6 +1564,10 @@ impl State {...@@ -1555,6 +1564,10 @@ impl State {
1555 show: self.pane.showing.shown_history != Some(self.pane.showing.space),1564 show: self.pane.showing.shown_history != Some(self.pane.showing.space),
1556 }1565 }
1557 }1566 }
1567 Id::MoveOrCopyPage => {
1568 self.move_or_copy_page(self.pane.showing.space);
1569 return Ok(());
1570 }
1558 Id::CopyPageLink => {1571 Id::CopyPageLink => {
1559 self.session.as_ref().ok_or("No notebook is open")?;1572 self.session.as_ref().ok_or("No notebook is open")?;
1560 let space = self.pane.showing.space;1573 let space = self.pane.showing.space;
crates/snowbound/src/main.rs+46-6
...@@ -45,6 +45,7 @@ mod meeting;...@@ -45,6 +45,7 @@ mod meeting;
45#[cfg(target_os = "macos")]45#[cfg(target_os = "macos")]
46mod menubar;46mod menubar;
47mod menus;47mod menus;
48mod move_copy;
48mod navigation;49mod navigation;
49mod options;50mod options;
50mod palette;51mod palette;
...@@ -848,9 +849,16 @@ enum Command {...@@ -848,9 +849,16 @@ enum Command {
848 Recycle(recycle::Request),849 Recycle(recycle::Request),
849 /// Moves or indents pages of the open section.850 /// Moves or indents pages of the open section.
850 Pages(Vec<onestore::PageEdit>),851 Pages(Vec<onestore::PageEdit>),
851 /// Moves a page of the open section to the end of another section of its folder.852 /// Moves a page of the open section to the end of another section.
852 MovePage {853 MovePage {
853 space: ExGuid,854 space: ExGuid,
855 library: Arc<Library>,
856 path: String,
857 },
858 /// Copies a page of the open section to the end of another section.
859 CopyPage {
860 space: ExGuid,
861 library: Arc<Library>,
854 path: String,862 path: String,
855 },863 },
856 /// Gives the open page a template's background.864 /// Gives the open page a template's background.
...@@ -982,6 +990,10 @@ struct State {...@@ -982,6 +990,10 @@ struct State {
982 updates: update::Updates,990 updates: update::Updates,
983 /// The Link dialog's fields while it is open.991 /// The Link dialog's fields while it is open.
984 link: Option<link::LinkDialog>,992 link: Option<link::LinkDialog>,
993 /// Move or Copy while it is open.
994 move_copy: Option<move_copy::Dialog>,
995 /// Sections on their way to another place, by notebook location and catalog path.
996 moving: Vec<(String, String)>,
985 properties: Option<properties::Properties>,997 properties: Option<properties::Properties>,
986 symbols: Option<symbol::Symbols>,998 symbols: Option<symbol::Symbols>,
987 /// Save As while it is open.999 /// Save As while it is open.
...@@ -1473,6 +1485,8 @@ impl State {...@@ -1473,6 +1485,8 @@ impl State {
1473 actions: None,1485 actions: None,
1474 after_open: None,1486 after_open: None,
1475 link: None,1487 link: None,
1488 move_copy: None,
1489 moving: Vec::new(),
1476 properties: None,1490 properties: None,
1477 symbols: None,1491 symbols: None,
1478 save_as: None,1492 save_as: None,
...@@ -1741,6 +1755,8 @@ impl State {...@@ -1741,6 +1755,8 @@ impl State {
1741 self.own_dialog();1755 self.own_dialog();
1742 self.customize_tags();1756 self.customize_tags();
1743 self.palette();1757 self.palette();
1758 // After the palette, which opens it, so that its field is there to take the focus.
1759 self.move_copy_dialog();
1744 self.sync_popup()?;1760 self.sync_popup()?;
1745 self.text_menu()?;1761 self.text_menu()?;
1746 platform::resize_grip(&mut self.ui, &self.window, size);1762 platform::resize_grip(&mut self.ui, &self.window, size);
...@@ -3856,10 +3872,19 @@ impl State {...@@ -3856,10 +3872,19 @@ impl State {
3856 }3872 }
3857 Command::Recycle(request) => self.recycle(request)?,3873 Command::Recycle(request) => self.recycle(request)?,
3858 Command::Pages(edits) => self.edit_pages(edits)?,3874 Command::Pages(edits) => self.edit_pages(edits)?,
3859 Command::MovePage { space, path } => {3875 Command::MovePage {
3860 self.move_page(space, path)?;3876 space,
3877 library,
3878 path,
3879 } => {
3880 self.move_page(space, &library, &path)?;
3861 self.edited(Vec::new());3881 self.edited(Vec::new());
3862 }3882 }
3883 Command::CopyPage {
3884 space,
3885 library,
3886 path,
3887 } => self.copy_page(space, library, path)?,
3863 Command::Template(name) => self.apply_template(name)?,3888 Command::Template(name) => self.apply_template(name)?,
3864 Command::Page(Request::EditDate(field)) => self.edit_date(field),3889 Command::Page(Request::EditDate(field)) => self.edit_date(field),
3865 Command::Page(Request::Copy(clip)) => self.clipboard.set(clip)?,3890 Command::Page(Request::Copy(clip)) => self.clipboard.set(clip)?,
...@@ -3888,8 +3913,10 @@ impl State {...@@ -3888,8 +3913,10 @@ impl State {
3888 path: String,3913 path: String,
3889 page: Option<ExGuid>,3914 page: Option<ExGuid>,
3890 ) -> Result<(), Box<dyn Error>> {3915 ) -> Result<(), Box<dyn Error>> {
3891 // Its files are on their way to the renamed folder.3916 // Its files are on their way to the renamed folder, or another notebook.
3892 if self.folder_renaming(&library.location) {3917 if self.folder_renaming(&library.location)
3918 || (self.moving.iter()).any(|(at, moving)| *at == library.location && *moving == path)
3919 {
3893 return Ok(());3920 return Ok(());
3894 }3921 }
3895 if library.locked(&path) {3922 if library.locked(&path) {
...@@ -6353,6 +6380,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> {...@@ -6353,6 +6380,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> {
6353 Cmd::NewSubpage => art::NEW_SUBPAGE,6380 Cmd::NewSubpage => art::NEW_SUBPAGE,
6354 Cmd::PageVersions => art::PAGE_VERSIONS,6381 Cmd::PageVersions => art::PAGE_VERSIONS,
6355 Cmd::CopyPageLink => art::COPY_LINK,6382 Cmd::CopyPageLink => art::COPY_LINK,
6383 Cmd::MoveOrCopyPage => art::MOVE,
6356 Cmd::PasswordProtect => art::PASSWORD,6384 Cmd::PasswordProtect => art::PASSWORD,
6357 Cmd::LockAll => art::LOCK,6385 Cmd::LockAll => art::LOCK,
6358 Cmd::ShowNotebook => art::FOLDER,6386 Cmd::ShowNotebook => art::FOLDER,
...@@ -6873,7 +6901,7 @@ impl State {...@@ -6873,7 +6901,7 @@ impl State {
6873 && (self.initial.iter())6901 && (self.initial.iter())
6874 .map(|(id, document)| (id, document))6902 .map(|(id, document)| (id, document))
6875 .eq((editor.outlines().iter()).map(|outline| (&outline.id, outline.document())));6903 .eq((editor.outlines().iter()).map(|outline| (&outline.id, outline.document())));
6876 if self.session.is_some() || unchanged {6904 if self.session.is_some() || self.pane.sectionless.is_some() || unchanged {
6877 let _ = self.proxy.send_event(UserEvent::Exit);6905 let _ = self.proxy.send_event(UserEvent::Exit);
6878 return;6906 return;
6879 }6907 }
...@@ -6896,6 +6924,18 @@ impl App {...@@ -6896,6 +6924,18 @@ impl App {
6896 let Some(state) = &self.state else {6924 let Some(state) = &self.state else {
6897 return event_loop.exit();6925 return event_loop.exit();
6898 };6926 };
6927 if !state.moving.is_empty() {
6928 return crate::confirm(
6929 "Quit while a section is moving?",
6930 "Quitting now can leave it in both notebooks, though nothing in it is lost.",
6931 "Keep Snowbound Open",
6932 "Quit Anyway",
6933 state.reply(|state, ()| {
6934 state.quit();
6935 Ok(())
6936 }),
6937 );
6938 }
6899 let changes = match notebook::unwritten() {6939 let changes = match notebook::unwritten() {
6900 0 => return state.quit(),6940 0 => return state.quit(),
6901 1 => "1 unsaved change".to_owned(),6941 1 => "1 unsaved change".to_owned(),
crates/snowbound/src/manage.rs+59-8
...@@ -1125,21 +1125,72 @@ impl State {...@@ -1125,21 +1125,72 @@ impl State {
1125 })1125 })
1126 }1126 }
11271127
1128 /// Moves page `space` of the open section to the end of the section at catalog `path`,1128 /// Moves page `space` of the open section to the end of the section at catalog `path` of
1129 /// as OneNote moves a page dropped on a section's tab: the page keeps its identity,1129 /// `library`, as OneNote moves a page dropped on a section's tab: the page keeps its
1130 /// title, date and content there and leaves this section.1130 /// identity, title, date and content there and leaves this section.
1131 pub(crate) fn move_page(&mut self, space: ExGuid, path: String) -> Result<(), Box<dyn Error>> {1131 pub(crate) fn move_page(
1132 let session = self.session.as_ref().ok_or("No section is open")?;1132 &mut self,
1133 let target = session1133 space: ExGuid,
1134 .library1134 library: &Library,
1135 .section_identity(&path)1135 path: &str,
1136 ) -> Result<(), Box<dyn Error>> {
1137 let target = library
1138 .section_identity(path)
1136 .ok_or("That section is not in the notebook")?;1139 .ok_or("That section is not in the notebook")?;
1137 self.change_pages(Change::Send {1140 self.change_pages(Change::Send {
1138 page: space,1141 page: space,
1142 notebook: library.location.clone(),
1139 target,1143 target,
1140 })1144 })
1141 }1145 }
11421146
1147 /// Copies page `space` of the open section to the end of the section at catalog `path` of
1148 /// `library`, under new identities, as OneNote's Move or Copy copies a page.
1149 pub(crate) fn copy_page(
1150 &mut self,
1151 space: ExGuid,
1152 library: Arc<Library>,
1153 path: String,
1154 ) -> Result<(), Box<dyn Error>> {
1155 self.persist()?;
1156 let session = self.session.as_ref().ok_or("No section is open")?;
1157 let op = notebook::session::copied(&session.section.page(space)?, &self.author)?;
1158 // A section a pane shows is open already, and opens nowhere else meanwhile.
1159 let open = (self.sessions())
1160 .find(|open| {
1161 open.library.location == library.location && open.tabs[open.tab].path == path
1162 })
1163 .map(|open| Arc::clone(open.section.replica()));
1164 let (author, proxy) = (self.author.clone(), self.proxy.clone());
1165 let (key, space) = (library.key(&path), crate::undo::imported(&op));
1166 crate::spawn_async(move || async move {
1167 let copied = async {
1168 let edit = onestore::op::Edit {
1169 at: crate::filetime(),
1170 ops: vec![op],
1171 };
1172 if let Some(replica) = open {
1173 replica.apply_async(&author, edit).await?;
1174 return Ok(());
1175 }
1176 let section = library.open_async(&path, || {}).await?;
1177 let copied = section.replica().apply_async(&author, edit).await;
1178 crate::undo::release(&library, &path, section).await;
1179 copied?;
1180 Ok::<_, Box<dyn Error>>(())
1181 };
1182 let copied = copied.await.map_err(|error| crate::plain(&*error, "page"));
1183 let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| {
1184 match copied {
1185 Ok(()) => state.edited_sections(&key, vec![space], |touched| touched == key),
1186 Err(error) => platform::alert("Couldn't copy the page", &error),
1187 }
1188 Ok(())
1189 })));
1190 });
1191 Ok(())
1192 }
1193
1143 /// Moves or indents pages of the open section, in order.1194 /// Moves or indents pages of the open section, in order.
1144 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {1195 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {
1145 self.persist()?;1196 self.persist()?;
crates/snowbound/src/menubar.rs+1
...@@ -66,6 +66,7 @@ const MENUS: &[Item] = &[...@@ -66,6 +66,7 @@ const MENUS: &[Item] = &[
66 S,66 S,
67 C(Id::PageVersions),67 C(Id::PageVersions),
68 C(Id::CopyPageLink),68 C(Id::CopyPageLink),
69 C(Id::MoveOrCopyPage),
69 C(Id::ShowNotebook),70 C(Id::ShowNotebook),
70 C(Id::LiveShare),71 C(Id::LiveShare),
71 S,72 S,
crates/snowbound/src/menus.rs+28-18
...@@ -111,6 +111,8 @@ pub enum Action {...@@ -111,6 +111,8 @@ pub enum Action {
111 Move,111 Move,
112 /// Moves it to a section, or into a folder, by catalog path.112 /// Moves it to a section, or into a folder, by catalog path.
113 MoveTo(String),113 MoveTo(String),
114 /// Opens Move or Copy on a page or section.
115 MoveOrCopy,
114 /// Opens the submenu of the sections `CopyTo` copies a page of the recycle bin to.116 /// Opens the submenu of the sections `CopyTo` copies a page of the recycle bin to.
115 Copy,117 Copy,
116 CopyTo(String),118 CopyTo(String),
...@@ -158,7 +160,7 @@ impl Action {...@@ -158,7 +160,7 @@ impl Action {
158 Action::Open => art::OPEN,160 Action::Open => art::OPEN,
159 Action::Rename => art::RENAME,161 Action::Rename => art::RENAME,
160 Action::Delete => art::DELETE,162 Action::Delete => art::DELETE,
161 Action::Move => art::MOVE,163 Action::Move | Action::MoveOrCopy => art::MOVE,
162 Action::Copy => art::COPY,164 Action::Copy => art::COPY,
163 Action::SaveAs => art::SAVE,165 Action::SaveAs => art::SAVE,
164 Action::RecycleBin => art::RECYCLE_BIN,166 Action::RecycleBin => art::RECYCLE_BIN,
...@@ -219,7 +221,9 @@ pub(crate) const SECTION_COLORS: [(u32, &str); 16] = [...@@ -219,7 +221,9 @@ pub(crate) const SECTION_COLORS: [(u32, &str); 16] = [
219pub(crate) fn covered(target: &Target, action: &Action) -> bool {221pub(crate) fn covered(target: &Target, action: &Action) -> bool {
220 use Action::*;222 use Action::*;
221 match target {223 match target {
222 Target::Page { .. } => matches!(action, CopyLink | NewPage | NewSubpage | Theme),224 Target::Page { .. } => {
225 matches!(action, CopyLink | NewPage | NewSubpage | Theme | MoveOrCopy)
226 }
223 Target::Section { .. } => matches!(227 Target::Section { .. } => matches!(
224 action,228 action,
225 SaveAs | NewSection | NewGroup | Password | Theme | EmptyRecycleBin229 SaveAs | NewSection | NewGroup | Password | Theme | EmptyRecycleBin
...@@ -259,6 +263,7 @@ pub(crate) fn command_title(target: &Target, action: &Action, label: &str) -> St...@@ -259,6 +263,7 @@ pub(crate) fn command_title(target: &Target, action: &Action, label: &str) -> St
259 }263 }
260 match label.split_once(' ') {264 match label.split_once(' ') {
261 _ if *action == Action::Properties => format!("{noun} {label}"),265 _ if *action == Action::Properties => format!("{noun} {label}"),
266 _ if *action == Action::MoveOrCopy => format!("{label} {noun}"),
262 Some((verb, rest)) => format!("{verb} {noun} {rest}"),267 Some((verb, rest)) => format!("{verb} {noun} {rest}"),
263 None => format!("{label} {noun}"),268 None => format!("{label} {noun}"),
264 }269 }
...@@ -465,7 +470,7 @@ impl State {...@@ -465,7 +470,7 @@ impl State {
465 let mut actions = vec![470 let mut actions = vec![
466 item(Action::Rename, "Rename", false, false),471 item(Action::Rename, "Rename", false, false),
467 item(Action::Delete, "Delete", false, false),472 item(Action::Delete, "Delete", false, false),
468 item(Action::Move, "Move to Section", nowhere(), false),473 item(Action::MoveOrCopy, "Move or Copy", false, false),
469 item(Action::CopyLink, "Copy Link to Page", false, true),474 item(Action::CopyLink, "Copy Link to Page", false, true),
470 item(475 item(
471 Action::MarkRead,476 Action::MarkRead,
...@@ -528,7 +533,10 @@ impl State {...@@ -528,7 +533,10 @@ impl State {
528 }533 }
529 actions.extend([534 actions.extend([
530 item(Action::Delete, "Delete", false, false),535 item(Action::Delete, "Delete", false, false),
531 item(Action::Move, "Move", nowhere(), false),536 match section {
537 true => item(Action::MoveOrCopy, "Move or Copy", false, false),
538 false => item(Action::Move, "Move", nowhere(), false),
539 },
532 ]);540 ]);
533 if section {541 if section {
534 let link = self.section_link(library, path).is_none();542 let link = self.section_link(library, path).is_none();
...@@ -762,8 +770,8 @@ impl State {...@@ -762,8 +770,8 @@ impl State {
762 }770 }
763 }771 }
764772
765 /// Where Move takes `target`: the other sections of a page's folder, or the folders a773 /// Where Move takes `target`: the sections a page of the recycle bin goes back to, or the
766 /// section or group may move into.774 /// folders a section or group may move into.
767 fn destinations(&self, target: &Target) -> Vec<Destination> {775 fn destinations(&self, target: &Target) -> Vec<Destination> {
768 let theme = &self.ui.theme;776 let theme = &self.ui.theme;
769 match target {777 match target {
...@@ -778,15 +786,6 @@ impl State {...@@ -778,15 +786,6 @@ impl State {
778 })786 })
779 .collect()787 .collect()
780 }788 }
781 Target::Page { library, path, .. } => (library.tabs(&folder(path)).into_iter())
782 .filter(|tab| tab.path != *path)
783 .map(|tab| Destination {
784 tint: Some(theme.section(crate::section_color(tab.color)).accent),
785 name: tab.name,
786 path: tab.path,
787 icon: crate::art::SECTION,
788 })
789 .collect(),
790 Target::Section { library, path } | Target::Group { library, path } => {789 Target::Section { library, path } | Target::Group { library, path } => {
791 let within = format!("{path}/");790 let within = format!("{path}/");
792 let home = folder(path);791 let home = folder(path);
...@@ -937,6 +936,10 @@ impl State {...@@ -937,6 +936,10 @@ impl State {
937 );936 );
938 None937 None
939 }938 }
939 (Target::Section { library, path }, Action::MoveOrCopy) => {
940 self.open_move_copy(crate::move_copy::Moving::Section { library, path });
941 None
942 }
940 (943 (
941 Target::Section { library, path } | Target::Group { library, path },944 Target::Section { library, path } | Target::Group { library, path },
942 Action::MoveTo(folder),945 Action::MoveTo(folder),
...@@ -1080,7 +1083,10 @@ impl State {...@@ -1080,7 +1083,10 @@ impl State {
1080 path,1083 path,
1081 copy: true,1084 copy: true,
1082 })),1085 })),
1083 Action::MoveTo(path) => Some(Command::MovePage { space, path }),1086 Action::MoveOrCopy => {
1087 self.move_or_copy_page(space);
1088 None
1089 }
1084 Action::CopyLink => {1090 Action::CopyLink => {
1085 let copied = self1091 let copied = self
1086 .page_link(space, None)1092 .page_link(space, None)
...@@ -1231,8 +1237,12 @@ impl State {...@@ -1231,8 +1237,12 @@ impl State {
1231 }1237 }
1232 let slot = drag.slot.take();1238 let slot = drag.slot.take();
1233 if let Some(tab) = target {1239 if let Some(tab) = target {
1234 let path = session.tabs[tab].path.clone();1240 let (library, path) = (Arc::clone(&session.library), session.tabs[tab].path.clone());
1235 self.commands.push(Command::MovePage { space, path });1241 self.commands.push(Command::MovePage {
1242 space,
1243 library,
1244 path,
1245 });
1236 return;1246 return;
1237 }1247 }
1238 let Some(slot) = slot.filter(|slot| *slot != from) else {1248 let Some(slot) = slot.filter(|slot| *slot != from) else {
crates/snowbound/src/move_copy.rs created+673
...@@ -0,0 +1,673 @@
1//! OneNote 2010's Move or Copy: a section into a notebook or section group, or after a
2//! section, of any open notebook, and a page to the end of any of their sections.
3
4use crate::{Command, Library, State, UserEvent, art, library, manage::Structure, menus, platform};
5use accesskit::Role;
6use notebook::discover::Folder;
7use onestore::ExGuid;
8use std::{
9 error::Error,
10 hash::{DefaultHasher, Hash, Hasher},
11 sync::Arc,
12};
13use ui::{Anchor, Axis, Flags, Id, Spec, Ui, children, fill, fit, px};
14use winit::keyboard::NamedKey;
15
16const WIDTH: f32 = 420.0;
17/// Places the list shows at once.
18const ROWS: usize = 12;
19const INDENT: f32 = 16.0;
20
21/// What Move or Copy moves.
22pub enum Moving {
23 Section {
24 library: Arc<Library>,
25 path: String,
26 },
27 /// A page of the open section, at catalog `path`.
28 Page {
29 library: Arc<Library>,
30 path: String,
31 space: ExGuid,
32 },
33}
34
35/// The dialog while it is open.
36pub struct Dialog {
37 moving: Moving,
38 search: String,
39 selected: Option<u64>,
40}
41
42/// A place the dialog lists: a notebook or group to go into, last, or a section to go after,
43/// or for a page, to go to the end of.
44struct Place {
45 library: Arc<Library>,
46 folder: String,
47 section: Option<String>,
48 name: String,
49 depth: usize,
50 icon: &'static [&'static str],
51 tint: Option<[f32; 4]>,
52 /// Whether what moves can go there.
53 open: bool,
54}
55
56impl Place {
57 fn key(&self) -> u64 {
58 let mut hasher = DefaultHasher::new();
59 (&self.library.location, &self.folder, &self.section).hash(&mut hasher);
60 hasher.finish()
61 }
62}
63
64struct Places(Vec<Place>);
65
66impl ui::Rows for Places {
67 fn count(&self) -> usize {
68 self.0.len()
69 }
70
71 fn key(&self, index: usize) -> u64 {
72 self.0[index].key()
73 }
74
75 fn find(&self, key: u64) -> Option<usize> {
76 self.0.iter().position(|place| place.key() == key)
77 }
78
79 fn selectable(&self, index: usize) -> bool {
80 self.0[index].open
81 }
82}
83
84fn id() -> Id {
85 Id::ROOT.child("move-or-copy")
86}
87
88fn search_field() -> Id {
89 id().child("search")
90}
91
92fn list() -> Id {
93 id().child("places")
94}
95
96/// The sections and groups of `folder` of `library`, groups after, each group's own after it.
97fn walk(
98 places: &mut Vec<Place>,
99 theme: &ui::Theme,
100 library: &Arc<Library>,
101 folder: &Folder,
102 depth: usize,
103 moving: &Moving,
104) {
105 let (from, path, page) = match moving {
106 Moving::Section { library, path } => (library, path, false),
107 Moving::Page { library, path, .. } => (library, path, true),
108 };
109 for tab in library.tabs(&folder.path) {
110 // A page goes nowhere locked, nor to its own section.
111 let mine = library.location == from.location && tab.path == *path;
112 places.push(Place {
113 library: Arc::clone(library),
114 folder: folder.path.clone(),
115 open: !mine && !(page && library.locked(&tab.path)),
116 section: Some(tab.path),
117 name: tab.name,
118 depth,
119 icon: art::SECTION,
120 tint: Some(theme.section(crate::section_color(tab.color)).accent),
121 });
122 }
123 for group in (folder.groups.iter()).filter(|group| !library::recycle_bin(&group.path)) {
124 // A group goes nowhere inside itself.
125 let within = library.location == from.location
126 && (group.path == *path || group.path.starts_with(&format!("{path}/")));
127 places.push(Place {
128 library: Arc::clone(library),
129 folder: group.path.clone(),
130 section: None,
131 name: library::entry_name(&group.path).to_owned(),
132 depth,
133 icon: art::SECTION_GROUP,
134 tint: None,
135 open: !page && !within,
136 });
137 walk(places, theme, library, group, depth + 1, moving);
138 }
139}
140
141impl State {
142 /// Opens Move or Copy on page `space` of the open section.
143 pub(crate) fn move_or_copy_page(&mut self, space: ExGuid) {
144 if let Some(session) = &self.session {
145 self.open_move_copy(Moving::Page {
146 library: Arc::clone(&session.library),
147 path: session.tabs[session.tab].path.clone(),
148 space,
149 });
150 }
151 }
152
153 /// Opens Move or Copy on what `moving` names.
154 pub(crate) fn open_move_copy(&mut self, moving: Moving) {
155 self.move_copy = Some(Dialog {
156 moving,
157 search: String::new(),
158 selected: None,
159 });
160 self.ui.open_popup(id());
161 self.ui.set_focus(Some(search_field()));
162 }
163
164 /// The places of the open notebooks whose names hold `search`, in the sidebar's order.
165 fn places(&self, moving: &Moving, search: &str) -> Places {
166 let theme = &self.ui.theme;
167 let mut places = Vec::new();
168 for library in &self.notebooks {
169 let Some(catalog) = library.catalog() else {
170 continue;
171 };
172 places.push(Place {
173 library: Arc::clone(library),
174 folder: String::new(),
175 section: None,
176 name: library.name.clone(),
177 depth: 0,
178 icon: art::NOTEBOOK,
179 tint: Some(crate::notebook_color(theme, library.color())),
180 open: matches!(moving, Moving::Section { .. }),
181 });
182 walk(&mut places, theme, library, catalog, 1, moving);
183 }
184 // A match keeps the notebook and groups above it, which tell like-named places apart.
185 let search = search.trim().to_lowercase();
186 let mut kept = vec![false; places.len()];
187 let mut above: Vec<usize> = Vec::new();
188 for (at, place) in places.iter().enumerate() {
189 above.truncate(place.depth);
190 above.push(at);
191 if place.name.to_lowercase().contains(&search) {
192 above.iter().for_each(|at| kept[*at] = true);
193 }
194 }
195 let mut kept = kept.into_iter();
196 places.retain(|_| kept.next() == Some(true));
197 Places(places)
198 }
199
200 /// Builds Move or Copy while it is open. Move, or Enter, moves to the place selected;
201 /// Copy copies there.
202 pub(crate) fn move_copy_dialog(&mut self) {
203 let Some(dialog) = &self.move_copy else {
204 return;
205 };
206 if !self.ui.popup_open(id()) {
207 self.move_copy = None;
208 return;
209 }
210 let places = self.places(&dialog.moving, &dialog.search);
211 let (title, label) = match &dialog.moving {
212 Moving::Section { path, .. } => (
213 "Move or Copy Section",
214 format!(
215 "Move or copy section \u{201c}{}\u{201d} into a notebook or after a section:",
216 library::entry_name(path).trim_end_matches(".one")
217 ),
218 ),
219 Moving::Page { .. } => ("Move or Copy Pages", "Move or copy page to:".to_owned()),
220 };
221 let dialog = self.move_copy.as_mut().unwrap();
222 let ui = &mut self.ui;
223 let theme = ui.theme.clone();
224 let row = theme.font_size * 2.0;
225 let keys = ui::popup::navigation(
226 ui,
227 &[search_field()],
228 &[
229 NamedKey::ArrowUp,
230 NamedKey::ArrowDown,
231 NamedKey::PageUp,
232 NamedKey::PageDown,
233 NamedKey::Enter,
234 ],
235 );
236 ui.open_as(
237 id(),
238 Spec {
239 axis: Axis::Y,
240 size: [px(WIDTH), children()],
241 fill: Some(theme.popup),
242 border: Some(theme.chip),
243 shadow: Some(theme.shadow),
244 radius: 8.0,
245 pad: [16.0, 12.0],
246 gap: 4.0,
247 anchor: Some(Anchor::Dialog),
248 role: Some(Role::Dialog),
249 ..Spec::default()
250 },
251 );
252 if let Some(node) = ui.access(id()) {
253 node.set_label(title);
254 }
255 ui.leaf(
256 "title",
257 Spec {
258 size: [fill(), px(row)],
259 text: Some(title),
260 bold: true,
261 role: Some(Role::Heading),
262 ..Spec::default()
263 },
264 );
265 ui.leaf(
266 "label",
267 Spec {
268 size: [fill(), px(row * 0.8)],
269 text: Some(&label),
270 ..Spec::default()
271 },
272 );
273 ui::text_field(
274 ui,
275 search_field(),
276 &mut dialog.search,
277 "Search by text in title",
278 Spec {
279 size: [fill(), px(row)],
280 fill: Some(theme.base),
281 border: Some(theme.accent),
282 radius: 4.0,
283 pad: [6.0, 0.0],
284 ..Spec::default()
285 },
286 );
287 if let Some(node) = ui.access(search_field()) {
288 node.set_label("Search by text in title");
289 }
290 ui::list(
291 ui,
292 list(),
293 Spec {
294 size: [fill(), px(row * ROWS as f32)],
295 fill: Some(theme.base),
296 border: Some(theme.chip),
297 radius: 4.0,
298 role: Some(Role::Tree),
299 ..Spec::default()
300 },
301 ui::List {
302 rows: &places,
303 row,
304 keys: &keys,
305 hover_selects: false,
306 },
307 &mut dialog.selected,
308 |ui, row| {
309 let place = &places.0[row.index];
310 if let Some(node) = ui.access(list().child(row.key)) {
311 node.set_role(Role::TreeItem);
312 node.set_label(place.name.as_str());
313 node.set_level(place.depth + 1);
314 node.set_selected(row.selected);
315 if !place.open {
316 node.set_disabled();
317 }
318 }
319 place_row(ui, &theme, place, row.selected);
320 },
321 );
322 if let Some(node) = ui.access(list()) {
323 node.set_label("All Notebooks");
324 }
325 if let Some(key) = dialog.selected
326 && let Some(node) = ui.access(search_field())
327 {
328 node.set_active_descendant(list().child(key).node());
329 }
330 let chosen = (dialog.selected)
331 .and_then(|key| ui::Rows::find(&places, key))
332 .filter(|at| places.0[*at].open);
333 crate::buttons(ui);
334 let [cancel, moved, copy] = ui::dialog_buttons_with(ui, "Move", chosen.is_some(), |ui| {
335 action(ui, "copy", "Copy", chosen.is_some())
336 });
337 let moved = moved || keys.contains(&NamedKey::Enter);
338 ui.close();
339 ui.close();
340 let Some(at) = chosen.filter(|_| moved || copy) else {
341 if cancel {
342 self.ui.close_popup(id());
343 }
344 return;
345 };
346 self.ui.close_popup(id());
347 let Some(dialog) = self.move_copy.take() else {
348 return;
349 };
350 let place = places.0.into_iter().nth(at).unwrap();
351 let noun = match dialog.moving {
352 Moving::Section { .. } => "section",
353 Moving::Page { .. } => "page",
354 };
355 if let Err(error) = self.carry(dialog.moving, place, copy) {
356 let verb = if copy { "copy" } else { "move" };
357 platform::alert(
358 &format!("Couldn't {verb} the {noun}"),
359 &crate::plain(&*error, noun),
360 );
361 }
362 }
363
364 /// Moves, or with `copy` copies, what `moving` names to `place`.
365 fn carry(&mut self, moving: Moving, place: Place, copy: bool) -> Result<(), Box<dyn Error>> {
366 match moving {
367 Moving::Page { space, .. } => {
368 let path = place.section.ok_or("Choose a section")?;
369 self.commands.push(if copy {
370 Command::CopyPage {
371 space,
372 library: place.library,
373 path,
374 }
375 } else {
376 Command::MovePage {
377 space,
378 library: place.library,
379 path,
380 }
381 });
382 }
383 Moving::Section { library, path }
384 if !copy && library.location == place.library.location =>
385 {
386 let change = within(&library, path, &place.folder, place.section.as_deref());
387 self.commands.push(Command::Structure(library, change));
388 }
389 Moving::Section { library, path } => self.carry_section(
390 library,
391 path,
392 place.library,
393 place.folder,
394 place.section,
395 copy,
396 )?,
397 }
398 Ok(())
399 }
400
401 /// Moves, or with `copy` copies, section `path` of `from` into `folder` of `to`, after
402 /// its section `after` or last, on a thread of its own, then lists both notebooks again.
403 /// A section moving opens nowhere until it has gone, and one shown leaves the window for
404 /// the notebook's first, or comes back where it stayed.
405 fn carry_section(
406 &mut self,
407 from: Arc<Library>,
408 path: String,
409 to: Arc<Library>,
410 folder: String,
411 after: Option<String>,
412 copy: bool,
413 ) -> Result<(), Box<dyn Error>> {
414 self.persist()?;
415 let moving = (!copy).then(|| (from.location.clone(), path.clone()));
416 self.moving.extend(moving.clone());
417 let mine = |session: &crate::Session| {
418 session.library.location == from.location && session.tabs[session.tab].path == path
419 };
420 let shown = self.session.as_ref().is_some_and(mine);
421 let (mut section, mut replica, mut panes) = (None, None, Vec::new());
422 if copy {
423 replica = (self.sessions().find(|session| mine(session)))
424 .map(|session| Arc::clone(session.section.replica()));
425 } else {
426 // Parked panes let it go, the focused one hands it over; each shows it again where
427 // it stayed, or the notebook's first section.
428 let key = Some(from.key(&path));
429 panes = (self.parked.iter())
430 .filter(|parked| parked.section == key)
431 .map(|parked| parked.pane.id)
432 .collect();
433 self.leave_sections(mine, |_, pane| pane.sectionless = Some(Arc::clone(&from)));
434 if shown {
435 section = self.session.take().map(|session| session.section);
436 self.pane.sectionless = Some(Arc::clone(&from));
437 self.title();
438 }
439 }
440 let proxy = self.proxy.clone();
441 crate::spawn_async(move || async move {
442 let carried = async {
443 // Both notebooks' in one order, whichever way a section goes.
444 let [first, second] = match from.location < to.location {
445 true => [&from, &to],
446 false => [&to, &from],
447 };
448 let _changing = first.structure.lock().await;
449 let _arriving = match from.location == to.location {
450 true => None,
451 false => Some(second.structure.lock().await),
452 };
453 let mut source = from.reopen()?;
454 let mut target = to.reopen()?;
455 let after = after.as_deref();
456 let kept = if copy {
457 let opened = match replica {
458 Some(_) => None,
459 None => Some(from.open_async(&path, || {}).await?),
460 };
461 let replica =
462 replica.unwrap_or_else(|| Arc::clone(opened.as_ref().unwrap().replica()));
463 let copied = source.copy_section(&path, &replica, &mut target, &folder, after);
464 if let Some(opened) = opened {
465 crate::undo::release(&from, &path, opened).await;
466 }
467 copied.map(|_| None)?
468 } else {
469 let section = match section {
470 Some(section) => section,
471 None => from.open_async(&path, || {}).await?,
472 };
473 source
474 .move_section(&path, section, &mut target, &folder, after)?
475 .kept
476 };
477 if from.location == to.location {
478 source = to.reopen()?;
479 }
480 let from = Arc::new(from.with(source));
481 let to = match from.location == to.location {
482 true => Arc::clone(&from),
483 false => Arc::new(to.with(target)),
484 };
485 Ok::<_, Box<dyn Error>>((from, to, kept))
486 };
487 let carried = carried
488 .await
489 .map_err(|error| crate::plain(&*error, "section"));
490 let _ = proxy.send_event(UserEvent::Then(Box::new(move |state| {
491 state
492 .moving
493 .retain(|listed| Some(listed) != moving.as_ref());
494 // What the panes that showed a section moving show after: it, where it stayed,
495 // or else the notebook's first section.
496 let (from, shows) = match carried {
497 Ok((from, to, kept)) => {
498 state.relisted(to)?;
499 state.relisted(Arc::clone(&from))?;
500 if let Some(kept) = &kept {
501 platform::alert(
502 "Section kept in both notebooks",
503 &crate::plain(kept, "section"),
504 );
505 }
506 let shows = match kept {
507 Some(_) => Some(path),
508 None => from.first_section(),
509 };
510 (from, shows)
511 }
512 Err(error) => {
513 let verb = if copy { "copy" } else { "move" };
514 platform::alert(&format!("Couldn't {verb} the section"), &error);
515 (from, Some(path))
516 }
517 };
518 // Parked panes wait their turn to open it, after the focused one.
519 for parked in
520 (state.parked.iter_mut()).filter(|parked| panes.contains(&parked.pane.id))
521 {
522 if let Some(shows) = &shows {
523 parked.pane.sectionless = None;
524 let place = crate::navigation::Place {
525 notebook: from.location.clone(),
526 section: shows.clone(),
527 page: ExGuid::default(),
528 };
529 state.reopening.push((parked.pane.id, place));
530 }
531 }
532 match shows {
533 Some(shows) if shown && !copy => {
534 state.commands.push(Command::OpenSection(from, shows));
535 }
536 None if shown && !copy => state.adopt(from, None)?,
537 _ => {}
538 }
539 Ok(())
540 })));
541 });
542 Ok(())
543 }
544}
545
546impl State {
547 /// Lists `library`, read again, in place of the notebook at its location, following the
548 /// section shown there.
549 fn relisted(&mut self, library: Arc<Library>) -> Result<(), Box<dyn Error>> {
550 if !(self.notebooks.iter()).any(|open| open.location == library.location) {
551 return Ok(());
552 }
553 let shown = (self.session.as_ref())
554 .filter(|session| session.library.location == library.location)
555 .and_then(|session| {
556 session
557 .library
558 .section_identity(&session.tabs[session.tab].path)
559 })
560 .and_then(|identity| {
561 (library.catalog()?.sections())
562 .find(|section| section.file_id == identity)
563 .map(|section| section.path.clone())
564 })
565 // Never into the recycle bin, where a section that moved has gone.
566 .filter(|path| !crate::recycle::binned(path));
567 if (self.pane.sectionless.as_ref()).is_some_and(|shown| shown.location == library.location)
568 {
569 self.pane.sectionless = Some(Arc::clone(&library));
570 }
571 match shown {
572 Some(path) => self.adopt(library, Some(&path)),
573 None => {
574 self.list(&library);
575 Ok(())
576 }
577 }
578 }
579}
580
581/// The structure change moving section `path` of `library` within it, into `folder` after
582/// its section `after`, or last.
583fn within(library: &Library, path: String, folder: &str, after: Option<&str>) -> Structure {
584 let name = library::entry_name(&path).to_owned();
585 let arrived = match folder {
586 "" => name,
587 folder => format!("{folder}/{name}"),
588 };
589 let mut paths: Vec<String> = (library.tabs(folder).into_iter())
590 .map(|tab| tab.path)
591 .filter(|listed| *listed != path)
592 .collect();
593 let at = after.and_then(|after| paths.iter().position(|listed| listed == after));
594 paths.insert(at.map_or(paths.len(), |at| at + 1), arrived);
595 match (menus::folder(&path) == folder, after) {
596 (true, _) => Structure::Reorder {
597 folder: folder.to_owned(),
598 paths,
599 },
600 (false, None) => Structure::Move {
601 path,
602 folder: folder.to_owned(),
603 },
604 (false, Some(_)) => Structure::Return {
605 path,
606 folder: folder.to_owned(),
607 paths,
608 },
609 }
610}
611
612/// A row of the list: `place`, indented by its depth, with its icon.
613fn place_row(ui: &mut Ui, theme: &ui::Theme, place: &Place, selected: bool) {
614 let row = theme.font_size * 2.0;
615 ui.open(
616 "place",
617 Spec {
618 size: [fill(), fill()],
619 fill: selected.then(|| theme.hover()),
620 hover_fill: place.open.then(|| theme.hover()),
621 radius: 4.0,
622 pad: [4.0 + place.depth as f32 * INDENT, 0.0],
623 gap: 6.0,
624 ..Spec::default()
625 },
626 );
627 ui.leaf(
628 "icon",
629 Spec {
630 size: [px(16.0), px(row)],
631 icon: Some(place.icon),
632 color: place.tint.or(Some(theme.text_dim)),
633 ..Spec::default()
634 },
635 );
636 ui.leaf(
637 "name",
638 Spec {
639 size: [fit(), px(row)],
640 text: Some(&place.name),
641 bold: place.depth == 0,
642 color: (!place.open).then_some(theme.text_dim),
643 flags: Flags::CLIP,
644 ..Spec::default()
645 },
646 );
647 ui.close();
648}
649
650/// A button of the dialog's row besides its default, which takes no clicks while not
651/// `enabled`: whether it was clicked.
652fn action(ui: &mut Ui, part: &str, text: &str, enabled: bool) -> bool {
653 if enabled {
654 return ui::button(ui, part, text).clicked;
655 }
656 let theme = &ui.theme;
657 let spec = Spec {
658 size: [fit(), px(theme.font_size * 2.0)],
659 text: Some(text),
660 color: Some(theme.text_dim),
661 fill: Some(theme.chip),
662 radius: 4.0,
663 pad: [theme.font_size * 0.75, 0.0],
664 center: true,
665 role: Some(Role::Button),
666 ..Spec::default()
667 };
668 ui.leaf(part, spec);
669 if let Some(node) = ui.access(ui.id(part)) {
670 node.set_disabled();
671 }
672 false
673}
crates/snowbound/src/sidebar.rs+3
...@@ -1536,6 +1536,7 @@ impl crate::State {...@@ -1536,6 +1536,7 @@ impl crate::State {
1536 pub(crate) fn no_sections(&mut self, library: Arc<Library>) {1536 pub(crate) fn no_sections(&mut self, library: Arc<Library>) {
1537 let downloading = library.downloading();1537 let downloading = library.downloading();
1538 let renaming = self.folder_renaming(&library.location);1538 let renaming = self.folder_renaming(&library.location);
1539 let moving = (self.moving.iter()).any(|(at, _)| *at == library.location);
1539 let new = crate::Command::Structure(1540 let new = crate::Command::Structure(
1540 library,1541 library,
1541 crate::manage::Structure::NewSection {1542 crate::manage::Structure::NewSection {
...@@ -1545,6 +1546,8 @@ impl crate::State {...@@ -1545,6 +1546,8 @@ impl crate::State {
1545 let id = self.ui.id("no sections");1546 let id = self.ui.id("no sections");
1546 let (title, buttons) = if renaming {1547 let (title, buttons) = if renaming {
1547 ("Renaming the folder…", Vec::new())1548 ("Renaming the folder…", Vec::new())
1549 } else if moving {
1550 ("Moving the section…", Vec::new())
1548 } else if downloading {1551 } else if downloading {
1549 ("Downloading from iCloud Drive…", Vec::new())1552 ("Downloading from iCloud Drive…", Vec::new())
1550 } else {1553 } else {
crates/snowbound/src/undo.rs+117-46
...@@ -83,12 +83,18 @@ pub enum Change {...@@ -83,12 +83,18 @@ pub enum Change {
83 from: String,83 from: String,
84 to: String,84 to: String,
85 },85 },
86 /// Moves a page to the end of the section `target` names, as a drop on its tab does.86 /// Moves a page to the end of the section `target` names in the notebook at `notebook`,
87 Send { page: ExGuid, target: [u8; 16] },87 /// as a drop on its tab does.
88 Send {
89 page: ExGuid,
90 notebook: String,
91 target: [u8; 16],
92 },
88 /// Brings a page sent to `target` back, before `before` at `level`, taking out `added`93 /// Brings a page sent to `target` back, before `before` at `level`, taking out `added`
89 /// while it holds nothing.94 /// while it holds nothing.
90 Return {95 Return {
91 page: ExGuid,96 page: ExGuid,
97 notebook: String,
92 target: [u8; 16],98 target: [u8; 16],
93 before: Option<ExGuid>,99 before: Option<ExGuid>,
94 level: u32,100 level: u32,
...@@ -333,25 +339,26 @@ fn neighbor(...@@ -333,25 +339,26 @@ fn neighbor(
333}339}
334340
335/// The space of the page an import op creates.341/// The space of the page an import op creates.
336fn imported(op: &Op) -> ExGuid {342pub(crate) fn imported(op: &Op) -> ExGuid {
337 match op {343 match op {
338 Op::Section(SectionOp::Import { creation, .. }) => creation.space(),344 Op::Section(SectionOp::Import { creation, .. }) => creation.space(),
339 _ => unreachable!("notebook::session::moved imports"),345 _ => unreachable!("notebook::session::moved and copied import"),
340 }346 }
341}347}
342348
343/// What a change to pages works with: the open section, its notebook, who changes it, and349/// What a change to pages works with: the open section, its notebook, who changes it, a
344/// a page to give it should it be left without pages.350/// page to give it should it be left without pages, and the open notebooks a page may go to.
345struct Site {351struct Site {
346 replica: Arc<Replica>,352 replica: Arc<Replica>,
347 library: Arc<Library>,353 library: Arc<Library>,
348 /// The replicas of the notebook's sections parked panes show, open already, by catalog354 /// The replicas of the sections parked panes show, open already, by notebook location
349 /// path.355 /// and catalog path.
350 held: Vec<(String, Arc<Replica>)>,356 held: Vec<(String, String, Arc<Replica>)>,
351 author: String,357 author: String,
352 /// The page a section left without pages gains; none in the recycle bin, which OneNote358 /// The page a section left without pages gains; none in the recycle bin, which OneNote
353 /// leaves empty.359 /// leaves empty.
354 fresh: Option<PageCreation>,360 fresh: Option<PageCreation>,
361 notebooks: Vec<Arc<Library>>,
355}362}
356363
357/// A change to pages done: the change taking it back, the page to show, and pages gone.364/// A change to pages done: the change taking it back, the page to show, and pages gone.
...@@ -416,37 +423,32 @@ impl Site {...@@ -416,37 +423,32 @@ impl Site {
416 gone423 gone
417 }424 }
418425
419 /// The catalog path of the section `identity` names.426 /// The section `identity` names in the notebook at `notebook`, and its catalog path.
420 fn section_path(&self, identity: [u8; 16]) -> Option<String> {427 fn section(&self, notebook: &str, identity: [u8; 16]) -> Option<(Arc<Library>, String)> {
421 entry_of(self.library.catalog()?, identity).map(|(_, path)| path)428 let library = match notebook == self.library.location {
429 true => &self.library,
430 false => (self.notebooks.iter()).find(|open| open.location == notebook)?,
431 };
432 let (_, path) = entry_of(library.catalog()?, identity)?;
433 Some((Arc::clone(library), path))
422 }434 }
423435
424 /// The replica of the notebook's section at catalog `path`, with the section where it436 /// The replica of `library`'s section at catalog `path`, with the section where it was
425 /// was opened for this, which `release` closes after.437 /// opened for this, which `release` closes after.
426 async fn reach(438 async fn reach(
427 &self,439 &self,
440 library: &Library,
428 path: &str,441 path: &str,
429 ) -> Result<(Arc<Replica>, Option<notebook::session::Section>), Box<dyn Error>> {442 ) -> Result<(Arc<Replica>, Option<notebook::session::Section>), Box<dyn Error>> {
430 if let Some((_, replica)) = self.held.iter().find(|(held, _)| held == path) {443 let held = (self.held.iter())
444 .find(|(location, held, _)| *location == library.location && held == path);
445 if let Some((.., replica)) = held {
431 return Ok((Arc::clone(replica), None));446 return Ok((Arc::clone(replica), None));
432 }447 }
433 let section = self.library.open_async(path, || {}).await?;448 let section = library.open_async(path, || {}).await?;
434 Ok((Arc::clone(section.replica()), Some(section)))449 Ok((Arc::clone(section.replica()), Some(section)))
435 }450 }
436451
437 /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be,
438 /// keeps it open, where they are tried again until they are.
439 async fn release(&self, path: &str, section: notebook::session::Section) {
440 match section.replica().written_async().await {
441 Ok(()) => {
442 if let Err(error) = section.close_async().await {
443 eprintln!("Synchronization stopped: {error}");
444 }
445 }
446 Err(_) => self.library.keep(path, section),
447 }
448 }
449
450 /// Does `change` to the section's pages, `shown` the page open; `None` where what it452 /// Does `change` to the section's pages, `shown` the page open; `None` where what it
451 /// changes is gone or holds what it did not make, which it leaves alone.453 /// changes is gone or holds what it did not make, which it leaves alone.
452 async fn change(454 async fn change(
...@@ -595,8 +597,14 @@ impl Site {...@@ -595,8 +597,14 @@ impl Site {
595 gone: Vec::new(),597 gone: Vec::new(),
596 }598 }
597 }599 }
598 Change::Send { page, target } => {600 Change::Send {
599 let (Some(from), Some(path)) = (at(page), self.section_path(target)) else {601 page,
602 notebook,
603 target,
604 } => {
605 let (Some(from), Some((library, path))) =
606 (at(page), self.section(&notebook, target))
607 else {
600 return Ok(None);608 return Ok(None);
601 };609 };
602 let sent = self.replica.moving(page)?;610 let sent = self.replica.moving(page)?;
...@@ -606,7 +614,7 @@ impl Site {...@@ -606,7 +614,7 @@ impl Site {
606 let level = listed[from].2;614 let level = listed[from].2;
607 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];615 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];
608 let (show, added) = self.after(&listed, &[page], None, &mut ops);616 let (show, added) = self.after(&listed, &[page], None, &mut ops);
609 let (other, opened) = self.reach(&path).await?;617 let (other, opened) = self.reach(&library, &path).await?;
610 other618 other
611 .apply_async(619 .apply_async(
612 &self.author,620 &self.author,
...@@ -617,7 +625,7 @@ impl Site {...@@ -617,7 +625,7 @@ impl Site {
617 )625 )
618 .await?;626 .await?;
619 if let Some(section) = opened {627 if let Some(section) = opened {
620 self.release(&path, section).await;628 release(&library, &path, section).await;
621 }629 }
622 let edit = Edit {630 let edit = Edit {
623 at: crate::filetime(),631 at: crate::filetime(),
...@@ -628,6 +636,7 @@ impl Site {...@@ -628,6 +636,7 @@ impl Site {
628 Ok(_) => Applied {636 Ok(_) => Applied {
629 undo: Ok(Change::Return {637 undo: Ok(Change::Return {
630 page: arrived,638 page: arrived,
639 notebook,
631 target,640 target,
632 before,641 before,
633 level,642 level,
...@@ -645,18 +654,26 @@ impl Site {...@@ -645,18 +654,26 @@ impl Site {
645 }654 }
646 Change::Return {655 Change::Return {
647 page,656 page,
657 notebook,
648 target,658 target,
649 before,659 before,
650 level,660 level,
651 added,661 added,
652 } => {662 } => {
653 let Some(path) = self.section_path(target) else {663 let open = notebook == self.library.location
654 return Ok(None);664 || (self.notebooks.iter()).any(|open| open.location == notebook);
665 let Some((library, path)) = self.section(&notebook, target) else {
666 return match open {
667 true => Ok(None),
668 false => {
669 Err("The notebook the page went to is closed, so it stays there".into())
670 }
671 };
655 };672 };
656 let (other, opened) = self.reach(&path).await?;673 let (other, opened) = self.reach(&library, &path).await?;
657 if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) {674 if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) {
658 if let Some(section) = opened {675 if let Some(section) = opened {
659 self.release(&path, section).await;676 release(&library, &path, section).await;
660 }677 }
661 return Ok(None);678 return Ok(None);
662 }679 }
...@@ -679,11 +696,15 @@ impl Site {...@@ -679,11 +696,15 @@ impl Site {
679 };696 };
680 let retired = other.retire_async(&self.author, delete, sent).await;697 let retired = other.retire_async(&self.author, delete, sent).await;
681 if let Some(section) = opened {698 if let Some(section) = opened {
682 self.release(&path, section).await;699 release(&library, &path, section).await;
683 }700 }
684 Applied {701 Applied {
685 undo: (retired.map(|_| Change::Send { page: back, target }))702 undo: (retired.map(|_| Change::Send {
686 .map_err(|error| crate::plain(&error, "page")),703 page: back,
704 notebook,
705 target,
706 }))
707 .map_err(|error| crate::plain(&error, "page")),
687 show: back,708 show: back,
688 gone,709 gone,
689 }710 }
...@@ -699,6 +720,19 @@ impl Site {...@@ -699,6 +720,19 @@ impl Site {
699 }720 }
700}721}
701722
723/// Closes `section`, at catalog `path` in `library`, once its edits are written; while some
724/// wait to be, keeps it open, where they are tried again until they are.
725pub(crate) async fn release(library: &Library, path: &str, section: notebook::session::Section) {
726 match section.replica().written_async().await {
727 Ok(()) => {
728 if let Err(error) = section.close_async().await {
729 eprintln!("Synchronization stopped: {error}");
730 }
731 }
732 Err(_) => library.keep(path, section),
733 }
734}
735
702/// The identity of each section and group in `folder`, in order, with its catalog path;736/// The identity of each section and group in `folder`, in order, with its catalog path;
703/// the recycle bin is left out.737/// the recycle bin is left out.
704fn entries(folder: &Folder) -> Vec<([u8; 16], String)> {738fn entries(folder: &Folder) -> Vec<([u8; 16], String)> {
...@@ -1131,9 +1165,25 @@ impl State {...@@ -1131,9 +1165,25 @@ impl State {
1131 } else {1165 } else {
1132 None1166 None
1133 };1167 };
1134 let held = self.held(&session.library.location);1168 let locations: std::collections::BTreeSet<&String> =
1169 (self.notebooks.iter().map(|library| &library.location))
1170 .chain([&session.library.location])
1171 .collect();
1172 let held = (locations.into_iter())
1173 .flat_map(|location| {
1174 (self.held(location).into_iter())
1175 .map(|(path, replica)| (location.clone(), path, replica))
1176 })
1177 .collect();
1135 let key = session.key();1178 let key = session.key();
1136 let notebook_key = session.library.key("");1179 let notebook_key = session.library.key("");
1180 // The notebook a page goes to or comes back from, whose panes follow too.
1181 let other_key = match &change {
1182 Change::Send { notebook, .. } | Change::Return { notebook, .. } => {
1183 Some(crate::library::key(notebook, ""))
1184 }
1185 _ => None,
1186 };
1137 let mut site = Site {1187 let mut site = Site {
1138 replica: Arc::clone(session.section.replica()),1188 replica: Arc::clone(session.section.replica()),
1139 library: Arc::clone(&session.library),1189 library: Arc::clone(&session.library),
...@@ -1142,6 +1192,7 @@ impl State {...@@ -1142,6 +1192,7 @@ impl State {
1142 fresh: (!self.in_recycle_bin())1192 fresh: (!self.in_recycle_bin())
1143 .then(|| self.dated_page(None, ""))1193 .then(|| self.dated_page(None, ""))
1144 .transpose()?,1194 .transpose()?,
1195 notebooks: self.notebooks.clone(),
1145 };1196 };
1146 let shown = self.pane.showing.space;1197 let shown = self.pane.showing.space;
1147 let original = Arc::clone(&site.library);1198 let original = Arc::clone(&site.library);
...@@ -1208,7 +1259,12 @@ impl State {...@@ -1208,7 +1259,12 @@ impl State {
1208 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),1259 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),
1209 }1260 }
1210 // Its section, and the one a page went to or came from, wherever the focus is.1261 // Its section, and the one a page went to or came from, wherever the focus is.
1211 state.edited_sections(&key, Vec::new(), |shown| shown.starts_with(&notebook_key));1262 state.edited_sections(&key, Vec::new(), |shown| {
1263 shown.starts_with(&notebook_key)
1264 || other_key
1265 .as_ref()
1266 .is_some_and(|other| shown.starts_with(other))
1267 });
1212 Ok(())1268 Ok(())
1213 })));1269 })));
1214 drop(changing);1270 drop(changing);
...@@ -1498,6 +1554,7 @@ mod tests {...@@ -1498,6 +1554,7 @@ mod tests {
1498 held: Vec::new(),1554 held: Vec::new(),
1499 author: AUTHOR.into(),1555 author: AUTHOR.into(),
1500 fresh: Some(dated()),1556 fresh: Some(dated()),
1557 notebooks: Vec::new(),
1501 }1558 }
1502 }1559 }
15031560
...@@ -1741,6 +1798,7 @@ mod tests {...@@ -1741,6 +1798,7 @@ mod tests {
1741 let sent = fixture1798 let sent = fixture
1742 .change(Change::Send {1799 .change(Change::Send {
1743 page: fixture.space("Second"),1800 page: fixture.space("Second"),
1801 notebook: fixture.library.location.clone(),
1744 target,1802 target,
1745 })1803 })
1746 .unwrap();1804 .unwrap();
...@@ -1769,7 +1827,13 @@ mod tests {...@@ -1769,7 +1827,13 @@ mod tests {
1769 let page = fixture.space("Only");1827 let page = fixture.space("Only");
1770 let mut site = fixture.site();1828 let mut site = fixture.site();
1771 site.fresh = None;1829 site.fresh = None;
1772 let sent = pollster::block_on(site.change(Change::Send { page, target }, page))1830 let notebook = fixture.library.location.clone();
1831 let send = Change::Send {
1832 page,
1833 notebook,
1834 target,
1835 };
1836 let sent = pollster::block_on(site.change(send, page))
1773 .unwrap()1837 .unwrap()
1774 .unwrap();1838 .unwrap();
1775 assert_eq!((sent.show, sent.gone), (page, vec![page]));1839 assert_eq!((sent.show, sent.gone), (page, vec![page]));
...@@ -1818,9 +1882,14 @@ mod tests {...@@ -1818,9 +1882,14 @@ mod tests {
1818 fixture.library.keep("B.one", b);1882 fixture.library.keep("B.one", b);
1819 let mut site = fixture.site();1883 let mut site = fixture.site();
1820 let shown = fixture.pages()[0].0;1884 let shown = fixture.pages()[0].0;
1885 let notebook = fixture.library.location.clone();
1821 let sending = std::thread::spawn(move || {1886 let sending = std::thread::spawn(move || {
1822 pollster::block_on(site.change(Change::Send { page, target }, shown))1887 let send = Change::Send {
1823 .map_err(|error| error.to_string())1888 page,
1889 notebook,
1890 target,
1891 };
1892 pollster::block_on(site.change(send, shown)).map_err(|error| error.to_string())
1824 });1893 });
1825 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);1894 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
1826 while !(arrived.pages().unwrap().iter()).any(|(_, title, _)| title == "Second") {1895 while !(arrived.pages().unwrap().iter()).any(|(_, title, _)| title == "Second") {
...@@ -1865,6 +1934,7 @@ mod tests {...@@ -1865,6 +1934,7 @@ mod tests {
1865 let target = fixture.library.section_identity("B.one").unwrap();1934 let target = fixture.library.section_identity("B.one").unwrap();
1866 let sent = (fixture.change(Change::Send {1935 let sent = (fixture.change(Change::Send {
1867 page: fixture.space("Second"),1936 page: fixture.space("Second"),
1937 notebook: fixture.library.location.clone(),
1868 target,1938 target,
1869 }))1939 }))
1870 .unwrap();1940 .unwrap();
...@@ -1905,7 +1975,7 @@ mod tests {...@@ -1905,7 +1975,7 @@ mod tests {
1905 b.apply(AUTHOR, edit).unwrap();1975 b.apply(AUTHOR, edit).unwrap();
1906 let replica = Arc::clone(b.replica());1976 let replica = Arc::clone(b.replica());
1907 assert!(replica.written().is_err());1977 assert!(replica.written().is_err());
1908 pollster::block_on(fixture.site().release("B.one", b));1978 pollster::block_on(release(&fixture.library, "B.one", b));
1909 *vfs::FAILING.lock().unwrap() = None;1979 *vfs::FAILING.lock().unwrap() = None;
1910 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);1980 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
1911 while replica.written().is_err() {1981 while replica.written().is_err() {
...@@ -2072,6 +2142,7 @@ mod tests {...@@ -2072,6 +2142,7 @@ mod tests {
2072 &fixture,2142 &fixture,
2073 Change::Send {2143 Change::Send {
2074 page: fixture.space("First"),2144 page: fixture.space("First"),
2145 notebook: fixture.library.location.clone(),
2075 target: fixture.library.section_identity("B.one").unwrap(),2146 target: fixture.library.section_identity("B.one").unwrap(),
2076 },2147 },
2077 );2148 );
crates/snowbound/tests/replay.rs+256
...@@ -2171,3 +2171,259 @@ fn settings_saved_while_panes_open_keep_them_all() {...@@ -2171,3 +2171,259 @@ fn settings_saved_while_panes_open_keep_them_all() {
2171 ]2171 ]
2172 );2172 );
2173}2173}
2174
2175/// The titles of the pages of the section file at `path`.
2176fn stored_titles(path: &Path) -> Vec<String> {
2177 let image = std::fs::read(path).unwrap();
2178 (notebook::session::stored_pages(&image).unwrap().into_iter())
2179 .map(|stored| stored.page.title)
2180 .collect()
2181}
2182
2183/// Move or Copy, as OneNote 2010 has it, takes a section and a page into another notebook
2184/// open beside, which holds a section of the same name: a copy of the section first, then the
2185/// page shown to the end of that notebook's section, then the section itself, which arrives
2186/// under the next free name and leaves for its notebook's recycle bin.
2187#[test]
2188fn move_or_copy_takes_sections_and_pages_into_another_notebook() {
2189 let scratch = Scratch::new("move-or-copy");
2190 let source =
2191 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate");
2192 let other = scratch.0.join("other");
2193 copy_notebook(&source, &other);
2194 let settings = serde_json::json!({
2195 "user_name": "Snowbound Test",
2196 "sidebar": true,
2197 "notebooks": [other],
2198 });
2199 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
2200 let pages = stored_titles(&source.join("Cross.one"));
2201 let palette = |command: &'static str| {
2202 [
2203 "modifiers command",
2204 "key p",
2205 "modifiers",
2206 "settle",
2207 command,
2208 "settle",
2209 "key Enter",
2210 "wait 400",
2211 ]
2212 };
2213 let mut steps = Vec::from(palette("type >Move or Copy Section"));
2214 steps.extend(["accessibility dialog", "type other", "key Down", "wait 200"]);
2215 // Copy.
2216 steps.extend(["move 637 529", "press", "release", "wait 2000", "settle"]);
2217 steps.extend(palette("type >Move or Copy Page"));
2218 // The other notebook's Cross, the first listed but the page's own.
2219 steps.extend(["accessibility pages", "type Cross", "key Down", "key Enter"]);
2220 steps.extend(["wait 2000", "settle"]);
2221 steps.extend(palette("type >Move or Copy Section"));
2222 steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]);
2223 let [dialog, pages_dialog] = replay(&scratch, Some(&source), &steps).try_into().unwrap();
2224 assert!(
2225 dialog.contains(r#"Dialog "Move or Copy Section""#),
2226 "{dialog}"
2227 );
2228 assert!(dialog.contains(r#"TreeItem "other""#), "{dialog}");
2229 assert!(dialog.contains(r#"Button "Move" [disabled]"#), "{dialog}");
2230 assert!(
2231 pages_dialog.contains(r#"Dialog "Move or Copy Pages""#),
2232 "{pages_dialog}"
2233 );
2234
2235 let notebook = scratch.0.join("notebook");
2236 assert!(!notebook.join("Cross.one").exists());
2237 let binned = stored_titles(&notebook.join("OneNote_RecycleBin/Cross.one"));
2238 assert_eq!(binned, pages[1..], "the page left before the section did");
2239 let [first, copied, moved] = ["Cross.one", "Cross 2.one", "Cross 3.one"]
2240 .map(|name| other.join(name))
2241 .map(|path| path.exists().then(|| stored_titles(&path)));
2242 let mut arrived = pages.clone();
2243 arrived.push(pages[0].clone());
2244 assert_eq!(first, Some(arrived));
2245 assert_eq!(copied.as_deref(), Some(&pages[..]));
2246 assert_eq!(moved.as_deref(), Some(&pages[1..]));
2247}
2248
2249/// Two copies of the cross-container notebook, the second listed beside the first, for Move
2250/// or Copy to carry things between.
2251fn two_notebooks(name: &str) -> (Scratch, PathBuf, PathBuf) {
2252 let scratch = Scratch::new(name);
2253 let source =
2254 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate");
2255 let other = scratch.0.join("other");
2256 copy_notebook(&source, &other);
2257 let settings = serde_json::json!({
2258 "user_name": "Snowbound Test",
2259 "sidebar": true,
2260 "notebooks": [other],
2261 });
2262 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
2263 (scratch, source, other)
2264}
2265
2266fn palette(command: &'static str) -> [&'static str; 8] {
2267 [
2268 "modifiers command",
2269 "key p",
2270 "modifiers",
2271 "settle",
2272 command,
2273 "settle",
2274 "key Enter",
2275 "wait 400",
2276 ]
2277}
2278
2279/// Copy is reached by keyboard alone: the search, an arrow to the place, Tab to Copy.
2280#[test]
2281fn move_or_copy_copies_by_keyboard_alone() {
2282 let (scratch, source, other) = two_notebooks("move-or-copy-keys");
2283 let mut steps = Vec::from(palette("type >Move or Copy Section"));
2284 steps.extend(["type other", "key Down", "key Tab", "key Tab", "key Space"]);
2285 steps.extend(["wait 2000", "settle"]);
2286 replay(&scratch, Some(&source), &steps);
2287 assert!(other.join("Cross 2.one").exists());
2288 assert!(scratch.0.join("notebook/Cross.one").exists());
2289}
2290
2291/// A section whose notebook has no room for it in its recycle bin stays, shown again, beside
2292/// the copy that arrived.
2293#[test]
2294fn a_move_that_cannot_leave_shows_the_section_where_it_stayed() {
2295 let (scratch, source, other) = two_notebooks("move-or-copy-kept");
2296 std::fs::write(scratch.0.join("notebook/OneNote_RecycleBin"), b"").unwrap();
2297 let mut steps = Vec::from(palette("type >Move or Copy Section"));
2298 steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]);
2299 steps.push("accessibility kept");
2300 let [kept] = replay(&scratch, Some(&source), &steps).try_into().unwrap();
2301 assert!(other.join("Cross 2.one").exists());
2302 assert_eq!(
2303 stored_titles(&scratch.0.join("notebook/Cross.one")),
2304 stored_titles(&source.join("Cross.one"))
2305 );
2306 assert!(!page_tabs(&kept).is_empty(), "{kept}");
2307}
2308
2309/// Undo brings a page moved into another notebook back where it was.
2310#[test]
2311fn undo_brings_a_page_back_from_another_notebook() {
2312 let (scratch, source, _) = two_notebooks("move-or-copy-undo");
2313 // Another notebook than a copy of this one, whose pages share none of its identities.
2314 let other = scratch.0.join("synthetic");
2315 copy_notebook(
2316 &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/conflict-page/candidate"),
2317 &other,
2318 );
2319 let settings = serde_json::json!({
2320 "user_name": "Snowbound Test",
2321 "sidebar": true,
2322 "notebooks": [other],
2323 });
2324 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
2325 let (pages, theirs) = (
2326 stored_titles(&source.join("Cross.one")),
2327 stored_titles(&other.join("synthetic.one")),
2328 );
2329 let mut steps = Vec::from(palette("type >Move or Copy Page"));
2330 steps.extend([
2331 "type synthetic",
2332 "key Down",
2333 "key Enter",
2334 "wait 2000",
2335 "settle",
2336 ]);
2337 steps.push("accessibility moved");
2338 // Long enough for the other notebook's section to publish the page leaving it.
2339 steps.extend([
2340 "modifiers command",
2341 "key z",
2342 "modifiers",
2343 "wait 6000",
2344 "settle",
2345 ]);
2346 steps.push("accessibility back");
2347 let [moved, back] = replay(&scratch, Some(&source), &steps).try_into().unwrap();
2348 assert_eq!(page_tabs(&moved).len(), pages.len() - 1, "{moved}");
2349 assert_eq!(page_tabs(&back).len(), pages.len(), "{back}");
2350 let mut here = stored_titles(&scratch.0.join("notebook/Cross.one"));
2351 let mut expected = pages.clone();
2352 here.sort();
2353 expected.sort();
2354 assert_eq!(here, expected);
2355 assert_eq!(stored_titles(&other.join("synthetic.one")), theirs);
2356}
2357
2358/// The search corpus's notebook, with the cross-container one listed beside it as "other".
2359fn split_notebooks(name: &str) -> (Scratch, PathBuf, PathBuf) {
2360 let scratch = Scratch::new(name);
2361 let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook");
2362 let other = scratch.0.join("other");
2363 copy_notebook(
2364 &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"),
2365 &other,
2366 );
2367 let settings = serde_json::json!({
2368 "user_name": "Snowbound Test",
2369 "sidebar": true,
2370 "notebooks": [other],
2371 });
2372 std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap();
2373 (scratch, source, other)
2374}
2375
2376/// A section two panes show moves to another notebook: neither pane offers to make a section
2377/// meanwhile, and both show the notebook's next one after.
2378#[test]
2379fn a_section_two_panes_show_moves_and_both_show_the_next() {
2380 let (scratch, source, other) = split_notebooks("move-split-section");
2381 let mut steps = vec!["split right", "settle"];
2382 steps.extend(palette("type >Move or Copy Section"));
2383 steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]);
2384 steps.push("accessibility moved");
2385 let [moved] = replay(&scratch, Some(&source), &steps).try_into().unwrap();
2386 assert!(other.join("Garden.one").exists());
2387 assert!(!moved.contains("No sections in this notebook"), "{moved}");
2388 let groups = pane_groups(&moved);
2389 assert_eq!(groups.len(), 2, "{moved}");
2390 assert!(
2391 groups.iter().all(|group| group.contains(r#""Kitchen, "#)),
2392 "{moved}"
2393 );
2394}
2395
2396/// A page moved into a section another pane shows, from another notebook, is listed there, and
2397/// gone again after Undo.
2398#[test]
2399fn a_page_moved_into_a_parked_pane_shows_there_and_leaves_on_undo() {
2400 let (scratch, source, _) = split_notebooks("move-split-page");
2401 let focus = |x: &'static str| [x, "press", "release", "settle"];
2402 let mut steps = vec!["split right", "settle"];
2403 // The other notebook's Cross in the right pane, then the focus back on Garden at the left.
2404 steps.extend(focus("move 63 100"));
2405 steps.extend(focus("move 350 650"));
2406 steps.extend(palette("type >Move or Copy Page"));
2407 steps.extend(["type Cross", "key Down", "key Enter", "wait 3000", "settle"]);
2408 steps.extend(focus("move 850 650"));
2409 steps.push("accessibility arrived");
2410 steps.extend(focus("move 350 650"));
2411 steps.extend([
2412 "modifiers command",
2413 "key z",
2414 "modifiers",
2415 "wait 3000",
2416 "settle",
2417 ]);
2418 steps.extend(focus("move 850 650"));
2419 steps.push("accessibility back");
2420 let [arrived, back] = replay(&scratch, Some(&source), &steps).try_into().unwrap();
2421 let moved = "Spring planting plan";
2422 let tabs = |tree: &str| -> Vec<String> {
2423 (page_tabs(tree).into_iter())
2424 .map(|tab| tab.trim_start_matches('*').to_owned())
2425 .collect()
2426 };
2427 assert!(tabs(&arrived).iter().any(|tab| tab == moved), "{arrived}");
2428 assert!(!tabs(&back).iter().any(|tab| tab == moved), "{back}");
2429}
crates/ui/src/lib.rs+2-2
...@@ -16,8 +16,8 @@ pub use list::{List, Row, Rows, list};...@@ -16,8 +16,8 @@ pub use list::{List, Row, Rows, list};
16pub use theme::{Menu, PopupMotion, Section, Shades, Shadow, Theme};16pub use theme::{Menu, PopupMotion, Section, Shades, Shadow, Theme};
17pub use widgets::{17pub use widgets::{
18 PaintedScroller, Scroller, ScrollerPart, Scrollers, Segments, badge, badge_width, button,18 PaintedScroller, Scroller, ScrollerPart, Scrollers, Segments, badge, badge_width, button,
19 check_box, dialog_buttons, edit_key, edit_modifiers, password_field, scrollbar, segmented,19 check_box, dialog_buttons, dialog_buttons_with, edit_key, edit_modifiers, password_field,
20 text_field,20 scrollbar, segmented, text_field,
21};21};
2222
23use draw::{23use draw::{
crates/ui/src/widgets.rs+15-1
...@@ -37,6 +37,19 @@ pub fn button(ui: &mut Ui, part: impl Hash, text: &str) -> Signal {...@@ -37,6 +37,19 @@ pub fn button(ui: &mut Ui, part: impl Hash, text: &str) -> Signal {
37/// own dialogs place them. The default wears the accent around it. Whether each was clicked,37/// own dialogs place them. The default wears the accent around it. Whether each was clicked,
38/// Cancel first.38/// Cancel first.
39pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {39pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {
40 let [cancel, chosen, _] = dialog_buttons_with(ui, text, enabled, |_| false);
41 [cancel, chosen]
42}
43
44/// `dialog_buttons` with another button, which `other` builds and says was clicked: after the
45/// default on Windows, before Cancel elsewhere. Whether each was clicked, Cancel, the default,
46/// then the other.
47pub fn dialog_buttons_with(
48 ui: &mut Ui,
49 text: &str,
50 enabled: bool,
51 other: impl FnOnce(&mut Ui) -> bool,
52) -> [bool; 3] {
40 let default = |ui: &mut Ui| {53 let default = |ui: &mut Ui| {
41 let theme = &ui.theme;54 let theme = &ui.theme;
42 let spec = Spec {55 let spec = Spec {
...@@ -65,11 +78,12 @@ pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {...@@ -65,11 +78,12 @@ pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {
65 };78 };
66 let windows = edit::Platform::CURRENT == edit::Platform::Windows;79 let windows = edit::Platform::CURRENT == edit::Platform::Windows;
67 let mut chosen = windows && default(ui);80 let mut chosen = windows && default(ui);
81 let other = other(ui);
68 let cancel = button(ui, "cancel", "Cancel").clicked;82 let cancel = button(ui, "cancel", "Cancel").clicked;
69 if !windows {83 if !windows {
70 chosen = default(ui);84 chosen = default(ui);
71 }85 }
72 [cancel, chosen]86 [cancel, chosen, other]
73}87}
7488
75/// A short tag in the accent's colour, centred in a box `height` tall, as BETA marks a89/// A short tag in the accent's colour, centred in a box `height` tall, as BETA marks a