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
347347what the bin has held unchanged for 60 days, as OneNote prunes it: judged by the
348348content's last change, the pages in one revision, binned section files deleted
349349with 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
351355What only Snowbound reads lives in the notebook's `.snowbound` folder, which carries the
352356Windows 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 {
3030 NewSubpage,
3131 PageVersions,
3232 CopyPageLink,
33 /// Move or Copy on the page shown.
34 MoveOrCopyPage,
3335 /// Password Protection on the section shown.
3436 PasswordProtect,
3537 /// Locks every password-protected section unlocked.
......@@ -278,6 +280,13 @@ pub const COMMANDS: &[Command] = &[
278280 ),
279281 row!(Id::PageVersions, "Page Versions", NONE, NONE),
280282 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 ),
281290 row!(
282291 Id::PasswordProtect,
283292 "Password Protect This Section",
......@@ -1255,8 +1264,8 @@ impl State {
12551264 .notebook()
12561265 .is_some_and(|library| library.catalog().is_some()),
12571266 ),
1258 // The recycle bin takes no new pages.
1259 Id::NewPage | Id::NewSubpage => {
1267 // The recycle bin takes no new pages, and moves its own by Restore To.
1268 Id::NewPage | Id::NewSubpage | Id::MoveOrCopyPage => {
12601269 enabled(!modal && session.is_some() && !self.in_recycle_bin())
12611270 }
12621271 Id::CopyPageLink | Id::Find | Id::Search | Id::ExportPdf | Id::Print => {
......@@ -1555,6 +1564,10 @@ impl State {
15551564 show: self.pane.showing.shown_history != Some(self.pane.showing.space),
15561565 }
15571566 }
1567 Id::MoveOrCopyPage => {
1568 self.move_or_copy_page(self.pane.showing.space);
1569 return Ok(());
1570 }
15581571 Id::CopyPageLink => {
15591572 self.session.as_ref().ok_or("No notebook is open")?;
15601573 let space = self.pane.showing.space;
crates/snowbound/src/main.rs+46-6
......@@ -45,6 +45,7 @@ mod meeting;
4545#[cfg(target_os = "macos")]
4646mod menubar;
4747mod menus;
48mod move_copy;
4849mod navigation;
4950mod options;
5051mod palette;
......@@ -848,9 +849,16 @@ enum Command {
848849 Recycle(recycle::Request),
849850 /// Moves or indents pages of the open section.
850851 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.
852853 MovePage {
853854 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>,
854862 path: String,
855863 },
856864 /// Gives the open page a template's background.
......@@ -982,6 +990,10 @@ struct State {
982990 updates: update::Updates,
983991 /// The Link dialog's fields while it is open.
984992 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)>,
985997 properties: Option<properties::Properties>,
986998 symbols: Option<symbol::Symbols>,
987999 /// Save As while it is open.
......@@ -1473,6 +1485,8 @@ impl State {
14731485 actions: None,
14741486 after_open: None,
14751487 link: None,
1488 move_copy: None,
1489 moving: Vec::new(),
14761490 properties: None,
14771491 symbols: None,
14781492 save_as: None,
......@@ -1741,6 +1755,8 @@ impl State {
17411755 self.own_dialog();
17421756 self.customize_tags();
17431757 self.palette();
1758 // After the palette, which opens it, so that its field is there to take the focus.
1759 self.move_copy_dialog();
17441760 self.sync_popup()?;
17451761 self.text_menu()?;
17461762 platform::resize_grip(&mut self.ui, &self.window, size);
......@@ -3856,10 +3872,19 @@ impl State {
38563872 }
38573873 Command::Recycle(request) => self.recycle(request)?,
38583874 Command::Pages(edits) => self.edit_pages(edits)?,
3859 Command::MovePage { space, path } => {
3860 self.move_page(space, path)?;
3875 Command::MovePage {
3876 space,
3877 library,
3878 path,
3879 } => {
3880 self.move_page(space, &library, &path)?;
38613881 self.edited(Vec::new());
38623882 }
3883 Command::CopyPage {
3884 space,
3885 library,
3886 path,
3887 } => self.copy_page(space, library, path)?,
38633888 Command::Template(name) => self.apply_template(name)?,
38643889 Command::Page(Request::EditDate(field)) => self.edit_date(field),
38653890 Command::Page(Request::Copy(clip)) => self.clipboard.set(clip)?,
......@@ -3888,8 +3913,10 @@ impl State {
38883913 path: String,
38893914 page: Option<ExGuid>,
38903915 ) -> Result<(), Box<dyn Error>> {
3891 // Its files are on their way to the renamed folder.
3892 if self.folder_renaming(&library.location) {
3916 // Its files are on their way to the renamed folder, or another notebook.
3917 if self.folder_renaming(&library.location)
3918 || (self.moving.iter()).any(|(at, moving)| *at == library.location && *moving == path)
3919 {
38933920 return Ok(());
38943921 }
38953922 if library.locked(&path) {
......@@ -6353,6 +6380,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> {
63536380 Cmd::NewSubpage => art::NEW_SUBPAGE,
63546381 Cmd::PageVersions => art::PAGE_VERSIONS,
63556382 Cmd::CopyPageLink => art::COPY_LINK,
6383 Cmd::MoveOrCopyPage => art::MOVE,
63566384 Cmd::PasswordProtect => art::PASSWORD,
63576385 Cmd::LockAll => art::LOCK,
63586386 Cmd::ShowNotebook => art::FOLDER,
......@@ -6873,7 +6901,7 @@ impl State {
68736901 && (self.initial.iter())
68746902 .map(|(id, document)| (id, document))
68756903 .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 {
68776905 let _ = self.proxy.send_event(UserEvent::Exit);
68786906 return;
68796907 }
......@@ -6896,6 +6924,18 @@ impl App {
68966924 let Some(state) = &self.state else {
68976925 return event_loop.exit();
68986926 };
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 }
68996939 let changes = match notebook::unwritten() {
69006940 0 => return state.quit(),
69016941 1 => "1 unsaved change".to_owned(),
crates/snowbound/src/manage.rs+59-8
......@@ -1125,21 +1125,72 @@ impl State {
11251125 })
11261126 }
11271127
1128 /// Moves page `space` of the open section to the end of the section at catalog `path`,
1129 /// as OneNote moves a page dropped on a section's tab: the page keeps its identity,
1130 /// 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>> {
1132 let session = self.session.as_ref().ok_or("No section is open")?;
1133 let target = session
1134 .library
1135 .section_identity(&path)
1128 /// Moves page `space` of the open section to the end of the section at catalog `path` of
1129 /// `library`, as OneNote moves a page dropped on a section's tab: the page keeps its
1130 /// identity, title, date and content there and leaves this section.
1131 pub(crate) fn move_page(
1132 &mut self,
1133 space: ExGuid,
1134 library: &Library,
1135 path: &str,
1136 ) -> Result<(), Box<dyn Error>> {
1137 let target = library
1138 .section_identity(path)
11361139 .ok_or("That section is not in the notebook")?;
11371140 self.change_pages(Change::Send {
11381141 page: space,
1142 notebook: library.location.clone(),
11391143 target,
11401144 })
11411145 }
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
11431194 /// Moves or indents pages of the open section, in order.
11441195 pub(crate) fn edit_pages(&mut self, edits: Vec<PageEdit>) -> Result<(), Box<dyn Error>> {
11451196 self.persist()?;
crates/snowbound/src/menubar.rs+1
......@@ -66,6 +66,7 @@ const MENUS: &[Item] = &[
6666 S,
6767 C(Id::PageVersions),
6868 C(Id::CopyPageLink),
69 C(Id::MoveOrCopyPage),
6970 C(Id::ShowNotebook),
7071 C(Id::LiveShare),
7172 S,
crates/snowbound/src/menus.rs+28-18
......@@ -111,6 +111,8 @@ pub enum Action {
111111 Move,
112112 /// Moves it to a section, or into a folder, by catalog path.
113113 MoveTo(String),
114 /// Opens Move or Copy on a page or section.
115 MoveOrCopy,
114116 /// Opens the submenu of the sections `CopyTo` copies a page of the recycle bin to.
115117 Copy,
116118 CopyTo(String),
......@@ -158,7 +160,7 @@ impl Action {
158160 Action::Open => art::OPEN,
159161 Action::Rename => art::RENAME,
160162 Action::Delete => art::DELETE,
161 Action::Move => art::MOVE,
163 Action::Move | Action::MoveOrCopy => art::MOVE,
162164 Action::Copy => art::COPY,
163165 Action::SaveAs => art::SAVE,
164166 Action::RecycleBin => art::RECYCLE_BIN,
......@@ -219,7 +221,9 @@ pub(crate) const SECTION_COLORS: [(u32, &str); 16] = [
219221pub(crate) fn covered(target: &Target, action: &Action) -> bool {
220222 use Action::*;
221223 match target {
222 Target::Page { .. } => matches!(action, CopyLink | NewPage | NewSubpage | Theme),
224 Target::Page { .. } => {
225 matches!(action, CopyLink | NewPage | NewSubpage | Theme | MoveOrCopy)
226 }
223227 Target::Section { .. } => matches!(
224228 action,
225229 SaveAs | NewSection | NewGroup | Password | Theme | EmptyRecycleBin
......@@ -259,6 +263,7 @@ pub(crate) fn command_title(target: &Target, action: &Action, label: &str) -> St
259263 }
260264 match label.split_once(' ') {
261265 _ if *action == Action::Properties => format!("{noun} {label}"),
266 _ if *action == Action::MoveOrCopy => format!("{label} {noun}"),
262267 Some((verb, rest)) => format!("{verb} {noun} {rest}"),
263268 None => format!("{label} {noun}"),
264269 }
......@@ -465,7 +470,7 @@ impl State {
465470 let mut actions = vec![
466471 item(Action::Rename, "Rename", false, false),
467472 item(Action::Delete, "Delete", false, false),
468 item(Action::Move, "Move to Section", nowhere(), false),
473 item(Action::MoveOrCopy, "Move or Copy", false, false),
469474 item(Action::CopyLink, "Copy Link to Page", false, true),
470475 item(
471476 Action::MarkRead,
......@@ -528,7 +533,10 @@ impl State {
528533 }
529534 actions.extend([
530535 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 },
532540 ]);
533541 if section {
534542 let link = self.section_link(library, path).is_none();
......@@ -762,8 +770,8 @@ impl State {
762770 }
763771 }
764772
765 /// Where Move takes `target`: the other sections of a page's folder, or the folders a
766 /// section or group may move into.
773 /// Where Move takes `target`: the sections a page of the recycle bin goes back to, or the
774 /// folders a section or group may move into.
767775 fn destinations(&self, target: &Target) -> Vec<Destination> {
768776 let theme = &self.ui.theme;
769777 match target {
......@@ -778,15 +786,6 @@ impl State {
778786 })
779787 .collect()
780788 }
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(),
790789 Target::Section { library, path } | Target::Group { library, path } => {
791790 let within = format!("{path}/");
792791 let home = folder(path);
......@@ -937,6 +936,10 @@ impl State {
937936 );
938937 None
939938 }
939 (Target::Section { library, path }, Action::MoveOrCopy) => {
940 self.open_move_copy(crate::move_copy::Moving::Section { library, path });
941 None
942 }
940943 (
941944 Target::Section { library, path } | Target::Group { library, path },
942945 Action::MoveTo(folder),
......@@ -1080,7 +1083,10 @@ impl State {
10801083 path,
10811084 copy: true,
10821085 })),
1083 Action::MoveTo(path) => Some(Command::MovePage { space, path }),
1086 Action::MoveOrCopy => {
1087 self.move_or_copy_page(space);
1088 None
1089 }
10841090 Action::CopyLink => {
10851091 let copied = self
10861092 .page_link(space, None)
......@@ -1231,8 +1237,12 @@ impl State {
12311237 }
12321238 let slot = drag.slot.take();
12331239 if let Some(tab) = target {
1234 let path = session.tabs[tab].path.clone();
1235 self.commands.push(Command::MovePage { space, path });
1240 let (library, path) = (Arc::clone(&session.library), session.tabs[tab].path.clone());
1241 self.commands.push(Command::MovePage {
1242 space,
1243 library,
1244 path,
1245 });
12361246 return;
12371247 }
12381248 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 {
15361536 pub(crate) fn no_sections(&mut self, library: Arc<Library>) {
15371537 let downloading = library.downloading();
15381538 let renaming = self.folder_renaming(&library.location);
1539 let moving = (self.moving.iter()).any(|(at, _)| *at == library.location);
15391540 let new = crate::Command::Structure(
15401541 library,
15411542 crate::manage::Structure::NewSection {
......@@ -1545,6 +1546,8 @@ impl crate::State {
15451546 let id = self.ui.id("no sections");
15461547 let (title, buttons) = if renaming {
15471548 ("Renaming the folder…", Vec::new())
1549 } else if moving {
1550 ("Moving the section…", Vec::new())
15481551 } else if downloading {
15491552 ("Downloading from iCloud Drive…", Vec::new())
15501553 } else {
crates/snowbound/src/undo.rs+117-46
......@@ -83,12 +83,18 @@ pub enum Change {
8383 from: String,
8484 to: String,
8585 },
86 /// Moves a page to the end of the section `target` names, as a drop on its tab does.
87 Send { page: ExGuid, target: [u8; 16] },
86 /// Moves a page to the end of the section `target` names in the notebook at `notebook`,
87 /// as a drop on its tab does.
88 Send {
89 page: ExGuid,
90 notebook: String,
91 target: [u8; 16],
92 },
8893 /// Brings a page sent to `target` back, before `before` at `level`, taking out `added`
8994 /// while it holds nothing.
9095 Return {
9196 page: ExGuid,
97 notebook: String,
9298 target: [u8; 16],
9399 before: Option<ExGuid>,
94100 level: u32,
......@@ -333,25 +339,26 @@ fn neighbor(
333339}
334340
335341/// The space of the page an import op creates.
336fn imported(op: &Op) -> ExGuid {
342pub(crate) fn imported(op: &Op) -> ExGuid {
337343 match op {
338344 Op::Section(SectionOp::Import { creation, .. }) => creation.space(),
339 _ => unreachable!("notebook::session::moved imports"),
345 _ => unreachable!("notebook::session::moved and copied import"),
340346 }
341347}
342348
343/// What a change to pages works with: the open section, its notebook, who changes it, and
344/// a page to give it should it be left without pages.
349/// What a change to pages works with: the open section, its notebook, who changes it, a
350/// page to give it should it be left without pages, and the open notebooks a page may go to.
345351struct Site {
346352 replica: Arc<Replica>,
347353 library: Arc<Library>,
348 /// The replicas of the notebook's sections parked panes show, open already, by catalog
349 /// path.
350 held: Vec<(String, Arc<Replica>)>,
354 /// The replicas of the sections parked panes show, open already, by notebook location
355 /// and catalog path.
356 held: Vec<(String, String, Arc<Replica>)>,
351357 author: String,
352358 /// The page a section left without pages gains; none in the recycle bin, which OneNote
353359 /// leaves empty.
354360 fresh: Option<PageCreation>,
361 notebooks: Vec<Arc<Library>>,
355362}
356363
357364/// A change to pages done: the change taking it back, the page to show, and pages gone.
......@@ -416,37 +423,32 @@ impl Site {
416423 gone
417424 }
418425
419 /// The catalog path of the section `identity` names.
420 fn section_path(&self, identity: [u8; 16]) -> Option<String> {
421 entry_of(self.library.catalog()?, identity).map(|(_, path)| path)
426 /// The section `identity` names in the notebook at `notebook`, and its catalog path.
427 fn section(&self, notebook: &str, identity: [u8; 16]) -> Option<(Arc<Library>, String)> {
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))
422434 }
423435
424 /// The replica of the notebook's section at catalog `path`, with the section where it
425 /// was opened for this, which `release` closes after.
436 /// The replica of `library`'s section at catalog `path`, with the section where it was
437 /// opened for this, which `release` closes after.
426438 async fn reach(
427439 &self,
440 library: &Library,
428441 path: &str,
429442 ) -> 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 {
431446 return Ok((Arc::clone(replica), None));
432447 }
433 let section = self.library.open_async(path, || {}).await?;
448 let section = library.open_async(path, || {}).await?;
434449 Ok((Arc::clone(section.replica()), Some(section)))
435450 }
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
450452 /// Does `change` to the section's pages, `shown` the page open; `None` where what it
451453 /// changes is gone or holds what it did not make, which it leaves alone.
452454 async fn change(
......@@ -595,8 +597,14 @@ impl Site {
595597 gone: Vec::new(),
596598 }
597599 }
598 Change::Send { page, target } => {
599 let (Some(from), Some(path)) = (at(page), self.section_path(target)) else {
600 Change::Send {
601 page,
602 notebook,
603 target,
604 } => {
605 let (Some(from), Some((library, path))) =
606 (at(page), self.section(&notebook, target))
607 else {
600608 return Ok(None);
601609 };
602610 let sent = self.replica.moving(page)?;
......@@ -606,7 +614,7 @@ impl Site {
606614 let level = listed[from].2;
607615 let mut ops = vec![Op::Section(SectionOp::Delete(vec![page]))];
608616 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?;
610618 other
611619 .apply_async(
612620 &self.author,
......@@ -617,7 +625,7 @@ impl Site {
617625 )
618626 .await?;
619627 if let Some(section) = opened {
620 self.release(&path, section).await;
628 release(&library, &path, section).await;
621629 }
622630 let edit = Edit {
623631 at: crate::filetime(),
......@@ -628,6 +636,7 @@ impl Site {
628636 Ok(_) => Applied {
629637 undo: Ok(Change::Return {
630638 page: arrived,
639 notebook,
631640 target,
632641 before,
633642 level,
......@@ -645,18 +654,26 @@ impl Site {
645654 }
646655 Change::Return {
647656 page,
657 notebook,
648658 target,
649659 before,
650660 level,
651661 added,
652662 } => {
653 let Some(path) = self.section_path(target) else {
654 return Ok(None);
663 let open = notebook == self.library.location
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 };
655672 };
656 let (other, opened) = self.reach(&path).await?;
673 let (other, opened) = self.reach(&library, &path).await?;
657674 if !(other.pages()?.iter()).any(|(listed, ..)| *listed == page) {
658675 if let Some(section) = opened {
659 self.release(&path, section).await;
676 release(&library, &path, section).await;
660677 }
661678 return Ok(None);
662679 }
......@@ -679,11 +696,15 @@ impl Site {
679696 };
680697 let retired = other.retire_async(&self.author, delete, sent).await;
681698 if let Some(section) = opened {
682 self.release(&path, section).await;
699 release(&library, &path, section).await;
683700 }
684701 Applied {
685 undo: (retired.map(|_| Change::Send { page: back, target }))
686 .map_err(|error| crate::plain(&error, "page")),
702 undo: (retired.map(|_| Change::Send {
703 page: back,
704 notebook,
705 target,
706 }))
707 .map_err(|error| crate::plain(&error, "page")),
687708 show: back,
688709 gone,
689710 }
......@@ -699,6 +720,19 @@ impl Site {
699720 }
700721}
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
702736/// The identity of each section and group in `folder`, in order, with its catalog path;
703737/// the recycle bin is left out.
704738fn entries(folder: &Folder) -> Vec<([u8; 16], String)> {
......@@ -1131,9 +1165,25 @@ impl State {
11311165 } else {
11321166 None
11331167 };
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();
11351178 let key = session.key();
11361179 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 };
11371187 let mut site = Site {
11381188 replica: Arc::clone(session.section.replica()),
11391189 library: Arc::clone(&session.library),
......@@ -1142,6 +1192,7 @@ impl State {
11421192 fresh: (!self.in_recycle_bin())
11431193 .then(|| self.dated_page(None, ""))
11441194 .transpose()?,
1195 notebooks: self.notebooks.clone(),
11451196 };
11461197 let shown = self.pane.showing.space;
11471198 let original = Arc::clone(&site.library);
......@@ -1208,7 +1259,12 @@ impl State {
12081259 Err(copied) => crate::platform::alert("Page kept in both sections", &copied),
12091260 }
12101261 // 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 });
12121268 Ok(())
12131269 })));
12141270 drop(changing);
......@@ -1498,6 +1554,7 @@ mod tests {
14981554 held: Vec::new(),
14991555 author: AUTHOR.into(),
15001556 fresh: Some(dated()),
1557 notebooks: Vec::new(),
15011558 }
15021559 }
15031560
......@@ -1741,6 +1798,7 @@ mod tests {
17411798 let sent = fixture
17421799 .change(Change::Send {
17431800 page: fixture.space("Second"),
1801 notebook: fixture.library.location.clone(),
17441802 target,
17451803 })
17461804 .unwrap();
......@@ -1769,7 +1827,13 @@ mod tests {
17691827 let page = fixture.space("Only");
17701828 let mut site = fixture.site();
17711829 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))
17731837 .unwrap()
17741838 .unwrap();
17751839 assert_eq!((sent.show, sent.gone), (page, vec![page]));
......@@ -1818,9 +1882,14 @@ mod tests {
18181882 fixture.library.keep("B.one", b);
18191883 let mut site = fixture.site();
18201884 let shown = fixture.pages()[0].0;
1885 let notebook = fixture.library.location.clone();
18211886 let sending = std::thread::spawn(move || {
1822 pollster::block_on(site.change(Change::Send { page, target }, shown))
1823 .map_err(|error| error.to_string())
1887 let send = Change::Send {
1888 page,
1889 notebook,
1890 target,
1891 };
1892 pollster::block_on(site.change(send, shown)).map_err(|error| error.to_string())
18241893 });
18251894 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
18261895 while !(arrived.pages().unwrap().iter()).any(|(_, title, _)| title == "Second") {
......@@ -1865,6 +1934,7 @@ mod tests {
18651934 let target = fixture.library.section_identity("B.one").unwrap();
18661935 let sent = (fixture.change(Change::Send {
18671936 page: fixture.space("Second"),
1937 notebook: fixture.library.location.clone(),
18681938 target,
18691939 }))
18701940 .unwrap();
......@@ -1905,7 +1975,7 @@ mod tests {
19051975 b.apply(AUTHOR, edit).unwrap();
19061976 let replica = Arc::clone(b.replica());
19071977 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));
19091979 *vfs::FAILING.lock().unwrap() = None;
19101980 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
19111981 while replica.written().is_err() {
......@@ -2072,6 +2142,7 @@ mod tests {
20722142 &fixture,
20732143 Change::Send {
20742144 page: fixture.space("First"),
2145 notebook: fixture.library.location.clone(),
20752146 target: fixture.library.section_identity("B.one").unwrap(),
20762147 },
20772148 );
crates/snowbound/tests/replay.rs+256
......@@ -2171,3 +2171,259 @@ fn settings_saved_while_panes_open_keep_them_all() {
21712171 ]
21722172 );
21732173}
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};
1616pub use theme::{Menu, PopupMotion, Section, Shades, Shadow, Theme};
1717pub use widgets::{
1818 PaintedScroller, Scroller, ScrollerPart, Scrollers, Segments, badge, badge_width, button,
19 check_box, dialog_buttons, edit_key, edit_modifiers, password_field, scrollbar, segmented,
20 text_field,
19 check_box, dialog_buttons, dialog_buttons_with, edit_key, edit_modifiers, password_field,
20 scrollbar, segmented, text_field,
2121};
2222
2323use draw::{
crates/ui/src/widgets.rs+15-1
......@@ -37,6 +37,19 @@ pub fn button(ui: &mut Ui, part: impl Hash, text: &str) -> Signal {
3737/// own dialogs place them. The default wears the accent around it. Whether each was clicked,
3838/// Cancel first.
3939pub 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] {
4053 let default = |ui: &mut Ui| {
4154 let theme = &ui.theme;
4255 let spec = Spec {
......@@ -65,11 +78,12 @@ pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {
6578 };
6679 let windows = edit::Platform::CURRENT == edit::Platform::Windows;
6780 let mut chosen = windows && default(ui);
81 let other = other(ui);
6882 let cancel = button(ui, "cancel", "Cancel").clicked;
6983 if !windows {
7084 chosen = default(ui);
7185 }
72 [cancel, chosen]
86 [cancel, chosen, other]
7387}
7488
7589/// A short tag in the accent's colour, centred in a box `height` tall, as BETA marks a