From 9ec5dfb963ad9d44a22beefd26d7382f9a45acc2 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 19 Oct 2026 11:52:00 -0700 Subject: [PATCH] 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 --- arc/sync.md | 4 + crates/snowbound/src/commands.rs | 17 +- crates/snowbound/src/main.rs | 52 ++- crates/snowbound/src/manage.rs | 67 ++- crates/snowbound/src/menubar.rs | 1 + crates/snowbound/src/menus.rs | 46 +- crates/snowbound/src/move_copy.rs | 673 ++++++++++++++++++++++++++++++ crates/snowbound/src/sidebar.rs | 3 + crates/snowbound/src/undo.rs | 163 ++++++-- crates/snowbound/tests/replay.rs | 256 ++++++++++++ crates/ui/src/lib.rs | 4 +- crates/ui/src/widgets.rs | 16 +- 12 files changed, 1219 insertions(+), 83 deletions(-) create mode 100644 crates/snowbound/src/move_copy.rs diff --git a/arc/sync.md b/arc/sync.md index 690824b4e8c1b5ecca9d93de10b69e104d3ad9ad..3b61adcbac690ff5b96a0b4a9c9420db60e1baec 100644 --- a/arc/sync.md +++ b/arc/sync.md @@ -347,6 +347,10 @@ pages to `OneNote_RecycleBin`, as OneNote does, and opening a notebook empties what the bin has held unchanged for 60 days, as OneNote prunes it: judged by the content's last change, the pages in one revision, binned section files deleted with their TOC entries left (`corpus/recycle-purge`). +Move or Copy puts a section in another notebook as OneNote 2010 does, written anew under new +identities, taking the edits its replica still queues. Where OneNote deletes the original, a +move sends it to the recycle bin, and only once the copy reads back whole and the original is +as it was copied; otherwise the section stays in both notebooks and the move says so. What only Snowbound reads lives in the notebook's `.snowbound` folder, which carries the Windows hidden attribute so that OneNote never makes a section group of it. Its files are diff --git a/crates/snowbound/src/commands.rs b/crates/snowbound/src/commands.rs index 3484d2f6ecdc54e4cf7403f3d0bc39a9ef2c3030..a8d7fdd20bd0ae15e8537cdb46593073cdbc7654 100644 --- a/crates/snowbound/src/commands.rs +++ b/crates/snowbound/src/commands.rs @@ -30,6 +30,8 @@ pub enum Id { NewSubpage, PageVersions, CopyPageLink, + /// Move or Copy on the page shown. + MoveOrCopyPage, /// Password Protection on the section shown. PasswordProtect, /// Locks every password-protected section unlocked. @@ -278,6 +280,13 @@ pub const COMMANDS: &[Command] = &[ ), row!(Id::PageVersions, "Page Versions", NONE, NONE), row!(Id::CopyPageLink, "Copy Link to Page", NONE, NONE), + // OneNote 2010's Ctrl+Alt+M; macOS keeps Option-Command-M for Minimize All. + row!( + Id::MoveOrCopyPage, + "Move or Copy Page", + NONE, + &[cmd('m').option()] + ), row!( Id::PasswordProtect, "Password Protect This Section", @@ -1255,8 +1264,8 @@ impl State { .notebook() .is_some_and(|library| library.catalog().is_some()), ), - // The recycle bin takes no new pages. - Id::NewPage | Id::NewSubpage => { + // The recycle bin takes no new pages, and moves its own by Restore To. + Id::NewPage | Id::NewSubpage | Id::MoveOrCopyPage => { enabled(!modal && session.is_some() && !self.in_recycle_bin()) } Id::CopyPageLink | Id::Find | Id::Search | Id::ExportPdf | Id::Print => { @@ -1555,6 +1564,10 @@ impl State { show: self.pane.showing.shown_history != Some(self.pane.showing.space), } } + Id::MoveOrCopyPage => { + self.move_or_copy_page(self.pane.showing.space); + return Ok(()); + } Id::CopyPageLink => { self.session.as_ref().ok_or("No notebook is open")?; let space = self.pane.showing.space; diff --git a/crates/snowbound/src/main.rs b/crates/snowbound/src/main.rs index e4a03436b64f9ebfbb12b0ef6b5a19493332e832..c6e08f93776fadc3161769708fb56a262f2ed56d 100644 --- a/crates/snowbound/src/main.rs +++ b/crates/snowbound/src/main.rs @@ -45,6 +45,7 @@ mod meeting; #[cfg(target_os = "macos")] mod menubar; mod menus; +mod move_copy; mod navigation; mod options; mod palette; @@ -848,9 +849,16 @@ enum Command { Recycle(recycle::Request), /// Moves or indents pages of the open section. Pages(Vec), - /// Moves a page of the open section to the end of another section of its folder. + /// Moves a page of the open section to the end of another section. MovePage { space: ExGuid, + library: Arc, + path: String, + }, + /// Copies a page of the open section to the end of another section. + CopyPage { + space: ExGuid, + library: Arc, path: String, }, /// Gives the open page a template's background. @@ -982,6 +990,10 @@ struct State { updates: update::Updates, /// The Link dialog's fields while it is open. link: Option, + /// Move or Copy while it is open. + move_copy: Option, + /// Sections on their way to another place, by notebook location and catalog path. + moving: Vec<(String, String)>, properties: Option, symbols: Option, /// Save As while it is open. @@ -1473,6 +1485,8 @@ impl State { actions: None, after_open: None, link: None, + move_copy: None, + moving: Vec::new(), properties: None, symbols: None, save_as: None, @@ -1741,6 +1755,8 @@ impl State { self.own_dialog(); self.customize_tags(); self.palette(); + // After the palette, which opens it, so that its field is there to take the focus. + self.move_copy_dialog(); self.sync_popup()?; self.text_menu()?; platform::resize_grip(&mut self.ui, &self.window, size); @@ -3856,10 +3872,19 @@ impl State { } Command::Recycle(request) => self.recycle(request)?, Command::Pages(edits) => self.edit_pages(edits)?, - Command::MovePage { space, path } => { - self.move_page(space, path)?; + Command::MovePage { + space, + library, + path, + } => { + self.move_page(space, &library, &path)?; self.edited(Vec::new()); } + Command::CopyPage { + space, + library, + path, + } => self.copy_page(space, library, path)?, Command::Template(name) => self.apply_template(name)?, Command::Page(Request::EditDate(field)) => self.edit_date(field), Command::Page(Request::Copy(clip)) => self.clipboard.set(clip)?, @@ -3888,8 +3913,10 @@ impl State { path: String, page: Option, ) -> Result<(), Box> { - // Its files are on their way to the renamed folder. - if self.folder_renaming(&library.location) { + // Its files are on their way to the renamed folder, or another notebook. + if self.folder_renaming(&library.location) + || (self.moving.iter()).any(|(at, moving)| *at == library.location && *moving == path) + { return Ok(()); } if library.locked(&path) { @@ -6353,6 +6380,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> { Cmd::NewSubpage => art::NEW_SUBPAGE, Cmd::PageVersions => art::PAGE_VERSIONS, Cmd::CopyPageLink => art::COPY_LINK, + Cmd::MoveOrCopyPage => art::MOVE, Cmd::PasswordProtect => art::PASSWORD, Cmd::LockAll => art::LOCK, Cmd::ShowNotebook => art::FOLDER, @@ -6873,7 +6901,7 @@ impl State { && (self.initial.iter()) .map(|(id, document)| (id, document)) .eq((editor.outlines().iter()).map(|outline| (&outline.id, outline.document()))); - if self.session.is_some() || unchanged { + if self.session.is_some() || self.pane.sectionless.is_some() || unchanged { let _ = self.proxy.send_event(UserEvent::Exit); return; } @@ -6896,6 +6924,18 @@ impl App { let Some(state) = &self.state else { return event_loop.exit(); }; + if !state.moving.is_empty() { + return crate::confirm( + "Quit while a section is moving?", + "Quitting now can leave it in both notebooks, though nothing in it is lost.", + "Keep Snowbound Open", + "Quit Anyway", + state.reply(|state, ()| { + state.quit(); + Ok(()) + }), + ); + } let changes = match notebook::unwritten() { 0 => return state.quit(), 1 => "1 unsaved change".to_owned(), diff --git a/crates/snowbound/src/manage.rs b/crates/snowbound/src/manage.rs index 62ada96c50e7ea4b91f3236e6fef64b1fe658e09..c9ccfc459c9e2dc726bbbc44ed4b7edbb00a38bf 100644 --- a/crates/snowbound/src/manage.rs +++ b/crates/snowbound/src/manage.rs @@ -1125,21 +1125,72 @@ impl State { }) } - /// Moves page `space` of the open section to the end of the section at catalog `path`, - /// as OneNote moves a page dropped on a section's tab: the page keeps its identity, - /// title, date and content there and leaves this section. - pub(crate) fn move_page(&mut self, space: ExGuid, path: String) -> Result<(), Box> { - let session = self.session.as_ref().ok_or("No section is open")?; - let target = session - .library - .section_identity(&path) + /// Moves page `space` of the open section to the end of the section at catalog `path` of + /// `library`, as OneNote moves a page dropped on a section's tab: the page keeps its + /// identity, title, date and content there and leaves this section. + pub(crate) fn move_page( + &mut self, + space: ExGuid, + library: &Library, + path: &str, + ) -> Result<(), Box> { + let target = library + .section_identity(path) .ok_or("That section is not in the notebook")?; self.change_pages(Change::Send { page: space, + notebook: library.location.clone(), target, }) } + /// Copies page `space` of the open section to the end of the section at catalog `path` of + /// `library`, under new identities, as OneNote's Move or Copy copies a page. + pub(crate) fn copy_page( + &mut self, + space: ExGuid, + library: Arc, + path: String, + ) -> Result<(), Box> { + self.persist()?; + let session = self.session.as_ref().ok_or("No section is open")?; + let op = notebook::session::copied(&session.section.page(space)?, &self.author)?; + // A section a pane shows is open already, and opens nowhere else meanwhile. + let open = (self.sessions()) + .find(|open| { + open.library.location == library.location && open.tabs[open.tab].path == path + }) + .map(|open| Arc::clone(open.section.replica())); + let (author, proxy) = (self.author.clone(), self.proxy.clone()); + let (key, space) = (library.key(&path), crate::undo::imported(&op)); + crate::spawn_async(move || async move { + let copied = async { + let edit = onestore::op::Edit { + at: crate::filetime(), + ops: vec![op], + }; + if let Some(replica) = open { + replica.apply_async(&author, edit).await?; + return Ok(()); + } + let section = library.open_async(&path, || {}).await?; + let copied = section.replica().apply_async(&author, edit).await; + crate::undo::release(&library, &path, section).await; + copied?; + Ok::<_, Box>(()) + }; + let copied = copied.await.map_err(|error| crate::plain(&*error, "page")); + let _ = proxy.send_event(crate::UserEvent::Then(Box::new(move |state| { + match copied { + Ok(()) => state.edited_sections(&key, vec![space], |touched| touched == key), + Err(error) => platform::alert("Couldn't copy the page", &error), + } + Ok(()) + }))); + }); + Ok(()) + } + /// Moves or indents pages of the open section, in order. pub(crate) fn edit_pages(&mut self, edits: Vec) -> Result<(), Box> { self.persist()?; diff --git a/crates/snowbound/src/menubar.rs b/crates/snowbound/src/menubar.rs index b432d4204a02591d5c487917b692febd48b92bb9..7d856842e55537e6a539abf77644b03cd401a577 100644 --- a/crates/snowbound/src/menubar.rs +++ b/crates/snowbound/src/menubar.rs @@ -66,6 +66,7 @@ const MENUS: &[Item] = &[ S, C(Id::PageVersions), C(Id::CopyPageLink), + C(Id::MoveOrCopyPage), C(Id::ShowNotebook), C(Id::LiveShare), S, diff --git a/crates/snowbound/src/menus.rs b/crates/snowbound/src/menus.rs index 8a53b18495d85ca4801c5da94991dd6d4d7f748f..4a9bcccaee517b70168942dce17390c4e98cc1d4 100644 --- a/crates/snowbound/src/menus.rs +++ b/crates/snowbound/src/menus.rs @@ -111,6 +111,8 @@ pub enum Action { Move, /// Moves it to a section, or into a folder, by catalog path. MoveTo(String), + /// Opens Move or Copy on a page or section. + MoveOrCopy, /// Opens the submenu of the sections `CopyTo` copies a page of the recycle bin to. Copy, CopyTo(String), @@ -158,7 +160,7 @@ impl Action { Action::Open => art::OPEN, Action::Rename => art::RENAME, Action::Delete => art::DELETE, - Action::Move => art::MOVE, + Action::Move | Action::MoveOrCopy => art::MOVE, Action::Copy => art::COPY, Action::SaveAs => art::SAVE, Action::RecycleBin => art::RECYCLE_BIN, @@ -219,7 +221,9 @@ pub(crate) const SECTION_COLORS: [(u32, &str); 16] = [ pub(crate) fn covered(target: &Target, action: &Action) -> bool { use Action::*; match target { - Target::Page { .. } => matches!(action, CopyLink | NewPage | NewSubpage | Theme), + Target::Page { .. } => { + matches!(action, CopyLink | NewPage | NewSubpage | Theme | MoveOrCopy) + } Target::Section { .. } => matches!( action, SaveAs | NewSection | NewGroup | Password | Theme | EmptyRecycleBin @@ -259,6 +263,7 @@ pub(crate) fn command_title(target: &Target, action: &Action, label: &str) -> St } match label.split_once(' ') { _ if *action == Action::Properties => format!("{noun} {label}"), + _ if *action == Action::MoveOrCopy => format!("{label} {noun}"), Some((verb, rest)) => format!("{verb} {noun} {rest}"), None => format!("{label} {noun}"), } @@ -465,7 +470,7 @@ impl State { let mut actions = vec![ item(Action::Rename, "Rename", false, false), item(Action::Delete, "Delete", false, false), - item(Action::Move, "Move to Section", nowhere(), false), + item(Action::MoveOrCopy, "Move or Copy", false, false), item(Action::CopyLink, "Copy Link to Page", false, true), item( Action::MarkRead, @@ -528,7 +533,10 @@ impl State { } actions.extend([ item(Action::Delete, "Delete", false, false), - item(Action::Move, "Move", nowhere(), false), + match section { + true => item(Action::MoveOrCopy, "Move or Copy", false, false), + false => item(Action::Move, "Move", nowhere(), false), + }, ]); if section { let link = self.section_link(library, path).is_none(); @@ -762,8 +770,8 @@ impl State { } } - /// Where Move takes `target`: the other sections of a page's folder, or the folders a - /// section or group may move into. + /// Where Move takes `target`: the sections a page of the recycle bin goes back to, or the + /// folders a section or group may move into. fn destinations(&self, target: &Target) -> Vec { let theme = &self.ui.theme; match target { @@ -778,15 +786,6 @@ impl State { }) .collect() } - Target::Page { library, path, .. } => (library.tabs(&folder(path)).into_iter()) - .filter(|tab| tab.path != *path) - .map(|tab| Destination { - tint: Some(theme.section(crate::section_color(tab.color)).accent), - name: tab.name, - path: tab.path, - icon: crate::art::SECTION, - }) - .collect(), Target::Section { library, path } | Target::Group { library, path } => { let within = format!("{path}/"); let home = folder(path); @@ -937,6 +936,10 @@ impl State { ); None } + (Target::Section { library, path }, Action::MoveOrCopy) => { + self.open_move_copy(crate::move_copy::Moving::Section { library, path }); + None + } ( Target::Section { library, path } | Target::Group { library, path }, Action::MoveTo(folder), @@ -1080,7 +1083,10 @@ impl State { path, copy: true, })), - Action::MoveTo(path) => Some(Command::MovePage { space, path }), + Action::MoveOrCopy => { + self.move_or_copy_page(space); + None + } Action::CopyLink => { let copied = self .page_link(space, None) @@ -1231,8 +1237,12 @@ impl State { } let slot = drag.slot.take(); if let Some(tab) = target { - let path = session.tabs[tab].path.clone(); - self.commands.push(Command::MovePage { space, path }); + let (library, path) = (Arc::clone(&session.library), session.tabs[tab].path.clone()); + self.commands.push(Command::MovePage { + space, + library, + path, + }); return; } let Some(slot) = slot.filter(|slot| *slot != from) else { diff --git a/crates/snowbound/src/move_copy.rs b/crates/snowbound/src/move_copy.rs new file mode 100644 index 0000000000000000000000000000000000000000..5d39c9a447ea59097f53cae273d8d75578093c49 --- /dev/null +++ b/crates/snowbound/src/move_copy.rs @@ -0,0 +1,673 @@ +//! OneNote 2010's Move or Copy: a section into a notebook or section group, or after a +//! section, of any open notebook, and a page to the end of any of their sections. + +use crate::{Command, Library, State, UserEvent, art, library, manage::Structure, menus, platform}; +use accesskit::Role; +use notebook::discover::Folder; +use onestore::ExGuid; +use std::{ + error::Error, + hash::{DefaultHasher, Hash, Hasher}, + sync::Arc, +}; +use ui::{Anchor, Axis, Flags, Id, Spec, Ui, children, fill, fit, px}; +use winit::keyboard::NamedKey; + +const WIDTH: f32 = 420.0; +/// Places the list shows at once. +const ROWS: usize = 12; +const INDENT: f32 = 16.0; + +/// What Move or Copy moves. +pub enum Moving { + Section { + library: Arc, + path: String, + }, + /// A page of the open section, at catalog `path`. + Page { + library: Arc, + path: String, + space: ExGuid, + }, +} + +/// The dialog while it is open. +pub struct Dialog { + moving: Moving, + search: String, + selected: Option, +} + +/// A place the dialog lists: a notebook or group to go into, last, or a section to go after, +/// or for a page, to go to the end of. +struct Place { + library: Arc, + folder: String, + section: Option, + name: String, + depth: usize, + icon: &'static [&'static str], + tint: Option<[f32; 4]>, + /// Whether what moves can go there. + open: bool, +} + +impl Place { + fn key(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + (&self.library.location, &self.folder, &self.section).hash(&mut hasher); + hasher.finish() + } +} + +struct Places(Vec); + +impl ui::Rows for Places { + fn count(&self) -> usize { + self.0.len() + } + + fn key(&self, index: usize) -> u64 { + self.0[index].key() + } + + fn find(&self, key: u64) -> Option { + self.0.iter().position(|place| place.key() == key) + } + + fn selectable(&self, index: usize) -> bool { + self.0[index].open + } +} + +fn id() -> Id { + Id::ROOT.child("move-or-copy") +} + +fn search_field() -> Id { + id().child("search") +} + +fn list() -> Id { + id().child("places") +} + +/// The sections and groups of `folder` of `library`, groups after, each group's own after it. +fn walk( + places: &mut Vec, + theme: &ui::Theme, + library: &Arc, + folder: &Folder, + depth: usize, + moving: &Moving, +) { + let (from, path, page) = match moving { + Moving::Section { library, path } => (library, path, false), + Moving::Page { library, path, .. } => (library, path, true), + }; + for tab in library.tabs(&folder.path) { + // A page goes nowhere locked, nor to its own section. + let mine = library.location == from.location && tab.path == *path; + places.push(Place { + library: Arc::clone(library), + folder: folder.path.clone(), + open: !mine && !(page && library.locked(&tab.path)), + section: Some(tab.path), + name: tab.name, + depth, + icon: art::SECTION, + tint: Some(theme.section(crate::section_color(tab.color)).accent), + }); + } + for group in (folder.groups.iter()).filter(|group| !library::recycle_bin(&group.path)) { + // A group goes nowhere inside itself. + let within = library.location == from.location + && (group.path == *path || group.path.starts_with(&format!("{path}/"))); + places.push(Place { + library: Arc::clone(library), + folder: group.path.clone(), + section: None, + name: library::entry_name(&group.path).to_owned(), + depth, + icon: art::SECTION_GROUP, + tint: None, + open: !page && !within, + }); + walk(places, theme, library, group, depth + 1, moving); + } +} + +impl State { + /// Opens Move or Copy on page `space` of the open section. + pub(crate) fn move_or_copy_page(&mut self, space: ExGuid) { + if let Some(session) = &self.session { + self.open_move_copy(Moving::Page { + library: Arc::clone(&session.library), + path: session.tabs[session.tab].path.clone(), + space, + }); + } + } + + /// Opens Move or Copy on what `moving` names. + pub(crate) fn open_move_copy(&mut self, moving: Moving) { + self.move_copy = Some(Dialog { + moving, + search: String::new(), + selected: None, + }); + self.ui.open_popup(id()); + self.ui.set_focus(Some(search_field())); + } + + /// The places of the open notebooks whose names hold `search`, in the sidebar's order. + fn places(&self, moving: &Moving, search: &str) -> Places { + let theme = &self.ui.theme; + let mut places = Vec::new(); + for library in &self.notebooks { + let Some(catalog) = library.catalog() else { + continue; + }; + places.push(Place { + library: Arc::clone(library), + folder: String::new(), + section: None, + name: library.name.clone(), + depth: 0, + icon: art::NOTEBOOK, + tint: Some(crate::notebook_color(theme, library.color())), + open: matches!(moving, Moving::Section { .. }), + }); + walk(&mut places, theme, library, catalog, 1, moving); + } + // A match keeps the notebook and groups above it, which tell like-named places apart. + let search = search.trim().to_lowercase(); + let mut kept = vec![false; places.len()]; + let mut above: Vec = Vec::new(); + for (at, place) in places.iter().enumerate() { + above.truncate(place.depth); + above.push(at); + if place.name.to_lowercase().contains(&search) { + above.iter().for_each(|at| kept[*at] = true); + } + } + let mut kept = kept.into_iter(); + places.retain(|_| kept.next() == Some(true)); + Places(places) + } + + /// Builds Move or Copy while it is open. Move, or Enter, moves to the place selected; + /// Copy copies there. + pub(crate) fn move_copy_dialog(&mut self) { + let Some(dialog) = &self.move_copy else { + return; + }; + if !self.ui.popup_open(id()) { + self.move_copy = None; + return; + } + let places = self.places(&dialog.moving, &dialog.search); + let (title, label) = match &dialog.moving { + Moving::Section { path, .. } => ( + "Move or Copy Section", + format!( + "Move or copy section \u{201c}{}\u{201d} into a notebook or after a section:", + library::entry_name(path).trim_end_matches(".one") + ), + ), + Moving::Page { .. } => ("Move or Copy Pages", "Move or copy page to:".to_owned()), + }; + let dialog = self.move_copy.as_mut().unwrap(); + let ui = &mut self.ui; + let theme = ui.theme.clone(); + let row = theme.font_size * 2.0; + let keys = ui::popup::navigation( + ui, + &[search_field()], + &[ + NamedKey::ArrowUp, + NamedKey::ArrowDown, + NamedKey::PageUp, + NamedKey::PageDown, + NamedKey::Enter, + ], + ); + ui.open_as( + id(), + Spec { + axis: Axis::Y, + size: [px(WIDTH), children()], + fill: Some(theme.popup), + border: Some(theme.chip), + shadow: Some(theme.shadow), + radius: 8.0, + pad: [16.0, 12.0], + gap: 4.0, + anchor: Some(Anchor::Dialog), + role: Some(Role::Dialog), + ..Spec::default() + }, + ); + if let Some(node) = ui.access(id()) { + node.set_label(title); + } + ui.leaf( + "title", + Spec { + size: [fill(), px(row)], + text: Some(title), + bold: true, + role: Some(Role::Heading), + ..Spec::default() + }, + ); + ui.leaf( + "label", + Spec { + size: [fill(), px(row * 0.8)], + text: Some(&label), + ..Spec::default() + }, + ); + ui::text_field( + ui, + search_field(), + &mut dialog.search, + "Search by text in title", + Spec { + size: [fill(), px(row)], + fill: Some(theme.base), + border: Some(theme.accent), + radius: 4.0, + pad: [6.0, 0.0], + ..Spec::default() + }, + ); + if let Some(node) = ui.access(search_field()) { + node.set_label("Search by text in title"); + } + ui::list( + ui, + list(), + Spec { + size: [fill(), px(row * ROWS as f32)], + fill: Some(theme.base), + border: Some(theme.chip), + radius: 4.0, + role: Some(Role::Tree), + ..Spec::default() + }, + ui::List { + rows: &places, + row, + keys: &keys, + hover_selects: false, + }, + &mut dialog.selected, + |ui, row| { + let place = &places.0[row.index]; + if let Some(node) = ui.access(list().child(row.key)) { + node.set_role(Role::TreeItem); + node.set_label(place.name.as_str()); + node.set_level(place.depth + 1); + node.set_selected(row.selected); + if !place.open { + node.set_disabled(); + } + } + place_row(ui, &theme, place, row.selected); + }, + ); + if let Some(node) = ui.access(list()) { + node.set_label("All Notebooks"); + } + if let Some(key) = dialog.selected + && let Some(node) = ui.access(search_field()) + { + node.set_active_descendant(list().child(key).node()); + } + let chosen = (dialog.selected) + .and_then(|key| ui::Rows::find(&places, key)) + .filter(|at| places.0[*at].open); + crate::buttons(ui); + let [cancel, moved, copy] = ui::dialog_buttons_with(ui, "Move", chosen.is_some(), |ui| { + action(ui, "copy", "Copy", chosen.is_some()) + }); + let moved = moved || keys.contains(&NamedKey::Enter); + ui.close(); + ui.close(); + let Some(at) = chosen.filter(|_| moved || copy) else { + if cancel { + self.ui.close_popup(id()); + } + return; + }; + self.ui.close_popup(id()); + let Some(dialog) = self.move_copy.take() else { + return; + }; + let place = places.0.into_iter().nth(at).unwrap(); + let noun = match dialog.moving { + Moving::Section { .. } => "section", + Moving::Page { .. } => "page", + }; + if let Err(error) = self.carry(dialog.moving, place, copy) { + let verb = if copy { "copy" } else { "move" }; + platform::alert( + &format!("Couldn't {verb} the {noun}"), + &crate::plain(&*error, noun), + ); + } + } + + /// Moves, or with `copy` copies, what `moving` names to `place`. + fn carry(&mut self, moving: Moving, place: Place, copy: bool) -> Result<(), Box> { + match moving { + Moving::Page { space, .. } => { + let path = place.section.ok_or("Choose a section")?; + self.commands.push(if copy { + Command::CopyPage { + space, + library: place.library, + path, + } + } else { + Command::MovePage { + space, + library: place.library, + path, + } + }); + } + Moving::Section { library, path } + if !copy && library.location == place.library.location => + { + let change = within(&library, path, &place.folder, place.section.as_deref()); + self.commands.push(Command::Structure(library, change)); + } + Moving::Section { library, path } => self.carry_section( + library, + path, + place.library, + place.folder, + place.section, + copy, + )?, + } + Ok(()) + } + + /// Moves, or with `copy` copies, section `path` of `from` into `folder` of `to`, after + /// its section `after` or last, on a thread of its own, then lists both notebooks again. + /// A section moving opens nowhere until it has gone, and one shown leaves the window for + /// the notebook's first, or comes back where it stayed. + fn carry_section( + &mut self, + from: Arc, + path: String, + to: Arc, + folder: String, + after: Option, + copy: bool, + ) -> Result<(), Box> { + self.persist()?; + let moving = (!copy).then(|| (from.location.clone(), path.clone())); + self.moving.extend(moving.clone()); + let mine = |session: &crate::Session| { + session.library.location == from.location && session.tabs[session.tab].path == path + }; + let shown = self.session.as_ref().is_some_and(mine); + let (mut section, mut replica, mut panes) = (None, None, Vec::new()); + if copy { + replica = (self.sessions().find(|session| mine(session))) + .map(|session| Arc::clone(session.section.replica())); + } else { + // Parked panes let it go, the focused one hands it over; each shows it again where + // it stayed, or the notebook's first section. + let key = Some(from.key(&path)); + panes = (self.parked.iter()) + .filter(|parked| parked.section == key) + .map(|parked| parked.pane.id) + .collect(); + self.leave_sections(mine, |_, pane| pane.sectionless = Some(Arc::clone(&from))); + if shown { + section = self.session.take().map(|session| session.section); + self.pane.sectionless = Some(Arc::clone(&from)); + self.title(); + } + } + let proxy = self.proxy.clone(); + crate::spawn_async(move || async move { + let carried = async { + // Both notebooks' in one order, whichever way a section goes. + let [first, second] = match from.location < to.location { + true => [&from, &to], + false => [&to, &from], + }; + let _changing = first.structure.lock().await; + let _arriving = match from.location == to.location { + true => None, + false => Some(second.structure.lock().await), + }; + let mut source = from.reopen()?; + let mut target = to.reopen()?; + let after = after.as_deref(); + let kept = if copy { + let opened = match replica { + Some(_) => None, + None => Some(from.open_async(&path, || {}).await?), + }; + let replica = + replica.unwrap_or_else(|| Arc::clone(opened.as_ref().unwrap().replica())); + let copied = source.copy_section(&path, &replica, &mut target, &folder, after); + if let Some(opened) = opened { + crate::undo::release(&from, &path, opened).await; + } + copied.map(|_| None)? + } else { + let section = match section { + Some(section) => section, + None => from.open_async(&path, || {}).await?, + }; + source + .move_section(&path, section, &mut target, &folder, after)? + .kept + }; + if from.location == to.location { + source = to.reopen()?; + } + let from = Arc::new(from.with(source)); + let to = match from.location == to.location { + true => Arc::clone(&from), + false => Arc::new(to.with(target)), + }; + Ok::<_, Box>((from, to, kept)) + }; + let carried = carried + .await + .map_err(|error| crate::plain(&*error, "section")); + let _ = proxy.send_event(UserEvent::Then(Box::new(move |state| { + state + .moving + .retain(|listed| Some(listed) != moving.as_ref()); + // What the panes that showed a section moving show after: it, where it stayed, + // or else the notebook's first section. + let (from, shows) = match carried { + Ok((from, to, kept)) => { + state.relisted(to)?; + state.relisted(Arc::clone(&from))?; + if let Some(kept) = &kept { + platform::alert( + "Section kept in both notebooks", + &crate::plain(kept, "section"), + ); + } + let shows = match kept { + Some(_) => Some(path), + None => from.first_section(), + }; + (from, shows) + } + Err(error) => { + let verb = if copy { "copy" } else { "move" }; + platform::alert(&format!("Couldn't {verb} the section"), &error); + (from, Some(path)) + } + }; + // Parked panes wait their turn to open it, after the focused one. + for parked in + (state.parked.iter_mut()).filter(|parked| panes.contains(&parked.pane.id)) + { + if let Some(shows) = &shows { + parked.pane.sectionless = None; + let place = crate::navigation::Place { + notebook: from.location.clone(), + section: shows.clone(), + page: ExGuid::default(), + }; + state.reopening.push((parked.pane.id, place)); + } + } + match shows { + Some(shows) if shown && !copy => { + state.commands.push(Command::OpenSection(from, shows)); + } + None if shown && !copy => state.adopt(from, None)?, + _ => {} + } + Ok(()) + }))); + }); + Ok(()) + } +} + +impl State { + /// Lists `library`, read again, in place of the notebook at its location, following the + /// section shown there. + fn relisted(&mut self, library: Arc) -> Result<(), Box> { + if !(self.notebooks.iter()).any(|open| open.location == library.location) { + return Ok(()); + } + let shown = (self.session.as_ref()) + .filter(|session| session.library.location == library.location) + .and_then(|session| { + session + .library + .section_identity(&session.tabs[session.tab].path) + }) + .and_then(|identity| { + (library.catalog()?.sections()) + .find(|section| section.file_id == identity) + .map(|section| section.path.clone()) + }) + // Never into the recycle bin, where a section that moved has gone. + .filter(|path| !crate::recycle::binned(path)); + if (self.pane.sectionless.as_ref()).is_some_and(|shown| shown.location == library.location) + { + self.pane.sectionless = Some(Arc::clone(&library)); + } + match shown { + Some(path) => self.adopt(library, Some(&path)), + None => { + self.list(&library); + Ok(()) + } + } + } +} + +/// The structure change moving section `path` of `library` within it, into `folder` after +/// its section `after`, or last. +fn within(library: &Library, path: String, folder: &str, after: Option<&str>) -> Structure { + let name = library::entry_name(&path).to_owned(); + let arrived = match folder { + "" => name, + folder => format!("{folder}/{name}"), + }; + let mut paths: Vec = (library.tabs(folder).into_iter()) + .map(|tab| tab.path) + .filter(|listed| *listed != path) + .collect(); + let at = after.and_then(|after| paths.iter().position(|listed| listed == after)); + paths.insert(at.map_or(paths.len(), |at| at + 1), arrived); + match (menus::folder(&path) == folder, after) { + (true, _) => Structure::Reorder { + folder: folder.to_owned(), + paths, + }, + (false, None) => Structure::Move { + path, + folder: folder.to_owned(), + }, + (false, Some(_)) => Structure::Return { + path, + folder: folder.to_owned(), + paths, + }, + } +} + +/// A row of the list: `place`, indented by its depth, with its icon. +fn place_row(ui: &mut Ui, theme: &ui::Theme, place: &Place, selected: bool) { + let row = theme.font_size * 2.0; + ui.open( + "place", + Spec { + size: [fill(), fill()], + fill: selected.then(|| theme.hover()), + hover_fill: place.open.then(|| theme.hover()), + radius: 4.0, + pad: [4.0 + place.depth as f32 * INDENT, 0.0], + gap: 6.0, + ..Spec::default() + }, + ); + ui.leaf( + "icon", + Spec { + size: [px(16.0), px(row)], + icon: Some(place.icon), + color: place.tint.or(Some(theme.text_dim)), + ..Spec::default() + }, + ); + ui.leaf( + "name", + Spec { + size: [fit(), px(row)], + text: Some(&place.name), + bold: place.depth == 0, + color: (!place.open).then_some(theme.text_dim), + flags: Flags::CLIP, + ..Spec::default() + }, + ); + ui.close(); +} + +/// A button of the dialog's row besides its default, which takes no clicks while not +/// `enabled`: whether it was clicked. +fn action(ui: &mut Ui, part: &str, text: &str, enabled: bool) -> bool { + if enabled { + return ui::button(ui, part, text).clicked; + } + let theme = &ui.theme; + let spec = Spec { + size: [fit(), px(theme.font_size * 2.0)], + text: Some(text), + color: Some(theme.text_dim), + fill: Some(theme.chip), + radius: 4.0, + pad: [theme.font_size * 0.75, 0.0], + center: true, + role: Some(Role::Button), + ..Spec::default() + }; + ui.leaf(part, spec); + if let Some(node) = ui.access(ui.id(part)) { + node.set_disabled(); + } + false +} diff --git a/crates/snowbound/src/sidebar.rs b/crates/snowbound/src/sidebar.rs index 2679f8c17309c84eb69a2979f4512fb11fdf83c0..c078e2f7278580bf74d3a9628b6052bcdf88b4f4 100644 --- a/crates/snowbound/src/sidebar.rs +++ b/crates/snowbound/src/sidebar.rs @@ -1536,6 +1536,7 @@ impl crate::State { pub(crate) fn no_sections(&mut self, library: Arc) { let downloading = library.downloading(); let renaming = self.folder_renaming(&library.location); + let moving = (self.moving.iter()).any(|(at, _)| *at == library.location); let new = crate::Command::Structure( library, crate::manage::Structure::NewSection { @@ -1545,6 +1546,8 @@ impl crate::State { let id = self.ui.id("no sections"); let (title, buttons) = if renaming { ("Renaming the folder…", Vec::new()) + } else if moving { + ("Moving the section…", Vec::new()) } else if downloading { ("Downloading from iCloud Drive…", Vec::new()) } else { diff --git a/crates/snowbound/src/undo.rs b/crates/snowbound/src/undo.rs index 66222b3c860f6eb66c3589b083c6a14dba41110e..fe53e9d323ff5dc6521ec52ca7765a53d1aa5a98 100644 --- a/crates/snowbound/src/undo.rs +++ b/crates/snowbound/src/undo.rs @@ -83,12 +83,18 @@ pub enum Change { from: String, to: String, }, - /// Moves a page to the end of the section `target` names, as a drop on its tab does. - Send { page: ExGuid, target: [u8; 16] }, + /// Moves a page to the end of the section `target` names in the notebook at `notebook`, + /// as a drop on its tab does. + Send { + page: ExGuid, + notebook: String, + target: [u8; 16], + }, /// Brings a page sent to `target` back, before `before` at `level`, taking out `added` /// while it holds nothing. Return { page: ExGuid, + notebook: String, target: [u8; 16], before: Option, level: u32, @@ -333,25 +339,26 @@ fn neighbor( } /// The space of the page an import op creates. -fn imported(op: &Op) -> ExGuid { +pub(crate) fn imported(op: &Op) -> ExGuid { match op { Op::Section(SectionOp::Import { creation, .. }) => creation.space(), - _ => unreachable!("notebook::session::moved imports"), + _ => unreachable!("notebook::session::moved and copied import"), } } -/// What a change to pages works with: the open section, its notebook, who changes it, and -/// a page to give it should it be left without pages. +/// What a change to pages works with: the open section, its notebook, who changes it, a +/// page to give it should it be left without pages, and the open notebooks a page may go to. struct Site { replica: Arc, library: Arc, - /// The replicas of the notebook's sections parked panes show, open already, by catalog - /// path. - held: Vec<(String, Arc)>, + /// The replicas of the sections parked panes show, open already, by notebook location + /// and catalog path. + held: Vec<(String, String, Arc)>, author: String, /// The page a section left without pages gains; none in the recycle bin, which OneNote /// leaves empty. fresh: Option, + notebooks: Vec>, } /// A change to pages done: the change taking it back, the page to show, and pages gone. @@ -416,37 +423,32 @@ impl Site { gone } - /// The catalog path of the section `identity` names. - fn section_path(&self, identity: [u8; 16]) -> Option { - entry_of(self.library.catalog()?, identity).map(|(_, path)| path) + /// The section `identity` names in the notebook at `notebook`, and its catalog path. + fn section(&self, notebook: &str, identity: [u8; 16]) -> Option<(Arc, String)> { + let library = match notebook == self.library.location { + true => &self.library, + false => (self.notebooks.iter()).find(|open| open.location == notebook)?, + }; + let (_, path) = entry_of(library.catalog()?, identity)?; + Some((Arc::clone(library), path)) } - /// The replica of the notebook's section at catalog `path`, with the section where it - /// was opened for this, which `release` closes after. + /// The replica of `library`'s section at catalog `path`, with the section where it was + /// opened for this, which `release` closes after. async fn reach( &self, + library: &Library, path: &str, ) -> Result<(Arc, Option), Box> { - if let Some((_, replica)) = self.held.iter().find(|(held, _)| held == path) { + let held = (self.held.iter()) + .find(|(location, held, _)| *location == library.location && held == path); + if let Some((.., replica)) = held { return Ok((Arc::clone(replica), None)); } - let section = self.library.open_async(path, || {}).await?; + let section = library.open_async(path, || {}).await?; Ok((Arc::clone(section.replica()), Some(section))) } - /// Closes `section`, at catalog `path`, once its edits are written; while some wait to be, - /// keeps it open, where they are tried again until they are. - async fn release(&self, path: &str, section: notebook::session::Section) { - match section.replica().written_async().await { - Ok(()) => { - if let Err(error) = section.close_async().await { - eprintln!("Synchronization stopped: {error}"); - } - } - Err(_) => self.library.keep(path, section), - } - } - /// Does `change` to the section's pages, `shown` the page open; `None` where what it /// changes is gone or holds what it did not make, which it leaves alone. async fn change( @@ -595,8 +597,14 @@ impl Site { gone: Vec::new(), } } - Change::Send { page, target } => { - let (Some(from), Some(path)) = (at(page), self.section_path(target)) else { + Change::Send { + page, + notebook, + target, + } => { + let (Some(from), Some((library, path))) = + (at(page), self.section(¬ebook, target)) + else { return Ok(None); }; let sent = self.replica.moving(page)?; @@ -606,7 +614,7 @@ impl Site { let level = listed[from].2; let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))]; let (show, added) = self.after(&listed, &[page], None, &mut ops); - let (other, opened) = self.reach(&path).await?; + let (other, opened) = self.reach(&library, &path).await?; other .apply_async( &self.author, @@ -617,7 +625,7 @@ impl Site { ) .await?; if let Some(section) = opened { - self.release(&path, section).await; + release(&library, &path, section).await; } let edit = Edit { at: crate::filetime(), @@ -628,6 +636,7 @@ impl Site { Ok(_) => Applied { undo: Ok(Change::Return { page: arrived, + notebook, target, before, level, @@ -645,18 +654,26 @@ impl Site { } Change::Return { page, + notebook, target, before, level, added, } => { - let Some(path) = self.section_path(target) else { - return Ok(None); + let open = notebook == self.library.location + || (self.notebooks.iter()).any(|open| open.location == notebook); + let Some((library, path)) = self.section(¬ebook, target) else { + return match open { + true => Ok(None), + false => { + Err("The notebook the page went to is closed, so it stays there".into()) + } + }; }; - let (other, opened) = self.reach(&path).await?; + let (other, opened) = self.reach(&library, &path).await?; if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) { if let Some(section) = opened { - self.release(&path, section).await; + release(&library, &path, section).await; } return Ok(None); } @@ -679,11 +696,15 @@ impl Site { }; let retired = other.retire_async(&self.author, delete, sent).await; if let Some(section) = opened { - self.release(&path, section).await; + release(&library, &path, section).await; } Applied { - undo: (retired.map(|_| Change::Send { page: back, target })) - .map_err(|error| crate::plain(&error, "page")), + undo: (retired.map(|_| Change::Send { + page: back, + notebook, + target, + })) + .map_err(|error| crate::plain(&error, "page")), show: back, gone, } @@ -699,6 +720,19 @@ impl Site { } } +/// Closes `section`, at catalog `path` in `library`, once its edits are written; while some +/// wait to be, keeps it open, where they are tried again until they are. +pub(crate) async fn release(library: &Library, path: &str, section: notebook::session::Section) { + match section.replica().written_async().await { + Ok(()) => { + if let Err(error) = section.close_async().await { + eprintln!("Synchronization stopped: {error}"); + } + } + Err(_) => library.keep(path, section), + } +} + /// The identity of each section and group in `folder`, in order, with its catalog path; /// the recycle bin is left out. fn entries(folder: &Folder) -> Vec<([u8; 16], String)> { @@ -1131,9 +1165,25 @@ impl State { } else { None }; - let held = self.held(&session.library.location); + let locations: std::collections::BTreeSet<&String> = + (self.notebooks.iter().map(|library| &library.location)) + .chain([&session.library.location]) + .collect(); + let held = (locations.into_iter()) + .flat_map(|location| { + (self.held(location).into_iter()) + .map(|(path, replica)| (location.clone(), path, replica)) + }) + .collect(); let key = session.key(); let notebook_key = session.library.key(""); + // The notebook a page goes to or comes back from, whose panes follow too. + let other_key = match &change { + Change::Send { notebook, .. } | Change::Return { notebook, .. } => { + Some(crate::library::key(notebook, "")) + } + _ => None, + }; let mut site = Site { replica: Arc::clone(session.section.replica()), library: Arc::clone(&session.library), @@ -1142,6 +1192,7 @@ impl State { fresh: (!self.in_recycle_bin()) .then(|| self.dated_page(None, "")) .transpose()?, + notebooks: self.notebooks.clone(), }; let shown = self.pane.showing.space; let original = Arc::clone(&site.library); @@ -1208,7 +1259,12 @@ impl State { Err(copied) => crate::platform::alert("Page kept in both sections", &copied), } // Its section, and the one a page went to or came from, wherever the focus is. - state.edited_sections(&key, Vec::new(), |shown| shown.starts_with(¬ebook_key)); + state.edited_sections(&key, Vec::new(), |shown| { + shown.starts_with(¬ebook_key) + || other_key + .as_ref() + .is_some_and(|other| shown.starts_with(other)) + }); Ok(()) }))); drop(changing); @@ -1498,6 +1554,7 @@ mod tests { held: Vec::new(), author: AUTHOR.into(), fresh: Some(dated()), + notebooks: Vec::new(), } } @@ -1741,6 +1798,7 @@ mod tests { let sent = fixture .change(Change::Send { page: fixture.space("Second"), + notebook: fixture.library.location.clone(), target, }) .unwrap(); @@ -1769,7 +1827,13 @@ mod tests { let page = fixture.space("Only"); let mut site = fixture.site(); site.fresh = None; - let sent = pollster::block_on(site.change(Change::Send { page, target }, page)) + let notebook = fixture.library.location.clone(); + let send = Change::Send { + page, + notebook, + target, + }; + let sent = pollster::block_on(site.change(send, page)) .unwrap() .unwrap(); assert_eq!((sent.show, sent.gone), (page, vec![page])); @@ -1818,9 +1882,14 @@ mod tests { fixture.library.keep("B.one", b); let mut site = fixture.site(); let shown = fixture.pages()[0].0; + let notebook = fixture.library.location.clone(); let sending = std::thread::spawn(move || { - pollster::block_on(site.change(Change::Send { page, target }, shown)) - .map_err(|error| error.to_string()) + let send = Change::Send { + page, + notebook, + target, + }; + pollster::block_on(site.change(send, shown)).map_err(|error| error.to_string()) }); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while !(arrived.pages().unwrap().iter()).any(|(_, title, _)| title == "Second") { @@ -1865,6 +1934,7 @@ mod tests { let target = fixture.library.section_identity("B.one").unwrap(); let sent = (fixture.change(Change::Send { page: fixture.space("Second"), + notebook: fixture.library.location.clone(), target, })) .unwrap(); @@ -1905,7 +1975,7 @@ mod tests { b.apply(AUTHOR, edit).unwrap(); let replica = Arc::clone(b.replica()); assert!(replica.written().is_err()); - pollster::block_on(fixture.site().release("B.one", b)); + pollster::block_on(release(&fixture.library, "B.one", b)); *vfs::FAILING.lock().unwrap() = None; let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while replica.written().is_err() { @@ -2072,6 +2142,7 @@ mod tests { &fixture, Change::Send { page: fixture.space("First"), + notebook: fixture.library.location.clone(), target: fixture.library.section_identity("B.one").unwrap(), }, ); diff --git a/crates/snowbound/tests/replay.rs b/crates/snowbound/tests/replay.rs index 6fdc9cc0bfc8e115bf922f3fdbdc4d8713dc71c4..7b031b97495a6405f8f700f49a43d9a6867ebb00 100644 --- a/crates/snowbound/tests/replay.rs +++ b/crates/snowbound/tests/replay.rs @@ -2171,3 +2171,259 @@ fn settings_saved_while_panes_open_keep_them_all() { ] ); } + +/// The titles of the pages of the section file at `path`. +fn stored_titles(path: &Path) -> Vec { + let image = std::fs::read(path).unwrap(); + (notebook::session::stored_pages(&image).unwrap().into_iter()) + .map(|stored| stored.page.title) + .collect() +} + +/// Move or Copy, as OneNote 2010 has it, takes a section and a page into another notebook +/// open beside, which holds a section of the same name: a copy of the section first, then the +/// page shown to the end of that notebook's section, then the section itself, which arrives +/// under the next free name and leaves for its notebook's recycle bin. +#[test] +fn move_or_copy_takes_sections_and_pages_into_another_notebook() { + let scratch = Scratch::new("move-or-copy"); + let source = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"); + let other = scratch.0.join("other"); + copy_notebook(&source, &other); + let settings = serde_json::json!({ + "user_name": "Snowbound Test", + "sidebar": true, + "notebooks": [other], + }); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + let pages = stored_titles(&source.join("Cross.one")); + let palette = |command: &'static str| { + [ + "modifiers command", + "key p", + "modifiers", + "settle", + command, + "settle", + "key Enter", + "wait 400", + ] + }; + let mut steps = Vec::from(palette("type >Move or Copy Section")); + steps.extend(["accessibility dialog", "type other", "key Down", "wait 200"]); + // Copy. + steps.extend(["move 637 529", "press", "release", "wait 2000", "settle"]); + steps.extend(palette("type >Move or Copy Page")); + // The other notebook's Cross, the first listed but the page's own. + steps.extend(["accessibility pages", "type Cross", "key Down", "key Enter"]); + steps.extend(["wait 2000", "settle"]); + steps.extend(palette("type >Move or Copy Section")); + steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]); + let [dialog, pages_dialog] = replay(&scratch, Some(&source), &steps).try_into().unwrap(); + assert!( + dialog.contains(r#"Dialog "Move or Copy Section""#), + "{dialog}" + ); + assert!(dialog.contains(r#"TreeItem "other""#), "{dialog}"); + assert!(dialog.contains(r#"Button "Move" [disabled]"#), "{dialog}"); + assert!( + pages_dialog.contains(r#"Dialog "Move or Copy Pages""#), + "{pages_dialog}" + ); + + let notebook = scratch.0.join("notebook"); + assert!(!notebook.join("Cross.one").exists()); + let binned = stored_titles(¬ebook.join("OneNote_RecycleBin/Cross.one")); + assert_eq!(binned, pages[1..], "the page left before the section did"); + let [first, copied, moved] = ["Cross.one", "Cross 2.one", "Cross 3.one"] + .map(|name| other.join(name)) + .map(|path| path.exists().then(|| stored_titles(&path))); + let mut arrived = pages.clone(); + arrived.push(pages[0].clone()); + assert_eq!(first, Some(arrived)); + assert_eq!(copied.as_deref(), Some(&pages[..])); + assert_eq!(moved.as_deref(), Some(&pages[1..])); +} + +/// Two copies of the cross-container notebook, the second listed beside the first, for Move +/// or Copy to carry things between. +fn two_notebooks(name: &str) -> (Scratch, PathBuf, PathBuf) { + let scratch = Scratch::new(name); + let source = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"); + let other = scratch.0.join("other"); + copy_notebook(&source, &other); + let settings = serde_json::json!({ + "user_name": "Snowbound Test", + "sidebar": true, + "notebooks": [other], + }); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + (scratch, source, other) +} + +fn palette(command: &'static str) -> [&'static str; 8] { + [ + "modifiers command", + "key p", + "modifiers", + "settle", + command, + "settle", + "key Enter", + "wait 400", + ] +} + +/// Copy is reached by keyboard alone: the search, an arrow to the place, Tab to Copy. +#[test] +fn move_or_copy_copies_by_keyboard_alone() { + let (scratch, source, other) = two_notebooks("move-or-copy-keys"); + let mut steps = Vec::from(palette("type >Move or Copy Section")); + steps.extend(["type other", "key Down", "key Tab", "key Tab", "key Space"]); + steps.extend(["wait 2000", "settle"]); + replay(&scratch, Some(&source), &steps); + assert!(other.join("Cross 2.one").exists()); + assert!(scratch.0.join("notebook/Cross.one").exists()); +} + +/// A section whose notebook has no room for it in its recycle bin stays, shown again, beside +/// the copy that arrived. +#[test] +fn a_move_that_cannot_leave_shows_the_section_where_it_stayed() { + let (scratch, source, other) = two_notebooks("move-or-copy-kept"); + std::fs::write(scratch.0.join("notebook/OneNote_RecycleBin"), b"").unwrap(); + let mut steps = Vec::from(palette("type >Move or Copy Section")); + steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]); + steps.push("accessibility kept"); + let [kept] = replay(&scratch, Some(&source), &steps).try_into().unwrap(); + assert!(other.join("Cross 2.one").exists()); + assert_eq!( + stored_titles(&scratch.0.join("notebook/Cross.one")), + stored_titles(&source.join("Cross.one")) + ); + assert!(!page_tabs(&kept).is_empty(), "{kept}"); +} + +/// Undo brings a page moved into another notebook back where it was. +#[test] +fn undo_brings_a_page_back_from_another_notebook() { + let (scratch, source, _) = two_notebooks("move-or-copy-undo"); + // Another notebook than a copy of this one, whose pages share none of its identities. + let other = scratch.0.join("synthetic"); + copy_notebook( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/conflict-page/candidate"), + &other, + ); + let settings = serde_json::json!({ + "user_name": "Snowbound Test", + "sidebar": true, + "notebooks": [other], + }); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + let (pages, theirs) = ( + stored_titles(&source.join("Cross.one")), + stored_titles(&other.join("synthetic.one")), + ); + let mut steps = Vec::from(palette("type >Move or Copy Page")); + steps.extend([ + "type synthetic", + "key Down", + "key Enter", + "wait 2000", + "settle", + ]); + steps.push("accessibility moved"); + // Long enough for the other notebook's section to publish the page leaving it. + steps.extend([ + "modifiers command", + "key z", + "modifiers", + "wait 6000", + "settle", + ]); + steps.push("accessibility back"); + let [moved, back] = replay(&scratch, Some(&source), &steps).try_into().unwrap(); + assert_eq!(page_tabs(&moved).len(), pages.len() - 1, "{moved}"); + assert_eq!(page_tabs(&back).len(), pages.len(), "{back}"); + let mut here = stored_titles(&scratch.0.join("notebook/Cross.one")); + let mut expected = pages.clone(); + here.sort(); + expected.sort(); + assert_eq!(here, expected); + assert_eq!(stored_titles(&other.join("synthetic.one")), theirs); +} + +/// The search corpus's notebook, with the cross-container one listed beside it as "other". +fn split_notebooks(name: &str) -> (Scratch, PathBuf, PathBuf) { + let scratch = Scratch::new(name); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/search/notebook"); + let other = scratch.0.join("other"); + copy_notebook( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"), + &other, + ); + let settings = serde_json::json!({ + "user_name": "Snowbound Test", + "sidebar": true, + "notebooks": [other], + }); + std::fs::write(scratch.0.join("settings.json"), settings.to_string()).unwrap(); + (scratch, source, other) +} + +/// A section two panes show moves to another notebook: neither pane offers to make a section +/// meanwhile, and both show the notebook's next one after. +#[test] +fn a_section_two_panes_show_moves_and_both_show_the_next() { + let (scratch, source, other) = split_notebooks("move-split-section"); + let mut steps = vec!["split right", "settle"]; + steps.extend(palette("type >Move or Copy Section")); + steps.extend(["type other", "key Down", "key Enter", "wait 3000", "settle"]); + steps.push("accessibility moved"); + let [moved] = replay(&scratch, Some(&source), &steps).try_into().unwrap(); + assert!(other.join("Garden.one").exists()); + assert!(!moved.contains("No sections in this notebook"), "{moved}"); + let groups = pane_groups(&moved); + assert_eq!(groups.len(), 2, "{moved}"); + assert!( + groups.iter().all(|group| group.contains(r#""Kitchen, "#)), + "{moved}" + ); +} + +/// A page moved into a section another pane shows, from another notebook, is listed there, and +/// gone again after Undo. +#[test] +fn a_page_moved_into_a_parked_pane_shows_there_and_leaves_on_undo() { + let (scratch, source, _) = split_notebooks("move-split-page"); + let focus = |x: &'static str| [x, "press", "release", "settle"]; + let mut steps = vec!["split right", "settle"]; + // The other notebook's Cross in the right pane, then the focus back on Garden at the left. + steps.extend(focus("move 63 100")); + steps.extend(focus("move 350 650")); + steps.extend(palette("type >Move or Copy Page")); + steps.extend(["type Cross", "key Down", "key Enter", "wait 3000", "settle"]); + steps.extend(focus("move 850 650")); + steps.push("accessibility arrived"); + steps.extend(focus("move 350 650")); + steps.extend([ + "modifiers command", + "key z", + "modifiers", + "wait 3000", + "settle", + ]); + steps.extend(focus("move 850 650")); + steps.push("accessibility back"); + let [arrived, back] = replay(&scratch, Some(&source), &steps).try_into().unwrap(); + let moved = "Spring planting plan"; + let tabs = |tree: &str| -> Vec { + (page_tabs(tree).into_iter()) + .map(|tab| tab.trim_start_matches('*').to_owned()) + .collect() + }; + assert!(tabs(&arrived).iter().any(|tab| tab == moved), "{arrived}"); + assert!(!tabs(&back).iter().any(|tab| tab == moved), "{back}"); +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index e843981af91881d07938d2987494a23f194d4920..1e358537639fa3037ecb801d90fa26bd1251c6cf 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -16,8 +16,8 @@ pub use list::{List, Row, Rows, list}; pub use theme::{Menu, PopupMotion, Section, Shades, Shadow, Theme}; pub use widgets::{ PaintedScroller, Scroller, ScrollerPart, Scrollers, Segments, badge, badge_width, button, - check_box, dialog_buttons, edit_key, edit_modifiers, password_field, scrollbar, segmented, - text_field, + check_box, dialog_buttons, dialog_buttons_with, edit_key, edit_modifiers, password_field, + scrollbar, segmented, text_field, }; use draw::{ diff --git a/crates/ui/src/widgets.rs b/crates/ui/src/widgets.rs index 685a6a04b72922fa8e8425a54379b75171115341..6796ac18c7ac339b549d5bab84ac097db1d6bc05 100644 --- a/crates/ui/src/widgets.rs +++ b/crates/ui/src/widgets.rs @@ -37,6 +37,19 @@ pub fn button(ui: &mut Ui, part: impl Hash, text: &str) -> Signal { /// own dialogs place them. The default wears the accent around it. Whether each was clicked, /// Cancel first. pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] { + let [cancel, chosen, _] = dialog_buttons_with(ui, text, enabled, |_| false); + [cancel, chosen] +} + +/// `dialog_buttons` with another button, which `other` builds and says was clicked: after the +/// default on Windows, before Cancel elsewhere. Whether each was clicked, Cancel, the default, +/// then the other. +pub fn dialog_buttons_with( + ui: &mut Ui, + text: &str, + enabled: bool, + other: impl FnOnce(&mut Ui) -> bool, +) -> [bool; 3] { let default = |ui: &mut Ui| { let theme = &ui.theme; let spec = Spec { @@ -65,11 +78,12 @@ pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] { }; let windows = edit::Platform::CURRENT == edit::Platform::Windows; let mut chosen = windows && default(ui); + let other = other(ui); let cancel = button(ui, "cancel", "Cancel").clicked; if !windows { chosen = default(ui); } - [cancel, chosen] + [cancel, chosen, other] } /// A short tag in the accent's colour, centred in a box `height` tall, as BETA marks a -- 2.54.1