From 98d01dfc3f7d9f522c2bf0fb84047b2407527df6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 22:57:38 -0500 Subject: [PATCH] fw-services: resolve the sync of origin/next into pdf-port/gaps platform (appearance, portal, clipboard, open), settings, host files, dialogs service, print, i18n date. Settings take upstream's LocalStorageFiles, with BrowserFiles a deprecated alias (L-313); Windows reduced motion is upstream's native worker; the port's forced pick answers, write intent, GNOME text scale, open-for and byte intake stay on upstream's code. --- crates/dialogs/src/service.rs | 173 ++++++--------- crates/host/src/files.rs | 27 +-- crates/i18n/src/date.rs | 15 +- crates/platform/Cargo.toml | 13 +- crates/platform/README.md | 13 +- crates/platform/src/appearance.rs | 98 +-------- crates/platform/src/appearance/portal.rs | 64 ++---- crates/platform/src/clipboard/backend.rs | 263 ----------------------- crates/platform/src/clipboard_tests.rs | 22 -- crates/platform/src/default_app_tests.rs | 11 +- crates/platform/src/open.rs | 17 +- crates/platform/src/open_tests.rs | 5 +- crates/print/Cargo.toml | 11 +- crates/print/src/ui/stories.rs | 57 ++--- crates/print/tests/it/main.rs | 7 +- crates/settings/Cargo.toml | 6 - crates/settings/src/files.rs | 69 +----- crates/settings/src/lib.rs | 12 +- crates/settings/src/paths.rs | 53 +---- crates/settings/src/recovery.rs | 49 ++--- crates/settings/src/store.rs | 64 +----- 21 files changed, 159 insertions(+), 890 deletions(-) diff --git a/crates/dialogs/src/service.rs b/crates/dialogs/src/service.rs index d1b2c58687..9c1679758e 100644 --- a/crates/dialogs/src/service.rs +++ b/crates/dialogs/src/service.rs @@ -182,14 +182,6 @@ struct ReplaceQuestion { settled: PathBuf, } -/// Where an answer to settle came from: a panel the user saw, or [`Files::answer_next`]. A -/// cancel only means "no dialog backend" when a panel gave it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Source { - Panel, - Forced, -} - /// A replace question shown on the app's `DialogHost`: the pick it settles and the prompt's id, /// once the host has accepted the prompt. #[cfg(feature = "ui")] @@ -347,15 +339,12 @@ impl FilePanels { /// the answer becomes a [`PickAnswer`]. // pc: crates/ui-egui/src/file_dialog.rs:310 poll_file_dialog, :349 finish_file_dialog, :365 saved_path pub fn pump(&mut self, parent: Option<&W>) { -<<<<<<< HEAD - // Forced answers settle first; a replace question queued by `finish` shows in the same - // pass, so the loop runs until no answer is left to settle. - let mut answers = self.start_requests(); - loop { - for (id, answer, source) in answers { - if let Some(question) = self.finish(id, answer, source) { -======= - self.start_requests(); + // Forced answers settle first, with no panel. + for (id, answer) in self.start_requests() { + if let Some(question) = self.finish(id, answer, false) { + self.dialogs.ask_message(self.replace_message(&question.settled), id); + } + } self.cancel_forgotten(); // A replace question queued by `finish` shows in the same pass, so the loop runs until no // answer is left to settle. @@ -367,15 +356,9 @@ impl FilePanels { } for (id, answer) in answers { if let Some(question) = self.finish(id, answer, true) { ->>>>>>> origin/next self.dialogs.ask_message(self.replace_message(&question.settled), id); } } - self.dialogs.show_pending(parent); - answers = self.panel_answers(); - if answers.is_empty() { - break; - } } self.mark_busy(); } @@ -395,15 +378,13 @@ impl FilePanels { #[cfg(feature = "ui")] pub fn pump_with(&mut self, dialogs: &mut craft_ui::dialog::DialogHost, parent: Option<&W>) { self.collect_prompt_answers(dialogs); -<<<<<<< HEAD - let mut answers = self.start_requests(); - loop { - for (id, answer, source) in answers { - if let Some(question) = self.finish(id, answer, source) { -======= self.collect_chooser_answers(dialogs); while let Ok((id, request)) = self.requests.try_recv() { - if request.fallback { + if let Some(answer) = self.forced_answer(id) { + if let Some(question) = self.finish(id, answer, false) { + self.prompts.push(AskedPrompt { id, question, dialog: None }); + } + } else if request.fallback { self.choosers.push(AskedChooser { id, request, cause: None, dialog: None }); } else { self.ask_panel(id, &request); @@ -433,15 +414,9 @@ impl FilePanels { answer => answer, }; if let Some(question) = self.finish(id, answer, true) { ->>>>>>> origin/next self.prompts.push(AskedPrompt { id, question, dialog: None }); } } - self.dialogs.show_pending(parent); - answers = self.panel_answers(); - if answers.is_empty() { - break; - } } self.open_choosers(dialogs); self.open_prompts(dialogs); @@ -551,34 +526,26 @@ impl FilePanels { /// Drains the requests the service queued into the native panels' queue. A request that finds /// a forced answer waiting takes it instead of a panel; those answers are returned for the - /// caller to settle. A ticket forgotten before it got here leaves the forced answer for the - /// next request. - fn start_requests(&mut self) -> Vec<(PickId, Answer, Source)> { + /// caller to settle. + fn start_requests(&mut self) -> Vec<(PickId, Answer)> { let mut forced = Vec::new(); while let Ok((id, request)) = self.requests.try_recv() { -<<<<<<< HEAD - let folder = { - let mut inner = lock(&self.inner); - if inner.pending.contains_key(&id) - && let Some(answer) = inner.forced.pop_front() - { - forced.push((id, answer, Source::Forced)); - continue; - } - inner.last_folder.get(&request.purpose).cloned() - }; - let dialog = self.file_dialog(&request, folder.as_deref()); - self.dialogs.ask(dialog, id); -======= - self.ask_panel(id, &request); ->>>>>>> origin/next + match self.forced_answer(id) { + Some(answer) => forced.push((id, answer)), + None => self.ask_panel(id, &request), + } } forced } - /// The answers the native panels gave since the last call. - fn panel_answers(&mut self) -> Vec<(PickId, Answer, Source)> { - self.dialogs.take_answers().into_iter().map(|(id, answer)| (id, answer, Source::Panel)).collect() + /// The oldest answer [`Files::answer_next`] gave, taken for pick `id`. A ticket forgotten + /// before it got here takes none, which leaves the answer for the next request. + fn forced_answer(&self, id: PickId) -> Option { + let mut inner = lock(&self.inner); + if !inner.pending.contains_key(&id) { + return None; + } + inner.forced.pop_front() } /// Queues the native panel of pick `id`. @@ -665,20 +632,13 @@ impl FilePanels { /// Turns a panel answer into the pick's answer: `Cancelled` stays, `Paths` for Save go through /// the policy and guard, `Unavailable` stays `Unavailable` with the cause, and a `Cancelled` on a /// system where the probe found no dialog backend becomes `Unavailable` with the probe's -<<<<<<< HEAD - /// cause when a panel gave it. A Save that needs the replace - /// question stays pending and returns the question for the caller to ask. - fn finish(&mut self, id: PickId, answer: Answer, source: Source) -> Option { - let pending = lock(&self.inner).pending.remove(&id)?; - let picked = match (answer, pending.awaiting_replace) { -======= /// cause. A Save that needs the replace /// question stays pending and returns the question for the caller to ask. `from_panel` says a - /// native panel answered, not the fallback chooser, whose Cancel is always the user's. + /// native panel answered, not the fallback chooser, whose Cancel is always the user's, nor a + /// forced answer ([`Files::answer_next`]), whose Cancel is the caller's. fn finish(&mut self, id: PickId, answer: Answer, from_panel: bool) -> Option { let Pending { request, awaiting_replace, bytes } = lock(&self.inner).pending.remove(&id)?; let picked = match (answer, awaiting_replace) { ->>>>>>> origin/next (Answer::Message(result), Some(question)) => { let replace = matches!(&result, MessageResult::Ok) || matches!(&result, MessageResult::Custom(label) if *label == self.replace_words.replace); @@ -701,11 +661,7 @@ impl FilePanels { (Answer::Unavailable(why), _) => Picked::Unavailable(why), // A panel that answers nothing on a system without a dialog backend did not get // cancelled; the probe knows why. -<<<<<<< HEAD - (Answer::Cancelled, None) if source == Source::Panel => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable), -======= (Answer::Cancelled, None) if from_panel => (self.backend_problem)().map_or(Picked::Cancelled, Picked::Unavailable), ->>>>>>> origin/next (Answer::Cancelled | Answer::Message(_), _) => Picked::Cancelled, }; self.complete(id, request, picked, bytes); @@ -773,26 +729,8 @@ impl Files for FileService { inner.answered.remove(at).map(|a| a.picked) } -<<<<<<< HEAD - /// Answers the next pick with `picked` instead of showing a panel, through the settling a native answer passes. - /// `Picked::Contents` has no `Answer` form: it is `Err(FileError::Unsupported)`. - fn answer_next(&self, picked: Picked) -> Result<(), FileError> { - let answer = match picked { - Picked::Paths(paths) => Answer::Paths(paths), - Picked::Cancelled => Answer::Cancelled, - Picked::Unavailable(why) => Answer::Unavailable(why), - // A native service reads paths; it has no file contents to hand over. - Picked::Contents(_) => return Err(FileError::Unsupported), - }; - lock(&self.inner).forced.push_back(answer); - Ok(()) - } - - // A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by `finish`. -======= // A ticket still pending leaves `pending`, so the answer the panel gives later is dropped by // `finish`, and the next pump closes its portal Save (`cancel_forgotten`). ->>>>>>> origin/next fn forget(&self, id: PickId) { let mut inner = lock(&self.inner); inner.pending.remove(&id); @@ -809,19 +747,14 @@ impl Files for FileService { std::fs::read(path).map_err(|e| file_error(e, path)) } -<<<<<<< HEAD - // pc: apps/photocraft/src/services.rs:359 write_atomic // A desktop app has no host page: every intent writes the path, and no page took the bytes. fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result { - craft_atomic::atomic_write(path, bytes).map_err(|e| file_error(e, path))?; + write_file(path, bytes)?; Ok(false) } fn exists(&self, path: &Path) -> bool { path.exists() -======= - fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> { - write_file(path, bytes) } /// Queues a Save pick, then writes `bytes` to the settled path and answers `Paths` or @@ -836,12 +769,26 @@ impl Files for FileService { fn browser_saves(&self) -> bool { false ->>>>>>> origin/next } fn last_folder(&self, purpose: &str) -> Option { self.inner.lock().unwrap_or_else(|e| e.into_inner()).last_folder.get(purpose).cloned() } + + /// Answers the next pick with `picked` instead of showing a panel, through the settling a native answer passes. + /// `Picked::Contents`, `Failed` and `Downloaded` have no `Answer` form: they are `Err(FileError::Unsupported)`. + fn answer_next(&self, picked: Picked) -> Result<(), FileError> { + let answer = match picked { + Picked::Paths(paths) => Answer::Paths(paths), + Picked::Cancelled => Answer::Cancelled, + Picked::Unavailable(why) => Answer::Unavailable(why), + // A native service reads paths; it has no file contents to hand over, and a write's + // outcome is its own to report. + Picked::Contents(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(FileError::Unsupported), + }; + lock(&self.inner).forced.push_back(answer); + Ok(()) + } } #[cfg(test)] @@ -1002,22 +949,6 @@ pub(crate) mod service_tests { let _ = std::fs::remove_dir_all(&dir); } -<<<<<<< HEAD - // `FileService::exists` checks the real file system, so batch writers on desktop see files already on disk. - #[trial] - fn exists_checks_the_file_system() { - let dir = std::env::temp_dir().join(format!("craft-dialogs-exists-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let present = dir.join("present.pdf"); - let missing = dir.join("missing.pdf"); - let _ = std::fs::remove_file(&present); - let _ = std::fs::remove_file(&missing); - let (service, _panels) = FileService::new(Wake::none()); - assert!(!service.exists(&present)); - assert_eq!(service.write(&present, b"data", WriteIntent::SaveAs), Ok(false)); - assert!(service.exists(&present)); - assert!(!service.exists(&missing)); -======= // A save is a ticketed pick that writes: the answer names the written file once; a target // that cannot be written answers `Failed`, which names no path. #[trial] @@ -1112,7 +1043,23 @@ pub(crate) mod service_tests { assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("PHOTO.PNG")]), "the existing file is replaced"); assert_eq!(log.borrow().len(), 1, "no second question: the panel asked about this file"); assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("Other.png")]), "a new file is lowercased"); ->>>>>>> origin/next + let _ = std::fs::remove_dir_all(&dir); + } + + // `FileService::exists` checks the real file system, so batch writers on desktop see files already on disk. + #[trial] + fn exists_checks_the_file_system() { + let dir = std::env::temp_dir().join(format!("craft-dialogs-exists-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let present = dir.join("present.pdf"); + let missing = dir.join("missing.pdf"); + let _ = std::fs::remove_file(&present); + let _ = std::fs::remove_file(&missing); + let (service, _panels) = FileService::new(Wake::none()); + assert!(!service.exists(&present)); + assert_eq!(service.write(&present, b"data", WriteIntent::SaveAs), Ok(false)); + assert!(service.exists(&present)); + assert!(!service.exists(&missing)); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/host/src/files.rs b/crates/host/src/files.rs index cdd73c7b3f..27df20f68e 100644 --- a/crates/host/src/files.rs +++ b/crates/host/src/files.rs @@ -301,14 +301,6 @@ pub trait Files: Send + Sync { } /// The folder the last answered pick of `purpose` chose. fn last_folder(&self, purpose: &str) -> Option; -<<<<<<< HEAD - /// Answers the next pick, or the oldest pick still open, with `picked` instead of showing a - /// picker; the answer arrives through [`take_answer`](Files::take_answer) on a later pass. - fn answer_next(&self, picked: Picked) -> Result<(), FileError> { - let _ = picked; - Err(FileError::Unsupported) - } -======= /// Queues a save of `bytes` as ticket `request`'s answer, taken with /// [`take_answer`](Files::take_answer): the desktop service asks for the path, then writes /// atomically; the browser service opens the save picker or makes one download. Counted in @@ -318,7 +310,12 @@ pub trait Files: Send + Sync { fn can_pick(&self) -> bool; /// Whether [`save`](Files::save) hands the bytes to the browser instead of writing a path. fn browser_saves(&self) -> bool; ->>>>>>> origin/next + /// Answers the next pick, or the oldest pick still open, with `picked` instead of showing a + /// picker; the answer arrives through [`take_answer`](Files::take_answer) on a later pass. + fn answer_next(&self, picked: Picked) -> Result<(), FileError> { + let _ = picked; + Err(FileError::Unsupported) + } } /// No pickers (every pick answers `Cancelled`); reads and writes go to the file system. The @@ -432,12 +429,10 @@ struct ScriptState { open: Vec<(PickId, PickRequest)>, answered: Vec, files: HashMap>, -<<<<<<< HEAD /// Paths a write to is refused ([`ScriptedFiles::failing_writes`]). refused: HashSet, /// The path of every write that took, in order ([`ScriptedFiles::written`]). written: Vec, -======= /// The bytes of the saves not answered yet, written to the chosen path with the answer. saves: HashMap>, /// Stands in for a browser host. @@ -455,7 +450,6 @@ impl ScriptState { } self.answered.push(PickAnswer { id, request, picked }); } ->>>>>>> origin/next } impl ScriptedFiles { @@ -575,14 +569,9 @@ impl ScriptedFiles { let picked = if state.held { state.queued.pop_front() } else { Some(suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled)) }; match picked { - Some(picked) => state.answered.push(PickAnswer { id, request, picked }), + Some(picked) => state.settle(id, request, picked), None => state.open.push((id, request)), } -<<<<<<< HEAD -======= - let picked = suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled); - state.settle(id, request, picked); ->>>>>>> origin/next id } } @@ -635,7 +624,7 @@ impl Files for ScriptedFiles { let mut state = self.state(); if state.held && !state.open.is_empty() { let (id, request) = state.open.remove(0); - state.answered.push(PickAnswer { id, request, picked }); + state.settle(id, request, picked); } else { state.queued.push_back(picked); } diff --git a/crates/i18n/src/date.rs b/crates/i18n/src/date.rs index 497dd22562..502439a24e 100644 --- a/crates/i18n/src/date.rs +++ b/crates/i18n/src/date.rs @@ -381,17 +381,14 @@ impl PartsWrite for Spliced { impl DateFormat { /// The format for `region`'s time locale and clock. pub fn new(region: &Region) -> DateFormat { -<<<<<<< HEAD - Self { locale: region.time.clone(), hour_cycle: region.hour_cycle, latin_digits: false, week_start: None, cache: Arc::default() } -======= Self { locale: region.time.clone(), hour_cycle: region.hour_cycle, latin_digits: false, + week_start: None, cache: Arc::default(), generation: crate::words::next_generation(), } ->>>>>>> origin/next } /// This format writing `0`–`9` for [`Digits::Latin`], else the locale's own digits. Formatters @@ -406,9 +403,10 @@ impl DateFormat { self.generation } - /// This format with weeks starting on `day` in place of the region's. + /// This format with weeks starting on `day` in place of the region's. It lays weeks out + /// differently, so it is a new [`generation`](Self::generation). pub fn with_first_weekday(self, day: Weekday) -> DateFormat { - DateFormat { week_start: Some(day), ..self } + DateFormat { week_start: Some(day), generation: crate::words::next_generation(), ..self } } /// The format for a locale tag (`de-CH`), with the locale's clock. @@ -535,9 +533,8 @@ impl DateFormat { }); // 2026-10-26 is a Monday; the week runs on into November (October has 31 days). let monday = CalendarDate { year: 2026, month: 10, day: 26 }; - let weekdays = ["ccccc", "ccc", "cccccc", "cccc"].map(|pattern| { - std::array::from_fn(|i| name(pattern, monday.add_days(i as i64)).unwrap_or_default()) - }); + let weekdays = ["ccccc", "ccc", "cccccc", "cccc"] + .map(|pattern| std::array::from_fn(|i| name(pattern, monday.add_days(i as i64)).unwrap_or_default())); Some(Names { months, weekdays }) }) .as_ref() diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml index e4a6efe472..128c8f27e1 100644 --- a/crates/platform/Cargo.toml +++ b/crates/platform/Cargo.toml @@ -13,15 +13,6 @@ workspace = true [features] default = [] -<<<<<<< HEAD -appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows"] -browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"] -======= -# `appearance`: also Windows' UI settings and macOS' accessibility display setting (reduced motion). -appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"] -# `browser`: downloads, and the file picker and save through `rfd`. -browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys", "dep:rfd", "dep:wasm-bindgen-futures"] ->>>>>>> origin/next # `SystemReader::report_contrast` and `report_reduced_motion`: preferences a test sets in place of an OS source. testing = ["appearance"] # Moving the system pointer (a scrub's screen-edge wrap). @@ -45,7 +36,7 @@ craft-atomic = { workspace = true } craft-docpath = { workspace = true } craft-host = { workspace = true } craft-i18n = { workspace = true } -serde ={ workspace = true } +serde = { workspace = true } serde_json = { workspace = true } # Version eframe already pulls in; image data only (no default features beyond it). @@ -83,8 +74,6 @@ clipboard-win = { version = "5.3.1", features = ["std"], optional = true } # The system's reduced-motion setting (`UISettings`). windows = { version = "0.62", features = ["UI_ViewManagement"], optional = true } xcap = { version = "=0.9.8", optional = true } -# WinRT's `UISettings::AnimationsEnabled` for the appearance watcher's reduced motion, without `unsafe` (MIT OR Apache-2.0). -windows = { version = "0.62", default-features = false, features = ["std", "UI_ViewManagement"], optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = { version = "0.2", optional = true } diff --git a/crates/platform/README.md b/crates/platform/README.md index 477ad2af50..36b1453652 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -10,23 +10,14 @@ pull in heavier dependencies. | always (not wasm) | `dialogs`: reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. | | always | `From for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. | | `pointer` | Move the system pointer (`pointer::warp`), installed by the app as craft-ui's `Scrub::install_warp` service for a scrub's screen-edge wrap; macOS only, `false` elsewhere. | -<<<<<<< HEAD -| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, GNOME's text scale, button layout); Windows' Animation effects setting as reduced motion; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. | -| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking. | -======= -| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, button layout); reduced motion on Windows and macOS; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. | +| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, GNOME's text scale, button layout); reduced motion on Windows and macOS; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. | | `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking; the file picker and save. | ->>>>>>> origin/next | always | `clock::Clock`: monotonic seconds (`web-time`, so also in the browser) for animation, autosave and deadlines, with a manual mode tests set and advance; `monotonic_ms`, `unix_ms`. | | always | `pacing`: `FrameCap` (desktop frame-rate cap without vsync), `WindowVisibility` (shown or hidden), `WorkBudget`/`WorkSlice` (background work per call, paused or sliced while hidden). No egui. | | always | The app log: `log` records to standard error and `/.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log (redacted message, written to standard error only when no logger takes errors), last panic for the error window, and `catch`. | | always | `session::Session` and `SessionKeeper`: the documents open at the last quit and where the user was in each, stored in the app's settings (serde) for a "Reopen Last Session" preference; `to_reopen` skips what is already open; a stored list longer than 64 documents is cut. No egui. | | `usage` | `usage::sample`: the process's resident memory and the memory it may still use (`MemorySample`, `None` when unknown), for the status readout's Scratch and Efficiency items. Linux reads `/proc`; other platforms return `None`. | -<<<<<<< HEAD -| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events, second-instance hand-over and web host feed it): one queue, in arrival order, for files the OS asks the app to open (`open`, as `Intake::Open`), files it asks to open for one of the app's own actions such as combining (`open_for`, as `Intake::OpenFor` with the action's name; made absolute and sorted like `open`), files that arrive as bytes with no path (`open_bytes`, as `Intake::Bytes`), and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window). Each batch stays separate, empty input is ignored, and every sender call wakes the UI. `natural_cmp` and `same_file` for opening order and duplicates; `reveal` (on the caller's thread; on Linux and BSD it can wait up to 2 s for the file manager, so hosts run it on their `Jobs`) and `open_external` (on the web, a new tab without `window.opener`); the shared open-error texts. No egui. | -======= -| always | `open::FileIntake` with `IntakeSender` (OS open requests, second-instance hand-over and `IntakeSender::dropped` and `quit` feed it; `open::apple_events` under `apple-events` on macOS): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. | ->>>>>>> origin/next +| always | `open::FileIntake` with `IntakeSender` (OS open requests, second-instance hand-over, the web host and `IntakeSender::dropped` and `quit` feed it; `open::apple_events` under `apple-events` on macOS): one queue, in arrival order, for files the OS asks the app to open (`open`, as `Intake::Open`), files it asks to open for one of the app's own actions such as combining (`open_for`, as `Intake::OpenFor` with the action's name; made absolute and sorted like `open`), files that arrive as bytes with no path (`open_bytes`, as `Intake::Bytes`), files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window) and the OS asking the app to quit (`Intake::Quit`). Each batch stays separate, empty input is ignored, and every sender call wakes the UI. `natural_cmp` and `same_file` for opening order and duplicates; `reveal` (on the caller's thread; on Linux and BSD it can wait up to 2 s for the file manager, so hosts run it on their `Jobs`) and `open_external` (on the web, a new tab without `window.opener`); the shared open-error texts. No egui. | | always | `autosave::Autosave` (the timer: which documents are due, results by revision), `recovery_dir`, `adopt_legacy_recovery` and `RecoveryStore`: the recovery folder of copies with a JSON sidecar each (`RecoveryEntry`, the fields craft-ui's `RecoveryDialog` lists), `AUTOSAVE_FAILED`. The app serializes its documents. | | `clipboard`, `clipboard-system` | `clipboard` has no system crates: `Clipboard`, `EventClipboard` (with `LateOffers`), `MemoryClipboard` and the probe. `clipboard-system` adds `SystemClipboard`. `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads text, HTML, RTF, one bitmap and copied files, and writes one offer; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (the pass clock the host gives it), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote; `holds_ours` asks the backend's owner marker first (`ClipboardBackend::owns`) and compares that flavor's content only when the backend cannot tell. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` and `formats` never read or decode: they list the formats on offer (`offer::formats`: Windows' and macOS' formats, Wayland's MIME types, X11's `TARGETS`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG and PDF flavors are neither written nor read by `SystemClipboard`; RTF is read, and RTF and MathML are written beside arboard's flavors (a write of only unsupported flavors fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. | | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs index f4e9fcb962..380ec9dcff 100644 --- a/crates/platform/src/appearance.rs +++ b/crates/platform/src/appearance.rs @@ -1,12 +1,6 @@ -<<<<<<< HEAD //! Desktop colour, contrast, motion and text-scale preferences and GNOME's window-button layout -//! through the XDG Settings portal, Windows' animation effects setting, plus the browser's contrast -//! and motion media queries on the web. -======= -//! Desktop colour, contrast and motion preferences and GNOME's window-button layout through the -//! XDG Settings portal, the system's animation setting on Windows and macOS, plus the browser's -//! contrast and motion media queries on the web. ->>>>>>> origin/next +//! through the XDG Settings portal, the system's animation setting on Windows and macOS, plus the +//! browser's contrast and motion media queries on the web. //! //! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback, //! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility. @@ -61,27 +55,6 @@ struct Shared { /// `XDG_CURRENT_DESKTOP` names GNOME; read once when the watcher starts. #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] gnome: bool, -<<<<<<< HEAD - #[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] - wake: Box, -} -impl Shared { - /// No answers yet. `settled` is true for a source that has nothing to wait for. - #[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] - fn new(active: bool, settled: bool, wake: Box) -> Self { - Shared { - value: AtomicU8::new(0), - contrast: AtomicU8::new(0), - motion: AtomicU8::new(0), - text_scale: AtomicU32::new(0), - generation: AtomicU64::new(0), - active: AtomicBool::new(active), - settled: Mutex::new(settled), - settled_changed: Condvar::new(), - layout: Mutex::new(None), - icons: Mutex::new(None), - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] -======= #[cfg(not(target_arch = "wasm32"))] wake: Box, } @@ -92,6 +65,7 @@ impl Shared { value: AtomicU8::new(0), contrast: AtomicU8::new(0), motion: AtomicU8::new(0), + text_scale: AtomicU32::new(0), generation: AtomicU64::new(0), active: AtomicBool::new(active), settled: Mutex::new(false), @@ -99,7 +73,6 @@ impl Shared { layout: Mutex::new(None), icons: Mutex::new(None), #[cfg(all(unix, not(target_os = "macos")))] ->>>>>>> origin/next gnome: is_gnome_session(&|k| std::env::var(k).ok()), wake, } @@ -132,18 +105,14 @@ impl Shared { (self.wake)(); } } -<<<<<<< HEAD - #[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] -======= #[cfg(not(target_arch = "wasm32"))] ->>>>>>> origin/next fn publish_code(&self, slot: &AtomicU8, code: u8) { if slot.swap(code, Ordering::AcqRel) != code { self.changed(); } } /// Raises the generation for a value just stored, then wakes an active host. - #[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] + #[cfg(not(target_arch = "wasm32"))] fn changed(&self) { self.generation.fetch_add(1, Ordering::AcqRel); if self.active.load(Ordering::Acquire) { @@ -160,13 +129,9 @@ impl Shared { }, ); } -<<<<<<< HEAD - #[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] -======= #[cfg(not(target_arch = "wasm32"))] ->>>>>>> origin/next fn publish_motion(&self, reduced: bool) { - self.publish_code(&self.motion, motion_code(reduced)); + self.publish_code(&self.motion, if reduced { 2 } else { 1 }); } /// `None` is no scaling: the desktop's value is out of range, or there is none. #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] @@ -201,11 +166,6 @@ impl Shared { } } } -/// The `Shared::motion` code of `reduced`. -#[cfg(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows))] -fn motion_code(reduced: bool) -> u8 { - if reduced { 2 } else { 1 } -} /// An owned subscription. Dropping cancels connection setup, reads, backoff and helper capture, /// and waits at most 100 ms for acknowledgement. Only a finished worker is joined: an OS call /// or caller wake callback can block synchronously, so an exceptional unfinished worker is @@ -234,33 +194,16 @@ impl Watcher { } /// Start observing with explicit control over wake notifications. /// An inactive subscription still updates its cache. Unsupported targets and worker -<<<<<<< HEAD - /// startup failure return `None`; browser targets never start a desktop watcher. On Windows no - /// worker runs: reduced motion is read here and again by [`Watcher::set_active`]. -======= /// startup failure return `None`; browser targets never start a desktop watcher. /// /// Linux and the BSDs subscribe to the XDG Settings portal. Windows and macOS start a worker /// that reads the system's animation setting once a second and answers /// [`reduced_motion`](Self::reduced_motion) only: theme and contrast stay `None` there. ->>>>>>> origin/next pub fn start_active(active: bool, wake: impl Fn() + Send + Sync + 'static) -> Option { #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] { Self::spawn(active, wake, portal::watch) } -<<<<<<< HEAD - #[cfg(windows)] - { - let shared = Shared::new(active, true, Box::new(wake)); - // Stored without a wake: the host reads the first answer when it builds its first frame. - if let Some(reduced) = windows::reduced_motion() { - shared.motion.store(motion_code(reduced), Ordering::Release); - } - Some(Self { shared: Arc::new(shared) }) - } - #[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows)))] -======= #[cfg(any(windows, target_os = "macos"))] { let shared = Arc::new(Shared::new(active, Box::new(wake))); @@ -268,7 +211,6 @@ impl Watcher { Some(Self { shared, worker: Worker::Native { stop, finished, thread: Some(thread) } }) } #[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows, target_os = "macos")))] ->>>>>>> origin/next { let _ = (active, wake); None @@ -313,15 +255,8 @@ impl Watcher { /// without a desktop watcher. /// /// It comes over the same connection as the theme, a change runs the same wake callback, and -<<<<<<< HEAD - /// [`Watcher::wait_first`] returns after the first read of it. macOS has no watcher and the - /// Windows one reads only reduced motion: their other settings need platform bindings that - /// call `unsafe` code, which this crate forbids. - /// On the web use `browser_contrast`. -======= /// [`Watcher::wait_first`] returns after the first read of it. Always `None` on Windows and /// macOS, whose watcher reads the animation setting only. On the web use `browser_contrast`. ->>>>>>> origin/next pub fn contrast(&self) -> Option { match self.shared.contrast.load(Ordering::Acquire) { 1 => Some(Contrast::Standard), @@ -329,16 +264,7 @@ impl Watcher { _ => None, } } -<<<<<<< HEAD - /// Whether the desktop asks for reduced motion, from the portal's `org.freedesktop.appearance` - /// `reduced-motion`, or GNOME's `org.gnome.desktop.interface` `enable-animations` (inverted) - /// when the portal has no `reduced-motion` key; on Windows, the inverse of the Animation effects - /// setting (`UISettings::AnimationsEnabled`), read at start and by [`Watcher::set_active`]. - /// `None` until one answers, when neither key exists or WinRT can't be asked, and on targets - /// without a desktop watcher. -======= /// Whether the system asks for reduced motion. ->>>>>>> origin/next /// /// - Linux and the BSDs: three portal keys, combined so that any one asking for reduced /// motion wins: `org.freedesktop.appearance` `reduced-motion` (1), GNOME's @@ -389,15 +315,9 @@ impl Watcher { self.current() } /// Enable or suppress future change notifications without stopping observation. - /// Changing this flag does not clear the cached preference. On Windows, becoming active reads - /// reduced motion again, since the user changes it in Settings while the app is in the - /// background; a changed answer raises the generation and wakes the host. + /// Changing this flag does not itself wake the host or clear the cached preference. pub fn set_active(&self, active: bool) { self.shared.active.store(active, Ordering::Release); - #[cfg(windows)] - if active && let Some(reduced) = windows::reduced_motion() { - self.shared.publish_motion(reduced); - } } #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] fn spawn + 'static>( @@ -405,11 +325,7 @@ impl Watcher { wake: impl Fn() + Send + Sync + 'static, source: impl FnOnce(Arc) -> F + Send + 'static, ) -> Option { -<<<<<<< HEAD - let shared = Arc::new(Shared::new(active, false, Box::new(wake))); -======= let shared = Arc::new(Shared::new(active, Box::new(wake))); ->>>>>>> origin/next let worker_shared = Arc::clone(&shared); let (stop, stopped) = async_channel::bounded::<()>(1); let (done, finished) = std::sync::mpsc::channel(); @@ -509,5 +425,3 @@ mod files; mod native; #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod portal; -#[cfg(windows)] -mod windows; diff --git a/crates/platform/src/appearance/portal.rs b/crates/platform/src/appearance/portal.rs index 5763891ffa..3e7675d29e 100644 --- a/crates/platform/src/appearance/portal.rs +++ b/crates/platform/src/appearance/portal.rs @@ -18,16 +18,13 @@ const ICONS_KEY: &str = "icon-theme"; const CONTRAST_KEY: &str = "contrast"; const MOTION_KEY: &str = "reduced-motion"; const ANIMATIONS_KEY: &str = "enable-animations"; -<<<<<<< HEAD +const KDE: &str = "org.kde.kdeglobals.KDE"; +const KDE_MOTION_KEY: &str = "AnimationDurationFactor"; // Read on GNOME-like sessions only (`Shared::gnome`): elsewhere the schema's key holds its default // or a GNOME session's value, not what this desktop applies to its own text. const TEXT_SCALE_KEY: &str = "text-scaling-factor"; /// The text scales applied; outside them a desktop's factor is no scaling, never clamped. const TEXT_SCALES: std::ops::RangeInclusive = 0.5..=3.0; -======= -const KDE: &str = "org.kde.kdeglobals.KDE"; -const KDE_MOTION_KEY: &str = "AnimationDurationFactor"; ->>>>>>> origin/next const TIMEOUT: Duration = Duration::from_secs(2); // Outer None means unknown/malformed; Some(None) is an explicit no-preference answer. @@ -167,25 +164,27 @@ pub(super) struct Fallbacks { theme_used: bool, layout_used: bool, icons_used: bool, -<<<<<<< HEAD - text_scale_used: bool, -======= motion_used: bool, ->>>>>>> origin/next + text_scale_used: bool, path: Option, /// `$XDG_CONFIG_HOME`, or `~/.config` when that is empty or unset. config_home: Option, } impl Fallbacks { fn from_env() -> Self { -<<<<<<< HEAD - Self { theme_used: false, layout_used: false, icons_used: false, text_scale_used: false, path: std::env::var_os("PATH") } -======= let config_home = std::env::var_os("XDG_CONFIG_HOME") .filter(|dir| !dir.is_empty()) .map(PathBuf::from) .or_else(|| std::env::var_os("HOME").filter(|home| !home.is_empty()).map(|home| PathBuf::from(home).join(".config"))); - Self { theme_used: false, layout_used: false, icons_used: false, motion_used: false, path: std::env::var_os("PATH"), config_home } + Self { + theme_used: false, + layout_used: false, + icons_used: false, + motion_used: false, + text_scale_used: false, + path: std::env::var_os("PATH"), + config_home, + } } /// The settings files' motion answer, for a session with no bus or a portal that knows none /// of the three motion keys. @@ -196,7 +195,6 @@ impl Fallbacks { if let Some(reduced) = self.config_home.as_deref().and_then(reduced_motion_from_files) { shared.publish_motion(reduced); } ->>>>>>> origin/next } async fn get(&self, schema: &str, key: &str) -> Option { let exe = gsettings_exe(self.path.as_deref())?; @@ -328,16 +326,12 @@ impl Answers { shared.publish_contrast(contrast); } } -<<<<<<< HEAD (GNOME, TEXT_SCALE_KEY) if shared.gnome => { if let Some(scale) = decode_text_scale(value) { shared.publish_text_scale(scale); } } - (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) => { -======= (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) | (KDE, KDE_MOTION_KEY) => { ->>>>>>> origin/next let Some(reduced) = decode_motion(namespace, value) else { return }; match namespace { STANDARD => self.motion = Some(reduced), @@ -400,50 +394,31 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: subscribe(&connection, rule(CONTRAST_KEY), 8).await?, subscribe(&connection, rule(MOTION_KEY), 8).await?, subscribe(&connection, rule(ANIMATIONS_KEY), 8).await?, -<<<<<<< HEAD + subscribe(&connection, rule(KDE_MOTION_KEY), 8).await?, subscribe(&connection, rule(TEXT_SCALE_KEY), 8).await?, ]; let mut owners = subscribe(&connection, owner_rule(), 8).await?; // Concurrent reads, so contrast, motion and text scale are known by the time the theme // settles `wait_first` without adding round trips before it. - let (((standard, gnome), (contrast, (motion, gnome_motion))), text_scale) = zip( + let (((standard, gnome), (contrast, (motion, gnome_motion, kde_motion))), text_scale) = zip( zip( zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)), - zip( - read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), - zip( - read_with(&connection, STANDARD, MOTION_KEY, |value, legacy| motion_reply(STANDARD, value, legacy)), - read_with(&connection, GNOME, ANIMATIONS_KEY, |value, legacy| motion_reply(GNOME, value, legacy)), - ), - ), + zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)), ), async { if shared.gnome { read_with(&connection, GNOME, TEXT_SCALE_KEY, text_scale_reply).await } else { None } }, -======= - subscribe(&connection, rule(KDE_MOTION_KEY), 8).await?, - ]; - let mut owners = subscribe(&connection, owner_rule(), 8).await?; - // Concurrent reads, so contrast and motion are known by the time the theme settles - // `wait_first` without adding round trips before it. - let ((standard, gnome), (contrast, (motion, gnome_motion, kde_motion))) = zip( - zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)), - zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)), ->>>>>>> origin/next ) .await; let mut answers = Answers { standard, gnome, motion, gnome_motion, kde_motion }; if let Some(contrast) = contrast { shared.publish_contrast(contrast); } -<<<<<<< HEAD - answers.publish_motion(shared); - if let Some(scale) = text_scale { - shared.publish_text_scale(scale); -======= match answers.reduced_motion() { Some(reduced) => shared.publish_motion(reduced), // A portal that knows none of the keys (a bare window manager's) leaves the files to answer. None => fallbacks.motion(shared), ->>>>>>> origin/next + } + if let Some(scale) = text_scale { + shared.publish_text_scale(scale); } match combined(standard, gnome) { Some(answer) => { @@ -467,12 +442,10 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: Some(icons) => shared.publish_icons(icons), None => fallbacks.icons(shared).await, } -<<<<<<< HEAD // A portal without GNOME's keys answered nothing for the text scale either. if text_scale.is_none() { fallbacks.text_scale(shared).await; } -======= follow(shared, &connection, &mut settings, &mut owners, &mut answers).await } /// Follows the settings after the first read until the portal's owner goes away or a stream ends. @@ -483,7 +456,6 @@ async fn follow( owners: &mut zbus::MessageStream, answers: &mut Answers, ) -> Option<()> { ->>>>>>> origin/next loop { let message = match next_event(settings, owners).await? { Event::Owner(message) => { diff --git a/crates/platform/src/clipboard/backend.rs b/crates/platform/src/clipboard/backend.rs index 890a8dd149..7dce1f0af9 100644 --- a/crates/platform/src/clipboard/backend.rs +++ b/crates/platform/src/clipboard/backend.rs @@ -2,10 +2,6 @@ use std::path::PathBuf; -<<<<<<< HEAD -use super::convert::{parse_uri_list, rgba8_flavor, rgba8_image, trim_cr, uri_list}; -use super::types::{BITMAP, ClipboardError, ClipboardImage, Flavor, HTML, PNG, RGBA8, TEXT, URI_LIST}; -======= #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] use super::convert::{trim_cr, uri_list}; #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] @@ -13,7 +9,6 @@ use super::offer; #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] use super::types::{BITMAP, HTML, RGBA8, RTF, TEXT, URI_LIST}; use super::types::{ClipboardError, ClipboardImage, Flavor}; ->>>>>>> origin/next /// What a write did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -162,249 +157,7 @@ pub(super) fn present(read: Result, unconvertible: bool) - } } -<<<<<<< HEAD -/// Whether the system clipboard offers a format, asked of the system without reading or decoding -/// any content: Windows `IsClipboardFormatAvailable`, macOS the pasteboard's type list, Wayland -/// the offer's MIME types (`wl_clipboard_rs::paste::get_mime_types`), X11 a `TARGETS` request. -/// -/// The macOS and Windows code is not built on the Linux box; it is a few lines each and needs a -/// check on those systems. -#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] -mod presence { - #[cfg(any(windows, target_os = "macos"))] - use super::{BITMAP, HTML, RGBA8, TEXT, URI_LIST}; - - pub(super) struct Presence { - #[cfg(any(windows, target_os = "macos"))] - _system: (), - #[cfg(not(any(windows, target_os = "macos")))] - x11: Option, - } - - #[cfg(windows)] - impl Presence { - pub(super) fn new() -> Self { - Self { _system: () } - } - - pub(super) fn any(&mut self, mimes: &[&str]) -> bool { - use clipboard_win::{formats, is_format_avail, register_format}; - let registered = |name: &str| register_format(name).is_some_and(|format| is_format_avail(format.get())); - mimes.iter().any(|&mime| match mime { - TEXT => is_format_avail(formats::CF_UNICODETEXT), - HTML => registered("HTML Format"), - BITMAP | RGBA8 => registered("PNG") || is_format_avail(formats::CF_DIBV5) || is_format_avail(formats::CF_DIB), - URI_LIST => is_format_avail(formats::CF_HDROP), - _ => false, - }) - } - } - - #[cfg(target_os = "macos")] - impl Presence { - pub(super) fn new() -> Self { - Self { _system: () } - } - - pub(super) fn any(&mut self, mimes: &[&str]) -> bool { - use objc2_app_kit::{NSPasteboard, NSPasteboardTypeFileURL, NSPasteboardTypeHTML, NSPasteboardTypeString, NSPasteboardTypeTIFF}; - // `types` lists the formats on offer; no item's data is fetched. - let Some(types) = (unsafe { NSPasteboard::generalPasteboard().types() }) else { return false }; - mimes.iter().any(|&mime| { - // Safety: the pasteboard type constants are valid for the life of the process. - let wanted = unsafe { - match mime { - TEXT => NSPasteboardTypeString, - HTML => NSPasteboardTypeHTML, - BITMAP | RGBA8 => NSPasteboardTypeTIFF, - URI_LIST => NSPasteboardTypeFileURL, - _ => return false, - } - }; - types.iter().any(|offered| offered.isEqualToString(wanted)) - }) - } - } - - /// Linux and BSD. Wayland when `WAYLAND_DISPLAY` is set and the compositor has a data-control - /// protocol, else X11: the order arboard picks its own backend in. - #[cfg(not(any(windows, target_os = "macos")))] - impl Presence { - pub(super) fn new() -> Self { - Self { x11: None } - } - - pub(super) fn any(&mut self, mimes: &[&str]) -> bool { - let offered = self.offered(); - mimes.iter().any(|&mime| super::offered_has(&offered, mime)) - } - - fn offered(&mut self) -> Vec { - use wl_clipboard_rs::paste::{ClipboardType, Error, Seat, get_mime_types}; - if std::env::var_os("WAYLAND_DISPLAY").is_some() { - match get_mime_types(ClipboardType::Regular, Seat::Unspecified) { - Ok(types) => return types.into_iter().collect(), - // Nothing is copied. - Err(Error::NoSeats | Error::ClipboardEmpty | Error::NoMimeType) => return Vec::new(), - Err(error) => log::debug!("no Wayland data control for the clipboard probe, trying X11: {error}"), - } - } - if self.x11.is_none() { - self.x11 = x11::Targets::connect(); - } - self.x11.as_ref().map(x11::Targets::offered).unwrap_or_default() - } - } - - #[cfg(not(any(windows, target_os = "macos")))] - mod x11 { - use std::time::{Duration, Instant}; - - use x11rb::connection::Connection; - use x11rb::protocol::Event; - use x11rb::protocol::xproto::{Atom, AtomEnum, ConnectionExt, CreateWindowAux, EventMask, WindowClass}; - use x11rb::rust_connection::RustConnection; - use x11rb::{COPY_DEPTH_FROM_PARENT, CURRENT_TIME, NONE}; - - /// How long a `TARGETS` request waits for the owner. The probe's worker waits, not the UI. - const ANSWER_WAIT: Duration = Duration::from_millis(250); - - /// A connection and a window that receive the clipboard owner's `TARGETS` answer. - pub(super) struct Targets { - conn: RustConnection, - window: u32, - clipboard: Atom, - targets: Atom, - property: Atom, - } - - impl Targets { - pub(super) fn connect() -> Option { - let (conn, screen) = RustConnection::connect(None).ok()?; - let root = conn.setup().roots.get(screen)?.root; - let window = conn.generate_id().ok()?; - conn.create_window( - COPY_DEPTH_FROM_PARENT, - window, - root, - 0, - 0, - 1, - 1, - 0, - WindowClass::INPUT_OUTPUT, - 0, - &CreateWindowAux::new().event_mask(EventMask::PROPERTY_CHANGE), - ) - .ok()?; - let atom = |name: &[u8]| conn.intern_atom(false, name).ok()?.reply().ok().map(|reply| reply.atom); - let (clipboard, targets, property) = (atom(b"CLIPBOARD")?, atom(b"TARGETS")?, atom(b"CRAFT_CLIPBOARD_TARGETS")?); - Some(Self { conn, window, clipboard, targets, property }) - } - - /// The target names the CLIPBOARD owner offers; none when nobody owns it or answers. - pub(super) fn offered(&self) -> Vec { - self.ask().unwrap_or_default() - } - - fn ask(&self) -> Option> { - self.conn.delete_property(self.window, self.property).ok()?; - self.conn.convert_selection(self.window, self.clipboard, self.targets, self.property, CURRENT_TIME).ok()?; - self.conn.flush().ok()?; - let end = Instant::now() + ANSWER_WAIT; - while Instant::now() < end { - match self.conn.poll_for_event().ok()? { - Some(Event::SelectionNotify(event)) if event.selection == self.clipboard => { - if event.property == NONE { - return None; - } - let reply = - self.conn.get_property(true, self.window, self.property, AtomEnum::ATOM, 0, u32::MAX / 4).ok()?.reply().ok()?; - let atoms: Vec = reply.value32()?.collect(); - return Some( - atoms - .into_iter() - .filter_map(|atom| { - let name = self.conn.get_atom_name(atom).ok()?.reply().ok()?.name; - String::from_utf8(name).ok() - }) - .collect(), - ); - } - Some(_) => {} - None => std::thread::sleep(Duration::from_millis(1)), - } - } - None - } - } - } -} - -/// Whether the target or MIME names a clipboard `offered` contain a format that [`SystemClipboard`] -/// can read as `mime`. Text includes the X11 text targets; a bitmap is `image/png`, the only -/// bitmap arboard reads on Linux. -#[allow(dead_code, reason = "only the Linux and BSD probe maps names")] -pub(crate) fn offered_has(offered: &[String], mime: &str) -> bool { - let any = |names: &[&str]| offered.iter().any(|offer| names.iter().any(|name| offer.eq_ignore_ascii_case(name))); - match mime { - TEXT => any(&["text/plain", "text/plain;charset=utf-8", "UTF8_STRING", "STRING", "TEXT"]), - HTML => any(&["text/html"]), - BITMAP | RGBA8 => any(&[PNG]), - URI_LIST => any(&[URI_LIST]), - _ => false, - } -} - -/// What a write puts on the system clipboard. -#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] -pub(crate) enum Put { - Clear, - Image(ClipboardImage), - Html { html: String, alt: Option }, - Text(String), - Files(Vec), -} - -/// The first flavor the system clipboard can hold, as its index in `flavors` and what to put -/// there. -#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] -pub(crate) fn plan_write(flavors: &[Flavor], decode: Option<&Decode>) -> Result<(usize, Put), ClipboardError> { - if flavors.is_empty() { - return Ok((0, Put::Clear)); - } - let text_of = |f: &Flavor| String::from_utf8_lossy(&f.data).into_owned(); - for (index, flavor) in flavors.iter().enumerate() { - match &*flavor.mime { - RGBA8 => { - if let Some(image) = rgba8_image(&flavor.data).filter(ClipboardImage::is_whole) { - return Ok((index, Put::Image(image))); - } - } - PNG => { - if let Some(image) = decode.and_then(|decode| decode(&flavor.data)).filter(ClipboardImage::is_whole) { - return Ok((index, Put::Image(image))); - } - } - HTML => return Ok((index, Put::Html { html: text_of(flavor), alt: flavors.iter().find(|f| f.mime == TEXT).map(text_of) })), - TEXT => return Ok((index, Put::Text(text_of(flavor)))), - // Only `file:` URIs become files; a list with none falls through to the next flavour. - URI_LIST => { - let files = parse_uri_list(&text_of(flavor)); - if !files.is_empty() { - return Ok((index, Put::Files(files))); - } - } - _ => {} - } - } - Err(ClipboardError::NoFormat) -} - -#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] -======= #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] ->>>>>>> origin/next impl Default for SystemClipboard { fn default() -> Self { Self::new() @@ -415,26 +168,10 @@ impl Default for SystemClipboard { impl ClipboardBackend for SystemClipboard { // pc: apps/photocraft/src/services.rs:702 clipboard_set_image (open on first use, "clipboard is busy") fn write(&mut self, flavors: &[Flavor]) -> Result { -<<<<<<< HEAD - let (index, put) = plan_write(flavors, self.decode.as_ref())?; - let handle = self.open()?; - match put { - Put::Clear => handle.clear(), - Put::Image(image) => { - handle.set_image(arboard::ImageData { width: image.width as usize, height: image.height as usize, bytes: Cow::Borrowed(&image.rgba) }) - } - Put::Html { html, alt } => handle.set_html(html, alt), - Put::Text(text) => handle.set_text(text), - Put::Files(files) => handle.set().file_list(&files), - } - .map_err(system_error)?; - Ok(index) -======= self.open()?; let Self { handle, offer, decode, owner, .. } = self; let handle = handle.as_mut().ok_or(ClipboardError::Unavailable)?; offer::write(handle, offer, flavors, decode.as_ref(), owner) ->>>>>>> origin/next } // vectorcraft: crates/ui-egui/src/sysclip.rs:27 SystemClipboard::read diff --git a/crates/platform/src/clipboard_tests.rs b/crates/platform/src/clipboard_tests.rs index 15ed66e4c6..a925e881f0 100644 --- a/crates/platform/src/clipboard_tests.rs +++ b/crates/platform/src/clipboard_tests.rs @@ -23,27 +23,6 @@ fn synthetic_input_never_replaces_what_the_user_copied() { assert_eq!(clipboard.read_text().unwrap().as_deref(), Some("mine")); } -<<<<<<< HEAD -// Copied files reach the system clipboard as a file list holding the same paths, spaces and -// non-ASCII names included; a URI that names no local file is never written as one, and a list -// with no file in it leaves the write to the next flavour. -#[cfg(not(target_arch = "wasm32"))] -#[test] -fn a_file_list_is_written_as_files() { - let paths = vec![std::env::temp_dir().join("a b#1.pdf"), std::env::temp_dir().join("café 100%.png")]; - let files = |plan: Result<(usize, Put), ClipboardError>| match plan { - Ok((index, Put::Files(files))) => Some((index, files)), - _ => None, - }; - assert_eq!(files(plan_write(&[Flavor::files(&paths), Flavor::text("names")], None)), Some((0, paths.clone()))); - - let mut mixed = b"# copied\r\nhttps://example.com/a.pdf\r\n".to_vec(); - mixed.extend(Flavor::files(&paths[..1]).data); - assert_eq!(files(plan_write(&[Flavor::new(URI_LIST, mixed)], None)), Some((0, paths[..1].to_vec()))); - - let web = Flavor::new(URI_LIST, b"https://example.com/a.pdf\r\n".to_vec()); - assert!(matches!(plan_write(&[web, Flavor::text("names")], None), Ok((1, Put::Text(text))) if text == "names")); -======= // Copied files arrive as a text/uri-list. A backend that holds the list but answers no files // turns every file paste in tests, and in hosts without a system clipboard, into a no-op. #[test] @@ -54,5 +33,4 @@ fn a_held_uri_list_reads_as_files() { let files = clipboard.read_files().unwrap().unwrap(); assert_eq!(files.len(), 2); assert!(files[0].ends_with("a b.txt") && files[1].ends_with("c.csv")); ->>>>>>> origin/next } diff --git a/crates/platform/src/default_app_tests.rs b/crates/platform/src/default_app_tests.rs index 64b201c69e..1d451ae6b0 100644 --- a/crates/platform/src/default_app_tests.rs +++ b/crates/platform/src/default_app_tests.rs @@ -2,11 +2,6 @@ use crate::default_app::{path_from_arg, rejoin_split_paths}; -<<<<<<< HEAD -// file:///a%20b.pdf and file://localhost/x decode to paths; truncated and invalid escapes are -// kept as written; http://, file://host/x, a bare file://, plain paths and non-UTF-8 escapes pass -// through; file:///C:/x.pdf is C:/x.pdf on Windows. -======= // XDG_DATA_HOME (else ~/.local/share) comes first, then each XDG_DATA_DIRS entry (else // /usr/local/share:/usr/share); relative and empty entries are skipped, and no home is fine. // Absolute here means a Unix path, so the trial runs on Unix. @@ -27,9 +22,9 @@ fn application_dirs_follow_the_xdg_spec() { assert_eq!(application_dirs(Some("rel"), None, Some("also-rel")), [p("/usr/local/share/applications"), p("/usr/share/applications")]); } -// file:///a%20b.pdf and file://localhost/x decode to paths; http://, file://host/x, plain paths -// and non-UTF-8 escapes pass through; file:///C:/x.pdf is C:/x.pdf on Windows. ->>>>>>> origin/next +// file:///a%20b.pdf and file://localhost/x decode to paths; truncated and invalid escapes are +// kept as written; http://, file://host/x, a bare file://, plain paths and non-UTF-8 escapes pass +// through; file:///C:/x.pdf is C:/x.pdf on Windows. #[test] fn file_uris_become_paths() { assert_eq!(path_from_arg("file:///a%20b.pdf".into()), "/a b.pdf"); diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index a77fc1a104..57b4820c82 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -88,7 +88,8 @@ pub enum Intake { /// Where they landed. target: DropTarget, }, -<<<<<<< HEAD + /// The OS asked the app to quit. + Quit, /// The OS asked to open these absolute paths for the app's own action. OpenFor { /// The files, absolute and sorted. @@ -103,10 +104,6 @@ pub enum Intake { /// The contents. bytes: Arc<[u8]>, }, -======= - /// The OS asked the app to quit. - Quit, ->>>>>>> origin/next } /// The sending side of a [`FileIntake`]: `Send + Clone`, for the threads that hear the OS (the @@ -213,7 +210,6 @@ impl IntakeSender { } } -<<<<<<< HEAD /// `paths` made absolute and sorted by [`natural_cmp`] of the path text, the order an OS open request opens in. fn ordered(paths: Vec) -> Vec { let mut paths: Vec = paths.iter().map(|p| absolute(p)).collect(); @@ -221,20 +217,13 @@ fn ordered(paths: Vec) -> Vec { paths } -/// Files waiting to be opened, read once per frame on the UI thread (spec Q-S4F-7). -/// -/// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS, pushes -/// drops from its frame with [`dropped`](Self::dropped), and takes the batches with -/// [`take`](Self::take). An [`Intake::Open`] or [`Intake::OpenFor`] batch comes made absolute and sorted by -======= /// OS requests waiting for the app (files to open, files dropped, quit), read once per frame on /// the UI thread (spec Q-S4F-7). /// /// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS /// (`apple_events::install` on macOS, its single-instance socket elsewhere), pushes drops /// through a sender's [`dropped`](IntakeSender::dropped), and takes the requests with -/// [`take`](Self::take). An [`Intake::Open`] batch comes made absolute and sorted by ->>>>>>> origin/next +/// [`take`](Self::take). An [`Intake::Open`] or [`Intake::OpenFor`] batch comes made absolute and sorted by /// [`natural_cmp`] of the path text; the app focuses documents already open ([`same_file`]) and /// opens the rest, then brings its window to the front (on Wayland, a user-attention request). /// [`Intake::Quit`] closes the app the way its own Quit command does. diff --git a/crates/platform/src/open_tests.rs b/crates/platform/src/open_tests.rs index 6a829f1630..15aa900dd2 100644 --- a/crates/platform/src/open_tests.rs +++ b/crates/platform/src/open_tests.rs @@ -1,6 +1,5 @@ //! `craft_platform::open`. -<<<<<<< HEAD // Requests heard on another thread (a second launch, an Apple Event) reach the UI once each, in // the order they arrived, an open for an action never merged with a plain open, and each wakes // the UI: a lost wake leaves a file unopened until the user moves the mouse. @@ -49,7 +48,8 @@ fn an_intake_delivers_each_batch_once_in_order_and_wakes() { // A relative path is made absolute against the working directory, as for a plain open. intake.sender().open_for(vec![PathBuf::from("rel.pdf")], "print"); assert!(matches!(intake.take().as_slice(), [Intake::OpenFor { paths, .. }] if paths.len() == 1 && paths[0].is_absolute())); -======= +} + // A source whose push calls the wake while holding its own borrow (the Apple-event inbox does) // must not be drained from the wake: the wake only repaints, and the next `take` collects it. #[test] @@ -83,7 +83,6 @@ fn a_request_pushed_while_its_source_is_borrowed_is_taken_on_the_next_take() { let taken = intake.take(); assert!(matches!(taken.as_slice(), [Intake::Open(paths)] if paths.len() == 1), "{taken:?}"); assert!(intake.take().is_empty(), "the source was emptied"); ->>>>>>> origin/next } // The target is one argument after `--` (or the Windows handler), so no shell reads a `&` and no diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index 3ed8f0ad05..9b68122539 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -17,22 +17,15 @@ harness = false suite = ["screen-testing", "craft-ui/suite"] default = [] # The printer and job settings widgets (`craft_print::ui`). -<<<<<<< HEAD -ui = ["dep:craft-behavior", "dep:craft-theme", "dep:craft-ui", "dep:egui", "dep:serde_json"] -======= -ui = ["dep:craft-behavior", "dep:craft-ui", "dep:egui"] ->>>>>>> origin/next +ui = ["dep:craft-behavior", "dep:craft-theme", "dep:craft-ui", "dep:egui"] # The stories and the integration binary of the print panel. screen-testing = ["ui", "craft-ui/testing"] [dependencies] craft-behavior = { workspace = true, optional = true } -<<<<<<< HEAD +craft-host = { workspace = true } # `Tone` for the dialog's refusal notice; craft-ui does not re-export it. craft-theme = { workspace = true, optional = true } -======= -craft-host = { workspace = true } ->>>>>>> origin/next craft-ui = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/print/src/ui/stories.rs b/crates/print/src/ui/stories.rs index e5bf8035af..648eb20937 100644 --- a/crates/print/src/ui/stories.rs +++ b/crates/print/src/ui/stories.rs @@ -11,11 +11,7 @@ use craft_ui::runtime::env::Message; use craft_ui::testing::pictures::sample_picture; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::load::SizedTexture; -<<<<<<< HEAD use egui::{Color32, ColorImage, Pos2, Rect, TextureId, Ui, Vec2, pos2}; -======= -use egui::{Color32, ColorImage, Rect, Ui, Vec2, pos2}; ->>>>>>> origin/next fn printers() -> Vec { vec![ @@ -47,7 +43,7 @@ fn print_panel_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn print_panel_collate_properties(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Settings { copies: 3, collate: false, ..office() }; let printers = printers(); - PrintPanel::new(Bind::bound(data.value("settings", start)), &printers).driver(DriverControls::Properties).show(ui).into() + PrintPanel::new(data.bind("settings", start), &printers).driver(DriverControls::Properties).show(ui).into() } const PICTURE: [usize; 2] = [240, 160]; @@ -82,29 +78,24 @@ fn image_box(sheet: &PrintSheet) -> Rect { #[story(PrintPreview<'static>, covers = [Default])] fn print_preview(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = preview_sheet(ui); -<<<<<<< HEAD - let position = data.value("position", image_box(&sheet).min); - PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into() + let (position, position_at) = data.value_at("position", image_box(&sheet).min); + PrintPreview::new("Print preview", &sheet, position_at.bind(position)).show(ui).into() } /// Four pages on a sheet with borders and cut lines, one still rendering as a stand-in. #[story(PrintPreview<'static>, covers = [])] fn print_preview_pages(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = four_up_sheet(ui); - let position = data.value("position", image_box(&sheet).min); - PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into() + let (position, position_at) = data.value_at("position", image_box(&sheet).min); + PrintPreview::new("Print preview", &sheet, position_at.bind(position)).show(ui).into() } /// A message in place of the sheet. #[story(PrintPreview<'static>, covers = [])] fn print_preview_message(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = PrintSheet::message(LETTER, "The page range selects no pages.".into(), "No pages".into()); - let position = data.value("position", image_box(&sheet).min); - PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into() -======= - let (position, position_at) = data.value_at("position", sheet.image.min); + let (position, position_at) = data.value_at("position", image_box(&sheet).min); PrintPreview::new("Print preview", &sheet, position_at.bind(position)).show(ui).into() ->>>>>>> origin/next } /// The image box hangs over the paper's right edge, a position the host refuses. @@ -112,20 +103,11 @@ fn print_preview_message(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn print_preview_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = preview_sheet(ui); let paper = Rect::from_min_size(pos2(0.0, 0.0), sheet.paper); -<<<<<<< HEAD let size = image_box(&sheet).size(); - let on_paper = move |at: &Pos2| { - if paper.contains_rect(Rect::from_min_size(*at, size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } - }; - let position = data.value("position", pos2(400.0, 156.0)); - PrintPreview::new("Print preview", &sheet, Bind::bound(position).check(on_paper)).show(ui).into() -======= - let size = sheet.image.size(); let position = data.bind("position", pos2(400.0, 156.0)).check_with((paper, size), |(paper, size), at| { if paper.contains_rect(Rect::from_min_size(*at, *size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } }); PrintPreview::new("Print preview", &sheet, position).show(ui).into() ->>>>>>> origin/next } #[story(PrintDialog<'static>, covers = [], drive = Drive::Never)] @@ -146,11 +128,7 @@ fn print_dialog_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn print_dialog_busy(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = sheet(ui, false); -<<<<<<< HEAD - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) - .busy(true) - .show(ui) - .into() + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into() } /// Letter paper in points. @@ -228,7 +206,7 @@ fn print_dialog_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = document_sheet(ui); let sections = [page_handling()]; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .sections(§ions) .ready(true) @@ -242,7 +220,7 @@ fn print_dialog_to_file(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = document_sheet(ui); let start = Settings { destination: Destination::File, ..Settings::default() }; - PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", start), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .ready(true) .show(ui) @@ -257,7 +235,7 @@ fn print_dialog_browser_printer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu printers.push(Printer::new("Browser").own_dialog("The browser's print dialog sets copies, collate, two-sided and colour.")); let sheet = document_sheet(ui); let start = Settings { destination: Destination::Printer("Browser".to_owned()), ..Settings::default() }; - PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", start), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .ready(true) .show(ui) @@ -269,7 +247,7 @@ fn print_dialog_browser_printer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu fn print_dialog_booklet(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = booklet_sheet(ui); - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .duplex_by_layout(true) .ready(true) @@ -283,7 +261,7 @@ fn print_dialog_four_up(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = four_up_sheet(ui); let pager = PanePager { shown: 1, count: 3, back: false, next: true, unit: PagerUnit::Sheet, ..PanePager::default() }; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .preview_pager(pager) .ready(true) @@ -297,7 +275,7 @@ fn print_dialog_message(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = PrintSheet::message(LETTER, "The page range selects no pages.".into(), "No pages".into()); let pager = PanePager { shown: 0, count: 0, back: false, next: false, unit: PagerUnit::Sheet, ..PanePager::default() }; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .preview_pager(pager) .show(ui) @@ -310,7 +288,7 @@ fn print_dialog_last_sheet(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let printers = printers(); let sheet = four_up_sheet(ui); let pager = PanePager { shown: 3, count: 3, back: true, next: false, unit: PagerUnit::Sheet, ..PanePager::default() }; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .preview_pager(pager) .ready(true) @@ -325,7 +303,7 @@ fn print_dialog_folded_section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput let sheet = document_sheet(ui); let comments = PrintSection::new("Comments and Forms", vec![Param::new("comments", "Print comments", ParamKind::bool(false))]).folded(false); let sections = [page_handling().folded(true), comments]; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .sections(§ions) .ready(true) @@ -339,13 +317,10 @@ fn print_dialog_section_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu let printers = printers(); let sheet = document_sheet(ui); let sections = [page_handling().button("pageSetup", "Page Setup…", true).button("resetPaper", "Reset", false)]; - PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet) + PrintDialog::new(data.bind("settings", office()), &printers, Bind::given(DialogFields::default()), &sheet) .layout(PrintLayout::Document) .sections(§ions) .ready(true) .show(ui) .into() -======= - PrintDialog::new(data.bind("settings", start), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into() ->>>>>>> origin/next } diff --git a/crates/print/tests/it/main.rs b/crates/print/tests/it/main.rs index 6ef9e6ec99..2088fa2d66 100644 --- a/crates/print/tests/it/main.rs +++ b/crates/print/tests/it/main.rs @@ -2,11 +2,6 @@ // Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -<<<<<<< HEAD -mod dialog; -mod panel; -mod print; -======= pub(crate) mod dialog; +pub(crate) mod panel; pub(crate) mod print; ->>>>>>> origin/next diff --git a/crates/settings/Cargo.toml b/crates/settings/Cargo.toml index eaf4e7e415..09c039fcd6 100644 --- a/crates/settings/Cargo.toml +++ b/crates/settings/Cargo.toml @@ -28,15 +28,9 @@ web-time = "1.1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] dirs = "7" -<<<<<<< HEAD -# `BrowserFiles`: the web build's settings in localStorage. -[target.'cfg(target_arch = "wasm32")'.dependencies] -web-sys = { version = "0.3", features = ["Window", "Storage"] } -======= # `LocalStorageFiles`: the browser's localStorage. [target.'cfg(target_arch = "wasm32")'.dependencies] web-sys = { version = "0.3", features = ["Storage", "Window"] } ->>>>>>> origin/next [dev-dependencies] craft-settings = { path = ".", features = ["testing"] } diff --git a/crates/settings/src/files.rs b/crates/settings/src/files.rs index 02b75a1d2c..1ff3681bf4 100644 --- a/crates/settings/src/files.rs +++ b/crates/settings/src/files.rs @@ -23,9 +23,9 @@ pub trait SettingsFiles: Send + Sync { /// Replaces the file atomically; a new file is owner-only. fn write(&self, path: &Path, text: &str) -> io::Result<()>; /// Renames a damaged file aside and returns the new path - /// ([`broken_path`](crate::recovery::broken_path)'s naming). + /// ([`move_aside`](crate::recovery::move_aside)'s naming). fn move_aside(&self, path: &Path) -> io::Result; - /// Writes the backup beside `path`, at [`backup_path`](crate::recovery::backup_path). + /// Writes the backup beside `path` ([`write_backup`](crate::recovery::write_backup)'s rules). fn write_backup(&self, path: &Path, text: &str) -> io::Result<()>; /// Makes sure the folder exists before the store checks it. Files that have no folders /// (browser storage) keep the default, which does nothing. @@ -110,70 +110,6 @@ impl SettingsFiles for DiskFiles { } } -<<<<<<< HEAD -/// Settings kept in the browser's localStorage, keyed by path: the files of a web build. -/// -/// Open the store with a [`Location::Dir`](crate::Location::Dir) naming the key root -/// (`config.toml` is stored under `/config.toml`); a storage the browser refuses or a full -/// quota comes back as an error, which the store reports like a disk's. -#[cfg(target_arch = "wasm32")] -#[derive(Clone, Copy, Debug, Default)] -pub struct BrowserFiles; - -#[cfg(target_arch = "wasm32")] -impl BrowserFiles { - /// The page's localStorage; an error where the page has none or the browser blocks it. - fn storage() -> io::Result { - let window = web_sys::window().ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "no browser window"))?; - window.local_storage().map_err(js_error)?.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "browser storage is unavailable")) - } - - /// The storage key of `path`: its text. - fn key(path: &Path) -> io::Result<&str> { - path.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path is not valid text")) - } -} - -#[cfg(target_arch = "wasm32")] -impl SettingsFiles for BrowserFiles { - fn read(&self, path: &Path) -> io::Result> { - Self::storage()?.get_item(Self::key(path)?).map_err(js_error) - } - - fn write(&self, path: &Path, text: &str) -> io::Result<()> { - Self::storage()?.set_item(Self::key(path)?, text).map_err(js_error) - } - - fn move_aside(&self, path: &Path) -> io::Result { - let storage = Self::storage()?; - let key = Self::key(path)?; - let Some(text) = storage.get_item(key).map_err(js_error)? else { - return Err(io::Error::new(io::ErrorKind::NotFound, "nothing to move aside")); - }; - let target = crate::recovery::free_broken_path(path, |target| Ok(storage.get_item(Self::key(target)?).map_err(js_error)?.is_some()))?; - storage.set_item(Self::key(&target)?, &text).map_err(js_error)?; - storage.remove_item(key).map_err(js_error)?; - Ok(target) - } - - fn write_backup(&self, path: &Path, text: &str) -> io::Result<()> { - let backup = crate::recovery::backup_path(path); - Self::storage()?.set_item(Self::key(&backup)?, text).map_err(js_error) - } - - /// Storage has no folders: any key root accepts items while the page has storage at all. - fn check_writable(&self, dir: &Path) -> io::Result<()> { - let _ = dir; - Self::storage().map(drop) - } -} - -/// A browser exception as an I/O error, so the store treats it like a disk's. -#[cfg(target_arch = "wasm32")] -fn js_error(e: impl std::fmt::Debug) -> io::Error { - io::Error::other(format!("browser storage: {e:?}")) -} -======= /// How long a save waits for another process's save to finish before going ahead anyway: a save takes /// milliseconds, and a process stuck holding the lock must not stop this one from saving. #[cfg(not(target_arch = "wasm32"))] @@ -182,7 +118,6 @@ const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2); /// How often a waiting save tries the lock again. #[cfg(not(target_arch = "wasm32"))] const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(10); ->>>>>>> origin/next /// New files are owner-only; on a replace `craft-atomic` keeps the existing file's mode. #[cfg(all(unix, not(target_arch = "wasm32")))] diff --git a/crates/settings/src/lib.rs b/crates/settings/src/lib.rs index 88b1bb9406..7fcd08a10b 100644 --- a/crates/settings/src/lib.rs +++ b/crates/settings/src/lib.rs @@ -54,21 +54,17 @@ pub mod testing; pub use document::MergeRule; pub use error::{LoadReport, MigrateError, ReadOnlyReason, SaveStatus, SectionError, SettingsError, Source, TickResult}; -#[cfg(target_arch = "wasm32")] -pub use files::BrowserFiles; #[cfg(not(target_arch = "wasm32"))] pub use files::DiskFiles; #[cfg(target_arch = "wasm32")] pub use files::LocalStorageFiles; +/// The browser's settings storage under its former name. +#[cfg(target_arch = "wasm32")] +#[deprecated(note = "use `LocalStorageFiles::new(cap)`")] +pub type BrowserFiles = LocalStorageFiles; pub use files::SettingsFiles; pub use migrate::LegacyFile; -<<<<<<< HEAD -#[cfg(not(target_arch = "wasm32"))] -pub use paths::Probe; -pub use paths::{Location, Portable, Resolved, Rule}; -======= pub use paths::{Location, Portable, Probe, Resolved, Rule}; ->>>>>>> origin/next #[cfg(not(target_arch = "wasm32"))] pub use profiles::{ProfileError, Profiles}; pub use remember::{Remembered, RememberedSection}; diff --git a/crates/settings/src/paths.rs b/crates/settings/src/paths.rs index 82ddeeefff..11755e9271 100644 --- a/crates/settings/src/paths.rs +++ b/crates/settings/src/paths.rs @@ -5,16 +5,9 @@ //! `_CONFIG_DIR`, or [`Location::Memory`], means no folder at all: nothing is read or written. //! A portable folder that cannot be created or written to is skipped in favour of the platform //! folder, and the reason comes back in [`Resolved::warning`]. -//! -//! A web build has no environment, executable folder or platform folder, so it has no rules: -//! its location names the key root in browser storage ([`Location::Dir`]) or nothing -//! ([`Location::Memory`]). -#[cfg(not(target_arch = "wasm32"))] use std::ffi::OsString; -#[cfg(not(target_arch = "wasm32"))] -use std::path::Path; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// How an application spells portable mode: the marker files that turn it on (any one, contents /// ignored) and the folder created beside the executable. Comes from [`crate::Settings`], so an @@ -35,8 +28,7 @@ impl Portable { /// Where the application wants its settings. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Location { - /// Apply the rules in order. Native only: the rules read the process and the disk. - #[cfg(not(target_arch = "wasm32"))] + /// Apply the rules in order. Auto, /// Use this folder, no questions asked (a `--config-dir` flag, or a library folder). Dir(PathBuf), @@ -96,11 +88,9 @@ impl Resolved { } /// Reads an environment variable by name. -#[cfg(not(target_arch = "wasm32"))] pub type EnvReader = Box Option>; /// What the rules look at. The defaults read the real process; tests supply their own. -#[cfg(not(target_arch = "wasm32"))] pub struct Probe { /// Reads an environment variable. pub env: EnvReader, @@ -121,9 +111,6 @@ impl Default for Probe { } } -<<<<<<< HEAD -#[cfg(not(target_arch = "wasm32"))] -======= /// A browser has no environment, executable or config folder. #[cfg(target_arch = "wasm32")] impl Default for Probe { @@ -132,7 +119,6 @@ impl Default for Probe { } } ->>>>>>> origin/next impl std::fmt::Debug for Probe { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Probe").field("exe_dir", &self.exe_dir).field("platform_config_dir", &self.platform_config_dir).finish_non_exhaustive() @@ -146,28 +132,8 @@ pub fn env_var_name(app_id: &str) -> String { name } -/// The folder of a location that names it: [`Location::Dir`] and [`Location::Memory`]. `None` for -/// [`Location::Auto`], which the rules decide. -fn given(location: &Location) -> Option { - match location { - Location::Dir(dir) => Some(Resolved::new(Some(dir.clone()), Rule::Override)), - Location::Memory => Some(Resolved::new(None, Rule::Memory)), - #[cfg(not(target_arch = "wasm32"))] - Location::Auto => None, - } -} - -/// The folder of a web build's location: the location names it, with no rules to apply. -#[cfg(target_arch = "wasm32")] -pub(crate) fn resolve_web(location: &Location) -> Resolved { - // Without `Location::Auto` every location names its folder; no folder is the answer that - // writes nothing should a later location not. - given(location).unwrap_or_else(|| Resolved::new(None, Rule::Memory)) -} - /// Applies the rules for `app_id`, with the app's portable-mode names. The platform folder is /// named after `app_id`; see [`resolve_named`] to name it differently. -#[cfg(not(target_arch = "wasm32"))] pub fn resolve(app_id: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved { resolve_named(app_id, app_id, portable, location, probe) } @@ -176,7 +142,6 @@ pub fn resolve(app_id: &str, portable: &Portable, location: &Location, probe: &P /// `folder` instead of the app id, so an app whose existing settings sit in a differently spelled /// folder (`Photocraft` on macOS and Windows) keeps them. The `_CONFIG_DIR` variable still /// comes from `app_id`. -#[cfg(not(target_arch = "wasm32"))] pub fn resolve_named(app_id: &str, folder: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved { resolve_checked(app_id, folder, portable, location, probe, ensure_writable) } @@ -184,13 +149,11 @@ pub fn resolve_named(app_id: &str, folder: &str, portable: &Portable, location: /// [`resolve_named`] without changing the disk: the portable folder is judged by its permissions (see /// [`accepts_files`]) instead of creating it and writing a probe, with the same fallback to the platform folder. /// For [`SettingsStore::read`](crate::SettingsStore::read), which writes nothing. -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn resolve_unprobed(app_id: &str, folder: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved { resolve_checked(app_id, folder, portable, location, probe, accepts_files) } /// The folder rules, with `writable` deciding whether a portable folder is used. -#[cfg(not(target_arch = "wasm32"))] fn resolve_checked( app_id: &str, folder: &str, @@ -199,8 +162,10 @@ fn resolve_checked( probe: &Probe, writable: impl Fn(&Path) -> std::io::Result<()>, ) -> Resolved { - if let Some(resolved) = given(location) { - return resolved; + match location { + Location::Dir(dir) => return Resolved::new(Some(dir.clone()), Rule::Override), + Location::Memory => return Resolved::new(None, Rule::Memory), + Location::Auto => {} } // A browser has no folders: the store keeps its files in `LocalStorageFiles`. if cfg!(target_arch = "wasm32") { @@ -239,7 +204,6 @@ fn resolve_checked( } /// Creates `dir` and proves a file can be written in it: a folder can exist and still be read-only. -#[cfg(not(target_arch = "wasm32"))] fn ensure_writable(dir: &Path) -> std::io::Result<()> { #[cfg(not(target_arch = "wasm32"))] { @@ -256,7 +220,6 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> { /// Whether `dir`, or for a folder that doesn't exist yet its nearest existing ancestor (where /// [`ensure_writable`] would create it), is a folder with write permission. Reads metadata only. -#[cfg(not(target_arch = "wasm32"))] fn accepts_files(dir: &Path) -> std::io::Result<()> { let existing = dir.ancestors().find(|ancestor| ancestor.exists()).unwrap_or(dir); let meta = std::fs::metadata(existing)?; @@ -273,13 +236,11 @@ fn accepts_files(dir: &Path) -> std::io::Result<()> { /// /// On macOS the executable sits in `X.app/Contents/MacOS`; the marker is looked for next to the /// `.app` bundle, because writing inside a signed bundle breaks its signature. -#[cfg(not(target_arch = "wasm32"))] fn portable_dir(exe_dir: &Path, portable: &Portable) -> Option<(PathBuf, PathBuf)> { let base = bundle_parent(exe_dir).unwrap_or(exe_dir); portable.markers.iter().map(|m| base.join(m)).find(|m| m.is_file()).map(|marker| (marker, base.join(portable.dir))) } -#[cfg(not(target_arch = "wasm32"))] fn bundle_parent(exe_dir: &Path) -> Option<&Path> { if !cfg!(target_os = "macos") || exe_dir.file_name()? != "MacOS" { return None; @@ -296,7 +257,6 @@ fn bundle_parent(exe_dir: &Path) -> Option<&Path> { } /// The platform cache folder for `app_id` (`%LOCALAPPDATA%` on Windows, so it does not roam). -#[cfg(not(target_arch = "wasm32"))] pub fn cache_dir(app_id: &str) -> Option { #[cfg(not(target_arch = "wasm32"))] { @@ -310,7 +270,6 @@ pub fn cache_dir(app_id: &str) -> Option { } /// The platform data folder for `app_id`, for recovery files and other non-settings state. -#[cfg(not(target_arch = "wasm32"))] pub fn data_dir(app_id: &str) -> Option { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/settings/src/recovery.rs b/crates/settings/src/recovery.rs index c35b615ec8..8eefb25d2e 100644 --- a/crates/settings/src/recovery.rs +++ b/crates/settings/src/recovery.rs @@ -1,23 +1,8 @@ //! Keeping damaged and previous files around. -//! -//! The names ([`broken_path`], [`backup_path`]) are the same for every -//! [`SettingsFiles`](crate::SettingsFiles); the file operations here are the disk's. #[cfg(not(target_arch = "wasm32"))] use std::io; use std::path::{Path, PathBuf}; -<<<<<<< HEAD - -// `std::time::SystemTime::now` panics on wasm32-unknown-unknown; `web_time` is std's on native. -use web_time::{SystemTime, UNIX_EPOCH}; - -/// How many `-` suffixes a broken copy may try before the move aside gives up. -const MAX_BROKEN_COPIES: u32 = 1000; - -/// The `n`th name for a damaged `config.toml` set aside at unix time `ts`, beside it: -/// `config.broken-.toml`, then `config.broken--.toml`. -pub fn broken_path(path: &Path, ts: u64, n: u32) -> PathBuf { -======= #[cfg(not(target_arch = "wasm32"))] use std::time::{SystemTime, UNIX_EPOCH}; @@ -25,34 +10,24 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// new path. Never overwrites: a name that exists gets a `-` suffix. #[cfg(not(target_arch = "wasm32"))] pub fn move_aside(path: &Path) -> io::Result { ->>>>>>> origin/next let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("config"); let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml"); let dir = path.parent().unwrap_or_else(|| Path::new(".")); - let name = if n == 0 { format!("{stem}.broken-{ts}.{ext}") } else { format!("{stem}.broken-{ts}-{n}.{ext}") }; - dir.join(name) -} - -/// The first [`broken_path`] for `path` now that `taken` says is free. Never overwrites: after -/// [`MAX_BROKEN_COPIES`] taken names it fails. -pub(crate) fn free_broken_path(path: &Path, mut taken: impl FnMut(&Path) -> io::Result) -> io::Result { let ts = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); - for n in 0..=MAX_BROKEN_COPIES { - let target = broken_path(path, ts, n); - if !taken(&target)? { - return Ok(target); + let mut n = 0u32; + loop { + let name = if n == 0 { format!("{stem}.broken-{ts}.{ext}") } else { format!("{stem}.broken-{ts}-{n}.{ext}") }; + let target = dir.join(name); + if target.exists() { + n = n.saturating_add(1); + if n > 1000 { + return Err(io::Error::new(io::ErrorKind::AlreadyExists, "too many broken copies")); + } + continue; } + std::fs::rename(path, &target)?; + return Ok(target); } - Err(io::Error::new(io::ErrorKind::AlreadyExists, "too many broken copies")) -} - -/// Renames a damaged `config.toml` to `config.broken-.toml` beside it and returns the -/// new path. Never overwrites: a name that exists gets a `-` suffix. -#[cfg(not(target_arch = "wasm32"))] -pub fn move_aside(path: &Path) -> io::Result { - let target = free_broken_path(path, |target| Ok(target.exists()))?; - std::fs::rename(path, &target)?; - Ok(target) } /// The backup path for a config file: `config.toml` → `config.toml.bak`. diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 8531f65b82..330fc34a88 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -3,34 +3,21 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; -<<<<<<< HEAD -======= use web_time::Instant; ->>>>>>> origin/next use toml_edit::DocumentMut; -use web_time::Instant; use crate::Settings; use crate::document::{self, merge_changes, merge_into, set_schema_version}; use crate::error::{LoadReport, ReadOnlyReason, SaveStatus, SettingsError, Source, TickResult}; -<<<<<<< HEAD -#[cfg(target_arch = "wasm32")] -use crate::files::BrowserFiles; -#[cfg(not(target_arch = "wasm32"))] -use crate::files::DiskFiles; -======= #[cfg(not(target_arch = "wasm32"))] use crate::files::DiskFiles; #[cfg(target_arch = "wasm32")] use crate::files::LocalStorageFiles; ->>>>>>> origin/next use crate::files::SettingsFiles; use crate::migrate::{self, LegacyFile, Upgrade}; -use crate::paths::{self, Location}; -#[cfg(not(target_arch = "wasm32"))] -use crate::paths::{Portable, Probe}; +use crate::paths::{self, Location, Portable, Probe}; mod sections; @@ -66,17 +53,13 @@ pub struct OpenOptions { /// Quiet period after a change before saving. pub debounce: Duration, /// What the folder rules look at. - #[cfg(not(target_arch = "wasm32"))] pub probe: Probe, - /// How the files are read and written (by default `DiskFiles`, on the web `BrowserFiles`). - /// The store reads and writes `config.toml`, its backup and the damaged-file rename only - /// through it. + /// How the files are read and written ([`DiskFiles`] by default). The store reads and writes + /// `config.toml`, its backup and the damaged-file rename only through it. pub files: Arc, } impl Default for OpenOptions { - /// Native: [`Location::Auto`] on the disk. - #[cfg(not(target_arch = "wasm32"))] fn default() -> Self { #[cfg(not(target_arch = "wasm32"))] let files: Arc = Arc::new(DiskFiles); @@ -85,13 +68,6 @@ impl Default for OpenOptions { let files: Arc = Arc::new(LocalStorageFiles::new(4 << 20)); Self { location: Location::Auto, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, probe: Probe::default(), files } } - - /// Web: browser storage, in memory until the app names its key root with [`Location::Dir`] - /// (there are no folder rules to find one). - #[cfg(target_arch = "wasm32")] - fn default() -> Self { - Self { location: Location::Memory, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, files: Arc::new(BrowserFiles) } - } } impl OpenOptions { @@ -113,7 +89,6 @@ impl OpenOptions { } /// What the folder rules look at. - #[cfg(not(target_arch = "wasm32"))] pub fn probe(mut self, probe: Probe) -> Self { self.probe = probe; self @@ -179,7 +154,8 @@ impl SettingsStore { /// Opens the store with full options. pub fn open_with(options: OpenOptions) -> (Self, LoadReport) { - let resolved = resolve(&options, Probing::Write); + let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR }; + let resolved = paths::resolve_named(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe); let (mut store, mut report) = Self::unloaded(resolved, options.files, options.debounce); let (Some(dir), Some(path)) = (store.dir.clone(), store.path.clone()) else { @@ -206,7 +182,8 @@ impl SettingsStore { /// damaged `config.toml` reads as defaults and stays where it is, and with no `config.toml` the legacy files are /// imported in memory only. pub fn read(options: &OpenOptions) -> (T, LoadReport) { - let resolved = resolve(options, Probing::ReadOnly); + let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR }; + let resolved = paths::resolve_unprobed(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe); let (mut store, mut report) = Self::unloaded(resolved, options.files.clone(), options.debounce); if let Some(path) = store.path.clone() { store.load(&path, &options.legacy, Damaged::Leave, &mut report); @@ -560,33 +537,6 @@ impl SettingsStore { } } -/// How the folder rules may judge a portable folder. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Probing { - /// Create it and write a probe (an opened store). - Write, - /// Judge it by its permissions, changing nothing (a read). - ReadOnly, -} - -/// The folder `options` asks for: by the folder rules on native, as named on the web. -#[cfg(not(target_arch = "wasm32"))] -fn resolve(options: &OpenOptions, probing: Probing) -> paths::Resolved { - let portable = Portable { markers: T::PORTABLE_MARKERS, dir: T::PORTABLE_DIR }; - match probing { - Probing::Write => paths::resolve_named(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe), - Probing::ReadOnly => paths::resolve_unprobed(T::APP_ID, T::FOLDER_NAME, &portable, &options.location, &options.probe), - } -} - -/// The folder `options` asks for: by the folder rules on native, as named on the web. -#[cfg(target_arch = "wasm32")] -fn resolve(options: &OpenOptions, probing: Probing) -> paths::Resolved { - // Nothing on the web is probed: the location names the key root. - let _ = probing; - paths::resolve_web(&options.location) -} - /// What a store with no file holds as its base: the defaults, so only a change from them counts /// as this store's change when another instance creates the file first. fn default_document() -> DocumentMut {