diff --git a/README.md b/README.md index 58c1f59..33ea8fa 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,27 @@ AutoFix is a native Windows typo-correction app for text fields. It is designed to run quietly from the system tray, correct only the text the user typed in the current session, and avoid changing text after the caret. -Planned capabilities include: +Implemented capabilities include: - Configurable shortcut, word-count, and character triggers. -- Local or API-backed correction engines. +- Local rule and API-backed correction engines. - Typos-only and typos-plus-grammar modes. - Custom dictionaries, app rules, blocklists, and allowlists. -- Clipboard preservation, app-level undo, and secure-field blocking. +- App-level undo and secure-field blocking. -This repository is currently in setup stage. +Local ML correction, suggestion acceptance, IME composition, and direct text API +or UI Automation mutation remain planned. App-level undo restores only recorded +corrections whose exact span and caret can still be verified. + +Native clipboard replacement preserves all readable formats and restores them +before reporting success. Disable it under **Correction > Use clipboard for +correction** or set `replacement.clipboard_enabled = false` in settings TOML. +See [the engine documentation](app-core-rust/README.md) for runtime boundaries. + +When safer methods are unavailable or clipboard correction is disabled, SendInput +can replace a verified pre-caret span in supported Unicode Edit controls. Unknown +controls, unsafe selections and security refusals skip correction and log only +failure metadata. ## Run App diff --git a/app-core-rust/Cargo.toml b/app-core-rust/Cargo.toml index 4d937c7..c22473f 100644 --- a/app-core-rust/Cargo.toml +++ b/app-core-rust/Cargo.toml @@ -17,4 +17,4 @@ toml = "0.8" tracing = "0.1" tracing-subscriber = "0.3" windows = { version = "0.61", features = ["Win32_System_Com", "Win32_System_Ole", "Win32_UI_Accessibility"] } -windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Networking_WinHttp", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Memory", "Win32_System_Pipes", "Win32_System_StationsAndDesktops", "Win32_System_Threading", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_DataExchange", "Win32_System_Ole", "Win32_Networking_WinHttp", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Memory", "Win32_System_Pipes", "Win32_System_StationsAndDesktops", "Win32_System_Threading", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } diff --git a/app-core-rust/README.md b/app-core-rust/README.md index 04b2f26..9efa6e8 100644 --- a/app-core-rust/README.md +++ b/app-core-rust/README.md @@ -37,8 +37,8 @@ language; it can disable correction or correct per token with the API engine. Structured tokens, names, explicit protected terms, and words in other scripts remain protected. The local rule engine supports English only; API engines can receive other language tags. The async pipeline invokes the selected engine with -these policies. Native replacement remains unavailable, so changed results do -not yet edit target application text. +these policies. Validated changed results can now use the native replacement +strategies described below. In grammar mode it applies only enabled categories. Conservative local rules cover capitalization, sentence-ending punctuation on manual correction, extra punctuation, repeated words, subject-verb agreement, a/an articles, a few @@ -76,7 +76,7 @@ the timeout notice when it completes. `ApiCorrectionEngine::notice_for` distinguishes manual timeout and failure feedback from silent automatic handling. The local ML engine remains a placeholder. Live triggers invoke these engines on the correction worker. -The native replacement path remains a placeholder. +The native replacement path verifies the session-owned pre-caret range. Engine selection is explicit per request; neither local nor API routing depends on task difficulty, and both correction modes are accepted by every engine. @@ -94,7 +94,7 @@ requires user acceptance. Suppressed outputs preserve the original executable text and discard edit details. Local results prioritize silent edits over suggested edits when both occur in one request. The pipeline snapshots confidence policy and rejects suggestions, suppressed edits, and low-confidence results at -completion. Target replacement remains a placeholder. +completion before allowing target replacement. The keyboard session tracker is implemented. It keeps up to 4,096 characters typed during the current engine run in memory and exposes only the known text @@ -140,8 +140,7 @@ Manual-only rules can still use the opt-in arbitrary-selection shortcut path. The correction pipeline invokes the selected engine and validates completions. Successful unchanged caret-range results commit the original executable segment into informative context. Changed caret-range results require confirmation from -the replacement owner before session completion or undo recording; the native -placeholder currently refuses confirmation. If the provider cannot +the replacement owner before session completion or undo recording. If the provider cannot read before the caret, informative context is empty and typing continues. Protected fields and unavailable targets are never read. Paste and @@ -176,8 +175,8 @@ the final-fix security gate for the old executable text. Final fix remains unavailable because the old caret cannot be safely targeted after movement. Pending corrections are invalidated on movement. Runtime ticks delete sessions when their owning process exits. All session state disappears on engine exit or -termination and is never written to disk. The replacement engine remains a -placeholder; session completion methods do not themselves change target text. +termination and is never written to disk. Session completion methods do not +themselves change target text; the replacement engine must confirm mutation first. The correction pipeline uses one worker, a FIFO of requests, and one completion slot with backpressure so results cannot overwrite each other. Each session has @@ -233,8 +232,8 @@ focused control identity and a fresh read-only TextPattern capture. The entire known session region must match exactly at the live caret, including text typed after a frozen segment. Missing captures or mismatches discard the result; no fuzzy search or replacement is attempted. Selected-text results are discarded -because their replacement range cannot be proven before the caret. Native -replacement remains unavailable. +because their replacement range cannot be proven before the caret, even when +arbitrary selected-text correction is enabled. Failed, suppressed, or refused frozen results release their slot and retire the original text without applying engine output. Results are consumed once. Only completed silent corrections above low confidence reach the @@ -242,8 +241,104 @@ replacement boundary. Failed and suppressed manual edits do not commit executabl context. Tests cover delayed engines, frozen queues and overflow policies, manual override, stale and reordered results, queued input, secure targets, failed replacement, selection boundaries, and commit/undo after -confirmed replacement. Native mutation, clipboard recovery, and real target undo -still require the replacement feature. +confirmed replacement. + +The replacement feature lives in `src/background/replacement`. Its strategy +interface tries direct text APIs, UI Automation replacement, clipboard paste, +then SendInput. Direct APIs/TSF and UI Automation mutation currently report +unavailable and can be implemented progressively. UI Automation TextPattern +must first prove a collapsed caret, the exact executable span and any newer +typed text between that span and the caret. Only that span is selected; text +after the original caret remains untouched. Missing or unreliable providers +refuse replacement rather than guessing a keystroke distance. + +Clipboard replacement uses synchronous `WM_PASTE` on recognized native Edit +and RichEdit controls. It snapshots every enumerated clipboard format, including +registered binary formats, bitmaps, palettes and metafiles, before changing the +clipboard. Owner-managed or unreadable formats refuse this strategy before any +clipboard write. It preallocates a complete restoration set, proves the target +selection while the clipboard stays untouched, then installs temporary Unicode +text immediately before synchronous paste. Privacy markers are installed before +text to disable clipboard history and cloud upload. Restoration runs immediately +after paste (including paste failure), before target verification, and on scope +exit. Success requires both verified replacement and complete restoration. +Ownership and independent copies of published data distinguish Windows-synthesized formats from +an external clipboard change. A user's newer copy is retained and the attempt +fails rather than overwriting it. + +`replacement.clipboard_enabled` defaults to true. The settings UI exposes +**Correction > Use clipboard for correction**; disabling it skips clipboard +preparation for both correction and app-level undo. Restoration failures emit +metadata-only warnings and skip clipboard replacement for that process name +(case-insensitive) until the engine exits. A failed restore removes temporary +text when the clipboard lock is available, keeps the full saved snapshot in +memory, and retries recovery on a dedicated worker until restored or superseded +by a new copy, with at most eight active attempts over two seconds. The worker pumps +clipboard-owner messages while retrying and waiting for the clipboard lock. +Exhaustion releases ownership but retains originals in memory and quarantines +clipboard replacement across all apps. Read-only probes recognize a newer copy +or resume one restoration when a previously busy lock clears. Partial restorations +are not emptied and republished on each probe. The gate clears only after full +restoration or an external copy. Other clipboard attempts use fallback while +recovery is pending or quarantined. The tray sends a +process-scoped graceful stop signal and waits for the engine to drain recovery +before closing its process job. Shutdown makes one final attempt for quarantined +data and reports incomplete cleanup separately from a clean exit. A permanently +locked clipboard, failed final restoration, forced termination, or a crash can +leave clipboard cleanup incomplete; metadata-only warnings report that outcome. Clipboard contents +are never persisted for crash recovery. + +SendInput fallback inserts UTF-16 Unicode key pairs into the same proved +selection; an empty replacement deletes the selection with Backspace. It does +not use or change the clipboard. The entire batch is validated and allocated +before selection. It runs only after all safer available methods refuse, or the +clipboard method is disabled. Only standard Unicode Edit controls with known +insert semantics are supported. Read-only, password, numeric, case-transforming, +ANSI, custom and RichEdit controls refuse this fallback before selection. +It refuses all control characters and held shortcut +modifiers (after a bounded release wait). Immediately before mutation it rechecks +the exact selected text, input generations, field security, modifiers and native +keyboard focus. Partial input, failed paste, or failed +verification stops the strategy chain and invalidates the tracked session. +If a partial batch ends on a keydown, only its matching keyup is attempted; +deletion and typing are never retried. +Verification reacquires a fresh UI Automation provider after mutation and restores +the caret beyond newer typed text only after checking that text exactly. +Range proof accepts scalar or UTF-16 provider units only when the text matches +exactly at its fixed anchor; it never searches for similar text. App rules are +reread under a SQLite writer reservation held through replacement and app undo. +Missing or busy policy storage skips mutation. Final native checks require all +authorized target attributes, including process name and window title, to remain +unchanged before mutation; title changes refuse correction and undo even without +caret movement. After mutation, verification and caret restoration permit an +editor's modified-title marker while still requiring every other identity and +safety attribute and the input generations to match. +Provider error messages are +discarded so failure logs cannot contain document text. + +Every replacement returns success/failure, the attempted method (or none for +pre-strategy rejection), the exact range when proved, and a failure reason. +Failure/skip metadata is logged at warning level under default logging, including +the attempted method and whether the tracked selection may have changed. +Range offsets count Unicode characters backwards from the original caret, +with `start_back >= end_back >= 0`; they are not document byte or UTF-16 offsets. +App-level undo uses only a recorded app correction that remains fully retained +in informative context. It verifies the live anchor and restores that recorded +span, preserving newer executable text. Memory truncation, movement, unknown +selection geometry and secure fields block native undo. + +Focused tests cover strategy ordering, the clipboard disable preference, +fail-closed authorization, mutation failures, Unicode ranges, rich/binary format +restoration, restoration failures and retry, Windows-synthesized formats, +per-app fallback preference, clipboard handle copying and app-owned undo spans. +The opt-in `native_clipboard_preservation_smoke` runs in a child with a separate +noninteractive Windows window station and seeds rich text, HTML, binary data +and a bitmap. It verifies actual native paste, restoration, recovery from a +locked clipboard, and retention of a newer copy without touching the desktop +clipboard. It refuses a visible station or unrelated existing clipboard data. +The opt-in `native_edit_replacement_smoke` test owns a separate native editor; +it checks clipboard/SendInput and preservation of the document suffix on an +interactive Windows desktop. It safely refuses unsupported clipboard formats. Feature code should be organized by product behavior, not technical layer. Keep modules small, private by default, and colocate tests with the behavior they verify. diff --git a/app-core-rust/src/background/components.rs b/app-core-rust/src/background/components.rs index 5564b52..79c90a2 100644 --- a/app-core-rust/src/background/components.rs +++ b/app-core-rust/src/background/components.rs @@ -3,7 +3,6 @@ use std::{ sync::{atomic::AtomicBool, Arc}, }; -use super::triggers::CorrectionRequest; use crate::{ background::{paths::RuntimePaths, BackgroundError}, ipc::IpcServerState, @@ -11,7 +10,6 @@ use crate::{ }; pub(crate) struct NamedPipeIpcServer(crate::ipc::NamedPipeIpcServer); -pub(crate) struct ReplacementEngine; impl NamedPipeIpcServer { pub(crate) fn initialize( @@ -42,28 +40,3 @@ impl NamedPipeIpcServer { tracing::info!("named pipe IPC server shut down"); } } - -impl ReplacementEngine { - /// Native mutation is a separate feature. Refuse success until it can preserve - /// clipboard, target undo, and the verified executable range atomically. - pub(crate) fn replace( - _target: &super::target::FocusedTarget, - request: &CorrectionRequest, - _output: &crate::correction::CorrectionOutput, - ) -> bool { - tracing::debug!( - session_id = request.session_id, - trigger = request.trigger.as_str(), - "correction validated; native replacement unavailable" - ); - false - } - pub(crate) fn initialize() -> Self { - tracing::info!("replacement engine placeholder initialized"); - Self - } - - pub(crate) fn shutdown(self) { - tracing::info!("replacement engine placeholder shut down"); - } -} diff --git a/app-core-rust/src/background/mod.rs b/app-core-rust/src/background/mod.rs index 47d0aea..a9efa9c 100644 --- a/app-core-rust/src/background/mod.rs +++ b/app-core-rust/src/background/mod.rs @@ -8,6 +8,7 @@ mod message_loop; mod paths; mod pipeline; mod process_group; +mod replacement; mod security; mod session; mod shortcuts; @@ -38,11 +39,12 @@ use crate::{ use self::{ admin::reject_elevated_process, - components::{NamedPipeIpcServer, ReplacementEngine}, + components::NamedPipeIpcServer, input_listener::{InputEvent, InputListener}, paths::RuntimePaths, pipeline::{CorrectionPipeline, InputStamp}, process_group::SiblingDisappearanceMonitor, + replacement::ReplacementEngine, security::{SecurityDecision, SecurityGate, TriggerKind}, session::{MovementResolution, SessionManager}, shortcuts::{GlobalShortcutListener, ShortcutAction}, @@ -62,14 +64,14 @@ struct RuntimeComponents { global_shortcut: GlobalShortcutListener, input_listener: InputListener, input_worker: InputWorker, - replacement_engine: ReplacementEngine, process_group_monitor: SiblingDisappearanceMonitor, + shutdown_signal: process_group::ShutdownSignal, shutdown_requested: Arc, } struct InputWorker { queue: Arc<(Mutex>, Condvar)>, - done: mpsc::Receiver<()>, + done: mpsc::Receiver, thread: Option>, } @@ -135,6 +137,7 @@ pub(crate) enum BackgroundError { Database(rusqlite::Error), InputHook(u32), InputWorker(std::io::Error), + ShutdownSignal(u32), } impl fmt::Display for BackgroundError { @@ -150,6 +153,10 @@ impl fmt::Display for BackgroundError { formatter, "failed to install input listener: Windows error {code}" ), + Self::ShutdownSignal(code) => write!( + formatter, + "failed to create engine stop signal: Windows error {code}" + ), Self::InputWorker(source) => { write!(formatter, "failed to start input worker: {source}") } @@ -164,7 +171,7 @@ impl Error for BackgroundError { Self::Config(source) => Some(source), Self::Database(source) => Some(source), Self::InputWorker(source) => Some(source), - Self::ElevatedProcess | Self::InputHook(_) => None, + Self::ElevatedProcess | Self::InputHook(_) | Self::ShutdownSignal(_) => None, } } } @@ -192,9 +199,13 @@ impl BackgroundRuntime { Ok(Self { components }) } + /// Report unresolved cleanup separately from a fully drained graceful exit. fn shutdown(self) { - self.components.shutdown(); - tracing::info!("AutoFix background process exited cleanly"); + if self.components.shutdown() { + tracing::info!("AutoFix background process exited cleanly"); + } else { + tracing::warn!("AutoFix background process exited with incomplete cleanup"); + } } fn run_until_exit(&mut self) { @@ -210,6 +221,8 @@ impl RuntimeComponents { database: Database, ) -> Result { let input_listener = InputListener::initialize().map_err(BackgroundError::InputHook)?; + let shutdown_signal = + process_group::ShutdownSignal::new().map_err(BackgroundError::ShutdownSignal)?; let input_worker = InputWorker::start(config.clone(), database)?; Ok(Self { config_path: paths.config_path().to_path_buf(), @@ -223,18 +236,19 @@ impl RuntimeComponents { global_shortcut: GlobalShortcutListener::initialize(config), input_listener, input_worker, - replacement_engine: ReplacementEngine::initialize(), process_group_monitor: SiblingDisappearanceMonitor::new(), + shutdown_signal, shutdown_requested, }) } - fn shutdown(self) { - self.input_worker.shutdown(); - self.replacement_engine.shutdown(); + /// Stop input mutation first and preserve the cleanup outcome through component teardown. + fn shutdown(self) -> bool { + let clean = self.input_worker.shutdown(); drop(self.input_listener); self.global_shortcut.shutdown(); self.ipc_server.shutdown(); + clean } fn run_until_exit(&mut self) { @@ -262,7 +276,7 @@ impl RuntimeComponents { } } - self.shutdown_requested.load(Ordering::Relaxed) + self.shutdown_requested.load(Ordering::Relaxed) || self.shutdown_signal.requested() }); } @@ -356,7 +370,7 @@ impl InputWorker { } processor.finish_correction(); } - let _ = done_sender.send(()); + let _ = done_sender.send(replacement::finish_shutdown()); }) .map_err(BackgroundError::InputWorker)?; Ok(Self { @@ -392,7 +406,9 @@ impl InputWorker { ready.notify_one(); } - fn shutdown(mut self) { + /// Wait for processor and clipboard cleanup without treating a timeout as success. + fn shutdown(mut self) -> bool { + replacement::begin_shutdown(); let (lock, ready) = &*self.queue; { let mut pending = lock.lock().unwrap(); @@ -400,12 +416,14 @@ impl InputWorker { pending.push_back(InputWork::Shutdown); ready.notify_one(); } - if self.done.recv_timeout(Duration::from_millis(500)).is_ok() { + if let Ok(clean) = self.done.recv_timeout(Duration::from_secs(4)) { if let Some(thread) = self.thread.take() { let _ = thread.join(); } + clean } else { tracing::warn!("input processor still waiting on UI Automation during shutdown"); + false } } } @@ -428,6 +446,8 @@ impl InputProcessor { } let config = &self.config; let database = &self.database; + let replacement_stamp = Self::input_stamp(); + let mut replacement_uncertain = false; self.pipeline.finish( &mut self.session_manager, &config.context, @@ -439,8 +459,35 @@ impl InputProcessor { |target, known_chars| { context_capture::read_before_caret(target, &config.context, known_chars) }, - ReplacementEngine::replace, + |target, request, output| { + let Some(_policy_guard) = + SecurityGate::authorize_replacement(request.trigger, config, database, target) + else { + tracing::warn!( + success = false, + method = "none", + reason = "replacement policy unavailable or denied", + "replacement skipped" + ); + return false; + }; + let result = ReplacementEngine::replace( + target, + request, + output, + replacement_stamp, + config.replacement.clipboard_enabled, + ); + replacement_uncertain = !result.success && result.may_have_changed; + result.log_outcome(false); + result.success + }, ); + if replacement_uncertain { + self.pipeline.cancel(); + self.session_manager + .deactivate(MovementSignal::UnknownPosition); + } if self.pipeline.take_timeout_notice() { timeout_notice::show(); } @@ -707,16 +754,81 @@ impl InputProcessor { } } Some(ShortcutAction::Undo) => { - if self.security_allows(TriggerKind::Undo, &self.database) { - tracing::info!("undo pipeline placeholder triggered by shortcut"); - } else { - tracing::info!("undo shortcut ignored because context is blocked"); - } + self.undo_correction(); } None => {} } } + fn undo_correction(&mut self) { + let stamp = Self::input_stamp(); + if stamp.sequence != self.processed_input_sequence { + return; + } + let SecurityDecision::Allowed { target } = + SecurityGate::check(TriggerKind::Undo, &self.config, &self.database) + else { + return; + }; + if !self.session_manager.active_matches(&target) { + return; + } + let Some(session) = self.session_manager.active() else { + return; + }; + let Some(undo) = session.undo_target() else { + return; + }; + let known = format!( + "{}{}", + session.informative_context(), + session.executable_context() + ); + let Some(live) = context_capture::read_before_caret( + &target, + &self.config.context, + known.chars().count(), + ) else { + return; + }; + if Self::input_stamp() != stamp || !live.ends_with(&known) { + return; + } + let Some(_policy_guard) = SecurityGate::authorize_replacement( + TriggerKind::Undo, + &self.config, + &self.database, + &target, + ) else { + tracing::warn!( + success = false, + method = "none", + reason = "replacement policy unavailable or denied", + "app correction undo skipped" + ); + return; + }; + self.pipeline.cancel(); + if let Some(session) = self.session_manager.active_mut() { + session.restore_pending(); + } + let result = ReplacementEngine::undo( + &target, + &undo, + stamp, + self.config.replacement.clipboard_enabled, + ); + result.log_outcome(true); + if result.success { + if let Some(session) = self.session_manager.active_mut() { + session.undo_last_correction(&self.config.context); + } + } else if result.may_have_changed { + self.session_manager + .deactivate(MovementSignal::UnknownPosition); + } + } + /// Update the typed session and retain trigger requests with their full scope. fn track_input( &mut self, diff --git a/app-core-rust/src/background/process_group.rs b/app-core-rust/src/background/process_group.rs index f005f6f..cab28ec 100644 --- a/app-core-rust/src/background/process_group.rs +++ b/app-core-rust/src/background/process_group.rs @@ -1,5 +1,8 @@ use std::path::{Path, PathBuf}; +mod shutdown_signal; +pub(super) use shutdown_signal::ShutdownSignal; + const ALLOWED_PROCESS_NAMES: [&str; 1] = ["Autofix.exe"]; pub(crate) struct SiblingDisappearanceMonitor { diff --git a/app-core-rust/src/background/process_group/shutdown_signal.rs b/app-core-rust/src/background/process_group/shutdown_signal.rs new file mode 100644 index 0000000..df36073 --- /dev/null +++ b/app-core-rust/src/background/process_group/shutdown_signal.rs @@ -0,0 +1,58 @@ +//! Process-scoped graceful stop signal shared with the Autofix.exe supervisor. +use std::ptr; +use windows_sys::Win32::{ + Foundation::{CloseHandle, GetLastError, HANDLE, WAIT_OBJECT_0}, + System::Threading::{CreateEventW, GetCurrentProcessId, WaitForSingleObject}, +}; + +pub(in crate::background) struct ShutdownSignal(HANDLE); + +impl ShutdownSignal { + /// Create before normal processing, so the shell can stop even during startup. + pub(in crate::background) fn new() -> Result { + let name: Vec = format!("Local\\AutoFix.EngineStop.{}", unsafe { + GetCurrentProcessId() + }) + .encode_utf16() + .chain(Some(0)) + .collect(); + let handle = unsafe { CreateEventW(ptr::null(), 1, 0, name.as_ptr()) }; + if handle.is_null() { + Err(unsafe { GetLastError() }) + } else { + Ok(Self(handle)) + } + } + + /// Poll without blocking the Windows input/message loop. + pub(in crate::background) fn requested(&self) -> bool { + unsafe { WaitForSingleObject(self.0, 0) == WAIT_OBJECT_0 } + } +} + +impl Drop for ShutdownSignal { + /// Release the process-scoped event after engine teardown. + fn drop(&mut self) { + unsafe { CloseHandle(self.0) }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An isolated manual-reset signal remains readable without blocking input processing. + #[test] + fn graceful_stop_signal_is_latched_and_polling_is_nonblocking() { + // Keep the signal isolated from background-runtime tests in this process. + let signal = ShutdownSignal(unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) }); + assert!(!signal.0.is_null()); + assert!(!signal.requested()); + assert_ne!( + unsafe { windows_sys::Win32::System::Threading::SetEvent(signal.0) }, + 0 + ); + assert!(signal.requested()); + assert!(signal.requested()); + } +} diff --git a/app-core-rust/src/background/replacement/clipboard.rs b/app-core-rust/src/background/replacement/clipboard.rs new file mode 100644 index 0000000..281244c --- /dev/null +++ b/app-core-rust/src/background/replacement/clipboard.rs @@ -0,0 +1,120 @@ +//! Preserve every available format before replacing clipboard contents. +//! Unsupported owner-managed formats refuse the path before EmptyClipboard. +use std::{ + collections::HashSet, + sync::{Mutex, OnceLock}, +}; + +#[derive(Default)] +struct ClipboardPolicy { + failed_apps: HashSet, +} +impl ClipboardPolicy { + /// Refuse clipboard mutation for apps with a prior restoration failure this run. + fn allowed(&self, app: &str) -> bool { + !self.failed_apps.contains(&app.to_ascii_lowercase()) + } + + /// Remember failure by case-insensitive process name without retaining target text. + #[cfg(any(windows, test))] + fn failed(&mut self, app: &str) { + self.failed_apps.insert(app.to_ascii_lowercase()); + } +} + +/// Share memory-only fallback preferences across correction and undo. +fn policy() -> &'static Mutex { + static POLICY: OnceLock> = OnceLock::new(); + POLICY.get_or_init(|| Mutex::new(ClipboardPolicy::default())) +} + +/// A poisoned policy lock fails closed to the non-clipboard fallback. +pub(super) fn allowed_for(app: &str) -> bool { + policy().lock().is_ok_and(|policy| policy.allowed(app)) +} + +/// Record per-app fallback and emit metadata without clipboard or document contents. +#[cfg(windows)] +pub(super) fn restore_failed(app: &str, process_id: u32) { + if let Ok(mut policy) = policy().lock() { + policy.failed(app); + } + // No document, replacement, clipboard contents, or window title in diagnostics. + tracing::warn!( + process_id, + method = "clipboard", + "clipboard restoration failed; prefer fallback for this app" + ); +} + +/// Restoration runs even after failed paste, before target verification. +#[cfg(any(windows, test))] +pub(super) fn paste_and_restore( + paste: impl FnOnce() -> Result<(), String>, + restore: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + let pasted = paste(); + let restored = restore(); + match (pasted, restored) { + (Ok(()), Ok(())) => Ok(()), + (Err(reason), Ok(())) | (Ok(()), Err(reason)) => Err(reason), + (Err(reason), Err(restore)) => Err(format!("{reason}; {restore}")), + } +} + +/// Saved originals are never transferred. Preallocated copies make the first restore +/// allocation-free; retries can duplicate originals without retaining temporary text. +#[cfg(any(windows, test))] +fn restore_snapshot( + saved: &[T], + prepared: &mut Option>, + mut duplicate: impl FnMut(&T) -> Result, + clear: impl FnOnce() -> Result<(), String>, + mut publish: impl FnMut(&mut T) -> Result<(), String>, +) -> Result<(), String> { + let copies = prepared.take().map(Ok).unwrap_or_else(|| { + saved + .iter() + .map(&mut duplicate) + .collect::, _>>() + }); + if let Err(reason) = clear() { + *prepared = copies.ok(); + return Err(reason); + } + let mut copies = copies?; + let mut failure = None; + for copy in &mut copies { + if let Err(reason) = publish(copy) { + failure = Some(reason); + } + } + failure.map_or(Ok(()), Err) +} + +/// Allow only published formats and their known Windows-synthesized equivalents. +#[cfg(any(windows, test))] +fn owned_format_or_synthesis(known: &[u32], format: u32) -> bool { + known.contains(&format) + || match format { + 1 | 7 | 13 | 16 => known.iter().any(|format| matches!(format, 1 | 7 | 13)), + 2 | 8 | 17 => known.iter().any(|format| matches!(format, 2 | 8 | 17)), + 3 | 14 => known.iter().any(|format| matches!(format, 3 | 14)), + _ => false, + } +} + +#[cfg(test)] +mod tests; + +#[cfg(windows)] +mod windows; + +#[cfg(windows)] +pub(in crate::background::replacement) use windows::{paste, supports_paste, ClipboardTransaction}; + +/// Finish memory-only recovery before the engine returns to its host. +#[cfg(windows)] +pub(super) fn shutdown() -> bool { + windows::shutdown() +} diff --git a/app-core-rust/src/background/replacement/clipboard/tests.rs b/app-core-rust/src/background/replacement/clipboard/tests.rs new file mode 100644 index 0000000..1f0c096 --- /dev/null +++ b/app-core-rust/src/background/replacement/clipboard/tests.rs @@ -0,0 +1,163 @@ +use super::*; +use std::cell::{Cell, RefCell}; + +#[test] +fn synthesized_formats_are_allowed_but_unrelated_changes_are_not() { + for format in [1, 7, 13, 16] { + assert!(owned_format_or_synthesis(&[13, 0xc001], format)); + } + assert!(owned_format_or_synthesis(&[13, 0xc001], 0xc001)); + for format in [2, 3, 14, 0xc002] { + assert!(!owned_format_or_synthesis(&[13, 0xc001], format)); + } + assert!(!owned_format_or_synthesis(&[], 13)); +} + +#[test] +fn paste_requires_restore_and_restores_before_verification() { + for pasted in [true, false] { + for restored in [true, false] { + let calls = RefCell::new(Vec::new()); + let result = paste_and_restore( + || { + calls.borrow_mut().push("paste"); + if pasted { + Ok(()) + } else { + Err("paste failed".into()) + } + }, + || { + calls.borrow_mut().push("restore"); + if restored { + Ok(()) + } else { + Err("restore failed".into()) + } + }, + ); + if result.is_ok() { + calls.borrow_mut().push("verify"); + } + assert_eq!(result.is_ok(), pasted && restored); + assert_eq!(&calls.borrow()[..2], &["paste", "restore"]); + if !restored { + assert!(result.unwrap_err().contains("restore failed")); + } + } + } +} + +#[test] +fn restore_is_allocation_free_and_preserves_all_formats_and_empty_clipboard() { + for saved in [ + Vec::new(), + vec![ + b"plain".to_vec(), + b"{\\rtf1 rich}".to_vec(), + vec![0, 255, 1], + ], + ] { + let clipboard = RefCell::new(vec![b"correction".to_vec()]); + let mut reserve = Some(saved.clone()); + restore_snapshot( + &saved, + &mut reserve, + |_| panic!("initial restore must use its preallocated copies"), + || { + clipboard.borrow_mut().clear(); + Ok(()) + }, + |value| { + clipboard.borrow_mut().push(std::mem::take(value)); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(*clipboard.borrow(), saved); + } +} + +#[test] +fn partial_restore_is_failure_scrubs_correction_and_retains_originals_for_retry() { + let saved = vec![b"plain".to_vec(), b"rich".to_vec(), vec![0, 255, 1]]; + let originals = saved.clone(); + let clipboard = RefCell::new(vec![b"correction".to_vec()]); + let mut reserve = Some(saved.clone()); + let attempted = Cell::new(0); + let result = restore_snapshot( + &saved, + &mut reserve, + |value| Ok(value.clone()), + || { + clipboard.borrow_mut().clear(); + Ok(()) + }, + |value| { + attempted.set(attempted.get() + 1); + if value == b"rich" { + return Err("rich format failed".into()); + } + clipboard.borrow_mut().push(std::mem::take(value)); + Ok(()) + }, + ); + assert!(result.is_err()); + assert_eq!(attempted.get(), 3); + assert_eq!(saved, originals); + assert!(!clipboard.borrow().contains(&b"correction".to_vec())); + restore_snapshot( + &saved, + &mut reserve, + |value| Ok(value.clone()), + || { + clipboard.borrow_mut().clear(); + Ok(()) + }, + |value| { + clipboard.borrow_mut().push(std::mem::take(value)); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(*clipboard.borrow(), saved); +} + +#[test] +fn busy_restore_keeps_reserved_data_and_failed_recovery_copy_scrubs_temporary_text() { + let saved = vec![b"rich".to_vec()]; + let mut reserve = Some(saved.clone()); + let result = restore_snapshot( + &saved, + &mut reserve, + |_| panic!("reserved"), + || Err("busy".into()), + |_| panic!("must not publish while busy"), + ); + assert!(result.is_err()); + assert_eq!(reserve, Some(saved.clone())); + reserve = None; + let cleared = Cell::new(false); + let result = restore_snapshot( + &saved, + &mut reserve, + |_| Err("copy failed".into()), + || { + cleared.set(true); + Ok(()) + }, + |_| panic!("failed copy"), + ); + assert!(result.is_err()); + assert!(cleared.get()); + assert_eq!(saved, vec![b"rich".to_vec()]); +} + +#[test] +fn restore_failure_prefers_fallback_only_for_affected_app() { + let mut policy = ClipboardPolicy::default(); + assert!(policy.allowed("Editor.exe")); + policy.failed("Editor.exe"); + assert!(!policy.allowed("EDITOR.EXE")); + assert!(policy.allowed("other.exe")); +} diff --git a/app-core-rust/src/background/replacement/clipboard/windows.rs b/app-core-rust/src/background/replacement/clipboard/windows.rs new file mode 100644 index 0000000..27a6e33 --- /dev/null +++ b/app-core-rust/src/background/replacement/clipboard/windows.rs @@ -0,0 +1,668 @@ +use std::{ + ptr, + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc, OnceLock, + }, + thread, + time::{Duration, Instant}, +}; +use windows_sys::Win32::{ + Foundation::{GetLastError, GlobalFree, SetLastError, HANDLE, HWND}, + Graphics::Gdi::{CopyEnhMetaFileW, DeleteEnhMetaFile, DeleteMetaFile, DeleteObject}, + System::{ + DataExchange::{ + CloseClipboard, EmptyClipboard, EnumClipboardFormats, GetClipboardData, + GetClipboardOwner, GetClipboardSequenceNumber, OpenClipboard, RegisterClipboardFormatW, + SetClipboardData, METAFILEPICT, + }, + Memory::{GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock, GMEM_MOVEABLE}, + Ole::OleDuplicateData, + }, + UI::WindowsAndMessaging::{ + CreateWindowExW, DestroyWindow, GetClassNameW, SendMessageTimeoutW, HWND_MESSAGE, + SMTO_ABORTIFHUNG, SMTO_BLOCK, WM_PASTE, + }, +}; + +const UNICODE_TEXT: u32 = 13; +const BITMAP: u32 = 2; +const METAFILE: u32 = 3; +const PALETTE: u32 = 9; +const ENH_METAFILE: u32 = 14; +/// Compare independent format snapshots to detect a newer external clipboard copy. +fn same_published_data(format: u32, expected: HANDLE, actual: HANDLE) -> bool { + if actual.is_null() { + return false; + } + if expected == actual { + return true; + } + if matches!( + format, + BITMAP | PALETTE | METAFILE | ENH_METAFILE | 0x82 | 0x83 | 0x8e + ) { + return native_object_bytes(format, expected) + .zip(native_object_bytes(format, actual)) + .is_some_and(|(expected, actual)| expected == actual); + } + // GetClipboardData may return a different local HGLOBAL on the recovery thread. + // Compare its bytes with our independent snapshot under the clipboard lock. + unsafe { + let length = GlobalSize(expected); + if length == 0 || GlobalSize(actual) != length { + return false; + } + let previous = GlobalLock(expected); + let current = GlobalLock(actual); + let same = !previous.is_null() + && !current.is_null() + && std::slice::from_raw_parts(previous.cast::(), length) + == std::slice::from_raw_parts(current.cast::(), length); + if !previous.is_null() { + GlobalUnlock(expected); + } + if !current.is_null() { + GlobalUnlock(actual); + } + same + } +} + +/// Fingerprint native graphics objects independently of thread-local clipboard handles. +fn native_object_bytes(format: u32, handle: HANDLE) -> Option> { + use windows_sys::Win32::Graphics::Gdi::{ + GetBitmapBits, GetEnhMetaFileBits, GetMetaFileBitsEx, GetObjectW, GetPaletteEntries, + BITMAP as NativeBitmap, PALETTEENTRY, + }; + /// Allocate native object bytes fallibly before accessing the copied object. + fn buffer(length: usize) -> Option> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(length).ok()?; + bytes.resize(length, 0); + Some(bytes) + } + if handle.is_null() { + return None; + } + unsafe { + match format { + BITMAP | 0x82 => { + let mut bitmap: NativeBitmap = std::mem::zeroed(); + if GetObjectW( + handle, + std::mem::size_of::() as i32, + (&mut bitmap as *mut NativeBitmap).cast(), + ) == 0 + { + return None; + } + let length = bitmap + .bmWidthBytes + .checked_mul(bitmap.bmHeight.checked_abs()?)?; + let mut bits = buffer(usize::try_from(length).ok()?)?; + if GetBitmapBits(handle, length, bits.as_mut_ptr().cast()) != length { + return None; + } + let mut bytes = [ + bitmap.bmWidth, + bitmap.bmHeight, + bitmap.bmWidthBytes, + i32::from(bitmap.bmPlanes), + i32::from(bitmap.bmBitsPixel), + ] + .into_iter() + .flat_map(i32::to_ne_bytes) + .collect::>(); + bytes.try_reserve(bits.len()).ok()?; + bytes.extend(bits); + Some(bytes) + } + PALETTE => { + let count = GetPaletteEntries(handle, 0, 0, ptr::null_mut()); + if count == 0 { + return None; + } + let mut entries = Vec::::new(); + entries.try_reserve_exact(count as usize).ok()?; + entries.resize(count as usize, std::mem::zeroed()); + if GetPaletteEntries(handle, 0, count, entries.as_mut_ptr()) != count { + return None; + } + let mut bytes = buffer( + entries + .len() + .checked_mul(std::mem::size_of::())?, + )?; + ptr::copy_nonoverlapping( + entries.as_ptr().cast::(), + bytes.as_mut_ptr(), + bytes.len(), + ); + Some(bytes) + } + ENH_METAFILE | 0x8e => { + let length = GetEnhMetaFileBits(handle, 0, ptr::null_mut()); + if length == 0 { + return None; + } + let mut bytes = buffer(length as usize)?; + (GetEnhMetaFileBits(handle, length, bytes.as_mut_ptr()) == length).then_some(bytes) + } + METAFILE | 0x83 => { + let picture = GlobalLock(handle).cast::(); + if picture.is_null() { + return None; + } + let dimensions = [(*picture).mm, (*picture).xExt, (*picture).yExt]; + let metafile = (*picture).hMF; + GlobalUnlock(handle); + let length = GetMetaFileBitsEx(metafile, 0, ptr::null_mut()); + if length == 0 { + return None; + } + let mut bits = buffer(length as usize)?; + if GetMetaFileBitsEx(metafile, length, bits.as_mut_ptr().cast()) != length { + return None; + } + let mut bytes = dimensions + .into_iter() + .flat_map(i32::to_ne_bytes) + .collect::>(); + bytes.try_reserve(bits.len()).ok()?; + bytes.extend(bits); + Some(bytes) + } + _ => None, + } + } +} + +static RECOVERY_PENDING: AtomicBool = AtomicBool::new(false); +/// Create a message-only clipboard owner on the calling thread. +fn owner_window() -> HWND { + unsafe { + CreateWindowExW( + 0, + wide("STATIC").as_ptr(), + wide("AutoFix clipboard").as_ptr(), + 0, + 0, + 0, + 0, + 0, + HWND_MESSAGE, + ptr::null_mut(), + ptr::null_mut(), + ptr::null(), + ) + } +} + +struct Recovery { + saved: Vec, + sequence: u32, + owned: Vec, + clipboard_owner: HWND, + temporary_snapshot: Vec, + restoring: bool, +} +// Exclusively owned duplicated HGLOBAL/GDI handles contain no Rust references. +// Windows permits their use and release from the recovery thread. +unsafe impl Send for Recovery {} + +mod recovery; +use recovery::recovery_sender; +/// Drain and stop the recovery worker before the engine exits. +pub(super) fn shutdown() -> bool { + recovery::shutdown() +} + +/// Encode a NUL-terminated Windows string without borrowing temporary data. +fn wide(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() +} + +struct ClipboardLock; +impl ClipboardLock { + /// Acquire the clipboard for a bounded period without modifying any formats. + fn open(owner: HWND) -> Result { + Self::open_with_messages(owner, false) + } + + /// Recovery must answer sent owner messages while another thread holds the lock. + fn open_with_messages(owner: HWND, pump: bool) -> Result { + let deadline = Instant::now() + Duration::from_millis(250); + loop { + if pump { + recovery::pump_messages(); + } + if unsafe { OpenClipboard(owner) } != 0 { + return Ok(Self); + } + if Instant::now() >= deadline { + return Err("clipboard is busy".into()); + } + thread::sleep(Duration::from_millis(5)); + } + } +} +impl Drop for ClipboardLock { + /// Release owned native resources on scope exit without touching a newer copy. + fn drop(&mut self) { + unsafe { + CloseClipboard(); + } + } +} + +struct SavedFormat { + format: u32, + handle: HANDLE, +} +impl SavedFormat { + /// Copy readable formats into independent owned handles; refuse owner-managed data. + fn duplicate(format: u32, source: HANDLE) -> Result { + // Private/GDI-owner and owner-display data cannot be restored by a new owner. + if source.is_null() || format == 0x80 || (0x200..=0x3ff).contains(&format) { + return Err(format!("clipboard format {format} cannot be preserved")); + } + let native_format = match format { + 0x82 => BITMAP, + 0x83 => METAFILE, + 0x8e => ENH_METAFILE, + other => other, + }; + let handle = unsafe { + if native_format == ENH_METAFILE { + CopyEnhMetaFileW(source, ptr::null()) + } else { + OleDuplicateData(source, native_format as u16, GMEM_MOVEABLE) + } + }; + if handle.is_null() { + return Err(format!("clipboard format {format} could not be duplicated")); + } + Ok(Self { format, handle }) + } + + /// Allocate movable clipboard memory and copy all bytes before publication. + fn bytes(format: u32, bytes: &[u8]) -> Result { + let handle = unsafe { GlobalAlloc(GMEM_MOVEABLE, bytes.len()) }; + if handle.is_null() { + return Err("clipboard allocation failed".into()); + } + let value = Self { format, handle }; + let memory = unsafe { GlobalLock(handle) }; + if memory.is_null() { + return Err("clipboard memory lock failed".into()); + } + unsafe { + ptr::copy_nonoverlapping(bytes.as_ptr(), memory.cast(), bytes.len()); + GlobalUnlock(handle); + } + Ok(value) + } + + /// Transfer ownership to Windows only after SetClipboardData succeeds. + fn publish(&mut self) -> Result<(), String> { + if unsafe { SetClipboardData(self.format, self.handle) }.is_null() { + return Err(format!( + "clipboard format {} could not be restored", + self.format + )); + } + self.handle = ptr::null_mut(); // Ownership transferred to Windows. + Ok(()) + } +} +impl Drop for SavedFormat { + /// Release owned native resources on scope exit without touching a newer copy. + fn drop(&mut self) { + if self.handle.is_null() { + return; + } + unsafe { + match self.format { + BITMAP | PALETTE | 0x82 => { + DeleteObject(self.handle); + } + ENH_METAFILE | 0x8e => { + DeleteEnhMetaFile(self.handle); + } + METAFILE | 0x83 => { + let picture = GlobalLock(self.handle).cast::(); + if !picture.is_null() { + DeleteMetaFile((*picture).hMF); + GlobalUnlock(self.handle); + } + GlobalFree(self.handle); + } + _ => { + GlobalFree(self.handle); + } + } + } + } +} + +pub(in crate::background::replacement) struct ClipboardTransaction { + owner: HWND, + saved: Vec, + restore_copy: Option>, + temporary: Vec, + sequence: u32, + owned: Vec, + clipboard_owner: HWND, + temporary_snapshot: Vec, + restoring: bool, + changed: bool, + recovery_owner: bool, +} +pub(in crate::background::replacement) struct PreparationFailure { + pub(in crate::background::replacement) reason: String, + pub(in crate::background::replacement) clipboard_uncertain: bool, +} +impl From for PreparationFailure { + /// Convert a pre-write failure without claiming any clipboard mutation. + fn from(reason: String) -> Self { + Self { + reason, + clipboard_uncertain: false, + } + } +} +impl From<&str> for PreparationFailure { + /// Convert a pre-write failure without claiming any clipboard mutation. + fn from(reason: &str) -> Self { + reason.to_owned().into() + } +} +impl ClipboardTransaction { + /// Snapshot every format and preallocate temporary and restoration data before any write. + pub(in crate::background::replacement) fn prepare(text: &str) -> Result { + if RECOVERY_PENDING.load(Ordering::Acquire) || super::super::shutting_down() { + return Err("clipboard recovery is pending; use fallback".into()); + } + // Prove recovery is available before any clipboard write. + recovery_sender()?; + let owner = owner_window(); + if owner.is_null() { + return Err("clipboard owner window unavailable".into()); + } + let mut transaction = Self { + owner, + saved: Vec::new(), + restore_copy: None, + temporary: Vec::new(), + sequence: 0, + owned: Vec::new(), + clipboard_owner: ptr::null_mut(), + temporary_snapshot: Vec::new(), + restoring: false, + changed: false, + recovery_owner: false, + }; + let lock = ClipboardLock::open(owner)?; + let mut format = 0; + loop { + unsafe { + SetLastError(0); + } + format = unsafe { EnumClipboardFormats(format) }; + if format == 0 { + if unsafe { GetLastError() } != 0 { + return Err("clipboard enumeration failed".into()); + } + break; + } + transaction + .saved + .push(SavedFormat::duplicate(format, unsafe { + GetClipboardData(format) + })?); + } + // Reserve a complete restoration set before replacing the clipboard. + transaction.restore_copy = Some( + transaction + .saved + .iter() + .map(|value| SavedFormat::duplicate(value.format, value.handle)) + .collect::, _>>()?, + ); + // Allocate everything before EmptyClipboard so allocation failure is harmless. + let text: Vec = text + .encode_utf16() + .chain(Some(0)) + .flat_map(u16::to_ne_bytes) + .collect(); + let mut temporary = vec![SavedFormat::bytes(UNICODE_TEXT, &text)?]; + for name in ["CanIncludeInClipboardHistory", "CanUploadToCloudClipboard"] { + let format = unsafe { RegisterClipboardFormatW(wide(name).as_ptr()) }; + if format == 0 { + return Err("clipboard privacy format unavailable".into()); + } + temporary.push(SavedFormat::bytes(format, &0u32.to_ne_bytes())?); + } + transaction.temporary = temporary; + transaction.temporary_snapshot = transaction + .temporary + .iter() + .map(|value| SavedFormat::duplicate(value.format, value.handle)) + .collect::, _>>()?; + transaction.owned = + Vec::with_capacity(transaction.saved.len().max(transaction.temporary.len())); + transaction.sequence = unsafe { GetClipboardSequenceNumber() }; + drop(lock); + Ok(transaction) + } + + /// Require an unchanged sequence and publish privacy markers before temporary text. + pub(in crate::background::replacement) fn install(&mut self) -> Result<(), PreparationFailure> { + if super::super::shutting_down() || RECOVERY_PENDING.load(Ordering::Acquire) { + return Err("clipboard replacement is shutting down or quarantined".into()); + } + let _lock = ClipboardLock::open(self.owner)?; + if unsafe { GetClipboardSequenceNumber() } != self.sequence { + return Err("clipboard changed before paste; newer clipboard retained".into()); + } + if unsafe { EmptyClipboard() } == 0 { + return Err("clipboard could not be prepared".into()); + } + self.changed = true; + self.owned.clear(); + self.clipboard_owner = self.owner; + self.sequence = unsafe { GetClipboardSequenceNumber() }; + // Install privacy markers before text can be observed by history/cloud. + for value in self.temporary.iter_mut().rev() { + if let Err(error) = value.publish() { + // We still hold the clipboard; restore directly before returning. + let restored = self.restore_locked(); + self.sequence = unsafe { GetClipboardSequenceNumber() }; + let clipboard_uncertain = restored.is_err(); + return Err(PreparationFailure { + reason: format!( + "{error}; {}", + restored + .err() + .unwrap_or_else(|| "clipboard restored".into()) + ), + clipboard_uncertain, + }); + } + self.owned.push(value.format); + } + self.sequence = unsafe { GetClipboardSequenceNumber() }; + Ok(()) + } + + /// Restore all originals while locked and retain snapshots on partial publication failure. + fn restore_locked(&mut self) -> Result<(), String> { + let owned = std::cell::RefCell::new(std::mem::take(&mut self.owned)); + let cleared = std::cell::Cell::new(false); + let restored = super::restore_snapshot( + &self.saved, + &mut self.restore_copy, + |value| SavedFormat::duplicate(value.format, value.handle), + || { + if unsafe { EmptyClipboard() } != 0 { + owned.borrow_mut().clear(); + cleared.set(true); + Ok(()) + } else { + Err("clipboard restore failed".into()) + } + }, + |value| { + value.publish()?; + owned.borrow_mut().push(value.format); + Ok(()) + }, + ); + self.owned = owned.into_inner(); + if cleared.get() { + self.clipboard_owner = self.owner; + self.restoring = true; + } + self.sequence = unsafe { GetClipboardSequenceNumber() }; + if restored.is_ok() { + self.changed = false; + } + restored + } + + /// Verify owner, independent published bytes and formats before overwriting anything. + fn owns_current_locked(&self) -> bool { + if unsafe { GetClipboardOwner() } != self.clipboard_owner { + return false; + } + // Closing/reading the clipboard can synthesize formats and change its sequence. + let expected = if self.restoring { + &self.saved + } else { + &self.temporary_snapshot + }; + if self.owned.iter().any(|format| { + expected + .iter() + .find(|value| value.format == *format) + .is_none_or(|value| { + !same_published_data(*format, value.handle, unsafe { + GetClipboardData(*format) + }) + }) + }) { + return false; + } + let mut format = 0; + loop { + unsafe { + SetLastError(0); + } + format = unsafe { EnumClipboardFormats(format) }; + if format == 0 { + return unsafe { GetLastError() } == 0; + } + if !super::owned_format_or_synthesis(&self.owned, format) { + return false; + } + } + } + + /// Restore only our own clipboard state; preserve a newer external copy. + pub(in crate::background::replacement) fn restore(&mut self) -> Result<(), String> { + if !self.changed { + return Ok(()); + } + let _lock = ClipboardLock::open_with_messages(self.owner, self.recovery_owner)?; + if !self.owns_current_locked() { + self.changed = false; + return Err("clipboard changed externally; newer clipboard retained".into()); + } + self.restore_locked() + } +} +impl Drop for ClipboardTransaction { + /// Release owned native resources on scope exit without touching a newer copy. + fn drop(&mut self) { + if self.recovery_owner { + return; + } + if let Err(reason) = self.restore() { + tracing::warn!( + reason, + recovery_pending = self.changed, + "clipboard restoration requires recovery" + ); + if self.changed { + RECOVERY_PENDING.store(true, Ordering::Release); + // Destroying the owner retains already-rendered data with no owner. + // Recovery checks independent copies of published data under the lock. + unsafe { + DestroyWindow(self.owner); + } + let recovery = Recovery { + saved: std::mem::take(&mut self.saved), + sequence: self.sequence, + owned: std::mem::take(&mut self.owned), + clipboard_owner: ptr::null_mut(), + temporary_snapshot: std::mem::take(&mut self.temporary_snapshot), + restoring: self.restoring, + }; + // The worker starts before mutation and is drained on graceful exit. + if recovery_sender() + .and_then(|sender| { + sender + .send(Some(recovery)) + .map_err(|_| "clipboard recovery worker stopped".into()) + }) + .is_err() + { + tracing::warn!("clipboard recovery worker stopped; clipboard method disabled"); + } + return; + } + } + unsafe { + DestroyWindow(self.owner); + } + } +} + +/// WM_PASTE is supported only by known native edit controls. Other apps use SendInput. +pub(in crate::background::replacement) fn supports_paste(window: isize) -> bool { + if window == 0 { + return false; + } + let mut class = [0u16; 128]; + let length = unsafe { GetClassNameW(window as HWND, class.as_mut_ptr(), class.len() as i32) }; + let class = String::from_utf16_lossy(&class[..length.max(0) as usize]).to_ascii_lowercase(); + matches!( + class.as_str(), + "edit" | "richedit20w" | "richedit50w" | "richedit20a" | "richedit" + ) +} + +/// Use bounded synchronous WM_PASTE; timeout means target mutation is uncertain. +pub(in crate::background::replacement) fn paste(window: isize) -> Result<(), String> { + let mut result = 0; + if unsafe { + SendMessageTimeoutW( + window as HWND, + WM_PASTE, + 0, + 0, + SMTO_ABORTIFHUNG | SMTO_BLOCK, + 250, + &mut result, + ) + } == 0 + { + Err("clipboard paste failed or timed out; mutation uncertain".into()) + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/app-core-rust/src/background/replacement/clipboard/windows/recovery.rs b/app-core-rust/src/background/replacement/clipboard/windows/recovery.rs new file mode 100644 index 0000000..30ae4be --- /dev/null +++ b/app-core-rust/src/background/replacement/clipboard/windows/recovery.rs @@ -0,0 +1,230 @@ +//! Bounded, message-responsive recovery, joined before graceful engine exit. +use super::*; +use std::sync::Mutex; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + DispatchMessageW, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, +}; + +const RECOVERY_TIMEOUT: Duration = Duration::from_secs(2); +const MAX_ATTEMPTS: usize = 8; +static STOP_REQUESTED: AtomicBool = AtomicBool::new(false); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RecoveryOutcome { + Restored, + Superseded, + Exhausted, +} + +struct Worker { + sender: mpsc::Sender>, + thread: thread::JoinHandle, +} + +#[derive(Default)] +struct State { + worker: Option, + stopped: bool, +} + +/// Keep the worker lifecycle separate from the exclusion gate for unresolved data. +fn state() -> &'static Mutex { + static STATE: OnceLock> = OnceLock::new(); + STATE.get_or_init(|| Mutex::new(State::default())) +} + +/// Start recovery before mutation; a stopped worker cannot be restarted on exit. +pub(super) fn recovery_sender() -> Result>, String> { + let mut state = state() + .lock() + .map_err(|_| "clipboard recovery state unavailable")?; + if state.stopped { + return Err("clipboard recovery is shutting down".into()); + } + if let Some(worker) = &state.worker { + if worker.thread.is_finished() { + return Err("clipboard recovery worker stopped".into()); + } + return Ok(worker.sender.clone()); + } + if crate::background::replacement::shutting_down() { + return Err("clipboard recovery is shutting down".into()); + } + let (sender, receiver) = mpsc::channel::>(); + let (ready, started) = mpsc::sync_channel(1); + let thread = thread::Builder::new() + .name("clipboard-recovery".into()) + .spawn(move || { + let mut owner = owner_window(); + let _ = ready.send(!owner.is_null()); + if owner.is_null() { + return false; + } + while let Ok(Some(recovery)) = receiver.recv() { + let mut transaction = ClipboardTransaction { + owner, + saved: recovery.saved, + restore_copy: None, + temporary: Vec::new(), + sequence: recovery.sequence, + owned: recovery.owned, + clipboard_owner: recovery.clipboard_owner, + temporary_snapshot: recovery.temporary_snapshot, + restoring: recovery.restoring, + changed: true, + recovery_owner: true, + }; + let mut outcome = recover(&mut transaction, RECOVERY_TIMEOUT); + if outcome == RecoveryOutcome::Exhausted { + // Retain originals and the global gate, but never leave a + // clipboard-owning window blocked on an idle receiver. + release_owner(&mut transaction); + outcome = quarantine(&mut transaction); + } + owner = transaction.owner; + drop(transaction); + // Rendered data survives destruction, but no later copy waits on + // an idle receiver to process WM_DESTROYCLIPBOARD. + unsafe { DestroyWindow(owner) }; + if !finish_recovery(outcome) { + return false; + } + owner = owner_window(); + if owner.is_null() { + tracing::warn!("clipboard recovery window unavailable"); + return false; + } + } + unsafe { DestroyWindow(owner) }; + !RECOVERY_PENDING.load(Ordering::Acquire) + }) + .map_err(|_| "clipboard recovery worker unavailable")?; + if !started.recv().unwrap_or(false) { + let _ = thread.join(); + return Err("clipboard recovery window unavailable".into()); + } + state.worker = Some(Worker { + sender: sender.clone(), + thread, + }); + Ok(sender) +} + +/// Drain queued recovery within its normal retry budget, then release its window. +pub(super) fn shutdown() -> bool { + STOP_REQUESTED.store(true, Ordering::Release); + let worker = { + let mut state = state().lock().unwrap_or_else(|error| error.into_inner()); + state.stopped = true; + state.worker.take() + }; + if let Some(worker) = worker { + let _ = worker.sender.send(None); + match worker.thread.join() { + Ok(clean) => return clean, + Err(_) => tracing::warn!("clipboard recovery worker panicked during shutdown"), + } + } + !RECOVERY_PENDING.load(Ordering::Acquire) +} + +/// Deliver sent clipboard-owner messages even while OpenClipboard is busy. +pub(super) fn pump_messages() { + unsafe { + let mut message: MSG = std::mem::zeroed(); + while PeekMessageW(&mut message, ptr::null_mut(), 0, 0, PM_REMOVE) != 0 { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } +} + +/// Bound permanent publication failures and back off instead of churning Copy. +pub(super) fn recover( + transaction: &mut ClipboardTransaction, + timeout: Duration, +) -> RecoveryOutcome { + let deadline = Instant::now() + timeout; + for attempt in 0..MAX_ATTEMPTS { + pump_messages(); + if !transaction.changed || Instant::now() >= deadline { + break; + } + match transaction.restore() { + Ok(()) => return RecoveryOutcome::Restored, + Err(_) if !transaction.changed => return RecoveryOutcome::Superseded, + Err(reason) => tracing::debug!(reason, "clipboard recovery attempt deferred"), + } + let delay = Duration::from_millis((25u64 << attempt).min(250)); + let next = (Instant::now() + delay).min(deadline); + while Instant::now() < next { + pump_messages(); + thread::sleep(Duration::from_millis(5)); + } + } + if transaction.changed { + tracing::warn!( + method = "clipboard", + attempts_limit = MAX_ATTEMPTS, + "clipboard recovery exhausted; originals retained and clipboard quarantined" + ); + RecoveryOutcome::Exhausted + } else { + RecoveryOutcome::Restored + } +} + +/// Release clipboard ownership while keeping a fresh window available for controlled cleanup. +fn release_owner(transaction: &mut ClipboardTransaction) { + if transaction.clipboard_owner == transaction.owner { + transaction.clipboard_owner = ptr::null_mut(); + } + unsafe { DestroyWindow(transaction.owner) }; + transaction.owner = owner_window(); +} + +/// Probe without republishing partial originals; resume one restore when a busy lock clears. +/// A newer copy ends quarantine. Shutdown gets one final cleanup attempt. +fn quarantine(transaction: &mut ClipboardTransaction) -> RecoveryOutcome { + let mut resume_restore = !transaction.restoring; + while !STOP_REQUESTED.load(Ordering::Acquire) { + if let Ok(_lock) = ClipboardLock::open_with_messages(transaction.owner, true) { + if !transaction.owns_current_locked() { + transaction.changed = false; + return RecoveryOutcome::Superseded; + } + if resume_restore && !transaction.owner.is_null() { + resume_restore = false; + if transaction.restore_locked().is_ok() { + return RecoveryOutcome::Restored; + } + // A partial restore must not be emptied and republished on each probe. + drop(_lock); + release_owner(transaction); + } + } + thread::sleep(Duration::from_millis(250)); + } + if transaction.owner.is_null() { + return RecoveryOutcome::Exhausted; + } + match transaction.restore() { + Ok(()) => RecoveryOutcome::Restored, + Err(_) if !transaction.changed => RecoveryOutcome::Superseded, + Err(_) => RecoveryOutcome::Exhausted, + } +} + +/// Only proven restoration or supersession releases clipboard exclusion across apps. +pub(super) fn finish_recovery(outcome: RecoveryOutcome) -> bool { + if outcome == RecoveryOutcome::Exhausted { + tracing::warn!( + method = "clipboard", + "engine stopped with incomplete clipboard cleanup" + ); + false + } else { + RECOVERY_PENDING.store(false, Ordering::Release); + true + } +} diff --git a/app-core-rust/src/background/replacement/clipboard/windows/tests.rs b/app-core-rust/src/background/replacement/clipboard/windows/tests.rs new file mode 100644 index 0000000..f82b81a --- /dev/null +++ b/app-core-rust/src/background/replacement/clipboard/windows/tests.rs @@ -0,0 +1,539 @@ +use super::*; + +/// Inspect native objects without printing any user clipboard bytes. +unsafe fn fingerprint(format: u32, handle: HANDLE) -> Vec { + use windows_sys::Win32::{ + Graphics::Gdi::{ + GetBitmapBits, GetEnhMetaFileBits, GetMetaFileBitsEx, GetObjectW, GetPaletteEntries, + BITMAP as NativeBitmap, PALETTEENTRY, + }, + System::Memory::GlobalSize, + }; + match format { + BITMAP | 0x82 => { + let mut bitmap: NativeBitmap = std::mem::zeroed(); + assert!( + GetObjectW( + handle, + std::mem::size_of::() as i32, + (&mut bitmap as *mut NativeBitmap).cast() + ) != 0 + ); + let length = (bitmap.bmWidthBytes * bitmap.bmHeight.abs()) as usize; + let mut bytes = vec![0; length]; + assert!( + GetBitmapBits(handle, length as i32, bytes.as_mut_ptr().cast()) as usize == length + ); + bytes + } + PALETTE => { + let count = GetPaletteEntries(handle, 0, 0, ptr::null_mut()); + let mut entries: Vec = vec![std::mem::zeroed(); count as usize]; + assert!(GetPaletteEntries(handle, 0, count, entries.as_mut_ptr()) == count); + std::slice::from_raw_parts( + entries.as_ptr().cast::(), + entries.len() * std::mem::size_of::(), + ) + .to_vec() + } + ENH_METAFILE | 0x8e => { + let length = GetEnhMetaFileBits(handle, 0, ptr::null_mut()); + let mut bytes = vec![0; length as usize]; + assert!(GetEnhMetaFileBits(handle, length, bytes.as_mut_ptr()) == length); + bytes + } + METAFILE | 0x83 => { + let picture = GlobalLock(handle).cast::(); + assert!(!picture.is_null()); + let mut bytes = [(*picture).mm, (*picture).xExt, (*picture).yExt] + .into_iter() + .flat_map(i32::to_ne_bytes) + .collect::>(); + let metafile = (*picture).hMF; + GlobalUnlock(handle); + let length = GetMetaFileBitsEx(metafile, 0, ptr::null_mut()); + let mut bits = vec![0; length as usize]; + assert!(GetMetaFileBitsEx(metafile, length, bits.as_mut_ptr().cast()) == length); + bytes.extend(bits); + bytes + } + _ => { + let length = GlobalSize(handle); + let memory = GlobalLock(handle); + assert!(!memory.is_null()); + let bytes = std::slice::from_raw_parts(memory.cast::(), length).to_vec(); + GlobalUnlock(handle); + bytes + } + } +} + +/// Verify native preservation, bounded quarantine, newer copies, and both shutdown outcomes. +#[test] +#[ignore = "runs native clipboard operations in a child with an isolated window station"] +fn native_clipboard_preservation_smoke() { + use std::{os::windows::process::CommandExt, process::Command}; + use windows_sys::Win32::{ + Graphics::Gdi::CreateBitmap, System::StationsAndDesktops::*, + UI::WindowsAndMessaging::WINSTA_ALL_ACCESS, + }; + if std::env::var("AUTOFIX_CLIPBOARD_TEST_HOST").as_deref() != Ok("1") { + for exhausted_exit in ["0", "1"] { + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "native_clipboard_preservation_smoke", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("AUTOFIX_CLIPBOARD_TEST_HOST", "1") + .env("AUTOFIX_CLIPBOARD_TEST_EXHAUSTED_EXIT", exhausted_exit) + .creation_flags(0x08000000) + .output() + .unwrap(); + assert!( + output.status.success(), + "isolated clipboard test failed: {} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + return; + } + // A clipboard belongs to a window station. Never write to the user's station. + let station = unsafe { + CreateWindowStationW( + ptr::null(), + 0, // System-named noninteractive station; no administrator rights required. + WINSTA_ALL_ACCESS as u32, + ptr::null(), + ) + }; + assert!( + !station.is_null(), + "isolated station unavailable: Windows error {}", + unsafe { GetLastError() } + ); + let mut flags: USEROBJECTFLAGS = unsafe { std::mem::zeroed() }; + assert!( + unsafe { + GetUserObjectInformationW( + station, + UOI_FLAGS, + (&mut flags as *mut USEROBJECTFLAGS).cast(), + std::mem::size_of::() as u32, + ptr::null_mut(), + ) + } != 0 + ); + assert!( + flags.dwFlags & 1 == 0, + "refuse the visible user window station" + ); + assert!(unsafe { SetProcessWindowStation(station) } != 0); + let desktop = unsafe { + CreateDesktopW( + wide("test").as_ptr(), + ptr::null(), + ptr::null(), + 0, + 0x01ff, + ptr::null(), + ) + }; + assert!(!desktop.is_null(), "isolated desktop unavailable"); + assert!(unsafe { SetThreadDesktop(desktop) } != 0); + let seed_owner = owner_window(); + assert!(!seed_owner.is_null()); + let seed_lock = ClipboardLock::open(seed_owner).unwrap(); + if unsafe { EnumClipboardFormats(0) } != 0 { + // Clean only the exact seed left by an earlier run of this isolated test. + let marker = unsafe { RegisterClipboardFormatW(wide("AutoFix test binary").as_ptr()) }; + let marker_handle = unsafe { GetClipboardData(marker) }; + let prior_text = wide(if marker_handle.is_null() { + "pending recovery" + } else { + "isolated original rich text" + }) + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + assert!( + unsafe { fingerprint(UNICODE_TEXT, GetClipboardData(UNICODE_TEXT)) } + .starts_with(&prior_text) + ); + if !marker_handle.is_null() { + assert!(unsafe { fingerprint(marker, marker_handle) }.starts_with(&[0, 255, 1, 0])); + } else { + let privacy = + unsafe { RegisterClipboardFormatW(wide("CanIncludeInClipboardHistory").as_ptr()) }; + let value = unsafe { GetClipboardData(privacy) }; + assert!(!value.is_null()); + assert!(unsafe { fingerprint(privacy, value) }.starts_with(&[0, 0, 0, 0])); + } + assert!(unsafe { EmptyClipboard() } != 0); + } + assert!( + unsafe { EnumClipboardFormats(0) } == 0, + "test station clipboard must be empty" + ); + assert!(unsafe { EmptyClipboard() } != 0); + let text = wide("isolated original rich text") + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + let mut seeds = vec![SavedFormat::bytes(UNICODE_TEXT, &text).unwrap()]; + for (name, bytes) in [ + ("Rich Text Format", b"{\\rtf1\\b original}\0".as_slice()), + ("HTML Format", b"original\0".as_slice()), + ("AutoFix test binary", &[0u8, 255, 1, 0][..]), + ] { + let format = unsafe { RegisterClipboardFormatW(wide(name).as_ptr()) }; + seeds.push(SavedFormat::bytes(format, bytes).unwrap()); + } + let pixel = [12u8, 34, 56, 78]; + seeds.push(SavedFormat { + format: BITMAP, + handle: unsafe { CreateBitmap(1, 1, 1, 32, pixel.as_ptr().cast()) }, + }); + for seed in &mut seeds { + seed.publish().unwrap(); + } + drop(seed_lock); + let mut transaction = match ClipboardTransaction::prepare("the") { + Ok(transaction) => transaction, + Err(reason) => { + panic!("clipboard preservation preflight refused safely: {reason}") + } + }; + // Failures while fingerprinting occur before the first clipboard write. + let expected: Vec<_> = transaction + .saved + .iter() + .map(|value| { + (value.format, unsafe { + fingerprint(value.format, value.handle) + }) + }) + .collect(); + transaction + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + let edit = unsafe { + CreateWindowExW( + 0, + wide("EDIT").as_ptr(), + wide("teh AFTER").as_ptr(), + windows_sys::Win32::UI::WindowsAndMessaging::WS_POPUP, + 0, + 0, + 200, + 80, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null(), + ) + }; + assert!(!edit.is_null()); + unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::SendMessageW(edit, 0x00b1, 0, 3); + } + super::super::paste_and_restore(|| paste(edit as isize), || transaction.restore()).unwrap(); + let mut text = [0u16; 32]; + let length = unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::GetWindowTextW( + edit, + text.as_mut_ptr(), + text.len() as i32, + ) + }; + assert_eq!( + String::from_utf16_lossy(&text[..length as usize]), + "the AFTER" + ); + unsafe { + DestroyWindow(edit); + } + let _lock = ClipboardLock::open(transaction.owner).unwrap(); + if expected.is_empty() { + assert!(unsafe { EnumClipboardFormats(0) } == 0); + } + let expected_formats: std::collections::BTreeSet<_> = + expected.iter().map(|(format, _)| *format).collect(); + let mut restored_formats = std::collections::BTreeSet::new(); + let mut format = 0; + loop { + format = unsafe { EnumClipboardFormats(format) }; + if format == 0 { + break; + } + restored_formats.insert(format); + } + assert_eq!( + restored_formats, expected_formats, + "temporary clipboard formats survived restoration" + ); + for (format, bytes) in &expected { + let restored = unsafe { GetClipboardData(*format) }; + assert!(!restored.is_null(), "clipboard format {format} missing"); + assert!( + unsafe { fingerprint(*format, restored) } == *bytes, + "clipboard format {format} changed" + ); + } + drop(_lock); + drop(transaction); + // A locked clipboard must retain recovery data until it can be restored. + let mut blocked = ClipboardTransaction::prepare("pending recovery").unwrap(); + blocked + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + let (ready, started) = mpsc::channel(); + let (release, released) = mpsc::channel(); + let holder = thread::spawn(move || { + let lock = ClipboardLock::open(ptr::null_mut()).unwrap(); + ready.send(()).unwrap(); + released.recv().unwrap(); + drop(lock); + }); + started.recv().unwrap(); + assert!(blocked.restore().is_err()); + drop(blocked); + assert!(RECOVERY_PENDING.load(Ordering::Acquire)); + // Keep the lock beyond the active retry budget. Originals and cross-app + // exclusion must survive exhaustion until controlled recovery can resume. + thread::sleep(Duration::from_millis(2500)); + assert!(RECOVERY_PENDING.load(Ordering::Acquire)); + assert!(ClipboardTransaction::prepare("another app correction").is_err()); + release.send(()).unwrap(); + holder.join().unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while RECOVERY_PENDING.load(Ordering::Acquire) && Instant::now() < deadline { + thread::sleep(Duration::from_millis(10)); + } + assert!( + !RECOVERY_PENDING.load(Ordering::Acquire), + "recovery did not finish" + ); + let lock = ClipboardLock::open(seed_owner).unwrap(); + for (format, bytes) in &expected { + assert!( + unsafe { fingerprint(*format, GetClipboardData(*format)) } == *bytes, + "recovered clipboard format {format} changed" + ); + } + assert!(unsafe { EmptyClipboard() } != 0); + drop(lock); + let mut superseded = ClipboardTransaction::prepare("superseded correction").unwrap(); + superseded + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + let lock = ClipboardLock::open(seed_owner).unwrap(); + assert!(unsafe { EmptyClipboard() } != 0); + let newer = wide("new copy") + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + SavedFormat::bytes(UNICODE_TEXT, &newer) + .unwrap() + .publish() + .unwrap(); + drop(lock); + assert!(superseded.restore().is_err()); + let lock = ClipboardLock::open(seed_owner).unwrap(); + let actual = unsafe { fingerprint(UNICODE_TEXT, GetClipboardData(UNICODE_TEXT)) }; + assert!(actual.starts_with(&newer), "newer copy was overwritten"); + assert!(unsafe { EmptyClipboard() } != 0); // Return the test station to its original empty state. + drop(lock); + + // A permanently invalid publication must terminate, scrub temporary text, + // and release ownership rather than republish forever. + let lock = ClipboardLock::open(seed_owner).unwrap(); + let original = wide("saved original") + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + SavedFormat::bytes(UNICODE_TEXT, &original) + .unwrap() + .publish() + .unwrap(); + drop(lock); + let mut permanent = ClipboardTransaction::prepare("temporary failure text").unwrap(); + permanent + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + permanent + .saved + .push(SavedFormat::bytes(0, b"invalid format").unwrap()); + permanent.restore_copy = None; + drop(permanent); + thread::sleep(Duration::from_millis(2500)); + assert!( + RECOVERY_PENDING.load(Ordering::Acquire), + "permanent failure released exclusion" + ); + assert!(ClipboardTransaction::prepare("another app correction").is_err()); + let lock = ClipboardLock::open(seed_owner).unwrap(); + assert!( + unsafe { fingerprint(UNICODE_TEXT, GetClipboardData(UNICODE_TEXT)) }.starts_with(&original) + ); + drop(lock); + let sequence = unsafe { GetClipboardSequenceNumber() }; + thread::sleep(Duration::from_millis(500)); + assert_eq!( + unsafe { GetClipboardSequenceNumber() }, + sequence, + "quarantine kept republishing partial data" + ); + let lock = ClipboardLock::open(seed_owner).unwrap(); + assert!(unsafe { EmptyClipboard() } != 0); + SavedFormat::bytes(UNICODE_TEXT, &original) + .unwrap() + .publish() + .unwrap(); + drop(lock); + let deadline = Instant::now() + Duration::from_secs(2); + while RECOVERY_PENDING.load(Ordering::Acquire) && Instant::now() < deadline { + thread::sleep(Duration::from_millis(10)); + } + assert!( + !RECOVERY_PENDING.load(Ordering::Acquire), + "new copy did not end quarantine" + ); + + // EmptyClipboard sends WM_DESTROYCLIPBOARD to the owner synchronously. + // The recovery thread must service it even when the caller holds the lock. + let mut copied = ClipboardTransaction::prepare("temporary copy text").unwrap(); + copied + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + copied.recovery_owner = true; + let (ready, started) = mpsc::channel(); + let (done, finished) = mpsc::channel(); + let copier = thread::spawn(move || { + let owner = owner_window(); + let lock = ClipboardLock::open(owner).unwrap(); + ready.send(()).unwrap(); + assert!(unsafe { EmptyClipboard() } != 0); + let text = wide("concurrent new copy") + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + SavedFormat::bytes(UNICODE_TEXT, &text) + .unwrap() + .publish() + .unwrap(); + drop(lock); + unsafe { DestroyWindow(owner) }; + done.send(()).unwrap(); + }); + started.recv_timeout(Duration::from_secs(1)).unwrap(); + recovery::recover(&mut copied, Duration::from_millis(500)); + unsafe { DestroyWindow(copied.owner) }; + finished + .recv_timeout(Duration::from_secs(1)) + .expect("Copy blocked on clipboard owner"); + copier.join().unwrap(); + assert!(!copied.changed, "newer copy must end recovery"); + drop(copied); + + // Graceful shutdown waits for queued restoration after a lock is released. + let mut exiting = ClipboardTransaction::prepare("temporary exit text").unwrap(); + exiting + .install() + .unwrap_or_else(|failure| panic!("{}", failure.reason)); + if std::env::var("AUTOFIX_CLIPBOARD_TEST_EXHAUSTED_EXIT").as_deref() == Ok("1") { + exiting + .saved + .push(SavedFormat::bytes(0, b"invalid format").unwrap()); + exiting.restore_copy = None; + drop(exiting); + assert!(RECOVERY_PENDING.load(Ordering::Acquire)); + assert!(!shutdown(), "incomplete cleanup was reported as clean"); + assert!(RECOVERY_PENDING.load(Ordering::Acquire)); + assert!(ClipboardTransaction::prepare("another app correction").is_err()); + let lock = ClipboardLock::open(seed_owner).unwrap(); + assert!(unsafe { EmptyClipboard() } != 0); + drop(lock); + return; + } + let (ready, started) = mpsc::channel(); + let (release, released) = mpsc::channel(); + let holder = thread::spawn(move || { + let lock = ClipboardLock::open(ptr::null_mut()).unwrap(); + ready.send(()).unwrap(); + released.recv().unwrap(); + thread::sleep(Duration::from_millis(100)); + drop(lock); + }); + started.recv().unwrap(); + drop(exiting); + assert!(RECOVERY_PENDING.load(Ordering::Acquire)); + release.send(()).unwrap(); + assert!(shutdown(), "restored clipboard was reported as incomplete"); + holder.join().unwrap(); + assert!(!RECOVERY_PENDING.load(Ordering::Acquire)); + assert!( + recovery_sender().is_err(), + "shutdown must not restart recovery" + ); + let lock = ClipboardLock::open(seed_owner).unwrap(); + let bytes = unsafe { fingerprint(UNICODE_TEXT, GetClipboardData(UNICODE_TEXT)) }; + let expected = wide("concurrent new copy") + .into_iter() + .flat_map(u16::to_ne_bytes) + .collect::>(); + assert!( + bytes.starts_with(&expected), + "shutdown lost the saved clipboard" + ); + assert!(unsafe { EmptyClipboard() } != 0); + drop(lock); +} + +#[test] +fn clipboard_format_snapshot_owns_all_bytes_independently() { + let bytes = b"{\\rtf1 rich text}\0\xff\x01"; + let source = SavedFormat::bytes(0xc001, bytes).unwrap(); + let copy = SavedFormat::duplicate(source.format, source.handle).unwrap(); + drop(source); + unsafe { + let memory = GlobalLock(copy.handle); + assert!(!memory.is_null()); + assert_eq!( + std::slice::from_raw_parts(memory.cast::(), bytes.len()), + bytes + ); + GlobalUnlock(copy.handle); + } +} + +#[test] +fn owner_managed_clipboard_formats_refuse_duplication() { + let source = SavedFormat::bytes(UNICODE_TEXT, b"data\0").unwrap(); + for format in [0x80, 0x200, 0x2ff, 0x300, 0x3ff] { + assert!(SavedFormat::duplicate(format, source.handle).is_err()); + } +} + +#[test] +fn bitmap_snapshot_owns_an_independent_gdi_object() { + use windows_sys::Win32::Graphics::Gdi::{CreateBitmap, GetBitmapBits}; + let pixel = [12u8, 34, 56, 78]; + let source = SavedFormat { + format: BITMAP, + handle: unsafe { CreateBitmap(1, 1, 1, 32, pixel.as_ptr().cast()) }, + }; + assert!(!source.handle.is_null()); + let copy = SavedFormat::duplicate(BITMAP, source.handle).unwrap(); + assert_ne!(source.handle, copy.handle); + assert!(same_published_data(BITMAP, source.handle, copy.handle)); + drop(source); + let mut actual = [0u8; 4]; + assert_eq!( + unsafe { GetBitmapBits(copy.handle, 4, actual.as_mut_ptr().cast()) }, + 4 + ); + assert_eq!(actual, pixel); +} diff --git a/app-core-rust/src/background/replacement/mod.rs b/app-core-rust/src/background/replacement/mod.rs new file mode 100644 index 0000000..76a2fb7 --- /dev/null +++ b/app-core-rust/src/background/replacement/mod.rs @@ -0,0 +1,239 @@ +//! The mutation owner. Strategies may fall through only before any target mutation. +mod clipboard; +mod native; +#[cfg(windows)] +mod send_input; +#[cfg(test)] +mod tests; + +use super::{ + pipeline::InputStamp, + target::{CorrectionEligibility, FocusedTarget}, + triggers::CorrectionRequest, +}; +use crate::correction::{ConfidenceBehavior, ConfidenceTier, CorrectionOutput, EngineStatus}; +use std::sync::atomic::{AtomicBool, Ordering}; + +static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false); + +/// Stop new native selections and mutations before waiting for input processing. +pub(super) fn begin_shutdown() { + SHUTTING_DOWN.store(true, Ordering::Release); +} + +/// Native boundary checks also cover a processor delayed by a provider call. +fn shutting_down() -> bool { + SHUTTING_DOWN.load(Ordering::Acquire) +} + +/// Join recovery after the input processor has dropped its clipboard transaction. +pub(super) fn finish_shutdown() -> bool { + #[cfg(windows)] + { + clipboard::shutdown() + } + #[cfg(not(windows))] + { + true + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ReplacementMethod { + DirectTextApi, + UiAutomation, + Clipboard, + SendInput, +} + +/// Exact character offsets backwards from the pre-replacement caret. +/// start_back >= end_back >= 0; the half-open range never extends after that caret. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ReplacedRange { + pub(super) start_back: usize, + pub(super) end_back: usize, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) struct ReplacementResult { + pub(super) success: bool, + /// None means rejected before any strategy was attempted. + pub(super) method: Option, + /// Present only after the native range was proved (also on uncertain failures). + pub(super) range: Option, + pub(super) reason: Option, + /// Failed verification or partial input requires dropping the tracked session. + pub(super) may_have_changed: bool, +} + +impl ReplacementResult { + /// Native failures remain visible with default logging. No target text is logged. + pub(super) fn log_outcome(&self, undo: bool) { + if self.success { + tracing::info!(success = true, method = ?self.method, range = ?self.range, undo, + "native replacement completed"); + } else { + tracing::warn!(success = false, method = ?self.method, range = ?self.range, + reason = ?self.reason, may_have_changed = self.may_have_changed, undo, + "native replacement failed or skipped"); + } + } +} + +struct ReplacementPlan<'a> { + target: &'a FocusedTarget, + original: &'a str, + replacement: &'a str, + following: &'a str, + stamp: InputStamp, +} + +impl ReplacementPlan<'_> { + /// Count Unicode scalars backwards from the live caret, excluding newer typed text. + fn range(&self) -> ReplacedRange { + let end_back = self.following.chars().count(); + ReplacedRange { + start_back: end_back + self.original.chars().count(), + end_back, + } + } +} + +enum Attempt { + /// Capability/preparation failed without changing target text or selection. + Unavailable(String), + Finished(ReplacementResult), +} + +trait ReplacementStrategy { + /// Identify the strategy so clipboard preferences can skip preparation entirely. + fn method(&self) -> ReplacementMethod; + /// Return Unavailable only before target selection or mutation can have changed. + fn replace(&mut self, plan: &ReplacementPlan<'_>) -> Attempt; +} + +/// Reserved layers have an explicit capability refusal, never pretend success. +struct DeferredStrategy(ReplacementMethod); +impl ReplacementStrategy for DeferredStrategy { + /// Identify the strategy so clipboard preferences can skip preparation entirely. + fn method(&self) -> ReplacementMethod { + self.0 + } + + /// Return Unavailable only before target selection or mutation can have changed. + fn replace(&mut self, _: &ReplacementPlan<'_>) -> Attempt { + Attempt::Unavailable(format!("{:?} replacement is not implemented", self.0)) + } +} + +/// Try methods in safety order and stop on every completed or uncertain attempt. +fn run_strategies( + plan: &ReplacementPlan<'_>, + strategies: &mut [&mut dyn ReplacementStrategy], + clipboard_allowed: bool, +) -> ReplacementResult { + let mut method = None; + let mut reasons = Vec::new(); + for strategy in strategies { + if strategy.method() == ReplacementMethod::Clipboard && !clipboard_allowed { + continue; + } + method = Some(strategy.method()); + match strategy.replace(plan) { + Attempt::Unavailable(reason) => reasons.push(reason), + Attempt::Finished(result) => return result, + } + } + ReplacementResult { + success: false, + method, + range: None, + reason: Some(reasons.join("; ")), + may_have_changed: false, + } +} + +pub(super) struct ReplacementEngine; +impl ReplacementEngine { + /// Called only after the pipeline proves session ownership, policy and live text. + pub(super) fn replace( + target: &FocusedTarget, + request: &CorrectionRequest, + output: &CorrectionOutput, + stamp: InputStamp, + clipboard_enabled: bool, + ) -> ReplacementResult { + let reason = if target.correction_eligibility() != CorrectionEligibility::Allowed { + Some("target is protected, unavailable or unsupported") + } else if request.selected_text { + // Even opt-in selections must prove the live caret end. V1 cannot do so. + Some("selected range has no verified pre-caret geometry") + } else if request.executable_context.is_empty() { + Some("executable context is empty") + } else if request.executable_context.contains('\0') + || output.corrected_executable_text.contains('\0') + || output.corrected_executable_text.encode_utf16().count() > 65_536 + { + Some("replacement contains NUL or exceeds the input budget") + } else if output.status != EngineStatus::Completed + || !output.changes_needed + || output.behavior != ConfidenceBehavior::Silent + || output.confidence == ConfidenceTier::Low + || output.corrected_executable_text == request.executable_context + { + Some("correction does not authorize replacement") + } else { + None + }; + if let Some(reason) = reason { + return ReplacementResult { + success: false, + method: None, + range: None, + reason: Some(reason.into()), + may_have_changed: false, + }; + } + let plan = ReplacementPlan { + target, + original: &request.executable_context, + replacement: &output.corrected_executable_text, + following: &request.replacement_following_text, + stamp, + }; + Self::execute(&plan, clipboard_enabled) + } + + /// Informative text is editable only through a session-issued app correction record. + pub(super) fn undo( + target: &FocusedTarget, + undo: &super::session::CorrectionUndoTarget, + stamp: InputStamp, + clipboard_enabled: bool, + ) -> ReplacementResult { + Self::execute( + &ReplacementPlan { + target, + original: &undo.corrected, + replacement: &undo.original, + following: &undo.following, + stamp, + }, + clipboard_enabled, + ) + } + + /// Apply the same strategy ordering and clipboard preference to correction and undo. + fn execute(plan: &ReplacementPlan<'_>, clipboard_enabled: bool) -> ReplacementResult { + run_strategies( + plan, + &mut [ + &mut DeferredStrategy(ReplacementMethod::DirectTextApi), + &mut DeferredStrategy(ReplacementMethod::UiAutomation), + &mut native::NativeStrategy(ReplacementMethod::Clipboard), + &mut native::NativeStrategy(ReplacementMethod::SendInput), + ], + clipboard_enabled && clipboard::allowed_for(&plan.target.process_name), + ) + } +} diff --git a/app-core-rust/src/background/replacement/native.rs b/app-core-rust/src/background/replacement/native.rs new file mode 100644 index 0000000..73c64d0 --- /dev/null +++ b/app-core-rust/src/background/replacement/native.rs @@ -0,0 +1,476 @@ +use super::{Attempt, ReplacementMethod, ReplacementPlan, ReplacementResult, ReplacementStrategy}; + +pub(super) struct NativeStrategy(pub(super) ReplacementMethod); + +impl ReplacementStrategy for NativeStrategy { + /// Identify the mutation method for strategy ordering and failure metadata. + fn method(&self) -> ReplacementMethod { + self.0 + } + + /// Attempt only the requested native method after proving the pre-caret range. + fn replace(&mut self, plan: &ReplacementPlan<'_>) -> Attempt { + replace(self.0, plan) + } +} + +/// Attempt only the requested native method after proving the pre-caret range. +#[cfg(windows)] +fn replace(method: ReplacementMethod, plan: &ReplacementPlan<'_>) -> Attempt { + use windows::Win32::{ + Foundation::{S_FALSE, S_OK}, + System::Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED}, + }; + let initialization = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + if initialization != S_OK && initialization != S_FALSE { + return Attempt::Unavailable("UI Automation apartment unavailable".into()); + } + struct Apartment; + impl Drop for Apartment { + /// Balance the COM initialization on the thread that acquired it. + fn drop(&mut self) { + unsafe { CoUninitialize() }; + } + } + let _apartment = Apartment; + match PreparedRange::new(plan) { + Err(reason) => Attempt::Unavailable(reason), + Ok(range) => range.replace(method, plan), + } +} + +/// Refuse native mutation on platforms without Windows replacement APIs. +#[cfg(not(windows))] +fn replace(_: ReplacementMethod, _: &ReplacementPlan<'_>) -> Attempt { + Attempt::Unavailable("native replacement requires Windows".into()) +} + +#[cfg(windows)] +use windows::Win32::UI::Accessibility::{ + IUIAutomation2, IUIAutomationElement, IUIAutomationTextPattern, IUIAutomationTextRange, + TextPatternRangeEndpoint_End as END, TextPatternRangeEndpoint_Start as START, + TextUnit_Character, UIA_TextPatternId, +}; + +#[cfg(windows)] +struct PreparedRange { + automation: IUIAutomation2, + element: IUIAutomationElement, + pattern: IUIAutomationTextPattern, + original_caret: IUIAutomationTextRange, + span: IUIAutomationTextRange, +} + +#[cfg(windows)] +impl PreparedRange { + /// Prove exact session text at a collapsed caret without modifying the document. + fn new(plan: &ReplacementPlan<'_>) -> Result { + if plan.original.contains('\0') || plan.replacement.contains('\0') { + return Err("embedded NUL cannot be replaced safely".into()); + } + if plan.original.is_empty() && plan.replacement.is_empty() { + return Err("empty span cannot authorize a deletion".into()); + } + if plan.range().start_back > 65_536 || plan.replacement.encode_utf16().count() > 65_536 { + return Err("replacement range exceeds the input budget".into()); + } + if !current(plan) { + return Err("target or input changed before replacement".into()); + } + let result = unsafe { + (|| -> windows::core::Result { + let automation = super::super::target::create_automation()?; + let element = automation.GetFocusedElement()?; + if element.CurrentIsPassword()?.as_bool() + || element.CurrentIsOffscreen()?.as_bool() + || !element.CurrentIsEnabled()?.as_bool() + { + return Err(range_error("field is protected, hidden or disabled")); + } + let pattern: IUIAutomationTextPattern = + element.GetCurrentPatternAs(UIA_TextPatternId)?; + let caret = collapsed_selection(&pattern)?; + // Providers differ on supplementary Unicode character units. + // Resolve both known spans independently and require exact text. + let following = adjacent_range(&caret, plan.following, true)?; + let original_end = following.Clone()?; + original_end.MoveEndpointByRange(END, &following, START)?; + let span = adjacent_range(&original_end, plan.original, true)?; + if span.CompareEndpoints(START, &span, END)? > 0 + || span.CompareEndpoints(END, &caret, END)? > 0 + || span.GetText(-1)? != plan.original + { + return Err(range_error("pre-caret text does not match")); + } + Ok(Self { + automation, + element, + pattern, + original_caret: caret, + span, + }) + })() + }; + // Provider error messages are untrusted and can contain document text. + let range = result.map_err(|_| "no reliable collapsed pre-caret range".to_owned())?; + if !current(plan) || !range.focused() { + return Err("focus or input changed while proving range".into()); + } + Ok(range) + } + + /// Require the same focused UI Automation element throughout the operation. + fn focused(&self) -> bool { + unsafe { + self.automation + .GetFocusedElement() + .ok() + .is_some_and(|element| { + self.automation + .CompareElements(&self.element, &element) + .is_ok_and(|equal| equal.as_bool()) + }) + } + } + + /// Attempt only the requested native method after proving the pre-caret range. + fn replace(&self, method: ReplacementMethod, plan: &ReplacementPlan<'_>) -> Attempt { + // Never release the user's modifiers or inject text through a held hotkey. + let released = std::time::Instant::now() + std::time::Duration::from_millis(250); + while super::send_input::modifiers_held() { + if std::time::Instant::now() >= released || !current(plan) { + return Attempt::Unavailable( + "shortcut modifiers remain held or input changed".into(), + ); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let paste_window = if method == ReplacementMethod::Clipboard { + match unsafe { self.element.CurrentNativeWindowHandle() } { + Ok(window) if super::clipboard::supports_paste(window.0 as isize) => { + Some(window.0 as isize) + } + _ => { + return Attempt::Unavailable( + "no reliable synchronous clipboard paste API".into(), + ) + } + } + } else { + None + }; + let input_window = if method == ReplacementMethod::SendInput { + match unsafe { self.element.CurrentNativeWindowHandle() } { + Ok(window) if super::send_input::supports_target(window.0 as isize) => { + Some(window.0 as isize) + } + _ => { + return Attempt::Unavailable( + "SendInput target has no verified insert semantics".into(), + ) + } + } + } else { + None + }; + let inputs = if input_window.is_some() { + match super::send_input::prepare(plan.replacement) { + Ok(inputs) => Some(inputs), + Err(reason) => return Attempt::Unavailable(reason), + } + } else { + None + }; + // Snapshot every clipboard format before selecting anything in the target. + let mut clipboard = if paste_window.is_some() { + match super::clipboard::ClipboardTransaction::prepare(plan.replacement) { + Ok(transaction) => Some(transaction), + Err(reason) => return Attempt::Unavailable(reason), + } + } else { + None + }; + let mut result = ReplacementResult { + success: false, + method: Some(method), + range: Some(plan.range()), + reason: None, + may_have_changed: false, + }; + let mut selection_attempted = false; + let operation = (|| -> Result<(), String> { + if !current(plan) || !self.focused() { + return Err("target changed before selection".into()); + } + selection_attempted = true; + unsafe { self.span.Select() }.map_err(|_| "range selection failed")?; + // Verify Select selected exactly the proven span, not a provider approximation. + self.verify_selection(plan)?; + if let Some(transaction) = clipboard.as_mut() { + transaction.install().map_err(|failure| { + if failure.clipboard_uncertain { + super::clipboard::restore_failed( + &plan.target.process_name, + plan.target.process_id, + ); + } + failure.reason + })?; + } + // Clipboard preparation and provider calls can take time. Recheck the + // exact selection and user modifiers at the last mutation boundary. + self.verify_selection(plan)?; + if super::send_input::modifiers_held() { + return Err("shortcut modifier pressed before mutation".into()); + } + if let Some(window) = input_window { + if !super::send_input::supports_target(window) || !keyboard_target(window, plan) { + return Err("SendInput keyboard focus or target safety changed".into()); + } + } + if !current(plan) || !self.focused() { + return Err("target or input changed before mutation".into()); + } + // After this point a failed call may have mutated text: never fall through. + result.may_have_changed = true; + if let Some(window) = paste_window { + super::clipboard::paste_and_restore( + || super::clipboard::paste(window), + || restore_clipboard(clipboard.as_mut(), plan), + )?; + } else { + super::send_input::send(inputs.as_deref().ok_or("SendInput batch unavailable")?)?; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250); + loop { + if !current_after_mutation(plan) || !self.focused() { + return Err("target or input changed during replacement".into()); + } + let failure = match self.verify_and_restore_caret(plan) { + Ok(()) => return Ok(()), + Err(reason) => reason, + }; + if std::time::Instant::now() >= deadline { + return Err(format!("replacement could not be verified: {failure}")); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + })(); + let restored = restore_clipboard(clipboard.as_mut(), plan); + if operation.is_err() && !result.may_have_changed && selection_attempted { + // An unverified selection is enough to invalidate the typed anchor. + result.may_have_changed = !self.restore_original_caret(plan); + } + match (operation, restored) { + (Ok(()), Ok(())) => result.success = true, + (Err(reason), Ok(())) | (Ok(()), Err(reason)) => result.reason = Some(reason), + (Err(reason), Err(restore)) => result.reason = Some(format!("{reason}; {restore}")), + } + Attempt::Finished(result) + } + + /// Undo selection only while the original target and input stamp remain current. + fn restore_original_caret(&self, plan: &ReplacementPlan<'_>) -> bool { + if !current(plan) || !self.focused() { + return false; + } + unsafe { + self.original_caret.Select().is_ok() + && collapsed_selection(&self.pattern).is_ok_and(|caret| { + caret.CompareEndpoints(END, &self.original_caret, END).ok() == Some(0) + }) + && current(plan) + && self.focused() + } + } + + /// Reject approximate provider selections before publishing or injecting text. + fn verify_selection(&self, plan: &ReplacementPlan<'_>) -> Result<(), String> { + unsafe { + let selections = self + .pattern + .GetSelection() + .map_err(|_| "selection unreadable")?; + if selections.Length().ok() != Some(1) { + return Err("selection is not a single range".into()); + } + let selected = selections + .GetElement(0) + .map_err(|_| "selection unreadable")?; + if selected.CompareEndpoints(START, &self.span, START).ok() != Some(0) + || selected.CompareEndpoints(END, &self.span, END).ok() != Some(0) + || selected.GetText(-1).map_err(|_| "selection unreadable")? != plan.original + || !current(plan) + || !self.focused() + { + return Err("selected range or input changed".into()); + } + } + Ok(()) + } + + /// Reacquire the provider and prove replacement and following text before moving the caret. + fn verify_and_restore_caret(&self, plan: &ReplacementPlan<'_>) -> Result<(), String> { + unsafe { + (|| -> windows::core::Result<()> { + // Discard the pre-mutation provider and its range snapshots. + let automation = super::super::target::create_automation()?; + let element = automation.GetFocusedElement()?; + let pattern: IUIAutomationTextPattern = + element.GetCurrentPatternAs(UIA_TextPatternId)?; + let caret = collapsed_selection(&pattern)?; + adjacent_range(&caret, plan.replacement, true)?; + let following = adjacent_range(&caret, plan.following, false)?; + if !current_after_mutation(plan) || !self.focused() { + return Err(range_error("target changed before caret restoration")); + } + following.MoveEndpointByRange(START, &following, END)?; + following.Select()?; + let restored = collapsed_selection(&pattern)?; + if restored.CompareEndpoints(END, &following, END)? != 0 + || !current_after_mutation(plan) + || !self.focused() + { + return Err(range_error("caret restoration could not be verified")); + } + Ok(()) + })() + .map_err(|_| "native replacement or caret verification failed".to_owned()) + } + } +} + +/// Restore saved formats and disable this app's clipboard strategy after failure. +#[cfg(windows)] +fn restore_clipboard( + clipboard: Option<&mut super::clipboard::ClipboardTransaction>, + plan: &ReplacementPlan<'_>, +) -> Result<(), String> { + let result = clipboard.map_or(Ok(()), |transaction| transaction.restore()); + if result.is_err() { + super::clipboard::restore_failed(&plan.target.process_name, plan.target.process_id); + } + result +} + +/// Create internal range errors; discard provider error text at the public boundary. +#[cfg(windows)] +fn range_error(message: &str) -> windows::core::Error { + windows::core::Error::new(windows::core::HRESULT(0x80004005u32 as i32), message) +} + +/// Resolve a known adjacent span, never search document text or move the caret. +/// Accept only exact text at the fixed anchor, using scalar or UTF-16 units. +#[cfg(windows)] +unsafe fn adjacent_range( + anchor: &IUIAutomationTextRange, + text: &str, + before: bool, +) -> windows::core::Result { + if anchor.CompareEndpoints(START, anchor, END)? != 0 { + return Err(range_error("range anchor is not collapsed")); + } + for count in [text.chars().count(), text.encode_utf16().count()] { + let count = i32::try_from(count).map_err(|_| range_error("range exceeds input budget"))?; + let range = anchor.Clone()?; + range.MoveEndpointByUnit( + if before { START } else { END }, + TextUnit_Character, + if before { -count } else { count }, + )?; + if range.GetText(-1)? == text { + return Ok(range); + } + } + Err(range_error("adjacent range does not match known text")) +} + +/// Accept exactly one empty selection, with no assumption about its active endpoint. +#[cfg(windows)] +unsafe fn collapsed_selection( + pattern: &IUIAutomationTextPattern, +) -> windows::core::Result { + let selections = pattern.GetSelection()?; + if selections.Length()? != 1 { + return Err(range_error("selection is not a single caret")); + } + let caret = selections.GetElement(0)?; + if caret.CompareEndpoints(START, &caret, END)? != 0 { + return Err(range_error("selection is not collapsed")); + } + Ok(caret) +} + +/// Recheck input generations and the complete authorized target before native actions. +#[cfg(windows)] +fn current(plan: &ReplacementPlan<'_>) -> bool { + current_target(plan, same_authorized_target) +} + +/// Verify the same eligible field after edits may have marked its title modified. +#[cfg(windows)] +fn current_after_mutation(plan: &ReplacementPlan<'_>) -> bool { + current_target(plan, same_mutated_target) +} + +/// Bracket target detection with input and shutdown checks for either operation phase. +#[cfg(windows)] +fn current_target( + plan: &ReplacementPlan<'_>, + matches_target: impl FnOnce(&super::FocusedTarget, &super::FocusedTarget) -> bool, +) -> bool { + use super::super::{ + input_listener, + target::{detect_focused_target, TargetDetection}, + }; + !super::shutting_down() + && input_listener::current_position_generation() == plan.stamp.position + && input_listener::current_input_sequence() == plan.stamp.sequence + && matches!(detect_focused_target(), TargetDetection::Available(target) + if matches_target(plan.target, &target)) + && input_listener::current_position_generation() == plan.stamp.position + && input_listener::current_input_sequence() == plan.stamp.sequence + && !super::shutting_down() +} + +/// Bind mutation to every policy-bearing attribute of the authorized target. +#[cfg(any(windows, test))] +pub(super) fn same_authorized_target( + expected: &super::FocusedTarget, + current: &super::FocusedTarget, +) -> bool { + current.correction_eligibility() == super::CorrectionEligibility::Allowed && current == expected +} + +/// After mutation only the title may change; identity and every safety flag remain bound. +#[cfg(any(windows, test))] +pub(super) fn same_mutated_target( + expected: &super::FocusedTarget, + current: &super::FocusedTarget, +) -> bool { + let mut retitled = current.clone(); + retitled.window_title.clone_from(&expected.window_title); + same_authorized_target(expected, &retitled) +} + +/// Confirm native keyboard focus belongs to the authorized process and control. +#[cfg(windows)] +fn keyboard_target(window: isize, plan: &ReplacementPlan<'_>) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetForegroundWindow, GetGUIThreadInfo, GetWindowThreadProcessId, GUITHREADINFO, + }; + unsafe { + let foreground = GetForegroundWindow(); + if foreground as isize != plan.target.window_handle { + return false; + } + let mut process = 0; + let thread = GetWindowThreadProcessId(foreground, &mut process); + let mut info: GUITHREADINFO = std::mem::zeroed(); + info.cbSize = std::mem::size_of::() as u32; + process == plan.target.process_id + && thread != 0 + && GetGUIThreadInfo(thread, &mut info) != 0 + && info.hwndFocus as isize == window + } +} diff --git a/app-core-rust/src/background/replacement/send_input.rs b/app-core-rust/src/background/replacement/send_input.rs new file mode 100644 index 0000000..73aceb8 --- /dev/null +++ b/app-core-rust/src/background/replacement/send_input.rs @@ -0,0 +1,227 @@ +//! Last-resort keyboard mutation of an already selected, verified pre-caret span. +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, IsWindowEnabled, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, + KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, VK_BACK, VK_CONTROL, VK_LWIN, VK_MENU, VK_RWIN, VK_SHIFT, +}; + +const MAX_UTF16_UNITS: usize = 65_536; + +/// Allocate and validate the entire batch before changing the target selection. +pub(super) fn prepare(text: &str) -> Result, String> { + if text.chars().any(char::is_control) { + return Err("SendInput refuses control characters".into()); + } + let units = text.encode_utf16().count(); + if units > MAX_UTF16_UNITS { + return Err("SendInput exceeds the input budget".into()); + } + let mut inputs = Vec::new(); + inputs + .try_reserve_exact(units.max(1) * 2) + .map_err(|_| "SendInput batch allocation failed")?; + if text.is_empty() { + // Backspace deletes only the proven nonempty selection. Never send Delete, + // which could consume text after the caret if a provider lost the selection. + push_pair(&mut inputs, VK_BACK, 0, 0); + } else { + for unit in text.encode_utf16() { + push_pair(&mut inputs, 0, unit, KEYEVENTF_UNICODE); + } + } + Ok(inputs) +} + +/// Keep each Unicode unit or virtual key adjacent to its matching release. +fn push_pair(inputs: &mut Vec, key: u16, scan: u16, flags: u32) { + for up in [false, true] { + inputs.push(INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: key, + wScan: scan, + dwFlags: flags | if up { KEYEVENTF_KEYUP } else { 0 }, + time: 0, + dwExtraInfo: 0, + }, + }, + }); + } +} + +/// Refuse insertion through held user shortcut modifiers without releasing their keys. +pub(super) fn modifiers_held() -> bool { + [VK_CONTROL, VK_MENU, VK_SHIFT, VK_LWIN, VK_RWIN] + .iter() + .any(|key| unsafe { GetAsyncKeyState(i32::from(*key)) } < 0) +} + +/// Only standard Unicode Edit controls have known insert/selection semantics. +/// Custom editors and RichEdit overtype modes require a safer native strategy. +pub(super) fn supports_target(window: isize) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetClassNameW, GetWindowLongPtrW, IsWindowUnicode, ES_LOWERCASE, ES_NUMBER, ES_PASSWORD, + ES_READONLY, ES_UPPERCASE, GWL_STYLE, + }; + if window == 0 { + return false; + } + let mut class = [0u16; 16]; + unsafe { + let window = window as _; + let length = GetClassNameW(window, class.as_mut_ptr(), class.len() as i32); + let style = GetWindowLongPtrW(window, GWL_STYLE) as u32; + length == 4 + && String::from_utf16_lossy(&class[..4]).eq_ignore_ascii_case("edit") + && IsWindowUnicode(window) != 0 + && IsWindowEnabled(window) != 0 + && style & (ES_READONLY | ES_PASSWORD | ES_NUMBER | ES_UPPERCASE | ES_LOWERCASE) as u32 + == 0 + } +} + +/// Submit one batch so user keystrokes cannot interleave its events. No retries: +/// even a partial batch may have deleted the selection or left a key down. +pub(super) fn send(inputs: &[INPUT]) -> Result<(), String> { + let sent = unsafe { + SendInput( + inputs.len() as u32, + inputs.as_ptr(), + std::mem::size_of::() as i32, + ) + }; + if let Some(up) = pending_keyup(sent as usize, inputs) { + // A partial batch can stop on a keydown (notably Backspace). Release + // only that injected key; never retry deletion or Unicode keydowns. + if unsafe { SendInput(1, up, std::mem::size_of::() as i32) } != 1 { + return Err("SendInput partial batch key release failed; mutation uncertain".into()); + } + } + check_sent(sent as usize, inputs.len()) +} + +/// After a partial batch, release only the last injected keydown. +fn pending_keyup(sent: usize, inputs: &[INPUT]) -> Option<&INPUT> { + (sent % 2 == 1).then(|| inputs.get(sent)).flatten() +} + +/// Treat every incomplete input batch as uncertain mutation and never retry it. +fn check_sent(sent: usize, expected: usize) -> Result<(), String> { + if sent == expected { + Ok(()) + } else { + Err(format!( + "SendInput inserted {sent} of {expected} events; mutation uncertain" + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unicode_batch_preserves_surrogate_pairs_and_key_releases() { + let text = "é😃 العربية"; + let inputs = prepare(text).unwrap(); + let units: Vec<_> = text.encode_utf16().collect(); + assert_eq!(inputs.len(), units.len() * 2); + for (pair, unit) in inputs.chunks_exact(2).zip(units) { + for (index, input) in pair.iter().enumerate() { + assert_eq!(input.r#type, INPUT_KEYBOARD); + let key = unsafe { input.Anonymous.ki }; + assert_eq!(key.wVk, 0); + assert_eq!(key.wScan, unit); + assert_eq!( + key.dwFlags, + KEYEVENTF_UNICODE | if index == 1 { KEYEVENTF_KEYUP } else { 0 } + ); + } + } + } + + #[test] + fn deletion_is_one_backspace_pair() { + let inputs = prepare("").unwrap(); + assert_eq!(inputs.len(), 2); + for (index, input) in inputs.iter().enumerate() { + let key = unsafe { input.Anonymous.ki }; + assert_eq!(key.wVk, VK_BACK); + assert_eq!(key.wScan, 0); + assert_eq!(key.dwFlags, if index == 1 { KEYEVENTF_KEYUP } else { 0 }); + } + } + + #[test] + fn controls_and_oversized_unicode_payloads_refuse_before_selection() { + for character in ['\0', '\n', '\r', '\t', '\x08', '\x1b', '\x7f', '\u{85}'] { + assert_eq!( + prepare(&format!("the{character}")).err().unwrap(), + "SendInput refuses control characters" + ); + } + assert!(prepare(&"😃".repeat(MAX_UTF16_UNITS / 2)).is_ok()); + assert!(prepare(&"😃".repeat(MAX_UTF16_UNITS / 2 + 1)).is_err()); + } + + #[test] + fn zero_or_partial_input_is_never_success() { + for count in [0, 1, 5] { + assert!(check_sent(count, 6).is_err()); + } + assert!(check_sent(6, 6).is_ok()); + } + + #[test] + fn partial_batch_releases_only_the_last_injected_key() { + for text in ["", "é😃"] { + let inputs = prepare(text).unwrap(); + for sent in 0..=inputs.len() { + let pending = pending_keyup(sent, &inputs); + assert_eq!(pending.is_some(), sent % 2 == 1 && sent < inputs.len()); + if let Some(up) = pending { + assert_ne!(unsafe { up.Anonymous.ki }.dwFlags & KEYEVENTF_KEYUP, 0); + } + } + } + } + + #[test] + fn protected_transforming_and_unknown_controls_refuse_send_input() { + use windows_sys::Win32::UI::WindowsAndMessaging::*; + fn wide(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() + } + for (class, style, allowed) in [ + ("EDIT", 0, true), + ("EDIT", ES_READONLY, false), + ("EDIT", ES_PASSWORD, false), + ("EDIT", ES_NUMBER, false), + ("EDIT", ES_UPPERCASE, false), + ("EDIT", ES_LOWERCASE, false), + ("STATIC", 0, false), + ] { + let window = unsafe { + CreateWindowExW( + 0, + wide(class).as_ptr(), + wide("").as_ptr(), + style as u32, + 0, + 0, + 100, + 40, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null(), + ) + }; + assert!(!window.is_null()); + let supported = supports_target(window as isize); + unsafe { DestroyWindow(window) }; + assert_eq!(supported, allowed, "class={class}, style={style}"); + } + assert!(!supports_target(0)); + } +} diff --git a/app-core-rust/src/background/replacement/tests.rs b/app-core-rust/src/background/replacement/tests.rs new file mode 100644 index 0000000..ca3b050 --- /dev/null +++ b/app-core-rust/src/background/replacement/tests.rs @@ -0,0 +1,756 @@ +use super::*; +use crate::{ + background::{ + context_capture::SelectionCapture, session::SessionManager, target::FocusedElementId, + triggers, typing::TypedInput, + }, + settings::AppConfig, +}; +use std::cell::RefCell; + +fn target() -> FocusedTarget { + FocusedTarget { + process_id: 1, + process_name: "editor.exe".into(), + window_handle: 1, + window_title: "Test".into(), + focused_element_id: Some(FocusedElementId::RuntimeId("editor".into())), + is_elevated: false, + is_password_or_protected: false, + is_hidden_or_unavailable: false, + field_safety_known: true, + is_secure_desktop: false, + is_lock_screen: false, + is_credential_dialog: false, + } +} +const STAMP: InputStamp = InputStamp { + position: 1, + sequence: 2, +}; + +/// Pre-mutation authorization rejects title, process policy, and protection changes. +#[test] +fn correction_and_undo_refuse_changed_policy_attributes_without_input_movement() { + let authorized = target(); + assert!(native::same_authorized_target(&authorized, &authorized)); + let mut changed = authorized.clone(); + changed.window_title = "Private document".into(); + assert!(!native::same_authorized_target(&authorized, &changed)); + changed = authorized.clone(); + changed.process_name = "other.exe".into(); + assert!(!native::same_authorized_target(&authorized, &changed)); + changed = authorized.clone(); + changed.is_password_or_protected = true; + assert!(!native::same_authorized_target(&authorized, &changed)); +} + +/// Post-edit title markers are accepted without relaxing process, element, or security checks. +#[test] +fn post_mutation_title_change_keeps_identity_and_security_guards() { + let authorized = target(); + let mut changed = authorized.clone(); + changed.window_title = "*Test".into(); + assert!(native::same_mutated_target(&authorized, &changed)); + for mutate in [ + (|t: &mut FocusedTarget| t.process_id += 1) as fn(&mut FocusedTarget), + |t| t.window_handle += 1, + |t| t.process_name = "other.exe".into(), + |t| t.focused_element_id = None, + |t| t.is_password_or_protected = true, + |t| t.is_elevated = true, + |t| t.is_hidden_or_unavailable = true, + |t| t.field_safety_known = false, + |t| t.is_secure_desktop = true, + |t| t.is_credential_dialog = true, + ] { + let mut unsafe_target = changed.clone(); + mutate(&mut unsafe_target); + assert!(!native::same_mutated_target(&authorized, &unsafe_target)); + } +} + +#[test] +fn disabling_clipboard_skips_its_preparation_and_uses_fallback() { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "teh", + replacement: "the", + following: "", + stamp: STAMP, + }; + let calls = RefCell::new(Vec::new()); + let mut clipboard = FakeStrategy { + method: ReplacementMethod::Clipboard, + calls: &calls, + result: Some(ReplacementResult { + success: true, + method: Some(ReplacementMethod::Clipboard), + range: Some(plan.range()), + reason: None, + may_have_changed: true, + }), + }; + let mut fallback = FakeStrategy { + method: ReplacementMethod::SendInput, + calls: &calls, + result: Some(ReplacementResult { + success: true, + method: Some(ReplacementMethod::SendInput), + range: Some(plan.range()), + reason: None, + may_have_changed: true, + }), + }; + let result = run_strategies(&plan, &mut [&mut clipboard, &mut fallback], false); + assert!(result.success); + assert_eq!(result.method, Some(ReplacementMethod::SendInput)); + assert_eq!(*calls.borrow(), [ReplacementMethod::SendInput]); +} + +struct FakeStrategy<'a> { + method: ReplacementMethod, + calls: &'a RefCell>, + result: Option, +} +impl ReplacementStrategy for FakeStrategy<'_> { + fn method(&self) -> ReplacementMethod { + self.method + } + fn replace(&mut self, _: &ReplacementPlan<'_>) -> Attempt { + self.calls.borrow_mut().push(self.method); + self.result.take().map_or_else( + || Attempt::Unavailable("capability unavailable".into()), + Attempt::Finished, + ) + } +} + +#[test] +fn strategy_order_and_preparation_failures_allow_fallback() { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "teh", + replacement: "the", + following: " newer", + stamp: STAMP, + }; + let calls = RefCell::new(Vec::new()); + let methods = [ + ReplacementMethod::DirectTextApi, + ReplacementMethod::UiAutomation, + ReplacementMethod::Clipboard, + ReplacementMethod::SendInput, + ]; + let mut strategies: Vec<_> = methods + .iter() + .map(|method| FakeStrategy { + method: *method, + calls: &calls, + result: (*method == ReplacementMethod::SendInput).then(|| ReplacementResult { + success: true, + method: Some(*method), + range: Some(plan.range()), + reason: None, + may_have_changed: true, + }), + }) + .collect(); + let mut refs: Vec<&mut dyn ReplacementStrategy> = strategies + .iter_mut() + .map(|s| s as &mut dyn ReplacementStrategy) + .collect(); + let result = run_strategies(&plan, &mut refs, true); + assert!(result.success); + assert_eq!(*calls.borrow(), methods); + assert_eq!( + result.range, + Some(ReplacedRange { + start_back: 9, + end_back: 6 + }) + ); +} + +#[test] +fn successful_safer_method_never_reaches_send_input() { + for method in [ + ReplacementMethod::DirectTextApi, + ReplacementMethod::UiAutomation, + ReplacementMethod::Clipboard, + ] { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "teh", + replacement: "the", + following: "", + stamp: STAMP, + }; + let calls = RefCell::new(Vec::new()); + let mut safer = FakeStrategy { + method, + calls: &calls, + result: Some(ReplacementResult { + success: true, + method: Some(method), + range: Some(plan.range()), + reason: None, + may_have_changed: true, + }), + }; + let mut fallback = FakeStrategy { + method: ReplacementMethod::SendInput, + calls: &calls, + result: None, + }; + let result = run_strategies(&plan, &mut [&mut safer, &mut fallback], true); + assert!(result.success); + assert_eq!(result.method, Some(method)); + assert_eq!(*calls.borrow(), [method]); + } +} + +#[test] +fn no_retry_after_paste_partial_input_or_failed_verification() { + for reason in [ + "clipboard paste timed out", + "partial SendInput", + "verification failed", + "clipboard restore failed", + ] { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "teh", + replacement: "the", + following: "", + stamp: STAMP, + }; + let calls = RefCell::new(Vec::new()); + let mut clipboard = FakeStrategy { + method: ReplacementMethod::Clipboard, + calls: &calls, + result: Some(ReplacementResult { + success: false, + method: Some(ReplacementMethod::Clipboard), + range: Some(plan.range()), + reason: Some(reason.into()), + may_have_changed: true, + }), + }; + let mut fallback = FakeStrategy { + method: ReplacementMethod::SendInput, + calls: &calls, + result: None, + }; + let result = run_strategies(&plan, &mut [&mut clipboard, &mut fallback], true); + assert!(!result.success); + assert!(result.may_have_changed); + assert_eq!(result.reason.as_deref(), Some(reason)); + assert_eq!(*calls.borrow(), [ReplacementMethod::Clipboard]); + } +} + +#[test] +fn unavailable_result_has_method_reason_and_unknown_range() { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "teh", + replacement: "the", + following: "", + stamp: STAMP, + }; + let calls = RefCell::new(Vec::new()); + let mut strategy = FakeStrategy { + method: ReplacementMethod::SendInput, + calls: &calls, + result: None, + }; + let result = run_strategies(&plan, &mut [&mut strategy], true); + assert!(!result.success); + assert_eq!(result.method, Some(ReplacementMethod::SendInput)); + assert_eq!(result.range, None); + assert_eq!(result.reason.as_deref(), Some("capability unavailable")); +} + +#[test] +fn exact_range_counts_unicode_characters_and_preserves_following_text() { + let target = target(); + let plan = ReplacementPlan { + target: &target, + original: "é😃", + replacement: "new", + following: " العربية", + stamp: STAMP, + }; + assert_eq!( + plan.range(), + ReplacedRange { + start_back: 10, + end_back: 8 + } + ); +} + +#[test] +fn protected_selected_empty_suppressed_and_failed_requests_never_reach_native_strategies() { + let config = AppConfig::default(); + let mut manager = SessionManager::new(config.context.clone()); + manager.focus(&target()); + manager.input(TypedInput::Text("teh".into())); + let session = manager.active().unwrap(); + let request = triggers::manual( + session.id(), + "informative stays read-only", + &session.editable_context(), + session.versions(), + &SelectionCapture::NoSelection, + &config, + ) + .unwrap(); + let mut output = CorrectionOutput::changed("the".into(), ConfidenceTier::High, None, 0); + output.behavior = ConfidenceBehavior::Silent; + for case in 0..7 { + let mut target = target(); + let mut request = request.clone(); + let mut output = output.clone(); + match case { + 0 => target.is_password_or_protected = true, + 1 => request.selected_text = true, + 2 => request.executable_context.clear(), + 3 => output.behavior = ConfidenceBehavior::Suggestion, + 4 => output.confidence = ConfidenceTier::Low, + 5 => output.status = EngineStatus::TimedOut, + 6 => output.corrected_executable_text = "bad\0text".into(), + _ => unreachable!(), + } + let result = ReplacementEngine::replace(&target, &request, &output, STAMP, true); + assert!(!result.success); + assert_eq!(result.method, None); + assert_eq!(result.range, None); + assert!(result.reason.is_some()); + assert!(!result.may_have_changed); + } +} + +#[test] +fn app_undo_targets_only_recorded_span_and_preserves_new_typing() { + let config = AppConfig::default(); + let mut manager = SessionManager::new(config.context.clone()); + manager.focus(&target()); + manager.input(TypedInput::Text("teh".into())); + let session = manager.active_mut().unwrap(); + assert!(session.undo_target().is_none()); + assert!(session.queue_correction("teh".into(), "the".into())); + assert!(session.apply_next_correction(&config.context)); + manager.input(TypedInput::Text(" next".into())); + let undo = manager.active().unwrap().undo_target().unwrap(); + assert_eq!(undo.corrected, "the"); + assert_eq!(undo.original, "teh"); + assert_eq!(undo.following, " next"); +} + +#[test] +fn app_undo_refuses_partially_retained_correction() { + let mut config = AppConfig::default(); + config.context.informative_context_max_chars = 2; + let mut manager = SessionManager::new(config.context.clone()); + manager.focus(&target()); + manager.input(TypedInput::Text("teh".into())); + let session = manager.active_mut().unwrap(); + assert!(session.queue_correction("teh".into(), "the".into())); + assert!(session.apply_next_correction(&config.context)); + assert!(session.undo_target().is_none()); +} + +/// Opt-in test owns its editor and returns focus/clipboard on exit. Default tests +/// never inject input into the user's desktop or touch the global clipboard. +#[cfg(windows)] +#[test] +#[ignore = "requires an interactive Windows desktop; briefly focuses an isolated test editor"] +fn native_edit_replacement_smoke() { + const EM_SETSEL: u32 = 0x00b1; + use std::{ + io::{BufRead, BufReader, Read}, + os::windows::process::CommandExt, + process::{Command, Stdio}, + thread, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::*; + fn wide(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() + } + let previous = unsafe { GetForegroundWindow() } as isize; + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "native_edit_test_host", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("AUTOFIX_NATIVE_TEST_HOST", "1") + .creation_flags(0x08000000) // CREATE_NO_WINDOW: the child owns only its test editor. + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let host = stdout + .by_ref() + .lines() + .map(|line| line.unwrap()) + .find(|line| line.contains("AUTOFIX_EDITOR ")) + .unwrap(); + let mut host = host + .split("AUTOFIX_EDITOR ") + .nth(1) + .unwrap() + .split_whitespace(); + let thread_id: u32 = host.next().unwrap().parse().unwrap(); + let edit: isize = host.next().unwrap().parse().unwrap(); + unsafe { + let root = GetAncestor(edit as _, GA_ROOT); + SetForegroundWindow(root); + PostMessageW(root, WM_APP + 1, 0, 0); + } + struct Editor { + thread_id: u32, + child: std::process::Child, + stdout: BufReader, + previous: isize, + } + impl Drop for Editor { + fn drop(&mut self) { + unsafe { + PostThreadMessageW(self.thread_id, WM_QUIT, 0, 0); + self.stdout.read_to_end(&mut Vec::new()).unwrap(); + self.child.wait().unwrap(); + if self.previous != 0 { + SetForegroundWindow(self.previous as _); + } + } + } + } + let _editor = Editor { + thread_id, + child, + stdout, + previous, + }; + // Foreground activation is asynchronous and may be denied without attaching + // this test's input queue to its own editor thread. Never accept another app. + let focus_deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + unsafe { + use windows_sys::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId}; + let current_thread = GetCurrentThreadId(); + let mut message: MSG = std::mem::zeroed(); + PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_NOREMOVE); + let foreground_thread = + GetWindowThreadProcessId(GetForegroundWindow(), std::ptr::null_mut()); + let foreground_attached = foreground_thread != current_thread + && AttachThreadInput(current_thread, foreground_thread, 1) != 0; + let attached = AttachThreadInput(current_thread, thread_id, 1) != 0; + SetForegroundWindow(GetAncestor(edit as _, GA_ROOT)); + windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus(edit as _); + PostMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 1, 0, 0); + if attached { + AttachThreadInput(current_thread, thread_id, 0); + } + if foreground_attached { + AttachThreadInput(current_thread, foreground_thread, 0); + } + } + if matches!(super::super::target::detect_focused_target(), + super::super::target::TargetDetection::Available(target) if target.process_id == _editor.child.id()) + { + break; + } + assert!( + std::time::Instant::now() < focus_deadline, + "test editor could not acquire foreground focus" + ); + thread::sleep(std::time::Duration::from_millis(25)); + } + // Both correction and undo use this boundary. A title-only change must + // refuse every native method while the selection and typed span stay intact. + let super::super::target::TargetDetection::Available(authorized) = + super::super::target::detect_focused_target() + else { + panic!("test editor is not available") + }; + let stale = ReplacementPlan { + target: &authorized, + original: "teh", + replacement: "the", + following: "", + stamp: InputStamp { + position: super::super::input_listener::current_position_generation(), + sequence: super::super::input_listener::current_input_sequence(), + }, + }; + unsafe { + let title = wide("Private document"); + assert_ne!( + SendMessageW( + GetAncestor(edit as _, GA_ROOT), + WM_SETTEXT, + 0, + title.as_ptr() as isize + ), + 0 + ); + } + for method in [ReplacementMethod::Clipboard, ReplacementMethod::SendInput] { + let refused = run_strategies(&stale, &mut [&mut native::NativeStrategy(method)], true); + assert!(!refused.success && !refused.may_have_changed); + assert!(refused.range.is_none()); + } + unsafe { + let title = wide("AutoFix replacement test"); + SendMessageW( + GetAncestor(edit as _, GA_ROOT), + WM_SETTEXT, + 0, + title.as_ptr() as isize, + ); + } + for (method, original, replacement, following) in [ + (ReplacementMethod::Clipboard, "teh", "the", ""), + (ReplacementMethod::Clipboard, "teh", "the", " newer"), + (ReplacementMethod::SendInput, "teh", "the", ""), + (ReplacementMethod::SendInput, "teh", "the", " newer"), + (ReplacementMethod::SendInput, "teh", "", " newer"), + (ReplacementMethod::SendInput, "teh", "é😃", ""), + (ReplacementMethod::SendInput, "teh", "العربية", ""), + ] { + let initial = format!("old {original}{following} AFTER"); + let initial_caret = format!("old {original}{following}").encode_utf16().count(); + unsafe { + let root = GetAncestor(edit as _, GA_ROOT); + SendMessageW(root, WM_APP + 2, 0, 0); + let title = wide("AutoFix replacement test"); + SendMessageW(root, WM_SETTEXT, 0, title.as_ptr() as isize); + let text = wide(&initial); + assert_ne!( + SendMessageW(edit as _, WM_SETTEXT, 0, text.as_ptr() as isize), + 0 + ); + SendMessageW(edit as _, EM_SETSEL, initial_caret, initial_caret as isize); + } + let super::super::target::TargetDetection::Available(target) = + super::super::target::detect_focused_target() + else { + panic!("test editor is not available") + }; + assert_eq!( + target.correction_eligibility(), + CorrectionEligibility::Allowed + ); + assert_eq!(target.process_id, _editor.child.id()); + assert_eq!( + super::super::context_capture::read_before_caret( + &target, + &AppConfig::default().context, + 32 + ) + .as_deref(), + Some(format!("old {original}{following}").as_str()) + ); + let stamp = InputStamp { + position: super::super::input_listener::current_position_generation(), + sequence: super::super::input_listener::current_input_sequence(), + }; + let plan = ReplacementPlan { + target: &target, + original, + replacement, + following, + stamp, + }; + unsafe { SendMessageW(GetAncestor(edit as _, GA_ROOT), WM_APP + 2, 1, 0) }; + let mut result = run_strategies(&plan, &mut [&mut native::NativeStrategy(method)], true); + for _ in 0..5 { + if result.success || result.may_have_changed { + break; + } + thread::sleep(std::time::Duration::from_millis(50)); + result = run_strategies(&plan, &mut [&mut native::NativeStrategy(method)], true); + } + let mut caret_start = 0u32; + let mut caret_end = 0u32; + unsafe { + SendMessageW( + edit as _, + 0x00b0, + &mut caret_start as *mut u32 as usize, + &mut caret_end as *mut u32 as isize, + ); + } + let mut observed = [0u16; 128]; + let observed_length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + observed.len(), + observed.as_mut_ptr() as isize, + ) + }; + if method == ReplacementMethod::Clipboard + && !result.may_have_changed + && result.reason.as_deref().is_some_and(|reason| { + reason.contains("clipboard format") && reason.contains("cannot be preserved") + }) + { + assert_eq!( + String::from_utf16_lossy(&observed[..observed_length as usize]), + initial + ); + eprintln!("clipboard path safely refused an owner-managed format; checking SendInput fallback"); + continue; + } + assert!( + result.success, + "{result:?}; test editor text: {:?}; caret: {caret_start}..{caret_end}", + String::from_utf16_lossy(&observed[..observed_length as usize]) + ); + assert_eq!(result.method, Some(method)); + let super::super::target::TargetDetection::Available(after) = + super::super::target::detect_focused_target() + else { + panic!("test editor lost focus after mutation") + }; + assert_eq!(after.window_title, "*AutoFix replacement test"); + assert_eq!( + result.range, + Some(ReplacedRange { + start_back: original.chars().count() + following.chars().count(), + end_back: following.chars().count() + }) + ); + let mut text = [0u16; 128]; + let length = unsafe { + SendMessageW( + edit as _, + WM_GETTEXT, + text.len(), + text.as_mut_ptr() as isize, + ) + }; + assert_eq!( + String::from_utf16_lossy(&text[..length as usize]), + format!("old {replacement}{following} AFTER") + ); + let expected_caret = format!("old {replacement}{following}") + .encode_utf16() + .count() as u32; + assert_eq!((caret_start, caret_end), (expected_caret, expected_caret)); + } +} + +#[cfg(windows)] +static NATIVE_TEST_PARENT_PROC: std::sync::atomic::AtomicIsize = + std::sync::atomic::AtomicIsize::new(0); + +/// Simulate editors that synchronously add a modified-title marker on EN_CHANGE. +#[cfg(windows)] +unsafe extern "system" fn native_test_editor_window_proc( + window: windows_sys::Win32::Foundation::HWND, + message: u32, + wparam: usize, + lparam: isize, +) -> isize { + use windows_sys::Win32::UI::WindowsAndMessaging::*; + if message == WM_APP + 2 { + SetWindowLongPtrW(window, GWLP_USERDATA, wparam as isize); + return 0; + } + if message == WM_COMMAND + && wparam >> 16 == 0x0300 + && GetWindowLongPtrW(window, GWLP_USERDATA) != 0 + { + let title: Vec = "*AutoFix replacement test" + .encode_utf16() + .chain(Some(0)) + .collect(); + SetWindowTextW(window, title.as_ptr()); + } + let previous: WNDPROC = + std::mem::transmute(NATIVE_TEST_PARENT_PROC.load(std::sync::atomic::Ordering::Relaxed)); + CallWindowProcW(previous, window, message, wparam, lparam) +} + +/// Child-owned editor supplies real notifications without reading or editing another app. +#[cfg(windows)] +#[test] +#[ignore = "helper process for native_edit_replacement_smoke"] +fn native_edit_test_host() { + if std::env::var("AUTOFIX_NATIVE_TEST_HOST").as_deref() != Ok("1") { + return; + } + use std::{io::Write, ptr}; + use windows_sys::Win32::{ + System::Threading::GetCurrentThreadId, + UI::{Input::KeyboardAndMouse::SetFocus, WindowsAndMessaging::*}, + }; + fn wide(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() + } + unsafe { + let window = CreateWindowExW( + 0, + wide("STATIC").as_ptr(), + wide("AutoFix replacement test").as_ptr(), + WS_OVERLAPPEDWINDOW | WS_VISIBLE, + 100, + 100, + 450, + 180, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null(), + ); + assert!(!window.is_null()); + let previous = SetWindowLongPtrW( + window, + GWLP_WNDPROC, + native_test_editor_window_proc as *const () as isize, + ); + assert_ne!(previous, 0); + NATIVE_TEST_PARENT_PROC.store(previous, std::sync::atomic::Ordering::Relaxed); + let edit = CreateWindowExW( + 0, + wide("EDIT").as_ptr(), + wide("old teh AFTER").as_ptr(), + WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_MULTILINE as u32, + 10, + 10, + 400, + 90, + window, + ptr::null_mut(), + ptr::null_mut(), + ptr::null(), + ); + assert!(!edit.is_null()); + SetForegroundWindow(window); + PostMessageW(window, WM_APP + 1, 0, 0); + let mut message: MSG = std::mem::zeroed(); + while GetMessageW(&mut message, ptr::null_mut(), 0, 0) > 0 { + if message.message == WM_APP + 1 { + SetFocus(edit); + SendMessageW(edit, 0x00b1, 7, 7); + println!("AUTOFIX_EDITOR {} {}", GetCurrentThreadId(), edit as isize); + std::io::stdout().flush().unwrap(); + continue; + } + TranslateMessage(&message); + DispatchMessageW(&message); + } + DestroyWindow(window); + } +} diff --git a/app-core-rust/src/background/security.rs b/app-core-rust/src/background/security.rs index 5a97114..b2579f5 100644 --- a/app-core-rust/src/background/security.rs +++ b/app-core-rust/src/background/security.rs @@ -1,6 +1,6 @@ use crate::{ settings::{AppConfig, CorrectionEngine, RunMode}, - storage::{AppRule, Database}, + storage::{AppPolicyGuard, AppRule, Database}, }; use super::target::{self, CorrectionEligibility, FocusedTarget, TargetDetection}; @@ -48,6 +48,31 @@ pub(crate) enum BlockReason { pub(crate) struct SecurityGate; impl SecurityGate { + /// Keep the current app rules stable through native mutation and verification. + /// Missing/busy storage refuses replacement before any selection or input. + pub(super) fn authorize_replacement( + trigger: TriggerKind, + config: &AppConfig, + database: &Database, + target: &FocusedTarget, + ) -> Option { + if !config.correction.enabled { + return None; + } + let guard = AppPolicyGuard::acquire(database.path()?).ok()?; + let rules = guard.rules().ok()?; + matches!( + check_detection( + trigger, + config, + &rules, + TargetDetection::Available(target.clone()) + ), + SecurityDecision::Allowed { .. } + ) + .then_some(guard) + } + /// Missing application policy denies capture and engine execution for every trigger. pub(crate) fn check( trigger: TriggerKind, @@ -432,6 +457,95 @@ mod tests { } } + #[test] + fn replacement_guard_denies_revocation_and_serializes_policy_writes() { + let path = std::env::temp_dir().join(format!( + "autofix-replacement-policy-{}-{}.sqlite", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let database = Database::open(&path).unwrap(); + let connection = rusqlite::Connection::open(&path).unwrap(); + connection.busy_timeout(std::time::Duration::ZERO).unwrap(); + let mut config = AppConfig::default(); + database + .app_rules() + .upsert(&allow_rule("notepad.exe")) + .unwrap(); + let editor = target("notepad.exe"); + let guard = SecurityGate::authorize_replacement( + TriggerKind::ManualShortcut, + &config, + &database, + &editor, + ) + .unwrap(); + // The rule cannot be revoked between authorization and native mutation. + assert!(connection + .execute("UPDATE app_rules SET list_behavior = 'blocklist'", []) + .is_err()); + drop(guard); + database + .app_rules() + .upsert(&block_rule("notepad.exe")) + .unwrap(); + for trigger in [ + TriggerKind::ManualShortcut, + TriggerKind::Character, + TriggerKind::WordCount, + TriggerKind::Undo, + ] { + assert!( + SecurityGate::authorize_replacement(trigger, &config, &database, &editor).is_none() + ); + } + database + .app_rules() + .upsert(&allow_rule("notepad.exe")) + .unwrap(); + connection.execute_batch("BEGIN IMMEDIATE").unwrap(); + assert!(SecurityGate::authorize_replacement( + TriggerKind::ManualShortcut, + &config, + &database, + &editor + ) + .is_none()); + connection.execute_batch("ROLLBACK").unwrap(); + config.correction.enabled = false; + assert!(SecurityGate::authorize_replacement( + TriggerKind::ManualShortcut, + &config, + &database, + &editor + ) + .is_none()); + config.correction.enabled = true; + let mut protected = editor.clone(); + protected.is_password_or_protected = true; + assert!(SecurityGate::authorize_replacement( + TriggerKind::Undo, + &config, + &database, + &protected + ) + .is_none()); + connection.execute("DROP TABLE app_rules", []).unwrap(); + assert!(SecurityGate::authorize_replacement( + TriggerKind::ManualShortcut, + &config, + &database, + &editor + ) + .is_none()); + drop(connection); + drop(database); + std::fs::remove_file(path).unwrap(); + } + fn block_rule(process_name: &str) -> AppRule { AppRule { list_behavior: "blocklist".to_owned(), diff --git a/app-core-rust/src/background/session.rs b/app-core-rust/src/background/session.rs index 3032a75..2d54014 100644 --- a/app-core-rust/src/background/session.rs +++ b/app-core-rust/src/background/session.rs @@ -44,6 +44,14 @@ pub(crate) struct CorrectionUndo { replacement: String, informative_start: usize, caret_anchor: u64, + complete_range_retained: bool, +} + +/// Only a recorded, fully retained app correction may make informative text editable. +pub(super) struct CorrectionUndoTarget { + pub(super) corrected: String, + pub(super) original: String, + pub(super) following: String, } pub(crate) struct Session { @@ -562,6 +570,7 @@ impl Session { .filter(|start| self.informative_context.get(*start..) == Some(replacement.as_str())) { self.correction_undo_history.push(CorrectionUndo { + complete_range_retained: replacement == correction.replacement, original: correction.original, replacement, informative_start, @@ -571,10 +580,27 @@ impl Session { true } - #[cfg_attr( - not(test), - expect(dead_code, reason = "called after target undo succeeds") - )] + pub(super) fn undo_target(&self) -> Option { + let last = self.correction_undo_history.last()?; + let end = last.informative_start.checked_add(last.replacement.len())?; + if self.position_uncertain() + || !last.complete_range_retained + || last.caret_anchor != self.versions.caret_anchor + || self.informative_context.get(last.informative_start..end)? != last.replacement + { + return None; + } + Some(CorrectionUndoTarget { + corrected: last.replacement.clone(), + original: last.original.clone(), + following: format!( + "{}{}", + self.informative_context.get(end..)?, + self.executable_context() + ), + }) + } + /// Restore a recorded original in session context while preserving newer typed text. pub(crate) fn undo_last_correction(&mut self, limits: &ContextConfig) -> bool { let Some(last) = self.correction_undo_history.last().cloned() else { diff --git a/app-core-rust/src/background/session/pending.rs b/app-core-rust/src/background/session/pending.rs index ab84b17..c3d8a1c 100644 --- a/app-core-rust/src/background/session/pending.rs +++ b/app-core-rust/src/background/session/pending.rs @@ -131,6 +131,7 @@ impl Session { .collect(); let start = self.informative_context.len() - retained.len(); self.correction_undo_history.push(CorrectionUndo { + complete_range_retained: retained == corrected, original: segment.original, replacement: retained, informative_start: start, diff --git a/app-core-rust/src/settings/model.rs b/app-core-rust/src/settings/model.rs index b650000..bbeedf5 100644 --- a/app-core-rust/src/settings/model.rs +++ b/app-core-rust/src/settings/model.rs @@ -14,6 +14,8 @@ pub(crate) struct AppConfig { pub(crate) triggers: TriggersConfig, pub(crate) context: ContextConfig, pub(crate) correction: CorrectionConfig, + #[serde(default)] + pub(crate) replacement: ReplacementConfig, pub(crate) api: ApiConfig, pub(crate) feedback: FeedbackConfig, pub(crate) logging: LoggingConfig, @@ -167,6 +169,20 @@ fn default_true() -> bool { true } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct ReplacementConfig { + #[serde(default = "default_true")] + pub(crate) clipboard_enabled: bool, +} + +impl Default for ReplacementConfig { + fn default() -> Self { + Self { + clipboard_enabled: true, + } + } +} + impl Default for CorrectionConfig { /// Starts with local typos, conservative language policies, and low confidence blocked. fn default() -> Self { diff --git a/app-core-rust/src/settings/tests.rs b/app-core-rust/src/settings/tests.rs index 1a44806..389e8c9 100644 --- a/app-core-rust/src/settings/tests.rs +++ b/app-core-rust/src/settings/tests.rs @@ -10,6 +10,38 @@ use super::{ AppConfig, ValidateConfig, }; +#[test] +fn clipboard_preference_round_trips_and_legacy_configs_keep_default() { + let mut config = AppConfig::default(); + assert!(config.replacement.clipboard_enabled); + config.replacement.clipboard_enabled = false; + let encoded = config_to_toml(&config).unwrap(); + assert!( + !super::toml_io::parse_config(&encoded) + .unwrap() + .replacement + .clipboard_enabled + ); + let legacy = encoded + .lines() + .filter(|line| !line.starts_with("clipboard_enabled")) + .collect::>() + .join("\n"); + assert!( + super::toml_io::parse_config(&legacy) + .unwrap() + .replacement + .clipboard_enabled + ); + let legacy = legacy.replace("[replacement]\n", ""); + assert!( + super::toml_io::parse_config(&legacy) + .unwrap() + .replacement + .clipboard_enabled + ); +} + /// Product defaults preserve conservative context, language, grammar, and confidence settings. #[test] fn default_config_has_requested_values() { diff --git a/app-core-rust/src/storage/app_policy.rs b/app-core-rust/src/storage/app_policy.rs index 7c07de9..9455ae2 100644 --- a/app-core-rust/src/storage/app_policy.rs +++ b/app-core-rust/src/storage/app_policy.rs @@ -1,4 +1,4 @@ -//! Serialize outbound authorization with SQLite policy writes from IPC and the UI. +//! Serialize outbound and replacement authorization with app-policy writes. use std::{path::Path, time::Duration}; @@ -14,7 +14,7 @@ impl AppPolicyGuard { /// Reserve the writer slot before reading, even in WAL mode. Never create or migrate. pub(crate) fn acquire(path: &Path) -> Result { let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)?; - // Contention denies this send immediately; do not extend its API deadline. + // Contention denies the operation immediately; never wait on policy writers. connection.busy_timeout(Duration::ZERO)?; connection.execute_batch("BEGIN IMMEDIATE")?; Ok(Self { connection }) @@ -30,7 +30,7 @@ impl Drop for AppPolicyGuard { /// Closing the connection rolls back the read-only transaction and releases writers. fn drop(&mut self) { if let Err(error) = self.connection.execute_batch("ROLLBACK") { - tracing::warn!(%error, "failed to release outbound policy transaction"); + tracing::warn!(%error, "failed to release app policy transaction"); } } } diff --git a/ui/settings-ui-tests/ConfigFormMapperTests.cs b/ui/settings-ui-tests/ConfigFormMapperTests.cs index a0ac444..d4dca33 100644 --- a/ui/settings-ui-tests/ConfigFormMapperTests.cs +++ b/ui/settings-ui-tests/ConfigFormMapperTests.cs @@ -6,6 +6,24 @@ namespace AutoFix.SettingsUi.Tests; [TestClass] public sealed class ConfigFormMapperTests { + [TestMethod] + public void ClipboardPreferenceSurvivesFormAndStorageRoundTrip() + { + using var fixture = TempConfigFixture.Create(); + var sections = SettingsSkeleton.CreateSections(); + Assert.IsTrue(Card(sections, "replacement.clipboard_enabled").IsEnabled); + Card(sections, "replacement.clipboard_enabled").IsEnabled = false; + var config = ConfigFormMapper.BuildConfig(sections); + Assert.IsFalse(config.Replacement.ClipboardEnabled); + fixture.Storage.Save(config); + var loaded = fixture.Storage.Load(fixture.Path); + Assert.IsFalse(loaded.Replacement.ClipboardEnabled); + Assert.IsFalse(Card(SettingsSkeleton.CreateSections(loaded), "replacement.clipboard_enabled").IsEnabled); + var legacy = File.ReadAllLines(fixture.Path).Where(line => !line.StartsWith("clipboard_enabled", StringComparison.Ordinal)); + File.WriteAllLines(fixture.Path, legacy); + Assert.IsTrue(fixture.Storage.Load(fixture.Path).Replacement.ClipboardEnabled); + } + [TestMethod] public void PendingQueueChoicesMapAndRejectInvalidCapacityOrPolicy() { diff --git a/ui/settings-ui-tests/EngineSupervisorTests.cs b/ui/settings-ui-tests/EngineSupervisorTests.cs index be904d6..4328d4e 100644 --- a/ui/settings-ui-tests/EngineSupervisorTests.cs +++ b/ui/settings-ui-tests/EngineSupervisorTests.cs @@ -168,7 +168,7 @@ public void Exit(int exitCode) public void RaiseExitedAgain() => Exited?.Invoke(this, EventArgs.Empty); - public void Kill() => Exit(0); + public void Stop() => Exit(0); public void Dispose() { } } } diff --git a/ui/settings-ui-tests/GracefulEngineStopTests.cs b/ui/settings-ui-tests/GracefulEngineStopTests.cs new file mode 100644 index 0000000..80c9dfa --- /dev/null +++ b/ui/settings-ui-tests/GracefulEngineStopTests.cs @@ -0,0 +1,56 @@ +using AutoFix.SettingsUi.Lifetime; + +namespace AutoFix.SettingsUi.Tests; + +[TestClass] +public sealed class GracefulEngineStopTests +{ + /// Normal stop waits for cleanup and never reaches forced termination. + [TestMethod] + public void IntentionalStopSignalsAndWaitsWithoutKilling() + { + var calls = new List(); + GracefulEngineStop.Run( + () => false, + () => { calls.Add("signal"); return true; }, + timeout => { Assert.IsTrue(timeout > 0); calls.Add("drain"); return true; }, + () => calls.Add("kill")); + CollectionAssert.AreEqual(new[] { "signal", "drain" }, calls); + } + + /// A cleanup timeout falls back to termination only after the wait. + [TestMethod] + public void TimedOutCleanupKillsOnlyAfterWaiting() + { + var calls = new List(); + GracefulEngineStop.Run( + () => false, + () => { calls.Add("signal"); return true; }, + _ => { calls.Add("drain"); return false; }, + () => calls.Add("kill")); + CollectionAssert.AreEqual(new[] { "signal", "drain", "kill" }, calls); + } + + /// An already exited engine must not receive signals or termination. + [TestMethod] + public void ExitedEngineNeedsNoSignalOrKill() + { + GracefulEngineStop.Run(() => true, + () => throw new AssertFailedException("signal"), + _ => throw new AssertFailedException("wait"), + () => throw new AssertFailedException("kill")); + } + + /// Stop targets the selected engine PID without signaling a different process. + [TestMethod] + public void StopSignalUsesTheEngineProcessId() + { + var processId = int.MaxValue; + using var signal = new EventWaitHandle(false, EventResetMode.ManualReset, + $@"Local\AutoFix.EngineStop.{processId}"); + Assert.IsFalse(signal.WaitOne(0)); + Assert.IsTrue(GracefulEngineStop.TrySignal(processId)); + Assert.IsTrue(signal.WaitOne(0)); + Assert.IsFalse(GracefulEngineStop.TrySignal(processId - 1)); + } +} diff --git a/ui/settings-ui/Lifetime/EngineProcess.cs b/ui/settings-ui/Lifetime/EngineProcess.cs index a6f7763..2260295 100644 --- a/ui/settings-ui/Lifetime/EngineProcess.cs +++ b/ui/settings-ui/Lifetime/EngineProcess.cs @@ -9,7 +9,8 @@ public interface IEngineProcess : IDisposable int Id { get; } int? ExitCode { get; } bool HasExited { get; } - void Kill(); + /// Request graceful cleanup and use bounded termination as a last resort. + void Stop(); } public interface IEngineProcessLauncher @@ -58,15 +59,59 @@ public RealEngineProcess(Process process) public int? ExitCode => process.HasExited ? process.ExitCode : null; public bool HasExited => process.HasExited; - public void Kill() + /// Signal this engine and await native cleanup before forced termination. + public void Stop() { - if (!process.HasExited) + GracefulEngineStop.Run( + () => process.HasExited, + () => GracefulEngineStop.TrySignal(process.Id), + timeout => process.WaitForExit(timeout), + () => process.Kill()); + } + + public void Dispose() => process.Dispose(); + } +} + +internal static class GracefulEngineStop +{ + // Rust allows four seconds for input processing and bounded clipboard recovery. + internal const int TimeoutMilliseconds = 6000; + + /// Wait for cleanup before the shell closes its kill-on-close process job. + internal static void Run(Func hasExited, Func signal, Func waitForExit, Action kill) + { + var deadline = Stopwatch.StartNew(); + while (!hasExited() && deadline.ElapsedMilliseconds < TimeoutMilliseconds) + { + if (signal()) { - process.Kill(); + if (waitForExit(Math.Max(0, TimeoutMilliseconds - (int)deadline.ElapsedMilliseconds))) + { + return; + } + break; } + Thread.Sleep(10); // Startup may not have created the process-scoped event yet. } + if (!hasExited()) + { + Trace.TraceWarning("Engine graceful stop timed out; clipboard cleanup may be incomplete."); + kill(); + } + } - public void Dispose() => process.Dispose(); + /// Signal this engine PID in the current Windows session. + internal static bool TrySignal(int processId) + { + if (!EventWaitHandle.TryOpenExisting($@"Local\AutoFix.EngineStop.{processId}", out var signal)) + { + return false; + } + using (signal) + { + return signal.Set(); + } } } diff --git a/ui/settings-ui/Lifetime/EngineSupervisor.cs b/ui/settings-ui/Lifetime/EngineSupervisor.cs index e90523c..7797e3f 100644 --- a/ui/settings-ui/Lifetime/EngineSupervisor.cs +++ b/ui/settings-ui/Lifetime/EngineSupervisor.cs @@ -73,7 +73,7 @@ public void StopIntentionally(ShutdownReason reason) } } - running?.Kill(); + running?.Stop(); } private void StartNewEngine() diff --git a/ui/settings-ui/Settings/AppConfig.cs b/ui/settings-ui/Settings/AppConfig.cs index dcda785..d7aceff 100644 --- a/ui/settings-ui/Settings/AppConfig.cs +++ b/ui/settings-ui/Settings/AppConfig.cs @@ -22,6 +22,9 @@ public sealed class AppConfig [JsonPropertyName("correction")] public CorrectionConfig Correction { get; set; } = new(); + [JsonPropertyName("replacement")] + public ReplacementConfig Replacement { get; set; } = new(); + [JsonPropertyName("api")] public ApiConfig Api { get; set; } = new(); @@ -49,6 +52,12 @@ public sealed class GeneralConfig public string RunMode { get; set; } = "blocklist"; } +public sealed class ReplacementConfig +{ + [JsonPropertyName("clipboard_enabled")] + public bool ClipboardEnabled { get; set; } = true; +} + public sealed class ShortcutsConfig { [JsonPropertyName("correct")] diff --git a/ui/settings-ui/Settings/ConfigFormMapper.cs b/ui/settings-ui/Settings/ConfigFormMapper.cs index 3c5e010..e07a019 100644 --- a/ui/settings-ui/Settings/ConfigFormMapper.cs +++ b/ui/settings-ui/Settings/ConfigFormMapper.cs @@ -36,6 +36,7 @@ public static AppConfig BuildConfig(IEnumerable sectio config.Triggers.Characters = List(values, "triggers.characters"); ApplyContext(config, values); ApplyCorrection(config, values); + config.Replacement.ClipboardEnabled = Toggle(values, "replacement.clipboard_enabled"); ApplyApi(config, values); ApplyFeedback(config, values); ApplyLogging(config, values); diff --git a/ui/settings-ui/ViewModels/SettingsSkeleton.cs b/ui/settings-ui/ViewModels/SettingsSkeleton.cs index 3012e86..d6bfcc3 100644 --- a/ui/settings-ui/ViewModels/SettingsSkeleton.cs +++ b/ui/settings-ui/ViewModels/SettingsSkeleton.cs @@ -92,6 +92,7 @@ public static ObservableCollection CreateSections(AppC Section("Correction", "Mode and confidence behavior", [ Toggle("Correction enabled", "Allow AutoFix to apply corrections.", "correction.enabled", config.Correction.Enabled), + Toggle("Use clipboard for correction", "Temporarily paste corrections through the clipboard and restore its previous contents. Turn off to use other replacement methods.", "replacement.clipboard_enabled", config.Replacement.ClipboardEnabled), Dropdown("Correction mode", "Choose typos only or grammar-aware correction.", "correction.mode", config.Correction.Mode, Modes()), Text("Preferred language", "Optional BCP 47 tag, such as en-US. Empty uses automatic detection.", "correction.preferred_language", config.Correction.PreferredLanguage ?? ""), Text("App language overrides", "Comma-separated process.exe=language-tag entries.", "correction.app_language_overrides", ConfigValue.Join(config.Correction.AppLanguageOverrides)),