diff --git a/.github/release-notes/v1.9.1.md b/.github/release-notes/v1.9.1.md new file mode 100644 index 00000000..51a5bb4f --- /dev/null +++ b/.github/release-notes/v1.9.1.md @@ -0,0 +1,53 @@ +Changes since [1.9.0](https://github.com/ops-software/mini-oled-dock/releases/tag/v1.9.0). + +A fix release for the first live test of 1.9.0 on a real PC. The dock bar is unchanged. Tasks and Folio are still alphas. + +### Both apps + +- **The window always shows the current state.** After a page switch, a navigation, new data, a search or a notice, Tasks and Folio could keep an old picture of a part of the window. They now repaint every part that changed, and focus rings are drawn whole. A new sample repaints only what it changed, never the whole window. + +### Tasks + +- **Search finds apps and background processes in Groups.** A group made of one process had no row of its own for the filter to look at, so a search missed it. It is found now. +- **Esc** clears the search, then leaves the search field, then clears the extra selection; it no longer closes the window. +- **No freeze at a custom display scale.** At some custom scaling values a dashed line of a chart (the network's "sent" series) could make Tasks stop responding. It is always drawn now. +- **Details.** The command band and the row menu name the program and offer **Close** for a process that shows a window and responds. Ctrl+N opens Run new task there as on Processes. A process that shows a window carries the name of its app, as on Processes. Efficiency mode shows a leaf in the Status column. The search hint is shorter ("Search processes") so it fits its field. The columns narrow to fit the window, the widest first, when the column chooser adds one or the window gets narrower. + +### Folio + +- **The mouse wheel scrolls the lists again.** In 1.9.0 a wheel turn over a list of files did not move it. A tab switch while a list still scrolls no longer leaves the rest of the scroll for the next wheel turn. +- **A tab's close button** lights its whole tab, as moving over the tab does. +- **Undo.** After a paste answered "keep both", Ctrl+Z takes back only the new item (a copy goes to the Recycle Bin, a moved file goes back) and leaves the older one; 1.9.0 refused, saying files were replaced. A paste that replaced files, or merged a folder into a folder of the same name (also a move stopped inside such a merge), still cannot be undone, and the notice says how many items replaced older ones. When the last change was made in another folder, Ctrl+Z and Ctrl+Y no longer change that folder out of sight: a notice names the change and its folder with **Undo there** or **Redo there**, and the **More** menu names the folder too. +- **The row menu** starts with **Cut**, **Copy** and **Paste**, as in File Explorer, each available or not as on the command bar; on one folder, Paste goes into that folder. +- **A path typed in the address row** opens its folder and gives the keyboard to the list, as in File Explorer. +- **A notice on the status line** is shown whole: the drive figures and the operations chip make room for it. +- **Language.** With the language set to automatic, Folio now follows the language of Windows like the other apps, from its first window and when the setting changes while it runs. It was English before. +- **A file without an extension** shows the plain file picture; it could show a folder's. +- **Accessibility.** The release build of Folio now serves its UI Automation tree, as Tasks does, and the popup menus of both apps expose their items to screen readers, with the focus moving through them. + +### Dark system menus and dialogs + +The classic "Show more options" menu and the system dialogs are dark again: Folio asks for the dark mode again just before it shows the classic menu, and each app asks for it before its first window. The classic menu no longer lists an entry twice. + +### Known limits + +The limits of 1.9.0 that this list does not change still hold. + +- The table of Tasks has no horizontal scroll; at a very narrow window with all columns shown some cells can still be cut. +- A folder merge that was stopped after it started counts as "replaced" in the undo refusal even when nothing had changed yet, to be safe. +- Folio does not restore items from the Recycle Bin, and does not change the protected places; a change that needs administrator rights is refused. +- Golden pictures changed on purpose are regenerated by the CI job. + +### Live checks + +Not yet run. + +### Install / update + +Requires Windows 11. Download `dock.exe` and run it from a terminal: + +```powershell +.\dock.exe --install +``` + +It asks for administrator rights, replaces the installed dock and restarts it. Settings are kept. Or use **Settings, Updates, Update now** from a running 1.4.2 or later. The apps follow on the dock's next sync. diff --git a/Cargo.lock b/Cargo.lock index fe6238f8..170fcd50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,7 +37,7 @@ dependencies = [ [[package]] name = "dock" -version = "1.9.0" +version = "1.9.1" dependencies = [ "embed-manifest", "oled-config", @@ -70,7 +70,7 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "files" -version = "1.9.0" +version = "1.9.1" dependencies = [ "embed-manifest", "oled-config", @@ -93,7 +93,7 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "gallery" -version = "1.9.0" +version = "1.9.1" dependencies = [ "embed-manifest", "oled-config", @@ -293,7 +293,7 @@ dependencies = [ [[package]] name = "tasks" -version = "1.9.0" +version = "1.9.1" dependencies = [ "embed-manifest", "oled-config", diff --git a/Cargo.toml b/Cargo.toml index ccc80475..d9866032 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dock" -version = "1.9.0" +version = "1.9.1" edition = "2021" rust-version = "1.87" description = "A minimal, ultra-light, OLED-black floating dock for Windows 11, written in Rust with no UI framework." diff --git a/README.md b/README.md index 7b1f9fb4..05dd92a0 100644 --- a/README.md +++ b/README.md @@ -374,6 +374,7 @@ Every build carries the same asInvoker manifest (see [Install](#install)); `DOCK | Version | Date | Highlights | |---|---|---| +| [1.9.1](.github/release-notes/v1.9.1.md) | unreleased | Fixes of the first live test of 1.9.0: the windows of Tasks and Folio always show the current state, Tasks search in groups, Esc and Details commands and columns, Folio mouse wheel, undo after keep both and in another folder, row menu, typed paths, language, icons and accessibility, dark system menus and dialogs again | | [1.9.0](.github/release-notes/v1.9.0.md) | unreleased | Tasks and Folio polished to stand in for Windows Task Manager and File Explorer (Tasks: resource strip, command band, Performance and Details pages; Folio: icons, search, details pane, cut, copy, paste and changes to real files behind refusals of system places), one accent colour for both apps in Settings, Appearance, and dark system menus only where a menu can show | | [1.8.1](.github/release-notes/v1.8.1.md) | unreleased | Every suite window has the dock's thin rim, dark system menus, Tasks and Folio labelled Alpha, an opt-in Reserve screen space (AppBar), and fixes: an install no longer records a task or key it found as its own, the Folio operations host exits when idle, the dock and Tasks start by safer paths | | [1.8.0](.github/release-notes/v1.8.0.md) | unreleased | The suite: Tasks and Folio as betas (installed by the dock's sync, off the Start menu with one switch), Suite and Safety pages in Settings, `--recover`, `--install --from`, a journal of the changes the suite makes to Windows with Undo all, a Ctrl+Shift+Esc option that cannot be switched on while Tasks is beta, and a stricter start of the dock's elevated children and watchdog | diff --git a/apps/files/Cargo.toml b/apps/files/Cargo.toml index caf878d4..f32b25c3 100644 --- a/apps/files/Cargo.toml +++ b/apps/files/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "files" -version = "1.9.0" +version = "1.9.1" edition = "2021" rust-version = "1.87" description = "The files app of the suite: its engine roles (ops host, shell host) and, later, its window." @@ -25,7 +25,10 @@ path = "examples/files_faultext/lib.rs" crate-type = ["cdylib"] [features] -default = [] +default = ["a11y"] +# The AccessKit bridge of the kit (UI Automation for Narrator), as in tasks.exe: without it the window and its menus +# answer a client with the bare window. The dock's build stays without it. +a11y = ["oled-ui/a11y"] [dependencies] oled-trust = { workspace = true } diff --git a/apps/files/src/app.rs b/apps/files/src/app.rs index c9e5de43..0d091174 100644 --- a/apps/files/src/app.rs +++ b/apps/files/src/app.rs @@ -236,7 +236,7 @@ impl Real { let _root = oled_sys::datadir::open_existing(false); let watch = oled_config::theme::ThemeWatch::open(); self.lang_setting = oled_ui::theme_lang(watch.current().language); - self.lang = UiLang::from_lang(self.lang_setting); + self.lang = crate::langfile::resolve_lang(self.lang_setting); let install_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(std::path::Path::to_path_buf)); crate::langfile::load_lang_file(install_dir.as_deref(), self.lang.italian); let (Some(hub), Some(services)) = (self.hub.clone(), self.services.take()) else { @@ -441,7 +441,7 @@ impl StepRunner for Real { /// window's formats and in every main window, which rebuilds what it caches (Msg::Lang). pub fn on_theme_change(shared: &Shared, cx: &mut LoopCx, file: &oled_config::theme::ThemeFile) { let setting = oled_ui::theme_lang(file.language); - let lang = UiLang::from_lang(setting); + let lang = crate::langfile::resolve_lang(setting); if lang == shared.lang.get() { return; } diff --git a/apps/files/src/home.rs b/apps/files/src/home.rs index 0ffd6355..3ca6a70d 100644 --- a/apps/files/src/home.rs +++ b/apps/files/src/home.rs @@ -357,7 +357,7 @@ pub fn home_paint(s: &FilesScreen, cx: &mut PaintCx) { } } for (i, it) in h.items.iter().enumerate() { - if !cx.visible(it.rect) { + if !cx.visible_ringed(it.rect) { continue; } let id = h.node(i); diff --git a/apps/files/src/icons.rs b/apps/files/src/icons.rs index 91acb051..e6b986ce 100644 --- a/apps/files/src/icons.rs +++ b/apps/files/src/icons.rs @@ -229,10 +229,11 @@ pub fn file_art(ext: &[u8]) -> Art { } } -/// Whether the class icon of `ext` is wanted: never for a family of the art (its art is the icon) nor for a program -/// (its own icon or the program art); for every other extension, and none. +/// Whether the class icon of `ext` is wanted: never for a family of the art (its art is the icon), for a program (its +/// own icon or the program art) nor for a file without an extension (the class of no extension can come back as a +/// folder's icon: such a file keeps the generic page); for every other extension. pub fn wants_class_icon(ext: &[u8]) -> bool { - family_of(ext).is_none() && !is_program(ext) + !ext.is_empty() && family_of(ext).is_none() && !is_program(ext) } /// The art of a drive root: the drive holding the Windows folder, a removable drive, a network drive; any other is a diff --git a/apps/files/src/langfile.rs b/apps/files/src/langfile.rs index 3a44eacb..27c42baa 100644 --- a/apps/files/src/langfile.rs +++ b/apps/files/src/langfile.rs @@ -7,6 +7,13 @@ use std::path::Path; use oled_sys::lang::{LangFile, LANG_MAX_BYTES}; use oled_trust::manifest::release::Version; +/// The language of the process for a setting, the way every app of the suite takes it: the setting is applied to the +/// process first (`auto` then reads Windows' language), then the kit's language is read back. +pub fn resolve_lang(setting: oled_sys::i18n::Lang) -> oled_ui::UiLang { + oled_sys::i18n::apply(setting); + oled_ui::UiLang::from_lang(setting) +} + /// True when the folder is an installed image: dock.exe and suite.json sit beside files.exe. fn is_installed(dir: &Path) -> bool { dir.join("dock.exe").is_file() && dir.join("suite.json").is_file() diff --git a/apps/files/src/listing/filter.rs b/apps/files/src/listing/filter.rs index 1334f250..515b78fe 100644 --- a/apps/files/src/listing/filter.rs +++ b/apps/files/src/listing/filter.rs @@ -291,6 +291,10 @@ mod tests { let only = |families: FamilySet, text: &str| ViewFilter { query: text.into(), families }; s.set_view_filter(only(FamilySet::default().toggled(NameFamily::Images), "")); assert_eq!(shown(&s), ["a.png", "b.JPG"]); + // A row the filter hides has no row at all: the table drops it from the selection and the focus. + let id = |s: &EntryStore, n: &str| s.find(n.as_bytes()).expect("the entry is live"); + assert_eq!(s.row_of(id(&s, "c.txt")), None); + assert_eq!(s.row_of(id(&s, "b.JPG")), Some(1)); assert_eq!(s.unfiltered_len(), 5, "the hidden file is not counted, the other kinds are"); s.set_view_filter(only(FamilySet::default().toggled(NameFamily::Images).toggled(NameFamily::Folders), "a")); assert_eq!(shown(&s), ["data", "a.png"], "a folder with an a in it, and the image: both families and the text"); diff --git a/apps/files/src/main.rs b/apps/files/src/main.rs index 3182e033..1f09828d 100644 --- a/apps/files/src/main.rs +++ b/apps/files/src/main.rs @@ -5,9 +5,12 @@ use files_engine::exit; fn main() { - // Every role can own a system-drawn menu (the shell host shows the classic one): dark, as the suite always is. - oled_sys::darkmenu::init(); let args: Vec = std::env::args().skip(1).collect(); + // Before the first window: a role that owns a surface Windows draws (a menu, a dialog, a file dialog) is dark, as + // the suite always is. + if owns_system_surface(&role(&args)) { + oled_sys::darkmenu::init(); + } std::process::exit(run(&args)); } @@ -24,6 +27,17 @@ enum Role<'a> { Window, } +/// Whether a role can own anything Windows draws: the window (its caption menu and the file dialogs it opens), the shell +/// host (the classic context menu and the property sheets) and the operations host (the shell's conflict and +/// confirmation dialogs). The other roles show nothing: a usage error, the debug test client and the message-only +/// window of the instance tests. +fn owns_system_surface(r: &Role<'_>) -> bool { + match r { + Role::Ops | Role::Shell | Role::Window => true, + Role::TestClient(_) | Role::TestIpc | Role::Usage => false, + } +} + fn role(args: &[String]) -> Role<'_> { match args.first().map(String::as_str) { Some("--role=ops") => Role::Ops, @@ -72,6 +86,33 @@ mod tests { a.iter().map(|s| s.to_string()).collect() } + /// Every role of files.exe, by what it can show: the three that own a surface of Windows' opt in, the rest do not. + #[test] + fn system_surface_roles() { + for (r, want) in [ + (Role::Window, true), + (Role::Shell, true), + (Role::Ops, true), + (Role::TestClient("x"), false), + (Role::TestIpc, false), + (Role::Usage, false), + ] { + assert_eq!(owns_system_surface(&r), want, "{r:?}"); + } + for a in [&["--role=ops"][..], &["--role=shell"], &[], &["C:\\x"], &["--bogus"]] { + let a = args(a); + let wants = !matches!(role(&a), Role::Usage); + assert_eq!(owns_system_surface(&role(&a)), wants, "{a:?}"); + } + let main = include_str!("main.rs"); + let main = main.split("#[cfg(test)]").next().unwrap(); + assert_eq!(main.matches("oled_sys::darkmenu::init();").count(), 1, "one opt-in, before the dispatch"); + assert!( + main.find("oled_sys::darkmenu::init();") < main.find("std::process::exit(run(&args))"), + "before the first window" + ); + } + #[test] fn role_table() { assert_eq!(role(&args(&["--role=ops", "--proto=1"])), Role::Ops); diff --git a/apps/files/src/menu.rs b/apps/files/src/menu.rs index e3ba827d..cb5aaf73 100644 --- a/apps/files/src/menu.rs +++ b/apps/files/src/menu.rs @@ -36,6 +36,8 @@ pub mod pick { pub const PIN: u32 = 0x2003; /// The background menu's "Show more options": the system menu of the folder itself. pub const MORE_BACKGROUND: u32 = 0x2004; + /// The row menu's Paste on one folder: into that folder, as File Explorer's does. + pub const PASTE_INTO: u32 = 0x2005; /// The toolbar View menu's Details row (the only view of the first version: checked, nothing to switch). pub const VIEW_DETAILS: u32 = 0x2132; /// SORT_COL + the column's ColKind. @@ -154,7 +156,9 @@ pub fn build_context(s: &FilesScreen) -> Vec { return background_items(s); } let folders = h.folders == h.count; - let mut items = vec![cmd_item(Cmd::Open)]; + let mut items = clip_items(s, &h); + items.push(MenuItem::Separator); + items.push(cmd_item(Cmd::Open)); if folders { items.push(row( s, @@ -193,6 +197,25 @@ pub fn build_context(s: &FilesScreen) -> Vec { items } +/// Cut, Copy and Paste at the top of the row menu, as in File Explorer, each on or off as the command bar has it, with +/// the bar's reason as its note. On one folder Paste goes into that folder (no chord: Ctrl+V pastes into the open +/// folder); on anything else into the open folder, as Ctrl+V does. +fn clip_items(s: &FilesScreen, h: &Held) -> Vec { + let lang = s.shared.lang.get(); + let a = toolmenus::avail(s); + let into_folder = h.count == 1 && h.folders == 1; + let (paste, paste_chord) = + if into_folder { (pick::PASTE_INTO, None) } else { (Cmd::Paste as u32, Some(Cmd::Paste)) }; + let clip_row = |id: u32, label: Text, glyph: Glyph, chord: Option, why: Option| { + toolmenus::item(s, id, label, Some(glyph), chord, None, why) + }; + vec![ + clip_row(Cmd::Cut as u32, t(k::FILES_CMD_CUT, lang), Glyph::CmdCut, Some(Cmd::Cut), a.cut), + clip_row(Cmd::Copy as u32, t(k::FILES_CMD_COPY, lang), Glyph::CmdCopy, Some(Cmd::Copy), a.copy), + clip_row(paste, t(k::FILES_CMD_PASTE, lang), Glyph::CmdPaste, paste_chord, a.paste), + ] +} + /// The menu of the empty space of the list. fn background_items(s: &FilesScreen) -> Vec { let lang = s.shared.lang.get(); @@ -334,6 +357,10 @@ pub fn on_pick(s: &mut FilesScreen, cx: &mut EventCx, id: CommandId) -> Reply { Reply::None } pick::PIN => Reply::None, + pick::PASTE_INTO => match selected(s).as_slice() { + [folder] => crate::clip_files::paste(s, cx, Some(folder.clone())), + _ => Reply::None, + }, pick::MORE_BACKGROUND => { let at = focus_anchor(s); let dir: Vec = folder(s).into_iter().collect(); @@ -465,6 +492,8 @@ pub fn cmd(s: &mut FilesScreen, cx: &mut EventCx, c: Cmd) -> Reply { if folder(s).is_none() { return Reply::None; } + // Paste's state as the clipboard is now, as a right click reads it. + crate::clip_files::look(s, cx); let at = focus_anchor(s); // The focused row is the target when nothing is selected. let t = s.tabs.active_mut(); diff --git a/apps/files/src/model.rs b/apps/files/src/model.rs index d4368a58..e200d2bc 100644 --- a/apps/files/src/model.rs +++ b/apps/files/src/model.rs @@ -494,7 +494,8 @@ impl FilesTable { /// The row's icon, never none: a folder draws its art at once (a known folder by its path, never by its name) and /// never a Windows icon; a file its own icon once it has arrived, else its family's art, the program art for a - /// program, its class icon once that has arrived, else the generic page. + /// program, its class icon once that has arrived, else the generic page. A file without an extension always draws + /// the generic page (icons::wants_class_icon). fn icon_ref(&self, id: EntryId, is_dir: bool, name: &[u8]) -> IconRef { let art = |a: Art| IconRef(ART_REF + art_index(a) as u32); if is_dir { @@ -508,7 +509,7 @@ impl FilesTable { if fallback != Art::FileGeneric { return art(fallback); } - let class = if ext.is_empty() { Some(&SLOT_NO_EXT) } else { self.icons.class.get(ext) }; + let class = if ext.is_empty() { None } else { self.icons.class.get(ext) }; match class { Some(&s) if self.icons.filled(s) => IconRef(s), _ => art(Art::FileGeneric), diff --git a/apps/files/src/ops/host.rs b/apps/files/src/ops/host.rs index f015d587..01abe578 100644 --- a/apps/files/src/ops/host.rs +++ b/apps/files/src/ops/host.rs @@ -942,6 +942,7 @@ impl Runner for RealRunner { bin_off: crate::ops::classify::bin_turned_off, places: places::system(), look: places::look, + keep_both: false, }; run(op, work, &ctx); ops.lock().unwrap_or_else(|e| e.into_inner()).remove(&op); diff --git a/apps/files/src/ops/places.rs b/apps/files/src/ops/places.rs index fb10e22a..ef5f6638 100644 --- a/apps/files/src/ops/places.rs +++ b/apps/files/src/ops/places.rs @@ -18,7 +18,8 @@ //! prompt. An item is judged as itself (a link in its last component is the link); the folder that gains something //! is judged through a link in its last component (a junction, a directory symbolic link, a mount folder), since //! IFileOperation writes into the link's target. The probe opens a handle and closes it unused; it never changes the -//! item. +//! item. After a copy or a move, the sink asks the same way which item a path names (item_key), to tell an item put +//! beside an older one from one that took its place. use std::sync::{Arc, OnceLock}; @@ -26,10 +27,10 @@ use oled_trust::frame::files::{OpKind, Refusal, WidePath}; use windows::core::{PCWSTR, PWSTR}; use windows::Win32::Foundation::{CloseHandle, ERROR_ACCESS_DENIED, HANDLE}; use windows::Win32::Storage::FileSystem::{ - CreateFileW, GetFinalPathNameByHandleW, GetVolumePathNameW, DELETE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, - FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_NO_RECALL, FILE_FLAG_OPEN_REPARSE_POINT, FILE_NAME_NORMALIZED, - FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GETFINALPATHNAMEBYHANDLE_FLAGS, OPEN_EXISTING, - VOLUME_NAME_DOS, + CreateFileW, GetFileInformationByHandle, GetFinalPathNameByHandleW, GetVolumePathNameW, BY_HANDLE_FILE_INFORMATION, + DELETE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_NO_RECALL, + FILE_FLAG_OPEN_REPARSE_POINT, FILE_NAME_NORMALIZED, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, GETFINALPATHNAMEBYHANDLE_FLAGS, OPEN_EXISTING, VOLUME_NAME_DOS, }; use windows::Win32::System::Com::CoTaskMemFree; use windows::Win32::System::SystemInformation::GetSystemWindowsDirectoryW; @@ -311,6 +312,21 @@ fn final_path(h: HANDLE) -> Option { None } +/// Which item `p` names now: its volume serial number and file index, read through a handle that may only read +/// attributes (a link in the last component opened as itself, a cloud file never recalled), closed at once. None when +/// it does not open or its file system gives no index. +pub fn item_key(p: &WidePath) -> Option<(u32, u64)> { + let h = open(&call_form(p), FILE_READ_ATTRIBUTES.0, false).ok()?; + let mut info = BY_HANDLE_FILE_INFORMATION::default(); + // SAFETY: a live handle of this thread; `info` is a writable struct of the declared type. + let got = unsafe { GetFileInformationByHandle(h, &mut info) }; + // SAFETY: opened above, closed once. + let _ = unsafe { CloseHandle(h) }; + got.ok()?; + let index = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow); + (index != 0).then_some((info.dwVolumeSerialNumber, index)) +} + fn is_volume_root(form: &[u16], p: &WidePath) -> bool { let mut buf = vec![0u16; 1024]; // SAFETY: `form` is NUL-terminated; the buffer is writable for its whole length. diff --git a/apps/files/src/ops/runner.rs b/apps/files/src/ops/runner.rs index e7a4d27f..5aeec5f2 100644 --- a/apps/files/src/ops/runner.rs +++ b/apps/files/src/ops/runner.rs @@ -23,6 +23,7 @@ use windows::Win32::System::Com::{ use windows::Win32::UI::Shell::{ FileOperation, IFileOperation, IFileOperationProgressSink, IShellItem, SHCreateItemFromParsingName, SHCreateItemFromRelativeName, COPYENGINE_E_RECYCLE_BIN_NOT_FOUND, FILEOPERATION_FLAGS, FOF_RENAMEONCOLLISION, + FOF_SILENT, }; use super::binrec::{bin_record, forget_record, Forgot}; @@ -141,6 +142,9 @@ pub struct RunCtx { pub places: Arc, /// What the disk says of an item before IFileOperation exists: places::look (tests pass their own). pub look: LookFn, + /// Tests: every name clash of a copy or a move is answered "keep both", as a person answers Windows' dialog + /// (FOF_RENAMEONCOLLISION, no dialog). Off everywhere else. + pub keep_both: bool, } impl RunCtx { @@ -163,6 +167,7 @@ impl RunCtx { bin_off: bin_turned_off, places: places::system(), look: places::look, + keep_both: false, } } } @@ -282,7 +287,7 @@ pub fn run(op: OpId, work: Work, ctx: &RunCtx) -> RunEnd { st.borrow_mut().journal = Some(w); } } - let mut out = Outcome { result: None, replaced: 0, index: 0 }; + let mut out = Outcome { result: None, index: 0 }; match work { Work::Staged(mut job) => { if job.kind == OpKind::NewFolder { @@ -320,7 +325,7 @@ pub fn run(op: OpId, work: Work, ctx: &RunCtx) -> RunEnd { } } let mut s = st.borrow_mut(); - let (done, failed, failed_top) = (s.done, s.failed, s.failed_top); + let (done, failed, failed_top, replaced) = (s.done, s.failed, s.failed_top, s.replaced); let result = out.result.unwrap_or(if failed_top > 0 && done == 0 { OpResult::Failed } else { OpResult::Done }); if let Some(j) = s.journal.as_mut() { let end = match result { @@ -334,9 +339,9 @@ pub fn run(op: OpId, work: Work, ctx: &RunCtx) -> RunEnd { s.journal = None; let undo = if done > 0 && result != OpResult::Refused { undo_kind(kind) } else { None }; let attached = ctx.attached.load(Ordering::Acquire); - let evs = s.co.finish(result, undo, out.replaced, done, failed, attached); + let evs = s.co.finish(result, undo, replaced, done, failed, attached); s.send(evs); - RunEnd { result, items: done, failed, replaced: out.replaced } + RunEnd { result, items: done, failed, replaced } } /// The "queued" records: every item held in memory, before anything runs. @@ -421,7 +426,6 @@ fn prepared(op: OpId, job: &OpJob, items: Vec) -> Prepared { struct Outcome { /// Set when the operation stops before its last chunk (or must report this result). result: Option, - replaced: u32, /// Top-level index of the next chunk's first item. index: u32, } @@ -540,8 +544,6 @@ fn run_chunk(p: &Prepared, ctx: &RunCtx, st: &Rc>, out: &mut s.journal_item(i, St::Skipped, None, 0, 0); } collisions = 0; - } else if matches!(p.kind, OpKind::Copy | OpKind::Move) { - out.replaced = out.replaced.saturating_add(pf.collisions); } if keep.is_empty() && p.kind != OpKind::NewFolder { return; @@ -550,6 +552,9 @@ fn run_chunk(p: &Prepared, ctx: &RunCtx, st: &Rc>, out: &mut if own_folder_copy(p) { flags |= FOF_RENAMEONCOLLISION.0; } + if ctx.keep_both && matches!(p.kind, OpKind::Copy | OpKind::Move) { + flags |= FOF_RENAMEONCOLLISION.0 | FOF_SILENT.0; + } ctx.stats.created.fetch_add(1, Ordering::Relaxed); // SAFETY: COM is initialised on this thread (run); FileOperation is the shell's in-process class. let fo: IFileOperation = match unsafe { CoCreateInstance(&FileOperation, None, CLSCTX_ALL) } { @@ -587,6 +592,7 @@ fn run_chunk(p: &Prepared, ctx: &RunCtx, st: &Rc>, out: &mut out.result = Some(OpResult::Cancelled); } } + st.borrow_mut().end_chunk(); if let Some(c) = cookie { // SAFETY: the cookie Advise returned on this IFileOperation. let _ = unsafe { fo.Unadvise(c) }; diff --git a/apps/files/src/ops/sink.rs b/apps/files/src/ops/sink.rs index c5a765c2..dbf8bb45 100644 --- a/apps/files/src/ops/sink.rs +++ b/apps/files/src/ops/sink.rs @@ -4,6 +4,8 @@ //! ("started" at Pre, "done", "failed" or "skipped" at Post) and give one change and one undo entry; a nested item //! adds nothing but its failure, so the user learns which file failed. Nothing about nested items is held. A top-level //! item moved out of the Recycle Bin is kept for the runner, which removes the bin's $I record of it after the chunk. +//! A folder moved onto a folder of its name is merged into it: the engine reports it "not handled" before it moves +//! what it holds one by one, and the item is done all the same. use std::cell::RefCell; use std::collections::HashMap; @@ -27,9 +29,10 @@ use windows::Win32::UI::Shell::{ }; use super::binrec::bin_record; -use super::checks::folded; +use super::checks::{folded, same_path}; use super::coalesce::Coalescer; use super::journal::{JournalWriter, PathRepr, Pre, Record, St}; +use super::places::item_key; /// Called with (op, top-level index) after each top-level item's successful Post (tests stop or kill there). pub type PostHook = Arc; @@ -56,6 +59,16 @@ pub struct SinkState { pub failed: u32, /// Top-level items that failed. pub failed_top: u32, + /// Top-level items of a copy or a move that took the place of what their destination held (landing): what Windows + /// did, never what the pre-flight expected, so a clash answered "keep both" or skipped counts nothing. A folder + /// merged into the one there counts, and so does a clash that failed or stopped once the engine was on it, unless + /// its older file is proven as it was. + pub replaced: u32, + /// How far the engine got with each top-level item of this chunk. + steps: Vec, + /// Per top-level item of this chunk whose destination held a file: that file as it was just before the chunk ran, + /// so a clash that failed or stopped and left it as it was counts as no replace. + before: Vec>, /// The top-level items of this chunk moved out of the Recycle Bin, each with where it was going and where it /// went: the runner removes their bin records after the chunk. pub from_bin: Vec<(WidePath, Vec)>, @@ -81,6 +94,9 @@ impl SinkState { done: 0, failed: 0, failed_top: 0, + replaced: 0, + steps: Vec::new(), + before: Vec::new(), from_bin: Vec::new(), } } @@ -110,6 +126,14 @@ impl SinkState { } } } + let copies = matches!(kind, OpKind::Copy | OpKind::Move); + self.before = (0..items.len()) + .map(|i| match (pre.get(i), dsts.get(i).and_then(Option::as_ref)) { + (Some(Pre::File), Some(d)) if copies => ident(d), + _ => None, + }) + .collect(); + self.steps = vec![Step::Queued; items.len()]; self.map = map; self.kind = kind; self.base = base; @@ -118,6 +142,30 @@ impl SinkState { self.dsts = dsts; } + /// The end of a chunk's PerformOperations: an item the engine started on and never reported (the operation + /// stopped first) counts as replaced when its destination was there and is not proven as it was. + pub fn end_chunk(&mut self) { + let unreported = (0..self.steps.len()).filter(|&i| self.steps.get(i) == Some(&Step::Started)); + let n = unreported.filter(|&i| self.may_have_replaced(i)).count(); + self.replaced = self.replaced.saturating_add(n as u32); + self.steps.clear(); + } + + /// Top-level item `i` is a copy or a move whose destination was there before the chunk ran. + fn clash(&self, i: usize) -> bool { + matches!(self.kind, OpKind::Copy | OpKind::Move) && self.pre.get(i).is_some_and(|p| *p != Pre::Absent) + } + + /// Top-level item `i` clashed and its destination is not proven as it was: a folder never is (a merge may have + /// replaced what it held); a file is when it is the same file with the same size and last-write time. + fn may_have_replaced(&self, i: usize) -> bool { + let same = match (self.before.get(i).copied().flatten(), self.dsts.get(i).and_then(Option::as_ref)) { + (Some(was), Some(d)) => ident(d) == Some(was), + _ => false, + }; + self.clash(i) && !same + } + pub fn send(&self, evs: Vec) { for e in evs { let _ = self.events.send(e); @@ -169,13 +217,18 @@ impl SinkState { } fn pre_item(&mut self, src: Src) -> WinResult<()> { - if let Some(i) = self.top(&src) { + let top = self.top(&src); + if let Some(i) = top { self.journal_item(i, St::Started, None, 0, 0); if let Some(name) = self.items.get(i).and_then(WidePath::file_name) { self.co.current(&String::from_utf16_lossy(name)); } } - if self.cancel.load(Ordering::Acquire) { + let refused = self.cancel.load(Ordering::Acquire); + if let Some(step) = top.and_then(|i| self.steps.get_mut(i)) { + *step = if refused { Step::Refused } else { Step::Started }; + } + if refused { return Err(windows::core::Error::from_hresult(ERROR_CANCELLED.to_hresult())); } Ok(()) @@ -192,29 +245,48 @@ impl SinkState { return; }; let item = self.items.get(i).cloned(); + let step = self.steps.get_mut(i).map_or(Step::Queued, |s| std::mem::replace(s, Step::Posted)); if hr.is_err() { self.failed_top = self.failed_top.saturating_add(1); self.journal_item(i, St::Failed, None, 0, 0); + // A clash the engine was let start on may have taken the older item's place before it failed or stopped. + if step != Step::Refused && self.may_have_replaced(i) { + self.replaced = self.replaced.saturating_add(1); + } if let Some(p) = item.or(created) { self.item_failed(p, hr.0); } return; } - if skipped(hr) || (kind != ChangeKind::Deleted && created.is_none()) { + // A folder moved onto a folder of its name: "not handled" as a whole, what it holds goes in one by one. + let merged = hr.0 == NOT_HANDLED && self.clash(i); + if !merged && (skipped(hr) || (kind != ChangeKind::Deleted && created.is_none())) { self.journal_item(i, St::Skipped, None, 0, 0); return; } + let created = if merged { created.or_else(|| self.dsts.get(i).cloned().flatten()) } else { created }; let (size, mtime, dir) = created.as_ref().and_then(attrs).unwrap_or((0, 0, false)); self.journal_item(i, St::Done, created.as_ref(), size, mtime); self.done = self.done.saturating_add(1); + if merged { + self.replaced = self.replaced.saturating_add(1); + } else if let Some(to) = created.as_ref().filter(|_| matches!(self.kind, OpKind::Copy | OpKind::Move)) { + let pre = self.pre.get(i).copied().unwrap_or(Pre::Absent); + let expected = self.dsts.get(i).and_then(Option::as_ref); + if landing(pre, expected, to, hr) == Landing::Replaced { + self.replaced = self.replaced.saturating_add(1); + } + } let from_bin = self.items.get(i).filter(|b| self.kind == OpKind::Move && bin_record(b).is_some()).cloned(); - if let (Some(bin), Some(to)) = (from_bin, created.as_ref()) { + if let (Some(bin), Some(to), false) = (from_bin, created.as_ref(), merged) { let restored = self.dsts.get(i).cloned().flatten().into_iter().chain([to.clone()]).collect(); self.from_bin.push((bin, restored)); } let (change, undo) = outcome(self.kind, kind, item, created, size, mtime, dir); let now = Instant::now(); - let mut out = self.co.change(change, now); + // A merge sends no change: the source folder leaves only once what it holds has gone, which the watcher + // shows. Its undo entry goes, so the UI holds the record whose undo is refused (replaced) and says so. + let mut out = if merged { Vec::new() } else { self.co.change(change, now) }; if let Some(e) = undo { out.extend(self.co.undo(e, self.attached.load(Ordering::Acquire))); } @@ -232,12 +304,84 @@ impl SinkState { /// skipped it, or the engine did not handle it, will retry it or still has it pending. Every other success code is /// done: a move, rename or delete reports COPYENGINE_S_DONT_PROCESS_CHILDREN (0x00270008), a merge or "keep both" /// their own codes. -const SKIP_CODES: [i32; 4] = [0x0027_0005, 0x0027_0003, 0x0027_0004, 0x0027_000B]; +const SKIP_CODES: [i32; 4] = [0x0027_0005, NOT_HANDLED, 0x0027_0004, 0x0027_000B]; + +/// COPYENGINE_S_NOT_HANDLED (winerror.h): skipped, except for a folder copied or moved onto a folder of its name, +/// which a move reports so before it moves what the folder holds into the one there (a merge). +const NOT_HANDLED: i32 = 0x0027_0003; fn skipped(hr: HRESULT) -> bool { SKIP_CODES.contains(&hr.0) } +/// COPYENGINE_S_KEEP_BOTH (winerror.h): the user answered a clash "keep both", and the item got a new name. +const KEEP_BOTH: i32 = 0x0027_000C; +/// COPYENGINE_S_COLLISIONRESOLVED (winerror.h): the engine gave the item a new name beside the one it found. +const COLLISION_RESOLVED: i32 = 0x0027_000E; + +/// Where a top-level item of a copy or a move landed against what its destination held before. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Landing { + /// Nothing was there: a new item. + New, + /// Something was there and the item took its name: the older item is gone (a folder merged into another counts + /// too: what it held may have been replaced). + Replaced, + /// Something was there and the item was put beside it under a new name (Windows' "keep both"). + KeptBoth, +} + +/// What Windows did with one item, from the pre-flight state of its destination (`expected`), the item it reports +/// (`created`) and the Post code. A present destination stays replaced unless there is evidence that the item was put +/// beside it: the code says "keep both" or "renamed", or the destination still holds a different item on disk than the +/// one reported (the same item may come back in another text form, its 8.3 path beyond MAX_PATH). Anything that +/// cannot be told counts as replaced, so an undo never takes what the paste did not make. Reads the disk only when +/// the paths differ as text. +pub fn landing(pre: Pre, expected: Option<&WidePath>, created: &WidePath, hr: HRESULT) -> Landing { + if pre == Pre::Absent { + return Landing::New; + } + if hr.0 == KEEP_BOTH || hr.0 == COLLISION_RESOLVED { + return Landing::KeptBoth; + } + match expected { + Some(dst) if !same_path(created, dst) && apart(dst, created) => Landing::KeptBoth, + _ => Landing::Replaced, + } +} + +/// How far the engine got with one top-level item of a chunk. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + /// No callback yet. + Queued, + /// Its Pre came after a cancel and the sink refused it: the engine leaves it alone. + Refused, + /// Its Pre was let through and no Post came yet. + Started, + /// Its Post came. + Posted, +} + +/// A file as it is now: volume serial and file index, size, last-write time. +type Ident = ((u32, u64), u64, i64); + +fn ident(p: &WidePath) -> Option { + let key = item_key(p)?; + let (size, mtime, dir) = attrs(p)?; + (!dir).then_some((key, size, mtime)) +} + +/// Whether `a` and `b` are two different items on disk now: both open and their volume serial numbers or file +/// indexes differ (places::item_key). An item that does not open, or a file system that gives no index, is no +/// evidence (false). +fn apart(a: &WidePath, b: &WidePath) -> bool { + match (item_key(a), item_key(b)) { + (Some(x), Some(y)) => x != y, + _ => false, + } +} + /// The change and the undo entry of one top-level item done. fn outcome( op_kind: OpKind, @@ -483,6 +627,8 @@ impl IFileOperationProgressSink_Impl for Sink_Impl { #[cfg(test)] mod tests { use super::*; + use oled_trust::frame::files::{OpResult, UndoKind}; + use windows::Win32::Foundation::E_FAIL; fn p(s: &str) -> WidePath { WidePath::parse(s).unwrap() @@ -496,6 +642,103 @@ mod tests { assert!(skipped(HRESULT(0x0027_0005)), "COPYENGINE_S_USER_IGNORED"); } + #[test] + fn landings_follow_what_windows_did() { + // Made-up paths, never on disk: only the codes and the text decide (the disk's evidence: tests/ops_undo.rs). + let (dst, kept) = (p("C:\\made-up\\b\\Note.txt"), p("C:\\made-up\\b\\Note (2).txt")); + let ok = HRESULT(0); + assert_eq!(landing(Pre::Absent, Some(&dst), &dst, ok), Landing::New, "nothing was there"); + assert_eq!(landing(Pre::File, Some(&dst), &dst, ok), Landing::Replaced, "the older file is gone"); + assert_eq!(landing(Pre::File, Some(&dst), &p("C:\\MADE-UP\\B\\NOTE.TXT"), ok), Landing::Replaced, "any case"); + assert_eq!(landing(Pre::File, Some(&dst), &kept, ok), Landing::Replaced, "another name, no evidence"); + assert_eq!(landing(Pre::File, Some(&dst), &kept, HRESULT(KEEP_BOTH)), Landing::KeptBoth, "the code says so"); + assert_eq!(landing(Pre::File, Some(&dst), &kept, HRESULT(COLLISION_RESOLVED)), Landing::KeptBoth, "renamed"); + assert_eq!(landing(Pre::Dir, Some(&dst), &dst, ok), Landing::Replaced, "a merge may have replaced files"); + assert_eq!(landing(Pre::Reparse, None, &kept, ok), Landing::Replaced, "unknown: never undone by mistake"); + } + + /// A sink fed by hand with one chunk of `kind` from C:\made-up\a into C:\made-up\b (never on disk), each item + /// with the pre-flight state of its destination. + fn chunk(kind: OpKind, items: &[(&str, Pre)]) -> (SinkState, std::sync::mpsc::Receiver) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut s = SinkState::new(OpId(1), tx, Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(true))); + let src = items.iter().map(|(n, _)| p(&format!("C:\\made-up\\a\\{n}"))).collect(); + let dst = items.iter().map(|(n, _)| Some(p(&format!("C:\\made-up\\b\\{n}")))).collect(); + s.begin_chunk(kind, 0, src, items.iter().map(|(_, pre)| *pre).collect(), dst); + (s, rx) + } + + fn src(s: &SinkState, i: usize) -> Src { + Src { item: true, path: s.items.get(i).cloned() } + } + + fn to(s: &SinkState, i: usize) -> Option { + s.dsts.get(i).cloned().flatten() + } + + #[test] + fn a_folder_merged_by_a_move_is_done_and_counts_as_replaced() { + let (mut s, rx) = chunk(OpKind::Move, &[("X", Pre::Dir), ("y.txt", Pre::Absent), ("Z", Pre::Absent)]); + let moved = HRESULT(0x0027_0008); + for (i, hr) in [(0, HRESULT(NOT_HANDLED)), (1, moved), (2, HRESULT(NOT_HANDLED))] { + assert!(s.pre_item(src(&s, i)).is_ok()); + let created = to(&s, i); + s.post_item(src(&s, i), hr, created, ChangeKind::Moved); + } + s.end_chunk(); + assert_eq!((s.done, s.replaced), (2, 1), "the merge is done and replaced; Z, not handled and no clash, is not"); + let evs: Vec = + rx.try_iter().chain(s.co.finish(OpResult::Done, Some(UndoKind::MoveBack), 1, 2, 0, true)).collect(); + let changed: Vec<_> = evs + .iter() + .filter_map(|e| match e { + OpEvt::ItemsDone { changes, .. } => Some(changes.clone()), + _ => None, + }) + .flatten() + .collect(); + assert_eq!(changed.len(), 1, "the merge sends no change (the watcher shows it): {changed:?}"); + assert_eq!(changed[0].to, to(&s, 1)); + let undo: Vec = evs + .iter() + .filter_map(|e| match e { + OpEvt::UndoPart { entries, .. } => Some(entries.clone()), + _ => None, + }) + .flatten() + .collect(); + assert_eq!(undo.len(), 2, "the merge's entry goes, so the UI holds the record whose undo is refused"); + } + + #[test] + fn a_clash_that_failed_or_stopped_counts_as_replaced_unless_the_sink_refused_it() { + let items = [ + ("X", Pre::Dir), + ("Note.txt", Pre::File), + ("new.txt", Pre::Absent), + ("W.txt", Pre::File), + ("Y", Pre::Dir), + ("Z", Pre::Dir), + ]; + let (mut s, _rx) = chunk(OpKind::Copy, &items); + let failed = E_FAIL; + let cancelled = ERROR_CANCELLED.to_hresult(); + for (i, hr) in [(0, failed), (1, cancelled), (2, failed), (3, HRESULT(0x0027_0005))] { + assert!(s.pre_item(src(&s, i)).is_ok()); + s.post_item(src(&s, i), hr, None, ChangeKind::Copied); + } + assert_eq!(s.replaced, 2, "a folder or a file there, not proven as it was; not the new file, not the skip"); + assert!(s.pre_item(src(&s, 4)).is_ok(), "Y is started and never reported"); + s.cancel.store(true, Ordering::Release); + assert!(s.pre_item(src(&s, 5)).is_err(), "Z is refused"); + s.post_item(src(&s, 5), cancelled, None, ChangeKind::Copied); + s.end_chunk(); + assert_eq!(s.replaced, 3, "Y counts; Z, which the engine never reached, does not"); + assert_eq!((s.done, s.failed_top), (0, 4)); + s.end_chunk(); + assert_eq!(s.replaced, 3, "a chunk ends once"); + } + #[test] fn outcomes_per_kind() { let (a, b) = (p("C:\\a\\x"), p("C:\\b\\x")); diff --git a/apps/files/src/ops_ui.rs b/apps/files/src/ops_ui.rs index a86e5674..d46eaa90 100644 --- a/apps/files/src/ops_ui.rs +++ b/apps/files/src/ops_ui.rs @@ -566,6 +566,7 @@ pub fn refusal_text_with(r: &Refusal, detail: &str, replaced: u32, lang: UiLang, } }; match r { + Refusal::Replaced if replaced == 1 => t(k::FILES_OPS_UNDO_REPLACED_ONE, lang), Refusal::Replaced => tf(k::FILES_OPS_UNDO_REPLACED, lang, &[("n", &fmt.count(u64::from(replaced)))]), Refusal::Changed => tf(k::FILES_OPS_UNDO_CHANGED, lang, &[("name", detail)]), Refusal::NotEmpty => tf(k::FILES_OPS_UNDO_NOT_EMPTY, lang, &[("name", detail)]), @@ -1467,6 +1468,7 @@ pub fn chip_layout(s: &mut FilesScreen, cx: &mut LayoutCx, r: RectP) -> RectP { // The bar takes the status line while open: no chip over its buttons. let text = if s.bar.is_open() { None } else { chip_text(&s.shared.ops.borrow(), undo_top, cx.now_ms(), cx.lang(), &fmt) }; + let notice = status::notice_room(s, cx); let fl = &mut s.flyout; fl.status = r; if fl.line_on { @@ -1483,7 +1485,19 @@ pub fn chip_layout(s: &mut FilesScreen, cx: &mut LayoutCx, r: RectP) -> RectP { let undo_w = text.undo.as_ref().map_or(0, |u| width(cx, &format!("{SEP_DOT}{u}"), role)); let h = cx.px(cx.tokens().size.chip_h).min(r.h()); let w = (pad * 2 + main_w + fail_w + undo_w).min(r.w()); - let x = r.l + (r.w() - w) / 2; + let mut x = r.l + (r.w() - w) / 2; + // A notice on show is read whole: the chip moves right of it, or waits for the notice's hold to end when the line + // has no room for both. A chip that asks for an answer in a Windows dialog stays where it is. + if let (Some(room), None) = (notice, text.attention) { + let clear = r.l + room + cx.px(CHIP_BACK); + if x < clear { + if clear + w + cx.px(CHIP_BACK) > r.r - status::inset(cx) { + fl.chip = ChipLayout::default(); + return r; + } + x = clear; + } + } let y = r.t + (r.h() - h) / 2; let rect = RectP::wh(x, y, w, h); let text_r = RectP { l: x + pad, r: (x + pad + main_w).min(rect.r), ..rect }; diff --git a/apps/files/src/pathline.rs b/apps/files/src/pathline.rs index b0060c62..d57f5a46 100644 --- a/apps/files/src/pathline.rs +++ b/apps/files/src/pathline.rs @@ -409,7 +409,7 @@ fn commit(s: &mut FilesScreen, cx: &mut EventCx, text: &str) { match parse(text, &cwd, &env) { Parsed::Path(p) => start_stat(s, text, p, None), Parsed::Shell(name) => match env.known.iter().find(|(n, _)| *n == name) { - Some((_, p)) => window::navigate(s, cx, Location::Fs(p.clone()), None), + Some((_, p)) => go(s, cx, Location::Fs(p.clone()), None), None => not_found(s, cx, text), }, Parsed::Virtual(target) => { @@ -471,12 +471,12 @@ pub fn on_stat(s: &mut FilesScreen, cx: &mut EventCx, req: u64, path: WidePath, } let Some(st) = s.chrome.path.stat.take() else { return false }; match (found, st.command) { - (Some(true), _) => window::navigate(s, cx, Location::Fs(st.path), None), + (Some(true), _) => go(s, cx, Location::Fs(st.path), None), (Some(false), _) => match (st.path.parent(), st.path.file_name()) { (Some(dir), Some(name)) => { let mut focus = Vec::new(); utf16_to_wtf8(name, &mut focus); - window::navigate(s, cx, Location::Fs(dir), Some(focus.into_boxed_slice())); + go(s, cx, Location::Fs(dir), Some(focus.into_boxed_slice())); } _ => not_found(s, cx, &st.text), }, @@ -486,6 +486,14 @@ pub fn on_stat(s: &mut FilesScreen, cx: &mut EventCx, req: u64, path: WidePath, true } +/// A typed path's folder opens and the list takes the keyboard, as after Enter in File Explorer's address bar: End and +/// the arrows move in the list, not in the address row. +fn go(s: &mut FilesScreen, cx: &mut EventCx, to: Location, focus: Option>) { + window::navigate(s, cx, to, focus); + s.region = window::Region::List; + cx.set_focus(oled_ui::NodeId::new(crate::tab::TABLE_ID, 0)); +} + /// A chevron: the subfolders of that level are listed on the Bg lane, and on_siblings opens the list. fn siblings(s: &mut FilesScreen, cx: &mut EventCx, key: u64, at: Anchor) { let _ = cx; diff --git a/apps/files/src/preview/mod.rs b/apps/files/src/preview/mod.rs index b3773cb2..2ccd8b90 100644 --- a/apps/files/src/preview/mod.rs +++ b/apps/files/src/preview/mod.rs @@ -19,6 +19,7 @@ pub mod icons; pub mod paste; pub mod places; pub mod search; +pub mod undo; use std::path::Path; @@ -70,6 +71,7 @@ pub fn scenes() -> Vec { search::scenes, details_pane::scenes, paste::scenes, + undo::scenes, ] { all.extend(part()); } diff --git a/apps/files/src/preview/undo.rs b/apps/files/src/preview/undo.rs new file mode 100644 index 00000000..8cbb6138 --- /dev/null +++ b/apps/files/src/preview/undo.rs @@ -0,0 +1,172 @@ +//! Preview scenes of undo: Ctrl+Z on a paste that replaced an older file (the helper refuses it and the notice says +//! why, whole), Ctrl+Z when the last change is in a folder that is not on screen (the notice names it and offers to +//! undo it there), Ctrl+Y when the last undone change is in such a folder (likewise, Redo there) and the More menu +//! naming those folders. Made-up names; system caption; the window at its default size. + +use oled_trust::frame::files::{OpEvt, OpId, OpKind, OpResult, Refusal, UndoEntry, UndoKind}; +use oled_ui::harness::Harness; +use oled_ui::host::Caption; +use oled_ui::SizeL; + +use super::fixtures::{self, settle, ROOT}; +use super::{Cells, Scene}; +use crate::fakes::Fakes; +use crate::format::Fmt; +use crate::ops_client::{OpsEvent, UndoRecord}; +use crate::ops_ui::OpRow; +use crate::window::FilesScreen; + +/// The window's default size (spec 6.5.1). +const WINDOW_SIZE: SizeL = SizeL { w: 1100, h: 720 }; +/// A narrow window: the notice, the chip and the drive block cannot all stand in the status line. +const NARROW_SIZE: SizeL = SizeL { w: 640, h: 480 }; +/// Longer than a finished operation's hold in the chip. +const AFTER_HOLD_MS: u32 = 7_000; +/// A rename this window did in another folder, earlier. +const RENAME: OpId = OpId(29); +/// The undo, done there, of a later rename in that folder. +const UNDONE: OpId = OpId(30); +/// The progress line's tween (DUR_PROGRESS) is over. +const SETTLED_MS: u32 = 300; +/// The folder the paste came from. +const FROM: &str = r"C:\made-up\Download"; +const PASTE: OpId = OpId(31); + +fn wp_in(dir: &str, name: &str) -> Option { + fixtures::wp(dir).join(&name.encode_utf16().collect::>()).ok() +} + +/// The documents folder, a folder where files may change. +fn documents(fakes: &Fakes, fmt: Fmt) -> FilesScreen { + fakes.enumr.queue(&fixtures::wp(ROOT), fixtures::documents()); + let s = fixtures::open(fakes, fmt, ROOT); + s.shared().paste_live.set(true); + s.toolbar().force_changes(Some(true)); + s +} + +/// The documents folder, with a paste of notes.txt into it asked by this window. +fn pasted(fakes: &Fakes, fmt: Fmt) -> FilesScreen { + let s = documents(fakes, fmt); + let mut row = OpRow::new(PASTE, OpKind::Copy, 1); + row.items = wp_in(FROM, "notes.txt").into_iter().collect(); + (row.count, row.folder) = (1, Some(fixtures::wp(ROOT))); + s.shared().ops.borrow_mut().insert(row); + s +} + +/// The paste is done, its undo record on the stack with `replaced` older files it took the place of. +fn paste_done(h: &mut Harness, fakes: &Fakes, replaced: u32) { + let entries = ["notes.txt"] + .iter() + .filter_map(|n| { + Some(UndoEntry { from: wp_in(FROM, n)?, to: wp_in(ROOT, n)?, size: 1, mtime: 2, dir: false, bin: None }) + }) + .collect(); + let record = UndoRecord { of: PASTE, kind: UndoKind::RecycleCopies, replaced, entries }; + fakes.ops.emit(OpsEvent::Evt(OpEvt::Started { op: PASTE, kind: OpKind::Copy, items: 1, bytes: 0 })); + fakes.ops.emit(OpsEvent::Undo(record)); + let undo = Some(UndoKind::RecycleCopies); + let finished = OpEvt::Finished { op: PASTE, result: OpResult::Done, undo, replaced, items: 1, failed: 0 }; + fakes.ops.emit(OpsEvent::Evt(finished)); + fakes.pump(h, 1); + h.render(); +} + +/// Ctrl+Z on a paste that replaced an older file: the helper refuses it, and the notice says why in full. +fn replaced(h: &mut Harness, fakes: &Fakes) { + settle(h, fakes); + paste_done(h, fakes, 1); + h.key("Ctrl+Z"); + let undo = h.screen().shared().ops.borrow().rows().iter().find(|r| r.kind == OpKind::Undo).map(|r| r.op); + if let Some(op) = undo { + fakes.ops.emit(OpsEvent::Evt(OpEvt::Refused { op, why: Refusal::Replaced, detail: "1".into() })); + } + fakes.pump(h, 1); + h.advance(SETTLED_MS); + h.render(); +} + +/// The documents folder, with a rename of a file in Download asked by this window earlier. +fn renamed_elsewhere(fakes: &Fakes, fmt: Fmt) -> FilesScreen { + let s = documents(fakes, fmt); + let mut row = OpRow::new(RENAME, OpKind::Rename, 1); + row.items = wp_in(FROM, "draft.txt").into_iter().collect(); + (row.count, row.folder, row.name) = (1, Some(fixtures::wp(FROM)), Some("plan.txt".into())); + s.shared().ops.borrow_mut().insert(row); + s +} + +/// The record of a rename of `from` to `to` in Download, as op `of`. +fn rename_in_download(of: OpId, from: &str, to: &str) -> Option { + let (from, to) = (wp_in(FROM, from)?, wp_in(FROM, to)?); + let entries = vec![UndoEntry { from, to, size: 1, mtime: 2, dir: false, bin: None }]; + Some(UndoRecord { of, kind: UndoKind::RenameBack, replaced: 0, entries }) +} + +/// Ctrl+Z in documents while the last change is a rename in Download: nothing is undone out of sight; the notice names +/// the change and its folder, with Undo there. +fn elsewhere(h: &mut Harness, fakes: &Fakes) { + settle(h, fakes); + let Some(record) = rename_in_download(RENAME, "draft.txt", "plan.txt") else { return }; + fakes.ops.emit(OpsEvent::Evt(OpEvt::Started { op: RENAME, kind: OpKind::Rename, items: 1, bytes: 0 })); + fakes.ops.emit(OpsEvent::Undo(record)); + let undo = Some(UndoKind::RenameBack); + let finished = OpEvt::Finished { op: RENAME, result: OpResult::Done, undo, replaced: 0, items: 1, failed: 0 }; + fakes.ops.emit(OpsEvent::Evt(finished)); + fakes.pump(h, 1); + h.render(); + h.advance(AFTER_HOLD_MS); + h.render(); + h.key("Ctrl+Z"); + h.advance(SETTLED_MS); + h.render(); +} + +/// Ctrl+Y in documents while the last undone change is a rename in Download: nothing is done again out of sight; the +/// notice names the change and its folder, with Redo there. +fn redo_elsewhere(h: &mut Harness, fakes: &Fakes) { + settle(h, fakes); + let Some(record) = rename_in_download(RENAME, "draft.txt", "plan.txt") else { return }; + let undone = crate::undo::UndoEntry { op: UNDONE, kind: OpKind::Rename, record }; + h.screen().shared().undo.borrow_mut().push_redo(undone); + h.key("Ctrl+Y"); + h.advance(SETTLED_MS); + h.render(); +} + +/// The More menu in documents while the last change and the last undone one are renames in Download: Undo and Redo +/// each name the folder. +fn more_elsewhere(h: &mut Harness, fakes: &Fakes) { + settle(h, fakes); + let last = rename_in_download(RENAME, "notes.txt", "notes-old.txt"); + let undone = rename_in_download(UNDONE, "draft.txt", "plan.txt"); + let (Some(last), Some(undone)) = (last, undone) else { return }; + let last = crate::undo::UndoEntry { op: RENAME, kind: OpKind::Rename, record: last }; + let undone = crate::undo::UndoEntry { op: UNDONE, kind: OpKind::Rename, record: undone }; + let shared = h.screen().shared(); + shared.undo.borrow_mut().push(last); + shared.undo.borrow_mut().push_redo(undone); + super::command_bar::open_more(h); +} + +fn scene( + name: &'static str, + size: SizeL, + cells: Cells, + build: fn(&Fakes, Fmt) -> FilesScreen, + script: fn(&mut Harness, &Fakes), +) -> Scene { + Scene { name, size, cells, caption: Caption::System, build, script } +} + +/// This file's scenes. +pub fn scenes() -> Vec { + vec![ + scene("undo_replaced_notice", WINDOW_SIZE, Cells::Full12, pasted, replaced), + scene("undo_replaced_notice_narrow", NARROW_SIZE, Cells::Four, pasted, replaced), + scene("undo_elsewhere_notice", WINDOW_SIZE, Cells::Full12, renamed_elsewhere, elsewhere), + scene("redo_elsewhere_notice", WINDOW_SIZE, Cells::Full12, documents, redo_elsewhere), + scene("undo_redo_elsewhere_more_menu", WINDOW_SIZE, Cells::Four, documents, more_elsewhere), + ] +} diff --git a/apps/files/src/rename.rs b/apps/files/src/rename.rs index 135c9877..debbe819 100644 --- a/apps/files/src/rename.rs +++ b/apps/files/src/rename.rs @@ -231,12 +231,13 @@ pub fn event(s: &mut FilesScreen, cx: &mut EventCx, ev: &Event) -> Option s.rename.field = None; return None; } - // The window leaves the kit's timers to nobody: the field's caret and the refusal line's 3 s are the table's. - if matches!(ev, Event::Timer(id) if id.is_kit()) { + // The field's caret and the refusal line's 3 s are kit timers of the table the field was begun in; the field and + // the line damage what they change. The shown tab's table takes them below with the other widgets' timers; a field + // left in a tab no longer shown gets them here, and the widgets shown still get theirs. + if matches!(ev, Event::Timer(id) if id.is_kit()) && tab != s.tabs.active().id { if let Some(t) = s.tabs.by_id_mut(tab) { let _ = t.table.event(cx, ev); } - return Some(Reply::Redraw); } None } diff --git a/apps/files/src/shell/menu.rs b/apps/files/src/shell/menu.rs index 7609b2fe..868d5cad 100644 --- a/apps/files/src/shell/menu.rs +++ b/apps/files/src/shell/menu.rs @@ -21,6 +21,9 @@ use windows::Win32::UI::WindowsAndMessaging::{ WM_CANCELMODE, WM_DRAWITEM, WM_INITMENUPOPUP, WM_MEASUREITEM, WM_MENUCHAR, WM_NULL, WM_TIMER, WNDCLASSW, WS_EX_TOOLWINDOW, WS_POPUP, }; +use windows::Win32::UI::WindowsAndMessaging::{ + DeleteMenu, GetMenuItemInfoW, MENUITEMINFOW, MFT_SEPARATOR, MF_BYPOSITION, MIIM_FTYPE, MIIM_STRING, MIIM_SUBMENU, +}; use crate::shell::crumbs; use crate::shell::host::{fault, HostCfg}; @@ -255,6 +258,8 @@ fn show(cm: &IContextMenu, menu: HMENU, owner: HWND, m: &MenuReq, ext: &str, w: SetTimer(Some(owner), DISMISS_TIMER, ms, None); } } + // The handlers loaded for this menu may have set another mode for the process: dark again, right before it shows. + oled_sys::darkmenu::init(); // SAFETY: a live menu and window of this thread's; TPM_RETURNCMD makes the result the chosen id. let chosen = unsafe { TrackPopupMenuEx(menu, (TPM_RETURNCMD | TPM_RIGHTBUTTON).0, m.at.0, m.at.1, owner, None) }; // SAFETY: as above; WM_NULL lets the menu's own loop end cleanly (the documented TrackPopupMenu pattern). @@ -302,6 +307,63 @@ impl Drop for Menu { } } +/// The text of a menu item compared for repeats: no mnemonic marks, no edge blanks, no case. +fn label_key(text: &str) -> String { + text.replace('&', "").trim().to_lowercase() +} + +/// The positions to remove from a menu whose top-level items have these labels (None: a separator, a submenu or an +/// item without text, which are never removed): every leaf item whose label an earlier item already has. Windows 11 +/// builds the classic menu from the extensions' legacy handlers and, below them, once more from the same extensions' +/// packaged commands, so an extension that has both (a file-lock tool, a batch renamer) shows twice. The first item is +/// kept: it is the legacy handler's, which has a verb of its own. +pub fn repeated(labels: &[Option]) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for (i, label) in labels.iter().enumerate() { + let Some(key) = label.as_deref().map(label_key).filter(|k| !k.is_empty()) else { continue }; + if !seen.insert(key) { + out.push(i); + } + } + out +} + +/// The labels of the top-level items of `menu`, as `repeated` reads them. +fn top_labels(menu: HMENU) -> Vec> { + // SAFETY: a live menu of this thread's. + let n = unsafe { GetMenuItemCount(Some(menu)) }.max(0); + (0..n) + .map(|i| { + let mut buf = [0u16; 256]; + let mut mi = MENUITEMINFOW { + cbSize: std::mem::size_of::() as u32, + fMask: MIIM_STRING | MIIM_SUBMENU | MIIM_FTYPE, + dwTypeData: windows::core::PWSTR(buf.as_mut_ptr()), + cch: (buf.len() - 1) as u32, + ..Default::default() + }; + // SAFETY: `mi` is sized and points at a buffer of the length it states; `i` is a position in the menu. + unsafe { GetMenuItemInfoW(menu, i as u32, true, &mut mi) }.ok()?; + if !mi.hSubMenu.0.is_null() || mi.fType.0 & MFT_SEPARATOR.0 != 0 { + return None; + } + let len = buf.iter().position(|&u| u == 0).unwrap_or(buf.len()); + Some(String::from_utf16_lossy(buf.get(..len).unwrap_or_default())) + }) + .collect() +} + +/// Removes the repeated top-level items of `menu` (see `repeated`); returns how many. +fn drop_repeats(menu: HMENU) -> usize { + let gone = repeated(&top_labels(menu)); + for &i in gone.iter().rev() { + // SAFETY: a position of the menu; positions after it shift, which the reverse order allows for. + let _ = unsafe { DeleteMenu(menu, i as u32, MF_BYPOSITION) }; + } + gone.len() +} + /// The folder's IContextMenu for `children` (the id lists stay alive in the returned Vec while it is used). With /// FILES_FAULT_DLL (debug builds), the fault DLL's FaultMenu initialized on the same items instead (registration-free). fn context_menu( @@ -426,6 +488,10 @@ fn menu(m: MenuReq, w: &Writer, cfg: &HostCfg) -> std::result::Result 0 { + oled_sys::log!("shell: menu {}: {removed} repeated item(s) left out", m.req.0); + } let chosen = if cfg.test_no_ui { w.send(&ShellEvt::MenuShown { req: m.req }); cfg.pick.as_deref().and_then(|p| find_verb(cm, menu.0, &ext, p)).unwrap_or(0) @@ -467,6 +533,64 @@ mod tests { } } + fn labels(items: &[&str]) -> Vec> { + items.iter().map(|s| (!s.is_empty() && !s.starts_with('>')).then(|| s.to_string())).collect() + } + + /// The classic menu of a text file on a Windows 11 system with a file-lock tool and a batch renamer installed (made-up names) (the + /// legacy handlers first, the same extensions' packaged commands below): each of those showed twice. + #[test] + fn repeated_items_are_the_later_ones() { + let menu = labels(&[ + "Apr&i", + "Sblocca con Esempio", + "Rinomina in blocco", + "Apr&i con", + "Cop&ia come percorso", + "Sblocca con Esempio", + "&Condividi", + "Rinomina in b&locco", + "", + "Tag&lia", + ]); + assert_eq!(repeated(&menu), vec![5, 7]); + } + + #[test] + fn separators_and_submenus_never_count_as_repeats() { + // None is a separator or a submenu; two of them in a row, or a repeat of a submenu's name, stay. + assert!(repeated(&[None, Some("A".into()), None, None, Some("B".into())]).is_empty()); + assert!(repeated(&labels(&["Apri", "Modifica", "Stampa"])).is_empty()); + assert_eq!(repeated(&labels(&["Copia", "&copia ", "COPIA"])), vec![1, 2], "case, blanks and marks ignored"); + assert!(repeated(&[Some(String::new()), Some(" ".into())]).is_empty(), "no text, no label"); + } + + /// The real classic menu of a file on this PC, built (never shown) the way the host builds it: no label shows + /// twice at the top level once the repeats are dropped. On a PC with an extension that registers both a legacy + /// handler and a packaged command it fails without `drop_repeats`; elsewhere it passes either way. + #[test] + fn real_menu_has_no_repeated_item() { + use windows::Win32::System::Com::{CoInitializeEx, COINIT_APARTMENTTHREADED}; + // SAFETY: COM for this test's thread; a second initialisation only reports it. + let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + let root = crate::testkit::TempRoot::new("menu_repeats"); + let file = root.file("a.txt", b"x"); + let dir = root.path().to_path_buf(); + let child = WidePath::parse(file.to_str().unwrap()).unwrap(); + let parent = WidePath::parse(dir.to_str().unwrap()).unwrap(); + let built = context_menu(&parent, &[child], HWND::default(), &HostCfg::default()); + if let Ok((cm, _ids)) = built { + // SAFETY: a new menu of this thread's, destroyed below. + let menu = Menu(unsafe { CreatePopupMenu() }.unwrap()); + // SAFETY: a live menu and the id range of the host. + let _ = unsafe { cm.QueryContextMenu(menu.0, 0, FIRST_ID, LAST_ID, CMF_NORMAL | CMF_CANRENAME) }; + drop_repeats(menu.0); + let left = top_labels(menu.0); + drop(cm); + assert!(repeated(&left).is_empty(), "repeated labels left in {left:?}"); + } + } + #[test] fn owner_msg_routing() { use windows::Win32::UI::WindowsAndMessaging::{WM_COMMAND, WM_MENUSELECT, WM_PAINT}; diff --git a/apps/files/src/status.rs b/apps/files/src/status.rs index f3ebd72a..c9760769 100644 --- a/apps/files/src/status.rs +++ b/apps/files/src/status.rs @@ -46,8 +46,6 @@ const DRIVE_ART: i32 = 16; const DRIVE_BAR_W: i32 = 48; /// Above this share used the bar and the free space ask for attention. const FULL: f32 = 0.9; -/// The most of a notice the left side keeps when the right block is made to fit. -const NOTICE_MIN: i32 = 160; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NoticeAct { @@ -56,6 +54,7 @@ pub enum NoticeAct { Reopen, Rest(OpId), Undo(OpId), + Redo(OpId), OpenRecycleBin, Details(OpId), /// The loop guard's notice: the hand-off it held back (F4.13). @@ -133,6 +132,10 @@ pub struct Placed { /// The drive's art, name and bar together. pub drive: RectP, pub free: RectP, + /// The notice's text and its action button together. + pub notice: RectP, + /// The notice's text and button got their whole width: nothing of it is cut. + pub notice_whole: bool, } /// The open folder's drive at the right end of the line. @@ -327,9 +330,36 @@ fn selected_text(s: &FilesScreen, st: Stats, lang: UiLang) -> String { out } +/// The width a notice on show needs to be read whole: its text, and its action button after the gap. None without a +/// notice. The drive block yields to it, and the chip stands clear of it (ops_ui::chip_layout). +pub fn notice_width(s: &FilesScreen, cx: &mut LayoutCx) -> Option { + let n = s.status.notice.as_ref()?; + let mut text = TextLabel::new(ID_NOTICE, n.text.clone(), TypeRole::Caption, FgRole::Primary); + let mut w = text.preferred(cx).w; + if let Some((label, _)) = &n.action { + let mut b = Button::new(ID_ACTION, label.clone(), ButtonKind::Secondary); + w += cx.scale().px(GAP) + b.preferred(cx).w; + } + Some(w) +} + +/// The room a notice on show takes from the line's left edge, the gap after it included: what the chip must leave it +/// (ops_ui::chip_layout). None without a notice. +pub fn notice_room(s: &FilesScreen, cx: &mut LayoutCx) -> Option { + let w = notice_width(s, cx)?; + let sc = cx.scale(); + Some(sc.px(INSET) + w + sc.px(GAP)) +} + +/// The line's inset at both ends. +pub fn inset(cx: &LayoutCx) -> i32 { + cx.scale().px(INSET) +} + /// The items and the selection on the left (or the notice in their place), the free space on the right. pub fn layout(s: &mut FilesScreen, cx: &mut LayoutCx, r: RectP) { refresh(s, true); + let notice_w = notice_width(s, cx); let lang = s.shared.lang.get(); let st = s.status.stats; let home = matches!(s.tabs.active().nav.page(), Page::Home); @@ -375,9 +405,9 @@ pub fn layout(s: &mut FilesScreen, cx: &mut LayoutCx, r: RectP) { if let Some(n) = ¬ice { me.text = TextLabel::new(ID_NOTICE, n.text.clone(), TypeRole::Caption, FgRole::Primary); } - // The least the left side keeps: the count, or a stretch of the notice. - let left_min = match ¬ice { - Some(_) => me.text.preferred(cx).w.min(sc.px(NOTICE_MIN)), + // The least the left side keeps: the count, or the whole notice (it is read whole: the drive block yields to it). + let left_min = match notice_w { + Some(w) => w, None => me.items.preferred(cx).w, }; // The right side starts after the chip's backdrop, or after what the left side keeps. @@ -421,19 +451,25 @@ pub fn layout(s: &mut FilesScreen, cx: &mut LayoutCx, r: RectP) { let avail = (limit - x0).max(0); match notice { Some(n) => { - let mut text_w = me.text.preferred(cx).w.min(avail); + let text_full = me.text.preferred(cx).w; + let mut text_w = text_full.min(avail); me.action = n.action.map(|(label, act)| (Button::new(ID_ACTION, label, ButtonKind::Secondary), act)); - let mut btn_w = 0; + let (mut btn_w, mut btn_full) = (0, 0); if let Some((b, _)) = me.action.as_mut() { - btn_w = b.preferred(cx).w.min(avail / 2); + btn_full = b.preferred(cx).w; + btn_w = btn_full.min(avail / 2); text_w = text_w.min((avail - btn_w - gap).max(0)); } me.text.layout(cx, RectP { l: x0, t: y, r: x0 + text_w, b: y + line }); + let mut right_end = x0 + text_w; if let Some((b, _)) = me.action.as_mut() { let (bh, bx) = (sc.px(ACTION_H), x0 + text_w + gap); let by = r.t + (r.h() - bh) / 2; b.layout(cx, RectP { l: bx, t: by, r: bx + btn_w, b: by + bh }); + right_end = bx + btn_w; } + me.placed.notice = RectP { l: x0, t: y, r: right_end, b: y + line }; + me.placed.notice_whole = text_w >= text_full && btn_w >= btn_full; } None => { me.action = None; @@ -558,8 +594,8 @@ pub fn on_notice_timer(s: &mut FilesScreen, cx: &mut EventCx) { } /// Retry -> window::cmd(Refresh); OpenInExplorer -> open::hand_off_current; Reopen -> notices::reopen; Rest -> -/// ops_ui::on_rest; Undo -> ops_ui::cmd(Undo); OpenRecycleBin -> handoff::hand_off; Details -> ops_ui::flyout_open; -/// HandOff -> handoff::open_held. +/// ops_ui::on_rest; Undo -> undo::undo_there and Redo -> undo::redo_there (the change it names, wherever it is); +/// OpenRecycleBin -> handoff::hand_off; Details -> ops_ui::flyout_open; HandOff -> handoff::open_held. pub fn on_notice_action(s: &mut FilesScreen, cx: &mut EventCx, a: NoticeAct) -> Reply { match a { NoticeAct::Retry => match open::retry(s, cx) { @@ -569,7 +605,8 @@ pub fn on_notice_action(s: &mut FilesScreen, cx: &mut EventCx, a: NoticeAct) -> NoticeAct::OpenInExplorer => open::hand_off_current(s, cx), NoticeAct::Reopen => notices::reopen(s, cx), NoticeAct::Rest(op) => ops_ui::on_rest(s, cx, op), - NoticeAct::Undo(_) => ops_ui::cmd(s, cx, Cmd::Undo), + NoticeAct::Undo(op) => crate::undo::undo_there(s, cx, op), + NoticeAct::Redo(op) => crate::undo::redo_there(s, cx, op), NoticeAct::OpenRecycleBin => handoff::hand_off(s, cx, handoff::Target::RecycleBin, false), NoticeAct::Details(op) => ops_ui::flyout_open(s, cx, Some(op)), NoticeAct::HandOff => handoff::open_held(s, cx), diff --git a/apps/files/src/tab.rs b/apps/files/src/tab.rs index bf9ed6f8..d5c254c4 100644 --- a/apps/files/src/tab.rs +++ b/apps/files/src/tab.rs @@ -126,10 +126,13 @@ impl Tabs { !self.closed.is_empty() } - /// The shown tab is about to become a background one: it is the most recently active of them. + /// The shown tab is about to become a background one: it is the most recently active of them, and a wheel scroll + /// of its list ends where it was going (every tab's table has the same id: its frames would reach the next one). fn stamp(&mut self) { self.clock += 1; - self.tabs[self.selected].used = self.clock; + let t = &mut self.tabs[self.selected]; + t.used = self.clock; + t.table.settle_scroll(); } /// Activates the right neighbour, else the left; None when it was the last (it stays). diff --git a/apps/files/src/toolmenus.rs b/apps/files/src/toolmenus.rs index b586cb58..1dd534fd 100644 --- a/apps/files/src/toolmenus.rs +++ b/apps/files/src/toolmenus.rs @@ -181,7 +181,7 @@ pub fn may_change_dir(dir: &WidePath) -> bool { /// A Custom row; `why` is the reason it is disabled (None: enabled). #[allow(clippy::too_many_arguments)] -fn item( +pub(crate) fn item( s: &FilesScreen, id: u32, label: Text, @@ -338,7 +338,8 @@ pub fn more_items(s: &FilesScreen) -> Vec { let lang = s.shared.lang.get(); let (undo, redo) = { let u = s.shared.undo.borrow(); - (u.label(lang), u.redo_label(lang)) + let at = s.tabs.active().nav.location(); + (u.label_at(lang, at), u.redo_label_at(lang, at)) }; let state = avail(s); let undo_label: Text = undo.unwrap_or_else(|| t(k::FILES_MORE_UNDO_PLAIN, lang)); diff --git a/apps/files/src/undo.rs b/apps/files/src/undo.rs index d50a988b..047a816b 100644 --- a/apps/files/src/undo.rs +++ b/apps/files/src/undo.rs @@ -1,18 +1,23 @@ //! Undo and redo: one stack per process in Shared, shared by every window. An entry is pushed //! when the helper sends the undo record of an operation this process asked for; Ctrl+Z sends it back through the //! gate (or hands the Recycle Bin to File Explorer); a successful undo goes on the redo stack, and a new operation -//! clears it. +//! clears it. Ctrl+Z stops at the folder on screen: File Explorer's undo reaches a change in any folder without a +//! word, ours undoes nothing out of sight and says what the last change is and where, with a button that undoes it +//! there. Ctrl+Y and Ctrl+Shift+Z stop there too, with a button that does the change again there. use std::collections::VecDeque; -use oled_trust::frame::files::{OpId, OpKind, UndoKind}; +use oled_trust::frame::files::{Location, OpId, OpKind, UndoKind}; use oled_ui::node::Text; use oled_ui::{EventCx, Reply, UiLang}; use crate::handoff::{self, Target}; +use crate::listing::WidePath; +use crate::ops::checks::same_path; use crate::ops_client::UndoRecord; use crate::ops_ui::{self, name_of, MutReq}; -use crate::status::{self, Notice}; +use crate::status::{self, Notice, NoticeAct}; +use crate::toolbar::place_name; use crate::tr::{k, t, tf}; use crate::window::FilesScreen; @@ -45,12 +50,47 @@ impl UndoStack { Some(tf(k::FILES_MORE_UNDO, lang, &[("op", &verb(e.kind, lang))])) } + /// label(), with the folder named when the newest entry changes a folder other than `at` ("Undo Rename in docs"). + pub fn label_at(&self, lang: UiLang, at: &Location) -> Option { + let e = self.undo.back()?; + match elsewhere(&e.record, at) { + Some(dir) => { + let folder = place_name(&Location::Fs(dir), lang); + Some(tf(k::FILES_MORE_UNDO_IN, lang, &[("op", &verb(e.kind, lang)), ("folder", &folder)])) + } + None => self.label(lang), + } + } + + /// The newest entry. + pub fn top(&self) -> Option<&UndoEntry> { + self.undo.back() + } + /// "Redo Rename", "Redo New folder", "Redo Delete" for the newest entry that can be done again. pub fn redo_label(&self, lang: UiLang) -> Option { let e = self.redo.last()?; Some(tf(k::FILES_MORE_REDO_OP, lang, &[("op", &verb(e.kind, lang))])) } + /// redo_label(), with the folder named when the newest entry would change a folder other than `at` ("Redo Rename in + /// docs"). + pub fn redo_label_at(&self, lang: UiLang, at: &Location) -> Option { + let e = self.redo.last()?; + match elsewhere(&e.record, at) { + Some(dir) => { + let folder = place_name(&Location::Fs(dir), lang); + Some(tf(k::FILES_MORE_REDO_IN, lang, &[("op", &verb(e.kind, lang)), ("folder", &folder)])) + } + None => self.redo_label(lang), + } + } + + /// The newest entry that can be done again. + pub fn redo_top(&self) -> Option<&UndoEntry> { + self.redo.last() + } + /// A new entry; past the cap the oldest goes. pub fn push(&mut self, e: UndoEntry) { self.undo.retain(|x| x.op != e.op); @@ -108,15 +148,78 @@ pub fn verb(kind: OpKind, lang: UiLang) -> Text { } } -/// Ctrl+Z: the newest entry. OpenRecycleBin hands the bin to File Explorer (the entry is consumed); any other goes to -/// the helper through the gate (a refusal comes back as its own text); a request that could not be made keeps the -/// entry. Nothing to undo: the notice says so. +/// The folders an undo record changes: where its items are now, where a move's go back to and where a restore's come +/// back; none for a record that names no item (the Recycle Bin's hand-off changes nothing). They are also the folders +/// its redo changes: a rename stays in its folder, a new folder is made where it was, a delete takes the restored +/// items where they came back. +pub fn folders(rec: &UndoRecord) -> Vec { + let mut out: Vec = Vec::new(); + for e in &rec.entries { + let at = match rec.kind { + UndoKind::RestoreRecycled => [e.from.parent(), None], + UndoKind::MoveBack => [e.to.parent(), e.from.parent()], + _ => [e.to.parent(), None], + }; + for p in at.into_iter().flatten() { + if !out.iter().any(|q| same_path(q, &p)) { + out.push(p); + } + } + } + out +} + +/// The folder to name when undoing `rec` would change none of the folder `at` shows (a page that is no folder shows +/// none); None when the record's change is here, or names no folder. +pub fn elsewhere(rec: &UndoRecord, at: &Location) -> Option { + let dirs = folders(rec); + let here = match at { + Location::Fs(dir) => dirs.iter().any(|d| same_path(d, dir)), + _ => false, + }; + if here { + return None; + } + dirs.into_iter().next() +} + +/// Ctrl+Z (and the chip's Undo, the More menu's Undo): the newest entry, when it changes the folder on screen. One that +/// changes another folder is not undone: the notice names it and its folder, with [Undo there] (NoticeAct::Undo). +/// Nothing to undo: the notice says so. pub fn undo(s: &mut FilesScreen, cx: &mut EventCx) -> Reply { - let entry = s.shared.undo.borrow_mut().pop(); - let Some(e) = entry else { - status::notice(s, cx, Notice::new(t(k::FILES_OPS_NOTHING_TO_UNDO, cx.lang()))); - return Reply::Relayout; + let lang = cx.lang(); + let away = { + let stack = s.shared.undo.borrow(); + let Some(e) = stack.top() else { + drop(stack); + status::notice(s, cx, Notice::new(t(k::FILES_OPS_NOTHING_TO_UNDO, lang))); + return Reply::Relayout; + }; + elsewhere(&e.record, s.tabs.active().nav.location()).map(|dir| (e.op, e.kind, dir)) }; + if let Some((op, kind, dir)) = away { + let folder = place_name(&Location::Fs(dir), lang); + let text = tf(k::FILES_OPS_UNDO_ELSEWHERE, lang, &[("op", &verb(kind, lang)), ("folder", &folder)]); + let act = (t(k::FILES_OPS_UNDO_THERE, lang), NoticeAct::Undo(op)); + status::notice(s, cx, Notice { action: Some(act), ..Notice::new(text) }); + return Reply::Relayout; + } + undo_top(s, cx) +} + +/// [Undo there]: the change the notice named, wherever it is, when it is still the newest; anything else does nothing. +pub fn undo_there(s: &mut FilesScreen, cx: &mut EventCx, op: OpId) -> Reply { + if s.shared.undo.borrow().top_op() != Some(op) { + return Reply::None; + } + undo_top(s, cx) +} + +/// The newest entry. OpenRecycleBin hands the bin to File Explorer (the entry is consumed); any other goes to the +/// helper through the gate (a refusal comes back as its own text); a request that could not be made keeps the entry. +fn undo_top(s: &mut FilesScreen, cx: &mut EventCx) -> Reply { + let entry = s.shared.undo.borrow_mut().pop(); + let Some(e) = entry else { return Reply::None }; if e.record.kind == UndoKind::OpenRecycleBin { return handoff::hand_off(s, cx, Target::RecycleBin, false); } @@ -126,10 +229,39 @@ pub fn undo(s: &mut FilesScreen, cx: &mut EventCx) -> Reply { Reply::Redraw } -/// Ctrl+Y and Ctrl+Shift+Z: the forward operation again. RenameBack: the rename; RecycleNewFolder: the new folder; -/// RestoreRecycled: the Del flow over the restored items, classified like every recycle (U3), so any No opens the bar -/// and nothing goes permanently without its Enter. Copies and moves are not in this beta. Nothing to redo: nothing. +/// Ctrl+Y and Ctrl+Shift+Z: the newest undone change again, when it changes the folder on screen. One that changes +/// another folder is not done again: the notice names it and its folder, with [Redo there] (NoticeAct::Redo). Nothing +/// to redo: nothing. pub fn redo(s: &mut FilesScreen, cx: &mut EventCx) -> Reply { + let lang = cx.lang(); + let away = { + let stack = s.shared.undo.borrow(); + let Some(e) = stack.redo_top() else { return Reply::None }; + elsewhere(&e.record, s.tabs.active().nav.location()).map(|dir| (e.op, e.kind, dir)) + }; + if let Some((op, kind, dir)) = away { + let folder = place_name(&Location::Fs(dir), lang); + let text = tf(k::FILES_OPS_REDO_ELSEWHERE, lang, &[("op", &verb(kind, lang)), ("folder", &folder)]); + let act = (t(k::FILES_OPS_REDO_THERE, lang), NoticeAct::Redo(op)); + status::notice(s, cx, Notice { action: Some(act), ..Notice::new(text) }); + return Reply::Relayout; + } + redo_top(s, cx) +} + +/// [Redo there]: the change the notice named, wherever it is, when it is still the newest undone one; anything else +/// does nothing. +pub fn redo_there(s: &mut FilesScreen, cx: &mut EventCx, op: OpId) -> Reply { + if s.shared.undo.borrow().redo_top().map(|e| e.op) != Some(op) { + return Reply::None; + } + redo_top(s, cx) +} + +/// The forward operation of the newest redo entry. RenameBack: the rename; RecycleNewFolder: the new folder; +/// RestoreRecycled: the Del flow over the restored items, classified like every recycle, so any No opens the bar and +/// nothing goes permanently without its Enter. Copies and moves are not in this beta. +fn redo_top(s: &mut FilesScreen, cx: &mut EventCx) -> Reply { let entry = s.shared.undo.borrow_mut().pop_redo(); let Some(e) = entry else { return Reply::None }; let first = e.record.entries.first(); diff --git a/apps/files/src/window.rs b/apps/files/src/window.rs index de6563c5..423de7bd 100644 --- a/apps/files/src/window.rs +++ b/apps/files/src/window.rs @@ -1072,7 +1072,8 @@ impl FilesScreen { self.closing(); return Reply::Close; } - Event::Timer(id) => return self.on_timer(cx, *id), + // The kit's own timers (a list's scroll animation, a scrollbar's hide) go on to their widgets below. + Event::Timer(id) if !id.is_kit() => return self.on_timer(cx, *id), Event::PointerDown { pos, button: MouseButton::Right, .. } if self.rects.body.contains(*pos) => { open::prespawn(&self.shared); // The rows that waited for the host ask on the next layout. diff --git a/apps/files/strings/en.toml b/apps/files/strings/en.toml index b2175e70..3dcf214b 100644 --- a/apps/files/strings/en.toml +++ b/apps/files/strings/en.toml @@ -82,8 +82,10 @@ "files.sort.desc" = "Descending" "files.more.undo" = "Undo {op}" "files.more.undo_plain" = "Undo" +"files.more.undo_in" = "Undo {op} in {folder}" "files.more.redo" = "Redo" "files.more.redo_op" = "Redo {op}" +"files.more.redo_in" = "Redo {op} in {folder}" "files.more.select_all" = "Select all" "files.more.select_none" = "Select none" "files.more.invert" = "Invert selection" @@ -127,6 +129,11 @@ "files.ops.bar_delete" = "Delete (Enter)" "files.ops.bar_cancel" = "Cancel (Esc)" "files.ops.undo_replaced" = "Can't undo: {n} items replaced older files" +"files.ops.undo_replaced_one" = "Can't undo: 1 item replaced an older file" +"files.ops.undo_elsewhere" = "Last change: {op} in {folder}" +"files.ops.undo_there" = "Undo there" +"files.ops.redo_elsewhere" = "Last undone: {op} in {folder}" +"files.ops.redo_there" = "Redo there" "files.ops.undo_changed" = "Can't undo: {name} changed since" "files.ops.undo_not_empty" = "Can't undo: {name} isn't empty any more" "files.ops.undo_bin" = "Open Recycle Bin ↗" diff --git a/apps/files/strings/it.toml b/apps/files/strings/it.toml index 0d15a6f7..5bdb84e9 100644 --- a/apps/files/strings/it.toml +++ b/apps/files/strings/it.toml @@ -82,8 +82,10 @@ "files.sort.desc" = "Decrescente" "files.more.undo" = "Annulla {op}" "files.more.undo_plain" = "Annulla" +"files.more.undo_in" = "Annulla {op} in {folder}" "files.more.redo" = "Ripeti" "files.more.redo_op" = "Ripeti {op}" +"files.more.redo_in" = "Ripeti {op} in {folder}" "files.more.select_all" = "Seleziona tutto" "files.more.select_none" = "Deseleziona tutto" "files.more.invert" = "Inverti selezione" @@ -127,6 +129,11 @@ "files.ops.bar_delete" = "Elimina (Invio)" "files.ops.bar_cancel" = "Annulla (Esc)" "files.ops.undo_replaced" = "Impossibile annullare: {n} elementi hanno sostituito file meno recenti" +"files.ops.undo_replaced_one" = "Impossibile annullare: 1 elemento ha sostituito un file meno recente" +"files.ops.undo_elsewhere" = "Ultima modifica: {op} in {folder}" +"files.ops.undo_there" = "Annulla lì" +"files.ops.redo_elsewhere" = "Ultimo annullamento: {op} in {folder}" +"files.ops.redo_there" = "Ripeti lì" "files.ops.undo_changed" = "Impossibile annullare: {name} è cambiato nel frattempo" "files.ops.undo_not_empty" = "Impossibile annullare: {name} non è più vuota" "files.ops.undo_bin" = "Apri il Cestino ↗" diff --git a/apps/files/tests/a11y_sweep.rs b/apps/files/tests/a11y_sweep.rs index af9957ac..7f5858ae 100644 --- a/apps/files/tests/a11y_sweep.rs +++ b/apps/files/tests/a11y_sweep.rs @@ -165,6 +165,16 @@ fn display_name_has_one_entry() { } } +/// The window serves its tree to UI Automation clients, as tasks' does: the package turns the kit's bridge on by default. +/// Without it a build of this package alone (the release job builds each app on its own) has no bridge, and a client +/// reading the real window finds only the window, although every tree of these tests is complete. +#[test] +fn the_window_serves_ui_automation() { + // (files' a11y feature, the kit's bridge): the feature is a default one, and it turns the kit's bridge on. + let built = (cfg!(feature = "a11y"), oled_ui::host::SERVES_UI_AUTOMATION); + assert_eq!(built, (true, true), "files' default features hold a11y, which builds the kit with its bridge"); +} + #[test] fn the_overlap_check_catches_a_planted_collision() { let line = RectP { l: 10, t: 100, r: 110, b: 116 }; diff --git a/apps/files/tests/golden/base/about/en-96.png b/apps/files/tests/golden/base/about/en-96.png index d2e389ce..6a2dfecf 100644 Binary files a/apps/files/tests/golden/base/about/en-96.png and b/apps/files/tests/golden/base/about/en-96.png differ diff --git a/apps/files/tests/golden/base/about/hc-144.png b/apps/files/tests/golden/base/about/hc-144.png index 5fa574c0..510d0283 100644 Binary files a/apps/files/tests/golden/base/about/hc-144.png and b/apps/files/tests/golden/base/about/hc-144.png differ diff --git a/apps/files/tests/golden/base/about/it-144.png b/apps/files/tests/golden/base/about/it-144.png index 7abb4808..9a97b244 100644 Binary files a/apps/files/tests/golden/base/about/it-144.png and b/apps/files/tests/golden/base/about/it-144.png differ diff --git a/apps/files/tests/golden/base/about/pseudo-144.png b/apps/files/tests/golden/base/about/pseudo-144.png index 6e194906..d2846aaa 100644 Binary files a/apps/files/tests/golden/base/about/pseudo-144.png and b/apps/files/tests/golden/base/about/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/context_menu_file/en-96-menu0.png b/apps/files/tests/golden/base/context_menu_file/en-96-menu0.png index 6f608dec..8c9ffe86 100644 Binary files a/apps/files/tests/golden/base/context_menu_file/en-96-menu0.png and b/apps/files/tests/golden/base/context_menu_file/en-96-menu0.png differ diff --git a/apps/files/tests/golden/base/context_menu_file/hc-144-menu0.png b/apps/files/tests/golden/base/context_menu_file/hc-144-menu0.png index 9e9622f3..60c5a60a 100644 Binary files a/apps/files/tests/golden/base/context_menu_file/hc-144-menu0.png and b/apps/files/tests/golden/base/context_menu_file/hc-144-menu0.png differ diff --git a/apps/files/tests/golden/base/context_menu_file/it-144-menu0.png b/apps/files/tests/golden/base/context_menu_file/it-144-menu0.png index ae8e1739..ee728fd4 100644 Binary files a/apps/files/tests/golden/base/context_menu_file/it-144-menu0.png and b/apps/files/tests/golden/base/context_menu_file/it-144-menu0.png differ diff --git a/apps/files/tests/golden/base/context_menu_file/pseudo-144-menu0.png b/apps/files/tests/golden/base/context_menu_file/pseudo-144-menu0.png index f4087783..52b32168 100644 Binary files a/apps/files/tests/golden/base/context_menu_file/pseudo-144-menu0.png and b/apps/files/tests/golden/base/context_menu_file/pseudo-144-menu0.png differ diff --git a/apps/files/tests/golden/base/ops_notice_rights/pseudo-144.png b/apps/files/tests/golden/base/ops_notice_rights/pseudo-144.png index 85a80696..4e275877 100644 Binary files a/apps/files/tests/golden/base/ops_notice_rights/pseudo-144.png and b/apps/files/tests/golden/base/ops_notice_rights/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-en.txt b/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-en.txt new file mode 100644 index 00000000..97a3483d --- /dev/null +++ b/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-en.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Close tab" + Button "New tab" [focusable] +Button "Back · Alt+←" [disabled] +Button "Forward · Alt+→" [disabled] +Button "Up to made-up · Alt+↑" [focusable] +SearchInput "Search this folder" [focusable] "" +Toolbar "Path" + Link "C:" [focusable] + Button "Subfolders" + Link "made-up" [focusable] + Button "Subfolders" + Link "documents" [focusable] + Button "Subfolders" + Button "Refresh" [focusable] +Toolbar "New" + Button "New" [focusable, expandable] + Button "Cut" [disabled] + Button "Copy" [disabled] + Button "Paste" [disabled] + Button "Rename" [disabled] + Button "Delete" [disabled] + Button "Sort" [focusable, expandable] + Button "View" [focusable, expandable] + Button "Filter" [focusable, expandable] + Button "More" [focusable, expandable] + Button "Details" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "This PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Network" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Network" [focusable] level 1 + TreeItem "Recycle Bin" [focusable] level 1 +Splitter "Resize panes" [focusable] 20.363636% +Pane "Details pane" +ColumnHeader "Name" [focusable] +ColumnHeader "Date modified" [focusable] +ColumnHeader "Type" [focusable] +ColumnHeader "Size" [focusable] +Table "Name" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB free of 1.81 TB" +Label "System (C:)" +Label "Last undone: Rename in Download" +Button "Redo there" [focusable] diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-it.txt b/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-it.txt new file mode 100644 index 00000000..b0ef1b5d --- /dev/null +++ b/apps/files/tests/golden/base/redo_elsewhere_notice/a11y-it.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Chiudi scheda" + Button "Nuova scheda" [focusable] +Button "Indietro · Alt+←" [disabled] +Button "Avanti · Alt+→" [disabled] +Button "Su a made-up · Alt+↑" [focusable] +SearchInput "Cerca in questa cartella" [focusable] "" +Toolbar "Percorso" + Link "C:" [focusable] + Button "Sottocartelle" + Link "made-up" [focusable] + Button "Sottocartelle" + Link "documents" [focusable] + Button "Sottocartelle" + Button "Aggiorna" [focusable] +Toolbar "Nuovo" + Button "Nuovo" [focusable, expandable] + Button "Taglia" [disabled] + Button "Copia" [disabled] + Button "Incolla" [disabled] + Button "Rinomina" [disabled] + Button "Elimina" [disabled] + Button "Ordina" [focusable, expandable] + Button "Visualizza" [focusable, expandable] + Button "Filtra" [focusable, expandable] + Button "Altro" [focusable, expandable] + Button "Dettagli" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "Questo PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Rete" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Rete" [focusable] level 1 + TreeItem "Cestino" [focusable] level 1 +Splitter "Ridimensiona i riquadri" [focusable] 20.363636% +Pane "Riquadro dei dettagli" +ColumnHeader "Nome" [focusable] +ColumnHeader "Ultima modifica" [focusable] +ColumnHeader "Tipo" [focusable] +ColumnHeader "Dimensione" [focusable] +Table "Nome" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB liberi di 1,81 TB" +Label "System (C:)" +Label "Ultimo annullamento: Rinomina in Download" +Button "Ripeti lì" [focusable] diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/contrast-144.png b/apps/files/tests/golden/base/redo_elsewhere_notice/contrast-144.png new file mode 100644 index 00000000..906237e6 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/contrast-144.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/en-120.png b/apps/files/tests/golden/base/redo_elsewhere_notice/en-120.png new file mode 100644 index 00000000..4945806a Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/en-120.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/en-144.png b/apps/files/tests/golden/base/redo_elsewhere_notice/en-144.png new file mode 100644 index 00000000..906237e6 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/en-144.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/en-192.png b/apps/files/tests/golden/base/redo_elsewhere_notice/en-192.png new file mode 100644 index 00000000..39fe0338 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/en-192.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/en-96.png b/apps/files/tests/golden/base/redo_elsewhere_notice/en-96.png new file mode 100644 index 00000000..b23c751b Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/en-96.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/hc-144.png b/apps/files/tests/golden/base/redo_elsewhere_notice/hc-144.png new file mode 100644 index 00000000..fd3ca3da Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/hc-144.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/hc-96.png b/apps/files/tests/golden/base/redo_elsewhere_notice/hc-96.png new file mode 100644 index 00000000..fee50865 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/hc-96.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/it-120.png b/apps/files/tests/golden/base/redo_elsewhere_notice/it-120.png new file mode 100644 index 00000000..36f6a637 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/it-120.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/it-144.png b/apps/files/tests/golden/base/redo_elsewhere_notice/it-144.png new file mode 100644 index 00000000..a9051f0c Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/it-144.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/it-192.png b/apps/files/tests/golden/base/redo_elsewhere_notice/it-192.png new file mode 100644 index 00000000..2836b748 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/it-192.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/it-96.png b/apps/files/tests/golden/base/redo_elsewhere_notice/it-96.png new file mode 100644 index 00000000..55db8a69 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/it-96.png differ diff --git a/apps/files/tests/golden/base/redo_elsewhere_notice/pseudo-144.png b/apps/files/tests/golden/base/redo_elsewhere_notice/pseudo-144.png new file mode 100644 index 00000000..e3ec21d5 Binary files /dev/null and b/apps/files/tests/golden/base/redo_elsewhere_notice/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-en.txt b/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-en.txt new file mode 100644 index 00000000..2a6df12f --- /dev/null +++ b/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-en.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Close tab" + Button "New tab" [focusable] +Button "Back · Alt+←" [disabled] +Button "Forward · Alt+→" [disabled] +Button "Up to made-up · Alt+↑" [focusable] +SearchInput "Search this folder" [focusable] "" +Toolbar "Path" + Link "C:" [focusable] + Button "Subfolders" + Link "made-up" [focusable] + Button "Subfolders" + Link "documents" [focusable] + Button "Subfolders" + Button "Refresh" [focusable] +Toolbar "New" + Button "New" [focusable, expandable] + Button "Cut" [disabled] + Button "Copy" [disabled] + Button "Paste" [disabled] + Button "Rename" [disabled] + Button "Delete" [disabled] + Button "Sort" [focusable, expandable] + Button "View" [focusable, expandable] + Button "Filter" [focusable, expandable] + Button "More" [focusable, expandable] + Button "Details" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "This PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Network" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Network" [focusable] level 1 + TreeItem "Recycle Bin" [focusable] level 1 +Splitter "Resize panes" [focusable] 20.363636% +Pane "Details pane" +ColumnHeader "Name" [focusable] +ColumnHeader "Date modified" [focusable] +ColumnHeader "Type" [focusable] +ColumnHeader "Size" [focusable] +Table "Name" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB free of 1.81 TB" +Label "System (C:)" +Label "Last change: Rename in Download" +Button "Undo there" [focusable] diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-it.txt b/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-it.txt new file mode 100644 index 00000000..2e99f40d --- /dev/null +++ b/apps/files/tests/golden/base/undo_elsewhere_notice/a11y-it.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Chiudi scheda" + Button "Nuova scheda" [focusable] +Button "Indietro · Alt+←" [disabled] +Button "Avanti · Alt+→" [disabled] +Button "Su a made-up · Alt+↑" [focusable] +SearchInput "Cerca in questa cartella" [focusable] "" +Toolbar "Percorso" + Link "C:" [focusable] + Button "Sottocartelle" + Link "made-up" [focusable] + Button "Sottocartelle" + Link "documents" [focusable] + Button "Sottocartelle" + Button "Aggiorna" [focusable] +Toolbar "Nuovo" + Button "Nuovo" [focusable, expandable] + Button "Taglia" [disabled] + Button "Copia" [disabled] + Button "Incolla" [disabled] + Button "Rinomina" [disabled] + Button "Elimina" [disabled] + Button "Ordina" [focusable, expandable] + Button "Visualizza" [focusable, expandable] + Button "Filtra" [focusable, expandable] + Button "Altro" [focusable, expandable] + Button "Dettagli" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "Questo PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Rete" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Rete" [focusable] level 1 + TreeItem "Cestino" [focusable] level 1 +Splitter "Ridimensiona i riquadri" [focusable] 20.363636% +Pane "Riquadro dei dettagli" +ColumnHeader "Nome" [focusable] +ColumnHeader "Ultima modifica" [focusable] +ColumnHeader "Tipo" [focusable] +ColumnHeader "Dimensione" [focusable] +Table "Nome" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB liberi di 1,81 TB" +Label "System (C:)" +Label "Ultima modifica: Rinomina in Download" +Button "Annulla lì" [focusable] diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/contrast-144.png b/apps/files/tests/golden/base/undo_elsewhere_notice/contrast-144.png new file mode 100644 index 00000000..f90ff22a Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/contrast-144.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/en-120.png b/apps/files/tests/golden/base/undo_elsewhere_notice/en-120.png new file mode 100644 index 00000000..d187bc3d Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/en-120.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/en-144.png b/apps/files/tests/golden/base/undo_elsewhere_notice/en-144.png new file mode 100644 index 00000000..f90ff22a Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/en-144.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/en-192.png b/apps/files/tests/golden/base/undo_elsewhere_notice/en-192.png new file mode 100644 index 00000000..880a0a4b Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/en-192.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/en-96.png b/apps/files/tests/golden/base/undo_elsewhere_notice/en-96.png new file mode 100644 index 00000000..bac2b97e Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/en-96.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/hc-144.png b/apps/files/tests/golden/base/undo_elsewhere_notice/hc-144.png new file mode 100644 index 00000000..7cc3eded Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/hc-144.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/hc-96.png b/apps/files/tests/golden/base/undo_elsewhere_notice/hc-96.png new file mode 100644 index 00000000..8c1d79f8 Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/hc-96.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/it-120.png b/apps/files/tests/golden/base/undo_elsewhere_notice/it-120.png new file mode 100644 index 00000000..60f325ab Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/it-120.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/it-144.png b/apps/files/tests/golden/base/undo_elsewhere_notice/it-144.png new file mode 100644 index 00000000..f637b16b Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/it-144.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/it-192.png b/apps/files/tests/golden/base/undo_elsewhere_notice/it-192.png new file mode 100644 index 00000000..673049a6 Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/it-192.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/it-96.png b/apps/files/tests/golden/base/undo_elsewhere_notice/it-96.png new file mode 100644 index 00000000..f178aa01 Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/it-96.png differ diff --git a/apps/files/tests/golden/base/undo_elsewhere_notice/pseudo-144.png b/apps/files/tests/golden/base/undo_elsewhere_notice/pseudo-144.png new file mode 100644 index 00000000..9c6ecbe0 Binary files /dev/null and b/apps/files/tests/golden/base/undo_elsewhere_notice/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-en.txt b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-en.txt new file mode 100644 index 00000000..2469fdb8 --- /dev/null +++ b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-en.txt @@ -0,0 +1,56 @@ +TabList + Tab "documents" [focusable, selected] + Button "Close tab" + Button "New tab" [focusable] +Button "Back · Alt+←" [disabled] +Button "Forward · Alt+→" [disabled] +Button "Up to made-up · Alt+↑" [focusable] +SearchInput "Search this folder" [focusable] "" +Toolbar "Path" + Link "C:" [focusable] + Button "Subfolders" + Link "made-up" [focusable] + Button "Subfolders" + Link "documents" [focusable] + Button "Subfolders" + Button "Refresh" [focusable] +Toolbar "New" + Button "New" [focusable, expandable] + Button "Cut" [disabled] + Button "Copy" [disabled] + Button "Paste" [disabled] + Button "Rename" [disabled] + Button "Delete" [disabled] + Button "Sort" [focusable, expandable] + Button "View" [focusable, expandable] + Button "Filter" [focusable, expandable] + Button "More" [focusable, expandable, expanded] + Button "Details" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "This PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Network" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Network" [focusable] level 1 + TreeItem "Recycle Bin" [focusable] level 1 +Splitter "Resize panes" [focusable] 20.363636% +Pane "Details pane" +ColumnHeader "Name" [focusable] +ColumnHeader "Date modified" [focusable] +ColumnHeader "Type" [focusable] +ColumnHeader "Size" [focusable] +Table "Name" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB free of 1.81 TB" +Label "System (C:)" +Label "9 items" diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-it.txt b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-it.txt new file mode 100644 index 00000000..e0ee5a2a --- /dev/null +++ b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/a11y-it.txt @@ -0,0 +1,56 @@ +TabList + Tab "documents" [focusable, selected] + Button "Chiudi scheda" + Button "Nuova scheda" [focusable] +Button "Indietro · Alt+←" [disabled] +Button "Avanti · Alt+→" [disabled] +Button "Su a made-up · Alt+↑" [focusable] +SearchInput "Cerca in questa cartella" [focusable] "" +Toolbar "Percorso" + Link "C:" [focusable] + Button "Sottocartelle" + Link "made-up" [focusable] + Button "Sottocartelle" + Link "documents" [focusable] + Button "Sottocartelle" + Button "Aggiorna" [focusable] +Toolbar "Nuovo" + Button "Nuovo" [focusable, expandable] + Button "Taglia" [disabled] + Button "Copia" [disabled] + Button "Incolla" [disabled] + Button "Rinomina" [disabled] + Button "Elimina" [disabled] + Button "Ordina" [focusable, expandable] + Button "Visualizza" [focusable, expandable] + Button "Filtra" [focusable, expandable] + Button "Altro" [focusable, expandable, expanded] + Button "Dettagli" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "Questo PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Rete" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Rete" [focusable] level 1 + TreeItem "Cestino" [focusable] level 1 +Splitter "Ridimensiona i riquadri" [focusable] 20.363636% +Pane "Riquadro dei dettagli" +ColumnHeader "Nome" [focusable] +ColumnHeader "Ultima modifica" [focusable] +ColumnHeader "Tipo" [focusable] +ColumnHeader "Dimensione" [focusable] +Table "Nome" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Label "384 GB liberi di 1,81 TB" +Label "System (C:)" +Label "9 elementi" diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96-menu0.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96-menu0.png new file mode 100644 index 00000000..73fc67eb Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96-menu0.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96.png new file mode 100644 index 00000000..6b1570e6 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/en-96.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144-menu0.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144-menu0.png new file mode 100644 index 00000000..65f8f398 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144-menu0.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144.png new file mode 100644 index 00000000..6b02a633 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/hc-144.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144-menu0.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144-menu0.png new file mode 100644 index 00000000..bb713228 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144-menu0.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144.png new file mode 100644 index 00000000..11c676ae Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/it-144.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144-menu0.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144-menu0.png new file mode 100644 index 00000000..d4225617 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144-menu0.png differ diff --git a/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144.png b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144.png new file mode 100644 index 00000000..ae78e656 Binary files /dev/null and b/apps/files/tests/golden/base/undo_redo_elsewhere_more_menu/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/a11y-en.txt b/apps/files/tests/golden/base/undo_replaced_notice/a11y-en.txt new file mode 100644 index 00000000..5d182b00 --- /dev/null +++ b/apps/files/tests/golden/base/undo_replaced_notice/a11y-en.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Close tab" + Button "New tab" [focusable] +Button "Back · Alt+←" [disabled] +Button "Forward · Alt+→" [disabled] +Button "Up to made-up · Alt+↑" [focusable] +SearchInput "Search this folder" [focusable] "" +Toolbar "Path" + Link "C:" [focusable] + Button "Subfolders" + Link "made-up" [focusable] + Button "Subfolders" + Link "documents" [focusable] + Button "Subfolders" + Button "Refresh" [focusable] +Toolbar "New" + Button "New" [focusable, expandable] + Button "Cut" [disabled] + Button "Copy" [disabled] + Button "Paste" [disabled] + Button "Rename" [disabled] + Button "Delete" [disabled] + Button "Sort" [focusable, expandable] + Button "View" [focusable, expandable] + Button "Filter" [focusable, expandable] + Button "More" [focusable, expandable] + Button "Details" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "This PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Network" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Network" [focusable] level 1 + TreeItem "Recycle Bin" [focusable] level 1 +Splitter "Resize panes" [focusable] 20.363636% +Pane "Details pane" +ColumnHeader "Name" [focusable] +ColumnHeader "Date modified" [focusable] +ColumnHeader "Type" [focusable] +ColumnHeader "Size" [focusable] +Table "Name" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Button "Copied 1 item to documents" [focusable] +Label "384 GB free of 1.81 TB" +Label "System (C:)" +Label "Can't undo: 1 item replaced an older file" diff --git a/apps/files/tests/golden/base/undo_replaced_notice/a11y-it.txt b/apps/files/tests/golden/base/undo_replaced_notice/a11y-it.txt new file mode 100644 index 00000000..39bedc26 --- /dev/null +++ b/apps/files/tests/golden/base/undo_replaced_notice/a11y-it.txt @@ -0,0 +1,57 @@ +TabList + Tab "documents" [focusable, selected] + Button "Chiudi scheda" + Button "Nuova scheda" [focusable] +Button "Indietro · Alt+←" [disabled] +Button "Avanti · Alt+→" [disabled] +Button "Su a made-up · Alt+↑" [focusable] +SearchInput "Cerca in questa cartella" [focusable] "" +Toolbar "Percorso" + Link "C:" [focusable] + Button "Sottocartelle" + Link "made-up" [focusable] + Button "Sottocartelle" + Link "documents" [focusable] + Button "Sottocartelle" + Button "Aggiorna" [focusable] +Toolbar "Nuovo" + Button "Nuovo" [focusable, expandable] + Button "Taglia" [disabled] + Button "Copia" [disabled] + Button "Incolla" [disabled] + Button "Rinomina" [disabled] + Button "Elimina" [disabled] + Button "Ordina" [focusable, expandable] + Button "Visualizza" [focusable, expandable] + Button "Filtra" [focusable, expandable] + Button "Altro" [focusable, expandable] + Button "Dettagli" [focusable, checked] +Tree + TreeItem "Home" [focusable] level 1 + Label "Questo PC" + TreeItem "System (C:)" [focusable, expandable] level 1 + TreeItem "Data (D:)" [focusable, expandable] level 1 + Label "Rete" + TreeItem "Share (Z:)" [focusable, expandable] level 1 + TreeItem "Rete" [focusable] level 1 + TreeItem "Cestino" [focusable] level 1 +Splitter "Ridimensiona i riquadri" [focusable] 20.363636% +Pane "Riquadro dei dettagli" +ColumnHeader "Nome" [focusable] +ColumnHeader "Ultima modifica" [focusable] +ColumnHeader "Tipo" [focusable] +ColumnHeader "Dimensione" [focusable] +Table "Nome" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Button "Copiato 1 elemento in documents" [focusable] +Label "384 GB liberi di 1,81 TB" +Label "System (C:)" +Label "Impossibile annullare: 1 elemento ha sostituito un file meno recente" diff --git a/apps/files/tests/golden/base/undo_replaced_notice/contrast-144.png b/apps/files/tests/golden/base/undo_replaced_notice/contrast-144.png new file mode 100644 index 00000000..0e36d66f Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/contrast-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/en-120.png b/apps/files/tests/golden/base/undo_replaced_notice/en-120.png new file mode 100644 index 00000000..10cf5f2a Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/en-120.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/en-144.png b/apps/files/tests/golden/base/undo_replaced_notice/en-144.png new file mode 100644 index 00000000..0e36d66f Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/en-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/en-192.png b/apps/files/tests/golden/base/undo_replaced_notice/en-192.png new file mode 100644 index 00000000..6b7c1034 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/en-192.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/en-96.png b/apps/files/tests/golden/base/undo_replaced_notice/en-96.png new file mode 100644 index 00000000..b1553247 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/en-96.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/hc-144.png b/apps/files/tests/golden/base/undo_replaced_notice/hc-144.png new file mode 100644 index 00000000..f326a2e6 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/hc-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/hc-96.png b/apps/files/tests/golden/base/undo_replaced_notice/hc-96.png new file mode 100644 index 00000000..e44e7ca1 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/hc-96.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/it-120.png b/apps/files/tests/golden/base/undo_replaced_notice/it-120.png new file mode 100644 index 00000000..e4e424ca Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/it-120.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/it-144.png b/apps/files/tests/golden/base/undo_replaced_notice/it-144.png new file mode 100644 index 00000000..f0ab75fc Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/it-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/it-192.png b/apps/files/tests/golden/base/undo_replaced_notice/it-192.png new file mode 100644 index 00000000..269ba756 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/it-192.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/it-96.png b/apps/files/tests/golden/base/undo_replaced_notice/it-96.png new file mode 100644 index 00000000..2828c3a7 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/it-96.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice/pseudo-144.png b/apps/files/tests/golden/base/undo_replaced_notice/pseudo-144.png new file mode 100644 index 00000000..c46a0088 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice/pseudo-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-en.txt b/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-en.txt new file mode 100644 index 00000000..6dabe442 --- /dev/null +++ b/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-en.txt @@ -0,0 +1,42 @@ +TabList + Tab "documents" [focusable, selected] + Button "Close tab" + Button "New tab" [focusable] +Button "Back · Alt+←" [disabled] +Button "Forward · Alt+→" [disabled] +Button "Up to made-up · Alt+↑" [focusable] +Button "Search in documents" [focusable] +SearchInput "Search this folder" [focusable] "" +Toolbar "Path" + Link "C:" [focusable] + Button "Subfolders" + Link "made-up" [focusable] + Button "Subfolders" + Link "documents" [focusable] + Button "Subfolders" + Button "Refresh" [focusable] +Toolbar "New" + Button "New" [focusable, expandable] + Button "Cut" [disabled] + Button "Copy" [disabled] + Button "Paste" [disabled] + Button "Rename" [disabled] + Button "More" [focusable, expandable] + Button "Details" [focusable] +ColumnHeader "Name" [focusable] +ColumnHeader "Date modified" [focusable] +ColumnHeader "Type" [focusable] +ColumnHeader "Size" [focusable] +Table "Name" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Button "Copied 1 item to documents" [focusable] +Label "384 GB free of 1.81 TB" +Label "Can't undo: 1 item replaced an older file" diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-it.txt b/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-it.txt new file mode 100644 index 00000000..e7f68d53 --- /dev/null +++ b/apps/files/tests/golden/base/undo_replaced_notice_narrow/a11y-it.txt @@ -0,0 +1,40 @@ +TabList + Tab "documents" [focusable, selected] + Button "Chiudi scheda" + Button "Nuova scheda" [focusable] +Button "Indietro · Alt+←" [disabled] +Button "Avanti · Alt+→" [disabled] +Button "Su a made-up · Alt+↑" [focusable] +Button "Cerca in documents" [focusable] +SearchInput "Cerca in questa cartella" [focusable] "" +Toolbar "Percorso" + Link "C:" [focusable] + Button "Sottocartelle" + Link "made-up" [focusable] + Button "Sottocartelle" + Link "documents" [focusable] + Button "Sottocartelle" + Button "Aggiorna" [focusable] +Toolbar "Nuovo" + Button "Nuovo" [focusable, expandable] + Button "Taglia" [disabled] + Button "Copia" [disabled] + Button "Incolla" [disabled] + Button "Altro" [focusable, expandable] + Button "Dettagli" [focusable] +ColumnHeader "Nome" [focusable] +ColumnHeader "Ultima modifica" [focusable] +ColumnHeader "Tipo" [focusable] +ColumnHeader "Dimensione" [focusable] +Table "Nome" 1 of 9 + Row "invoices" [focusable] 1 of 9 + Row "link-to-projects" [focusable] 2 of 9 + Row "projects" [focusable] 3 of 9 + Row "contract-draft-for-the-apartment-on-the-long-street-07.docx" [focusable] 4 of 9 + Row "notes.txt" [focusable] 5 of 9 + Row "photos-raw.zip" [focusable] 6 of 9 + Row "report-final-v2.pdf" [focusable] 7 of 9 + Row "report-final-v3.pdf" [focusable] 8 of 9 + Row "setup-tool-1.4.2.exe" [focusable] 9 of 9 +Button "Copiato 1 elemento in documents" [focusable] +Label "Impossibile annullare: 1 elemento ha sostituito un file meno recente" diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/en-96.png b/apps/files/tests/golden/base/undo_replaced_notice_narrow/en-96.png new file mode 100644 index 00000000..351e5f2c Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice_narrow/en-96.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/hc-144.png b/apps/files/tests/golden/base/undo_replaced_notice_narrow/hc-144.png new file mode 100644 index 00000000..8672cdd4 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice_narrow/hc-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/it-144.png b/apps/files/tests/golden/base/undo_replaced_notice_narrow/it-144.png new file mode 100644 index 00000000..5656e201 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice_narrow/it-144.png differ diff --git a/apps/files/tests/golden/base/undo_replaced_notice_narrow/pseudo-144.png b/apps/files/tests/golden/base/undo_replaced_notice_narrow/pseudo-144.png new file mode 100644 index 00000000..66d53534 Binary files /dev/null and b/apps/files/tests/golden/base/undo_replaced_notice_narrow/pseudo-144.png differ diff --git a/apps/files/tests/icons_art.rs b/apps/files/tests/icons_art.rs index b54685a6..a11610a2 100644 --- a/apps/files/tests/icons_art.rs +++ b/apps/files/tests/icons_art.rs @@ -46,10 +46,12 @@ fn programs_and_other_kinds() { assert_eq!(file_art(ext.as_bytes()), Art::Program, "{ext}"); assert!(!wants_class_icon(ext.as_bytes()), "{ext}: its own icon, else the program art"); } - for ext in ["lnk", "url", "msi", "bat", "cmd", "ps1", "vbs", "ico", "cur", "ani", "bin", "dll", ""] { + for ext in ["lnk", "url", "msi", "bat", "cmd", "ps1", "vbs", "ico", "cur", "ani", "bin", "dll"] { assert_eq!(file_art(ext.as_bytes()), Art::FileGeneric, "{ext}: the generic page until Windows' icon"); assert!(wants_class_icon(ext.as_bytes()), "{ext}"); } + assert_eq!(file_art(b""), Art::FileGeneric, "no extension: the generic page"); + assert!(!wants_class_icon(b""), "no extension: never the class icon, which can be a folder's"); assert_eq!(file_art(&[0xFF, 0xFE]), Art::FileGeneric, "an extension that is not Unicode"); } diff --git a/apps/files/tests/lang_pick.rs b/apps/files/tests/lang_pick.rs new file mode 100644 index 00000000..c82a298f --- /dev/null +++ b/apps/files/tests/lang_pick.rs @@ -0,0 +1,81 @@ +//! The window's language follows the suite's: the same setting gives the same language as the task manager, and +//! every text has its Italian. + +use oled_sys::i18n::Lang; +use oled_ui::UiLang; + +/// What the task manager does at start-up for a setting: apply it to the process, then ask the kit. +fn tasks_choice(setting: Lang) -> UiLang { + oled_sys::i18n::apply(setting); + UiLang::from_lang(setting) +} + +#[test] +fn the_window_picks_the_language_the_way_the_task_manager_does() { + for first in [Lang::It, Lang::En] { + for setting in [Lang::Auto, Lang::En, Lang::It] { + // The process may carry a language set earlier (a changed config); the choice must not depend on it. + oled_sys::i18n::apply(first); + let own = files_engine::langfile::resolve_lang(setting); + let other = tasks_choice(setting); + assert_eq!(own, other, "setting {setting:?} after {first:?}"); + } + } +} + +#[test] +fn auto_follows_the_windows_language() { + // The reference the dock uses for "auto": the user's default UI language. + let windows_italian = files_engine::strings::lang() == files_engine::strings::Lang::It; + for first in [Lang::It, Lang::En] { + oled_sys::i18n::apply(first); + let l = files_engine::langfile::resolve_lang(Lang::Auto); + assert_eq!(l.italian, windows_italian, "auto after {first:?}"); + } +} + +fn keys(text: &str) -> Vec<(String, String)> { + text.lines() + .filter_map(|l| { + let (k, v) = l.split_once(" = ")?; + Some((k.trim().trim_matches('"').to_string(), v.trim().trim_matches('"').to_string())) + }) + .collect() +} + +/// Texts that read the same in both languages (a name, a unit, a symbol). +const SAME: &[&str] = &[ + "files.app.title_beta", + "files.app.beta", + "files.app.home", + "files.type.file", + "files.size.b", + "files.size.kb", + "files.size.mb", + "files.size.gb", + "files.size.tb", + "files.ops.chip", + "files.ops.eta_min", + "files.ops.eta_s", + "files.side.drive", + "files.side.home", + "files.side.known_desktop", + "files.filter.audio", + "files.filter.video", + "files.ops.chip_paste", +]; + +#[test] +fn every_text_has_its_italian() { + let en = keys(include_str!("../strings/en.toml")); + let it = keys(include_str!("../strings/it.toml")); + assert!(en.len() > 200); + for (k, v) in &en { + let Some((_, t)) = it.iter().find(|(ik, _)| ik == k) else { panic!("{k}: no Italian") }; + assert!(!t.is_empty(), "{k}: empty Italian"); + if t == v { + assert!(SAME.contains(&k.as_str()), "{k}: the Italian is the English text"); + } + } + assert_eq!(en.len(), it.len(), "keys only in the Italian file"); +} diff --git a/apps/files/tests/lints.rs b/apps/files/tests/lints.rs index f8c3a1e2..96e6352b 100644 --- a/apps/files/tests/lints.rs +++ b/apps/files/tests/lints.rs @@ -68,7 +68,7 @@ const MUTATION_ALLOWED: [&str; 5] = [ /// The files that may also open a file handle with CreateFileW: the change watcher, icons.bin's reader, the pipe, the /// hand-off's folder pin, the shell host's pinned icon sources (read only; its tests hold a writer's handle) and the ops /// host's look at an item before an operation (its real path and whether the user's rights allow the operation; the -/// handle is closed unused). +/// handle is closed unused) or after a copy or a move (which item a path names; read attributes only). const CREATE_FILE_ALLOWED: [&str; 7] = [ "src/watch/iocp.rs", "src/decor/iconsbin.rs", diff --git a/apps/files/tests/model.rs b/apps/files/tests/model.rs index ef6e7878..917609dc 100644 --- a/apps/files/tests/model.rs +++ b/apps/files/tests/model.rs @@ -345,7 +345,7 @@ fn icons_come_from_the_art_and_the_tables_own_icon_table() { assert!(t.set_icon(IconKey::Class(b"pdf".to_vec().into()), 2, px(5))); assert!(t.set_icon(IconKey::Class(b"exe".to_vec().into()), 2, px(6))); let (g, b) = (icon(&t, "readme"), icon(&t, "c.bin")); - assert_eq!(g, Some(IconRef(0)), "the class icon of no extension"); + assert_eq!(art(&t, "readme"), Some(Art::FileGeneric), "no extension: the generic page, never its class icon"); assert!(b.is_some() && b != g, "a class icon of its own, found by the lower-case extension"); assert_eq!(art(&t, "c.bin"), None); let bmp = t.icon(b.unwrap(), 16).expect("filled slot"); diff --git a/apps/files/tests/ops_undo.rs b/apps/files/tests/ops_undo.rs index 3fa705ca..02c870f5 100644 --- a/apps/files/tests/ops_undo.rs +++ b/apps/files/tests/ops_undo.rs @@ -11,14 +11,16 @@ use std::sync::{Arc, Mutex}; use common::temp::{fence, fnv1a64, TempRoot}; use files_engine::ops::binrec::{bin_record, forget_record, Forgot}; use files_engine::ops::consts::CHUNK_ITEMS; -use files_engine::ops::runner::{run, RunEnd, Work}; -use files_engine::ops::sink::attrs; +use files_engine::ops::journal::{journal_rel, parse, PathRepr, Pre, St}; +use files_engine::ops::runner::{run, JournalCtx, RunEnd, Work}; +use files_engine::ops::sink::{attrs, landing, short_form, Landing}; use files_engine::ops::undo::{check, plan, OsFs}; use files_engine::ops_client::UndoRecord; use oled_trust::frame::files::{ ChangeKind, Conflicts, OpEvt, OpId, OpKind, OpResult, Refusal, UndoEntry, UndoKind, WidePath, }; use ops_util::*; +use windows::core::HRESULT; use windows::Win32::Foundation::{CloseHandle, HANDLE}; use windows::Win32::Storage::FileSystem::{ReOpenFile, FILE_FLAGS_AND_ATTRIBUTES, FILE_GENERIC_READ, FILE_SHARE_READ}; @@ -438,3 +440,280 @@ fn disposable_undo_recycle_restores() { assert_eq!(check(&rec, &OsFs), Ok(UndoKind::OpenRecycleBin), "FS-3 g not green: the bin opens"); } } + +// ---- what Windows did with a clash ------------------------------------------------------------------------------ + +/// A runner context fenced to `root` that answers every clash "keep both", as a person does in Windows' dialog. +fn keep_both_ctx(root: &TempRoot) -> (files_engine::ops::runner::RunCtx, std::sync::mpsc::Receiver) { + let (mut c, rx) = ctx(&[root]); + c.keep_both = true; + (c, rx) +} + +#[test] +fn a_copy_kept_beside_an_older_file_replaced_nothing_and_its_undo_takes_the_copy_alone() { + let root = TempRoot::new("undo_keep_both_copy"); + let src = wp(&root.file("A/Note.txt", b"newer")); + root.file("B/Note.txt", b"older"); + let older = wp(&root.at("B/Note.txt")); + let (c, rx) = keep_both_ctx(&root); + let end = run(OpId(40), job(OpKind::Copy, vec![src.clone()], Some(wp(&root.at("B"))), Conflicts::AskSystem), &c); + let evs: Vec = rx.try_iter().collect(); + assert_eq!(end.result, OpResult::Done, "{evs:?}"); + assert_eq!(root.hash("B/Note.txt"), fnv1a64(b"older"), "the older file is kept"); + let rec = record(40, &evs); + assert_eq!(rec.replaced, 0, "keep both replaced nothing: {evs:?}"); + assert_eq!(end.replaced, 0); + let [e] = rec.entries.as_slice() else { panic!("one entry: {:?}", rec.entries) }; + assert!(e.to != older && e.to.parent() == older.parent(), "the entry names the new copy: {:?}", e.to); + assert_eq!(attrs(&e.to).map(|a| a.0), Some(5), "the copy holds the newer bytes"); + assert_eq!(check(&rec, &OsFs), Ok(UndoKind::RecycleCopies), "the copy can be undone"); + // Its undo goes for the copy alone (planned only: a recycle would reach the volume's real Recycle Bin). + let p = plan(OpId(41), &rec); + assert_eq!(p.len(), 1); + assert_eq!((p[0].kind, p[0].items.clone()), (OpKind::Recycle, vec![e.to.clone()]), "never the older file"); +} + +#[test] +fn a_move_kept_beside_an_older_file_goes_back_and_leaves_the_older_one() { + let root = TempRoot::new("undo_keep_both_move"); + let src = wp(&root.file("A/Note.txt", b"newer")); + root.file("B/Note.txt", b"older"); + let (c, rx) = keep_both_ctx(&root); + let end = run(OpId(42), job(OpKind::Move, vec![src.clone()], Some(wp(&root.at("B"))), Conflicts::AskSystem), &c); + let evs: Vec = rx.try_iter().collect(); + assert_eq!(end.result, OpResult::Done, "{evs:?}"); + assert!(!root.at("A/Note.txt").exists(), "moved"); + let rec = record(42, &evs); + assert_eq!(rec.replaced, 0, "{evs:?}"); + assert_eq!(check(&rec, &OsFs), Ok(UndoKind::MoveBack)); + let (end, evs) = run_plan(43, plan(OpId(43), &rec), &[&root]); + assert_eq!(end.result, OpResult::Done, "{evs:?}"); + assert_eq!(root.hash("A/Note.txt"), fnv1a64(b"newer"), "the moved file is back"); + assert_eq!(root.hash("B/Note.txt"), fnv1a64(b"older"), "the older file stays where it was"); + assert_eq!(root.hash_tree("B").len(), 1, "nothing else is left in B: {:?}", root.hash_tree("B")); +} + +#[test] +fn a_paste_that_replaced_an_older_file_still_refuses_its_undo() { + let root = TempRoot::new("undo_replaced_for_real"); + let src = wp(&root.file("A/Note.txt", b"newer")); + root.file("B/Note.txt", b"older"); + root.file("A/Fresh.txt", b"fresh"); + let items = vec![src, wp(&root.at("A/Fresh.txt"))]; + let (end, evs) = run_in(44, job(OpKind::Copy, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &[&root]); + assert_eq!(end.result, OpResult::Done, "{evs:?}"); + assert_eq!(root.hash("B/Note.txt"), fnv1a64(b"newer"), "replaced"); + let rec = record(44, &evs); + assert_eq!(rec.replaced, 1, "one file replaced an older one, the other was new"); + assert_eq!(check(&rec, &OsFs), Err((Refusal::Replaced, "1".into()))); +} + +/// A folder copied or moved onto a folder of its name merges into it: the older items that folder held are not the +/// paste's, so the paste counts as replacing and its undo is refused (it never recycles or moves back the merged +/// folder). +#[test] +fn a_folder_merged_into_one_of_its_name_counts_as_replaced_and_refuses_its_undo() { + for (op, kind) in [(50, OpKind::Copy), (52, OpKind::Move)] { + let root = TempRoot::new(&format!("undo_merge_{op}")); + root.file("A/X/same.txt", b"newer"); + root.file("A/X/new.txt", b"new"); + root.file("B/X/same.txt", b"older"); + root.file("B/X/old.txt", b"kept"); + let items = vec![wp(&root.at("A/X"))]; + let (end, evs) = run_in(op, job(kind, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &[&root]); + assert_eq!(end.result, OpResult::Done, "{kind:?}: {evs:?}"); + assert_eq!(root.hash("B/X/old.txt"), fnv1a64(b"kept"), "{kind:?}: merged, the older item stays"); + assert_eq!(root.hash("B/X/same.txt"), fnv1a64(b"newer"), "{kind:?}: the clash inside was replaced"); + // A move reports the folder "not handled" (its items go into the folder there one by one): the merge is done + // all the same, and the UI keeps an undo record only with its entries, so Ctrl+Z says why it cannot undo. + assert!(!undo_entries(&evs).is_empty(), "{kind:?}: the record reaches the UI: {evs:?}"); + let rec = record(op, &evs); + assert_eq!((rec.replaced, end.replaced, end.items), (1, 1, 1), "{kind:?}: the merge counts: {evs:?}"); + assert_eq!(check(&rec, &OsFs), Err((Refusal::Replaced, "1".into())), "{kind:?}"); + } +} + +/// A paste of a folder that merges into one of its name and of a new file beside it: the merge may have replaced what +/// the older folder held, so the whole paste counts as replacing and its undo is refused, though the new file alone +/// could go back. A move reports the folder "not handled" and moves what it holds one by one: the merge is done all the +/// same, and the journal says so. +#[test] +fn a_paste_with_a_merged_folder_and_a_new_file_refuses_its_undo() { + for (op, kind) in [(54, OpKind::Copy), (56, OpKind::Move)] { + let root = TempRoot::new(&format!("undo_merge_mixed_{op}")); + root.file("A/X/img1.jpg", b"newer"); + root.file("A/y.txt", b"y"); + root.file("B/X/img1.jpg", b"older"); + let items = vec![wp(&root.at("A/X")), wp(&root.at("A/y.txt"))]; + let data = files_engine::own_files::OwnDir::open(&root.dir("data")).unwrap(); + let (mut c, rx) = ctx(&[&root]); + c.journal = Some(JournalCtx { dir: data.clone(), pid: 4_242, created: 1 }); + let end = run(OpId(op), job(kind, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &c); + let evs: Vec = rx.try_iter().collect(); + assert_eq!(end.result, OpResult::Done, "{kind:?}: {evs:?}"); + assert_eq!(root.hash("B/X/img1.jpg"), fnv1a64(b"newer"), "{kind:?}: the older file inside was replaced"); + assert_eq!(root.hash("B/y.txt"), fnv1a64(b"y"), "{kind:?}"); + let rec = record(op, &evs); + assert!(rec.replaced >= 1 && end.replaced == rec.replaced, "{kind:?}: the merge counts: {evs:?}"); + assert_eq!(check(&rec, &OsFs), Err((Refusal::Replaced, rec.replaced.to_string().into())), "{kind:?}"); + // The journal says what happened: the folder is done, at the folder of its name there. + let j = parse(&data.read(&journal_rel(OpId(op), 4_242)).unwrap()).unwrap(); + let folder = j.latest().into_iter().find(|r| r.i == 0).cloned().expect("the folder's record"); + assert_eq!((folder.st, folder.dst), (St::Done, Some(PathRepr::of(&wp(&root.at("B/X"))))), "{kind:?}"); + } +} + +/// `rel` held open as another program holds a file it works on: the handle shares only reading, so nothing may write, +/// replace or delete the file until the guard is dropped. +struct Held { + _opened: std::fs::File, + handle: HANDLE, +} + +fn hold(root: &TempRoot, rel: &str) -> Held { + let opened = std::fs::File::open(root.at(rel)).unwrap(); + // SAFETY: the live handle just opened; the new one is closed by Drop. + let handle = unsafe { + ReOpenFile(HANDLE(opened.as_raw_handle()), FILE_GENERIC_READ.0, FILE_SHARE_READ, FILE_FLAGS_AND_ATTRIBUTES(0)) + } + .unwrap(); + Held { _opened: opened, handle } +} + +impl Drop for Held { + fn drop(&mut self) { + // SAFETY: the handle ReOpenFile returned, closed once. + let _ = unsafe { CloseHandle(self.handle) }; + } +} + +/// A merge that stops inside (a file there is held open by another program, so the operation ends there) may already +/// have replaced older files: the paste still refuses its undo, though the new file beside it could go back. +#[test] +fn a_merge_stopped_inside_still_refuses_its_undo() { + for (op, kind) in [(58, OpKind::Copy), (60, OpKind::Move)] { + let root = TempRoot::new(&format!("undo_merge_stopped_{op}")); + root.file("A/X/a.txt", b"newer a"); + root.file("A/X/b.txt", b"newer b"); + root.file("A/y.txt", b"y"); + root.file("B/X/a.txt", b"older a"); + root.file("B/X/b.txt", b"older b"); + let held = hold(&root, "B/X/b.txt"); + let items = vec![wp(&root.at("A/y.txt")), wp(&root.at("A/X"))]; + let (end, evs) = run_in(op, job(kind, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &[&root]); + drop(held); + assert_eq!(root.hash("B/X/a.txt"), fnv1a64(b"newer a"), "{kind:?}: an older file was replaced: {evs:?}"); + assert_eq!(root.hash("B/X/b.txt"), fnv1a64(b"older b"), "{kind:?}: the one held open was not"); + assert_eq!(root.hash("B/y.txt"), fnv1a64(b"y"), "{kind:?}"); + let rec = record(op, &evs); + assert!(rec.replaced >= 1 && end.replaced == rec.replaced, "{kind:?}: {end:?} {evs:?}"); + assert_eq!(check(&rec, &OsFs), Err((Refusal::Replaced, rec.replaced.to_string().into())), "{kind:?}"); + } +} + +/// A clash whose older file is held open by another program fails and leaves that file as it was: nothing was +/// replaced, so the new file pasted beside it can still be undone. +#[test] +fn a_clash_that_failed_and_left_the_older_file_as_it_was_replaced_nothing() { + for (op, kind) in [(62, OpKind::Copy), (64, OpKind::Move)] { + let root = TempRoot::new(&format!("undo_clash_held_{op}")); + root.file("A/new.txt", b"new"); + root.file("A/Note.txt", b"newer"); + root.file("B/Note.txt", b"older"); + let held = hold(&root, "B/Note.txt"); + let items = vec![wp(&root.at("A/new.txt")), wp(&root.at("A/Note.txt"))]; + let (end, evs) = run_in(op, job(kind, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &[&root]); + drop(held); + assert_eq!(root.hash("B/Note.txt"), fnv1a64(b"older"), "{kind:?}: the older file is as it was: {evs:?}"); + assert_eq!(root.hash("B/new.txt"), fnv1a64(b"new"), "{kind:?}"); + assert!(end.failed >= 1, "{kind:?}: the clash failed: {end:?} {evs:?}"); + let rec = record(op, &evs); + assert_eq!((rec.replaced, end.replaced), (0, 0), "{kind:?}: {evs:?}"); + assert!(check(&rec, &OsFs).is_ok(), "{kind:?}: the new file can be undone"); + } +} + +/// A paste cancelled after its first item: the sink refuses the next item's Pre, so the engine never reaches the +/// folder of the same name there (the cancel test of the runner measured it), and nothing was replaced. +#[test] +fn a_paste_cancelled_before_a_clash_replaced_nothing() { + use std::sync::atomic::Ordering; + for (op, kind) in [(66, OpKind::Copy), (68, OpKind::Move)] { + let root = TempRoot::new(&format!("undo_cancel_clash_{op}")); + root.file("A/y.txt", b"y"); + root.file("A/X/img1.jpg", b"newer"); + root.file("B/X/img1.jpg", b"older"); + let items = vec![wp(&root.at("A/y.txt")), wp(&root.at("A/X"))]; + let (mut c, rx) = ctx(&[&root]); + let cancel = c.cancel.clone(); + c.hook_post = Some(Arc::new(move |_, i| { + if i == 0 { + cancel.store(true, Ordering::Release); + } + })); + let end = run(OpId(op), job(kind, items, Some(wp(&root.at("B"))), Conflicts::ReplaceAll), &c); + let evs: Vec = rx.try_iter().collect(); + assert_eq!(end.result, OpResult::Cancelled, "{kind:?}: {evs:?}"); + assert_eq!(root.hash("B/X/img1.jpg"), fnv1a64(b"older"), "{kind:?}: the folder there is untouched"); + let rec = record(op, &evs); + assert_eq!((rec.replaced, end.replaced, end.items), (0, 0, 1), "{kind:?}: {evs:?}"); + assert!(check(&rec, &OsFs).is_ok(), "{kind:?}"); + } +} + +/// What Windows reports as the item it made may name it in another form than the destination the pre-flight expected +/// (its 8.3 path beyond MAX_PATH, its path through a junction): the same item took the destination's place, so it +/// counts as replaced. "Kept beside it" needs evidence: the engine's code, or a different item still at the +/// destination. +#[test] +fn a_landing_is_kept_beside_only_on_evidence() { + let root = TempRoot::new("undo_landing_forms"); + let ok = HRESULT(0); + let dst = wp(&root.file("B/Older notes of the week.txt", b"older")); + let folder = wp(&root.dir("B/Folder with a long name")); + root.junction("J", &root.at("B")); + let through = wp(&root.at("J/Older notes of the week.txt")); + assert_eq!(landing(Pre::File, Some(&dst), &through, ok), Landing::Replaced, "the same file through a junction"); + let merged = wp(&root.at("J/Folder with a long name")); + assert_eq!(landing(Pre::Dir, Some(&folder), &merged, ok), Landing::Replaced, "the same folder through a junction"); + match (short_form(&dst), short_form(&folder)) { + (Some(file), Some(dir)) => { + assert_eq!(landing(Pre::File, Some(&dst), &file, ok), Landing::Replaced, "its 8.3 form: {file:?}"); + assert_eq!(landing(Pre::Dir, Some(&folder), &dir, ok), Landing::Replaced, "a merge, 8.3: {dir:?}"); + } + _ => eprintln!("this volume keeps no 8.3 names: the short forms are not tried"), + } + // Kept beside it: a different item, the older one still in its place. + let kept = wp(&root.file("B/Older notes of the week (2).txt", b"newer")); + assert_eq!(landing(Pre::File, Some(&dst), &kept, ok), Landing::KeptBoth); + // Nothing on disk to tell them apart: replaced (the undo refuses rather than take what the paste did not make). + let gone = wp(&root.at("B/never made.txt")); + assert_eq!(landing(Pre::File, Some(&dst), &gone, ok), Landing::Replaced, "the reported item is not there"); + assert_eq!(landing(Pre::File, Some(&gone), &kept, ok), Landing::Replaced, "the destination is not there"); + assert_eq!(landing(Pre::Dir, None, &kept, ok), Landing::Replaced, "no destination known"); + // The engine's own codes are evidence enough. + assert_eq!(landing(Pre::File, Some(&dst), &gone, HRESULT(0x0027_000C)), Landing::KeptBoth, "KEEP_BOTH"); + assert_eq!(landing(Pre::File, Some(&dst), &gone, HRESULT(0x0027_000E)), Landing::KeptBoth, "COLLISIONRESOLVED"); + assert_eq!(landing(Pre::Absent, Some(&dst), &dst, ok), Landing::New, "nothing was there"); +} + +#[test] +#[ignore = "disposable: CI files-disposable job only"] +fn disposable_undo_keep_both_copy_recycles_the_copy_alone() { + common::disposable(); + let root = TempRoot::new("undo_disp_keep_both"); + let src = wp(&root.file("A/Note.txt", b"newer")); + root.file("B/Note.txt", b"older"); + let (c, rx) = keep_both_ctx(&root); + run(OpId(45), job(OpKind::Copy, vec![src], Some(wp(&root.at("B"))), Conflicts::AskSystem), &c); + let evs: Vec = rx.try_iter().collect(); + let rec = record(45, &evs); + assert_eq!(check(&rec, &OsFs), Ok(UndoKind::RecycleCopies), "{evs:?}"); + let (end, evs) = run_plan(46, plan(OpId(46), &rec), &[&root]); + assert_eq!(end.result, OpResult::Done, "{evs:?}"); + assert_eq!(changed(&evs, ChangeKind::Recycled), 1, "the kept copy went to the bin: {evs:?}"); + assert_eq!(root.hash_tree("B").len(), 1, "only the older file is left: {:?}", root.hash_tree("B")); + assert_eq!(root.hash("B/Note.txt"), fnv1a64(b"older")); + assert_eq!(root.hash("A/Note.txt"), fnv1a64(b"newer"), "the source is untouched"); +} diff --git a/apps/files/tests/paste.rs b/apps/files/tests/paste.rs index 9b28a451..fec348c7 100644 --- a/apps/files/tests/paste.rs +++ b/apps/files/tests/paste.rs @@ -421,3 +421,65 @@ fn the_switch_off_keeps_the_clipboard_and_the_files_as_they_are() { assert!(!it.enabled && it.tip == "Not available in this alpha: use File Explorer", "{cmd:?}"); } } + +/// The ids of a menu's rows, separators left out. +fn menu_ids(items: &[oled_ui::MenuItem]) -> Vec { + items + .iter() + .filter_map(|i| match i { + oled_ui::MenuItem::Command(id) | oled_ui::MenuItem::Custom { id, .. } => Some(id.0), + _ => None, + }) + .collect() +} + +/// Whether the row of that id is enabled, and the note it carries. +fn menu_state(items: &[oled_ui::MenuItem], id: u32) -> Option<(bool, Option)> { + items.iter().find_map(|i| match i { + oled_ui::MenuItem::Custom { id: x, enabled, note, .. } if x.0 == id => { + Some((*enabled, note.as_ref().map(|n| n.to_string()))) + } + _ => None, + }) +} + +#[test] +fn the_row_menu_starts_with_cut_copy_and_paste_as_the_bar_allows_them() { + let mut w = win(); + let (cut, copy, paste) = (Cmd::Cut as u32, Cmd::Copy as u32, Cmd::Paste as u32); + // A file, the clipboard empty: Cut and Copy on, Paste off with the bar's reason. + w.select(1, 1); + w.key("Apps"); + let items = w.h.menus()[0].items.clone(); + assert_eq!(menu_ids(&items)[..3], [cut, copy, paste], "{items:?}"); + assert!(matches!(items.get(3), Some(oled_ui::MenuItem::Separator)), "a separator under them: {items:?}"); + assert_eq!(menu_state(&items, cut), Some((true, None))); + assert_eq!(menu_state(&items, copy), Some((true, None))); + let (on, tip) = w.paste_state(); + assert!(!on); + assert_eq!(menu_state(&items, paste), Some((false, Some(tip))), "Paste says why, as the bar does"); + // Copy from the menu puts the file on the clipboard, as Ctrl+C does. + w.key("Down").key("Down").key("Enter"); + assert!(w.h.menus().is_empty(), "the pick closes the menu"); + let notes = w.path("notes.txt"); + assert_eq!(w.h.clipboard().paths, [notes]); + assert_eq!(w.h.clipboard().effect, DropEffect::Copy); + // Files on the clipboard: Paste is on; on a file row it pastes into the open folder. + let a = w.root.file("src/a.txt", b"x"); + w.place(std::slice::from_ref(&a), DropEffect::Copy); + w.select(1, 1); + w.key("Apps"); + let items = w.h.menus()[0].items.clone(); + assert_eq!(menu_state(&items, paste).map(|s| s.0), Some(true), "{items:?}"); + w.key("Down").key("Down").key("Down").key("Enter"); + let src = wp(&a.to_string_lossy()); + assert_eq!(w.f.ops.calls().last(), Some(&OpsCall::Copy(refs(std::slice::from_ref(&src)), w.dir()))); + // On a folder row, Paste goes into that folder, as File Explorer's does. + w.select(0, 0); + w.key("Apps"); + let items = w.h.menus()[0].items.clone(); + let into = menu_ids(&items)[2]; + assert_eq!(menu_state(&items, into).map(|s| s.0), Some(true), "{items:?}"); + w.key("Down").key("Down").key("Down").key("Enter"); + assert_eq!(w.f.ops.calls().last(), Some(&OpsCall::Copy(refs(&[src]), w.item("invoices")))); +} diff --git a/apps/files/tests/repaint.rs b/apps/files/tests/repaint.rs new file mode 100644 index 00000000..290bc10e --- /dev/null +++ b/apps/files/tests/repaint.rs @@ -0,0 +1,960 @@ +//! The window always shows the current state. A window repaints only what was damaged, over the pixels it showed +//! before; after real sequences of inputs and new data (the drives found after the first frame, a listing, Home from +//! the sidebar, Back, a search, a refresh with fewer items) the pixels it presents must equal a fresh paint of the same +//! state. Plain tests over the fakes through the kit's Harness: no window, no file system. + +use std::rc::Rc; + +use files_engine::drives::{DriveInfo, DriveKind}; +use files_engine::fakes::{self, Fakes, FT_2026_11_21}; +use files_engine::format::Fmt; +use files_engine::home; +use files_engine::listing::{NameFamily, WidePath}; +use files_engine::msg::{Fwd, JobDone, Msg}; +use files_engine::ops_client::UndoRecord; +use files_engine::sidebar; +use files_engine::tab::TABLE_ID; +use files_engine::toolmenus::filter_pick; +use files_engine::undo::{self, UndoEntry}; +use files_engine::watch::{ChangeAction, RawChange, WatchEvent}; +use files_engine::window::{FilesScreen, Shared, WinKind, WinRec}; +use oled_trust::frame::files::{Location, OpId, OpKind, UndoEntry as Entry, UndoKind}; +use oled_ui::harness::Harness; +use oled_ui::host::AppMsg; +use oled_ui::model::ListModel; +use oled_ui::{ + CaptionHit, CommandId, CommandTable, Event, EventCx, Lang, LayoutCx, PaintCx, PointL, PointP, RectP, Reply, Screen, + SizeL, SizeP, Tokens, UiLang, WidgetId, +}; + +const GB: u64 = 1 << 30; +const ROOT: &str = r"C:\made-up\reports"; + +fn wp(s: &str) -> WidePath { + WidePath::parse(s).unwrap() +} + +fn day(n: i64) -> i64 { + FT_2026_11_21 - n * 864_000_000_000 +} + +fn drives() -> Vec { + let d = |letter, label: &str, free, total| DriveInfo { + letter, + label: Some(label.to_string()), + kind: DriveKind::Fixed, + free: Some(free * GB), + total: Some(total * GB), + ready: true, + }; + vec![d(b'C', "System", 412, 1000), d(b'D', "Data", 50, 1000)] +} + +fn reports() -> Vec<(&'static str, bool, u64, i64)> { + vec![ + ("invoices", true, 0, day(3)), + ("projects", true, 0, day(9)), + ("notes.txt", false, 1_200, day(1)), + ("report-final-v2.pdf", false, 3_400_000, day(5)), + ("photos-raw.zip", false, 90_000_000, day(40)), + ] +} + +/// A window at `at`, its queued jobs delivered, presented once as a window's first paint. +fn window(f: &Fakes, at: Location) -> Harness { + window_at(f, at, 96) +} + +/// window() at `dpi`. +fn window_at(f: &Fakes, at: Location, dpi: u32) -> Harness { + window_sized(f, at, dpi, SizeL { w: 1000, h: 640 }) +} + +/// window() at `dpi` and `size` (logical px). +fn window_sized(f: &Fakes, at: Location, dpi: u32, size: SizeL) -> Harness { + let shared = f.shared(UiLang::EN); + *shared.fmt.borrow_mut() = Rc::new(Fmt::fixed_en()); + let tab = shared.new_tab(); + let s = FilesScreen::new(shared, 1, at, None, tab); + let mut h = Harness::new(s, size, dpi, Tokens::oled()); + h.present(); + pump(f, &mut h); + h +} + +/// Delivers what the fakes hold for the window until nothing is left. +fn pump(f: &Fakes, h: &mut Harness) { + for _ in 0..8 { + if f.pump(h, 1) == 0 { + break; + } + } +} + +#[track_caller] +fn clean(h: &mut Harness, what: &str) { + assert_eq!(h.stale(), None, "{what}: the window shows old pixels there"); +} + +fn centre(r: RectP) -> PointL { + PointL { x: (r.l + r.r) / 2, y: (r.t + r.b) / 2 } +} + +fn here(h: &Harness) -> Location { + h.screen().tabs().active().nav.location().clone() +} + +#[test] +fn the_drives_found_after_the_first_frame_reach_home() { + let f = Fakes::new(); + let mut h = window(&f, Location::Home); + clean(&mut h, "Home before the drives"); + f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(drives()) }); + pump(&f, &mut h); + clean(&mut h, "the drives arrived"); +} + +#[test] +fn a_listing_home_back_and_a_refresh_repaint_the_window() { + let f = Fakes::new(); + f.enumr.queue(&wp(ROOT), fakes::listing(&reports())); + let mut h = window(&f, Location::Fs(wp(ROOT))); + f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(drives()) }); + pump(&f, &mut h); + clean(&mut h, "the first listing"); + h.key("Down").key("Down"); + clean(&mut h, "rows selected by keys"); + let rows = sidebar::of(h.screen()).rows().to_vec(); + let home = sidebar::current_key(&rows, &Location::Home).expect("Home in the sidebar"); + let r = sidebar::of(h.screen()).entry_rect(home).expect("shown"); + h.click(centre(r)); + pump(&f, &mut h); + assert_eq!(here(&h), Location::Home); + clean(&mut h, "Home from the sidebar"); + f.enumr.queue(&wp(ROOT), fakes::listing(&reports())); + h.key("Alt+Left"); + pump(&f, &mut h); + assert_eq!(here(&h), Location::Fs(wp(ROOT))); + clean(&mut h, "Back to the folder"); + // A delete as the folder's watch reports it: the row goes and the status line counts one item fewer. + let (id, _, gen) = f.watch.watches().into_iter().last().expect("the folder is watched"); + let gone = RawChange { action: ChangeAction::Removed, name: b"notes.txt".to_vec().into_boxed_slice() }; + f.watch.emit(WatchEvent::Changes { id, gen, items: vec![gone] }); + pump(&f, &mut h); + h.advance(300); + pump(&f, &mut h); + assert_eq!(ListModel::len(h.screen().tabs().active().table.model()), 4, "the deleted item left the list"); + clean(&mut h, "an item deleted"); + let fewer: Vec<_> = reports().into_iter().filter(|r| r.0 != "notes.txt" && r.0 != "photos-raw.zip").collect(); + f.enumr.queue(&wp(ROOT), fakes::listing(&fewer)); + h.key("F5"); + pump(&f, &mut h); + clean(&mut h, "a refresh with one item fewer"); +} + +#[test] +fn a_search_and_its_end_repaint_the_window() { + let f = Fakes::new(); + f.enumr.queue(&wp(ROOT), fakes::listing(&reports())); + let mut h = window(&f, Location::Fs(wp(ROOT))); + h.key("Ctrl+F"); + clean(&mut h, "Ctrl+F"); + h.type_text("no"); + h.advance(130); + clean(&mut h, "a query narrows the list"); + h.type_text("zzqx"); + h.advance(130); + clean(&mut h, "a query that finds nothing"); + h.key("Esc"); + h.advance(130); + clean(&mut h, "Esc clears it"); +} + +/// The notes.txt of the folder removed, as its watch reports it. +fn remove_notes(f: &Fakes, h: &mut Harness) { + let (id, _, gen) = f.watch.watches().into_iter().last().expect("the folder is watched"); + let gone = RawChange { action: ChangeAction::Removed, name: b"notes.txt".to_vec().into_boxed_slice() }; + f.watch.emit(WatchEvent::Changes { id, gen, items: vec![gone] }); + pump(f, h); + h.advance(300); + pump(f, h); +} + +#[test] +fn the_selection_follows_the_window_in_and_out_of_focus() { + for dpi in [96, 120] { + let f = Fakes::new(); + f.enumr.queue(&wp(ROOT), fakes::listing(&reports())); + let mut h = window_at(&f, Location::Fs(wp(ROOT)), dpi); + f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(drives()) }); + pump(&f, &mut h); + h.key("Down").key("Shift+Down").key("Shift+Down"); + clean(&mut h, &format!("{dpi} dpi: three rows selected")); + h.set_active(false); + clean(&mut h, &format!("{dpi} dpi: the window inactive (the selection and the sidebar's entry in grey)")); + h.set_active(true); + clean(&mut h, &format!("{dpi} dpi: active again")); + // Away to another window, a file of the folder goes, then back. + h.set_active(false); + remove_notes(&f, &mut h); + assert_eq!(ListModel::len(h.screen().tabs().active().table.model()), 4, "the removed item left the list"); + clean(&mut h, &format!("{dpi} dpi: an item removed while the window is inactive")); + h.set_active(true); + clean(&mut h, &format!("{dpi} dpi: back to the window")); + } +} + +/// Home at `dpi` and `size` with its drives. +fn home_with_drives(f: &Fakes, dpi: u32, size: SizeL) -> Harness { + let mut h = window_sized(f, Location::Home, dpi, size); + f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(drives()) }); + pump(f, &mut h); + h +} + +/// The focus is on an item of the Home page (its widget). +fn on_home(h: &Harness) -> bool { + h.focused().is_some_and(|n| n.owner() == WidgetId(70)) +} + +/// From a Home item, the arrows walk its section and back: every item's ring is drawn whole. +fn walk_home(h: &mut Harness, what: &str) { + let n = home::of(h.screen()).items().len(); + for key in ["Right", "Down", "End", "Left", "Up", "Home"] { + for k in 1..=n { + let before = h.focused(); + h.key(key); + let at = h.focused(); + clean(h, &format!("{what}: {key} {k} on {at:?}")); + if at == before { + break; + } + } + } +} + +#[test] +fn every_focus_ring_is_drawn_whole_by_the_keyboard() { + for dpi in [96, 120, 144] { + let f = Fakes::new(); + let mut h = home_with_drives(&f, dpi, SizeL { w: 1000, h: 640 }); + clean(&mut h, &format!("{dpi} dpi: Home with its drives")); + let mut walked = 0; + for n in 1..=4 { + h.key("Tab"); + let at = h.focused(); + clean(&mut h, &format!("{dpi} dpi: Tab {n} on {at:?}")); + if on_home(&h) { + walk_home(&mut h, &format!("{dpi} dpi: Tab {n}")); + walked += 1; + } + } + // The sidebar's entries one by one (the arrows move the focus; Enter would go there). + let mut moved = 0; + for n in 1..=12 { + let before = h.focused(); + h.key("Down"); + moved += usize::from(h.focused() != before); + let at = h.focused(); + clean(&mut h, &format!("{dpi} dpi: Down {n} on {at:?}")); + } + assert!(moved > 3, "{dpi} dpi: the arrows move the focus through the sidebar"); + for n in 5..=24 { + h.key("Tab"); + let at = h.focused(); + clean(&mut h, &format!("{dpi} dpi: Tab {n} on {at:?}")); + if on_home(&h) { + walk_home(&mut h, &format!("{dpi} dpi: Tab {n}")); + walked += 1; + } + } + assert!(walked > 0, "{dpi} dpi: Tab reaches the Home page's items"); + for n in 1..=24 { + h.key("Shift+Tab"); + let at = h.focused(); + clean(&mut h, &format!("{dpi} dpi: Shift+Tab {n} on {at:?}")); + } + } +} + +/// Home's rings at 144 dpi where a band edge or the window's width falls next to them, also as the window goes out +/// of focus and back. +#[test] +fn the_rings_of_home_stay_whole_at_144_dpi() { + let f = Fakes::new(); + let mut h = home_with_drives(&f, 144, SizeL { w: 1040, h: 640 }); + clean(&mut h, "1040x640: Home with its drives"); + for n in 1..=8 { + h.key("Tab"); + let at = h.focused(); + clean(&mut h, &format!("1040x640: Tab {n} on {at:?}")); + } + let f = Fakes::new(); + let mut h = home_with_drives(&f, 144, SizeL { w: 1100, h: 640 }); + clean(&mut h, "1100x640: Home with its drives"); + for n in 1..=6 { + h.key("Tab"); + let at = h.focused(); + clean(&mut h, &format!("1100x640: Tab {n} on {at:?}")); + h.set_active(false); + clean(&mut h, &format!("1100x640: Tab {n} on {at:?}, the window inactive")); + h.set_active(true); + clean(&mut h, &format!("1100x640: Tab {n} on {at:?}, active again")); + } +} + +/// A new tab at Home, the focus on the last stop, then the wheel over the page. +#[test] +fn a_new_tab_and_the_wheel_over_home_repaint_the_window() { + let f = Fakes::new(); + let mut h = home_with_drives(&f, 120, SizeL { w: 1000, h: 640 }); + h.key("Ctrl+T"); + pump(&f, &mut h); + clean(&mut h, "Ctrl+T"); + h.key("Shift+Tab"); + let at = h.focused(); + clean(&mut h, &format!("Shift+Tab on {at:?}")); + let body = h.screen().rects().body; + let at = PointL { x: centre(body).x * 96 / 120, y: centre(body).y * 96 / 120 }; + for notches in [-3.0, -3.0, 3.0, -1.0] { + h.wheel(at, notches); + clean(&mut h, &format!("{notches} notches over Home")); + for n in 0..10 { + h.advance(16); + clean(&mut h, &format!("{notches} notches over Home, frame {n}")); + } + } +} + +// The general property, by random sequences: after any sequence of keys, typing, clicks, hovers, wheel turns, time, +// files removed in the folder shown, drives coming and going, activation flips, families of the Filter menu, typed +// addresses, changes waiting to be undone or done again in another folder and a change of language, the window +// presented after each step equals a fresh paint of the same state. Fake data only (Fakes for every service), and only +// inputs that open, move, select, narrow or tell: no Space, Delete, rename, clipboard or right click, no click in the +// command bar (hovers only) or on a notice's button, no pointer step on the caption (Part::Tabs), Enter only in the address field after a shell: name (a known folder or one +// with no folder), a Filter family as its pick reaches the window (no menu is picked from), Ctrl+Z and Ctrl+Y only +// while what they name is in another folder (they answer with a notice), and an open menu is closed with Esc before +// anything else. The sequences come from fixed seeds; a failure prints the seed and the shortest failing sequence. + +/// SplitMix64: a small generator whose output depends on the seed only. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: i32) -> i32 { + (self.next() % n.max(1) as u64) as i32 + } + + fn pick(&mut self, v: &[T]) -> T { + v[self.below(v.len() as i32) as usize] + } +} + +/// Where a pointer step lands: a part of the window's layout, at a fraction (per mille) of its width and height. +#[derive(Clone, Copy, Debug)] +enum Part { + Side, + Body, + Status, + Address, + /// The tab strip's row; a point the window gives to its caption (the drag area and the caption buttons) is left + /// out: the real window handles it in its frame, the screen never sees it. + Tabs, + /// The command bar, for hovers only: a click there runs a file command, the clipboard or a menu. + CommandBar, +} + +/// One step of a sequence. +#[derive(Clone, Copy, Debug)] +enum Step { + Key(&'static str), + Char(char), + Click(Part, i32, i32), + Hover(Part, i32, i32), + Wheel(Part, i32, i32, i8), + Wait(u32), + /// The n-th name still listed in the watched folder shown goes, as its watch reports it. + Remove(u32), + /// A new list of drives (more free space, one drive more or fewer, by the number). + Drives(u8), + Active(bool), + /// A family of the Filter menu turned on or off, or Show all (by the number), as its pick reaches the window. + Filter(u8), + /// Ctrl+L, an address typed (a known folder, or a known name with no folder, by the number), Enter. + Go(u8), + /// A change made in another folder waits on the undo stack (even) or the redo stack (odd), as an operation's + /// record leaves it; the window is told as after any operation. + Elsewhere(u8), + /// The suite's language changes while the window is open: Italian (true) or English. + Lang(bool), +} + +/// The keys that move, select, search, open tabs and go back or up; none of them changes a file. +const KEYS: &str = "Tab Tab Shift+Tab Up Down Down Left Right Home End PgUp PgDn Esc Esc Backspace Ctrl+F Ctrl+T \ + Ctrl+Tab Ctrl+Shift+Tab Ctrl+A Alt+Left Alt+Right Alt+Up F5 F6 Ctrl+L Shift+Down Shift+Up Ctrl+Z Ctrl+Y"; + +/// What Step::Go types: two known folders of the session (the 200 files, the small folder) and a known name the +/// session has no folder for. +const ADDRESSES: [&str; 3] = ["shell:Documents", "shell:Downloads", "shell:Music"]; + +/// The folder of the changes Step::Elsewhere leaves: never listed, never shown. +const ELSEWHERE: &str = r"C:\made-up\elsewhere"; + +/// Characters typed: a type-ahead in a list, a query in the search field, a path in the address field. +const CHARS: &[char] = &['r', 'e', 'p', 'o', 'n', 'z', 'q', 'a', '1', '.', '-']; + +fn part(r: &mut Rng) -> Part { + r.pick(&[Part::Side, Part::Body, Part::Body, Part::Body, Part::Status, Part::Address, Part::Tabs]) +} + +/// part() and the command bar: where a hover lands. +fn hover_part(r: &mut Rng) -> Part { + r.pick(&[Part::Side, Part::Body, Part::Body, Part::Body, Part::Status, Part::Address, Part::Tabs, Part::CommandBar]) +} + +/// `n` steps from `seed`. A wheel turn is often followed by frames of its animation. +fn sequence(seed: u64, n: usize) -> Vec { + let mut r = Rng(seed); + let keys: Vec<&'static str> = KEYS.split_whitespace().collect(); + let (mut active, mut italian) = (true, false); + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + let step = match r.below(100) { + 0..=29 => Step::Key(r.pick(&keys)), + 30..=37 => Step::Char(r.pick(CHARS)), + 38..=48 => Step::Click(part(&mut r), r.below(1000), r.below(1000)), + 49..=62 => Step::Hover(hover_part(&mut r), r.below(1000), r.below(1000)), + 63..=72 => { + let p = part(&mut r); + out.push(Step::Wheel(p, r.below(1000), r.below(1000), r.pick(&[-3, -1, 1, 3]))); + for _ in 0..r.below(6) { + out.push(Step::Wait(16)); + } + continue; + } + 73..=84 => Step::Wait(r.pick(&[16, 16, 16, 33, 50, 130, 300, 1100])), + 85..=89 => Step::Remove(r.below(1000) as u32), + 90..=92 => Step::Drives(r.below(250) as u8), + 93..=94 => Step::Filter(r.below(250) as u8), + 95 => Step::Go(r.below(250) as u8), + 96 => Step::Elsewhere(r.below(250) as u8), + 97 => { + italian = !italian; + Step::Lang(italian) + } + _ => { + active = !active; + Step::Active(active) + } + }; + out.push(step); + } + out.truncate(n); + out +} + +/// The folder of 200 made-up files a sequence can start in, beside the small one and Home. +const BIG: &str = r"C:\made-up\big"; + +/// The names of a batch, in order. +fn names_of(b: &files_engine::listing::types::Batch) -> Vec> { + let name = |e: &files_engine::listing::types::RawEntry| { + let at = e.name_off as usize; + b.names[at..at + usize::from(e.name_len)].to_vec() + }; + b.entries.iter().map(name).collect() +} + +/// A menu's pick as it reaches the window (Event::Command), so a sequence never picks a menu's row by a key. +struct Pick(u32); + +/// The window as the sequences drive it: a Pick reaches the screen as from its menu, with the screen's own reply. +struct Wrap(FilesScreen); + +impl Screen for Wrap { + fn layout(&mut self, cx: &mut LayoutCx, avail: SizeP) -> SizeP { + self.0.layout(cx, avail) + } + fn paint(&self, cx: &mut PaintCx) { + self.0.paint(cx) + } + fn event(&mut self, cx: &mut EventCx, ev: &Event) -> Reply { + self.0.event(cx, ev) + } + fn data(&mut self, cx: &mut EventCx, msg: AppMsg) -> Reply { + match msg.downcast::() { + Ok(p) => self.0.event(cx, &Event::Command(CommandId(p.0))), + Err(msg) => self.0.data(cx, msg), + } + } + fn commands(&self) -> &CommandTable { + self.0.commands() + } + fn caption_hit(&self, p: PointP) -> CaptionHit { + self.0.caption_hit(p) + } +} + +/// A window on the fakes, the names each folder holds as far as the window was told, and how many enumerations were +/// answered. +struct Run { + f: Fakes, + h: Harness, + shared: Rc, + dpi: u32, + listed: Vec<(WidePath, Vec>)>, + answered: usize, +} + +impl Run { + /// A window in Home, the 200 files or the small folder (by `start`), in English or Italian (by `start` too), + /// with its drives, presented. + fn new(start: u64, size: SizeL, dpi: u32) -> Run { + let f = Fakes::new(); + let at = match start % 3 { + 0 => Location::Home, + 1 => Location::Fs(wp(BIG)), + _ => Location::Fs(wp(ROOT)), + }; + let italian = start % 6 >= 3; + let shared = f.shared(if italian { UiLang::IT } else { UiLang::EN }); + *shared.fmt.borrow_mut() = Rc::new(if italian { Fmt::fixed_it() } else { Fmt::fixed_en() }); + // As the app records every main window: news for all of them (the drives) reach this one as a Bump. + let rec = WinRec { win: 1, kind: WinKind::Main, wref: None, hwnd: None, location: None }; + shared.windows.borrow_mut().push(rec); + // The known folders a typed shell: name opens (Step::Go). + let mut session = shared.session.borrow_mut(); + session.known.insert("documents".into(), BIG.into()); + session.known.insert("downloads".into(), ROOT.into()); + drop(session); + let tab = shared.new_tab(); + let screen = Wrap(FilesScreen::new(Rc::clone(&shared), 1, at, None, tab)); + let mut h = Harness::new(screen, size, dpi, Tokens::oled()).lang(if italian { Lang::It } else { Lang::En }); + h.present(); + let mut run = Run { f, h, shared, dpi, listed: Vec::new(), answered: 0 }; + run.f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(drives()) }); + run.settle(); + run.h.present(); + run + } + + /// Answers every enumeration the window started (the 200 files for BIG, the small folder's for any other) and + /// delivers what the fakes hold. + fn settle(&mut self) { + for _ in 0..6 { + pump(&self.f, &mut self.h); + let jobs = self.f.enumr.jobs(); + if jobs.len() == self.answered { + break; + } + for j in &jobs[self.answered..] { + let b = if j.dir == wp(BIG) { fakes::listing_n(200, 7) } else { fakes::listing(&reports()) }; + self.listed.retain(|(d, _)| *d != j.dir); + self.listed.push((j.dir.clone(), names_of(&b))); + self.f.enumr.queue(&j.dir, b); + } + self.answered = jobs.len(); + } + } + + fn at(&self) -> Location { + self.h.screen().0.tabs().active().nav.location().clone() + } + + /// The address row's field has the keyboard: the path bar's field (pathline's widget 23 with the bar's field bit). + fn in_address(&self) -> bool { + self.h.focused().is_some_and(|n| n.owner() == WidgetId(23 | 0x4000_0000)) + } + + /// The window gives the point `at` (logical px) to its caption: its drag area or a caption button. + fn on_caption(&self, at: PointL) -> bool { + let d = self.dpi as i32; + self.h.screen().caption_hit(PointP { x: at.x * d / 96, y: at.y * d / 96 }) != CaptionHit::Client + } + + /// The physical point `at` (logical px) falls on the notice of the status line while it has a button. + fn on_notice_button(&self, at: PointL) -> bool { + let st = self.h.screen().0.status(); + let d = self.dpi as i32; + let p = PointP { x: at.x * d / 96, y: at.y * d / 96 }; + st.notice().is_some_and(|n| n.action.is_some()) && st.placed().notice.inset(-d / 12, -d / 12).contains(p) + } + + /// Ctrl+Z or Ctrl+Y would change the folder on screen (what they name is here): the sequence leaves the key out. + fn would_change_here(&self, key: &str) -> bool { + let stack = self.shared.undo.borrow(); + let top = match key { + "Ctrl+Z" => stack.top(), + "Ctrl+Y" => stack.redo_top(), + _ => return false, + }; + top.is_some_and(|e| undo::elsewhere(&e.record, &self.at()).is_none()) + } + + /// A point of `part` at (fx, fy) per mille, in logical px. + fn point(&self, part: Part, fx: i32, fy: i32) -> PointL { + let l = self.h.screen().0.rects(); + let r = match part { + Part::Side => l.side, + Part::Body => l.body, + Part::Status => l.status, + Part::Address => l.toolbar, + Part::Tabs => l.chrome, + Part::CommandBar => l.cmdbar, + }; + let r = if r.is_empty() { l.client } else { r }; + let (x, y) = (r.l + (r.w() - 1).max(0) * fx / 1000, r.t + (r.h() - 1).max(0) * fy / 1000); + let d = self.dpi as i32; + PointL { x: x * 96 / d, y: y * 96 / d } + } + + fn apply(&mut self, s: Step) { + // An open menu (or list) takes the next key: it is closed first, so no pick is ever made. + if !self.h.menus().is_empty() { + self.h.key("Esc"); + self.settle(); + return; + } + match s { + Step::Key(k) => { + if !self.would_change_here(k) { + self.h.key(k); + } + } + Step::Char(c) => { + self.h.type_text(&c.to_string()); + } + Step::Click(p, x, y) => { + let at = self.point(p, x, y); + if !self.on_caption(at) { + if self.on_notice_button(at) || matches!(p, Part::CommandBar) { + self.h.hover(at); + } else { + self.h.click(at); + } + } + } + Step::Hover(p, x, y) => { + let at = self.point(p, x, y); + if !self.on_caption(at) { + self.h.hover(at); + } + } + Step::Wheel(p, x, y, n) => { + let at = self.point(p, x, y); + if !self.on_caption(at) { + self.h.wheel(at, f32::from(n)); + } + } + Step::Wait(ms) => { + self.h.advance(ms); + } + Step::Remove(n) => self.remove(n), + Step::Drives(n) => { + let d = |letter, kind, free: u64| DriveInfo { + letter, + label: Some(format!("Disk {}", letter as char)), + kind, + free: Some(free * GB), + total: Some(1000 * GB), + ready: true, + }; + let mut v = vec![d(b'C', DriveKind::Fixed, 100 + u64::from(n) * 3)]; + if n % 5 != 0 { + v.push(d(b'D', DriveKind::Fixed, 50 + u64::from(n))); + } + if n % 3 == 0 { + v.push(d(b'E', DriveKind::Removable, 7)); + } + self.f.hub.post(Msg::Job { win: 1, done: JobDone::Drives(v) }); + } + Step::Active(on) => { + self.h.set_active(on); + } + Step::Filter(n) => { + // The Filter button works in a folder only. + if matches!(self.at(), Location::Fs(_)) { + let all = NameFamily::ALL.len() as u32; + let n = u32::from(n) % (all + 1); + self.h.send(Box::new(Pick(if n == all { filter_pick::SHOW_ALL } else { filter_pick::BASE + n }))); + } + } + Step::Go(n) => self.go(ADDRESSES[usize::from(n) % ADDRESSES.len()]), + Step::Elsewhere(n) => { + let dir = wp(ELSEWHERE); + let file = |name: &str| dir.join(&name.encode_utf16().collect::>()).unwrap(); + let (from, to) = (file("draft.txt"), file("plan.txt")); + let op = OpId(900 + u32::from(n)); + let entries = vec![Entry { from, to, size: 1, mtime: 0, dir: false, bin: None }]; + let record = UndoRecord { of: op, kind: UndoKind::RenameBack, replaced: 0, entries }; + let e = UndoEntry { op, kind: OpKind::Rename, record }; + if n % 2 == 0 { + self.shared.undo.borrow_mut().push(e); + } else { + self.shared.undo.borrow_mut().push_redo(e); + } + self.h.send(Box::new(Msg::Fwd(Fwd::Ops))); + } + Step::Lang(italian) => { + // As the theme file's change reaches the app: nothing when the language is the same. + let lang = if italian { UiLang::IT } else { UiLang::EN }; + if self.shared.lang.get() != lang { + self.h.set_lang(if italian { Lang::It } else { Lang::En }); + self.shared.lang.set(lang); + *self.shared.fmt.borrow_mut() = Rc::new(if italian { Fmt::fixed_it() } else { Fmt::fixed_en() }); + self.h.send(Box::new(Msg::Lang)); + } + } + } + self.settle(); + } + + /// Ctrl+L, `text` typed, Enter: only while the address field has the keyboard and no list is open under it. + fn go(&mut self, text: &str) { + self.h.key("Ctrl+L"); + self.settle(); + if !self.in_address() { + return; + } + self.h.type_text(text); + self.settle(); + if !self.h.menus().is_empty() { + self.h.key("Esc"); + self.settle(); + } + if self.in_address() && self.h.menus().is_empty() { + self.h.key("Enter"); + } + } + + /// A name the folder shown still lists goes, as its watch reports it. + fn remove(&mut self, n: u32) { + let Location::Fs(dir) = self.at() else { return }; + let Some((id, _, gen)) = self.f.watch.watches().into_iter().rev().find(|w| w.1 == dir) else { return }; + let Some((_, names)) = self.listed.iter_mut().find(|(d, _)| *d == dir) else { return }; + if names.is_empty() { + return; + } + let name = names.remove(n as usize % names.len()); + let gone = RawChange { action: ChangeAction::Removed, name: name.into_boxed_slice() }; + self.f.watch.emit(WatchEvent::Changes { id, gen, items: vec![gone] }); + self.settle(); + self.h.advance(300); + } +} + +/// Runs `steps`, presenting after each: the index of the first step that leaves stale pixels, and where. +fn first_stale(start: u64, size: SizeL, dpi: u32, steps: &[Step]) -> Option<(usize, RectP)> { + let mut run = Run::new(start, size, dpi); + for (i, s) in steps.iter().enumerate() { + run.apply(*s); + run.h.present(); + if let Some(r) = run.h.stale() { + return Some((i, r)); + } + } + None +} + +/// The failing prefix made shorter: steps left out one chunk at a time while the window still goes stale. +fn shrink(start: u64, size: SizeL, dpi: u32, mut steps: Vec) -> (Vec, RectP) { + let mut bad = first_stale(start, size, dpi, &steps).expect("the sequence fails"); + steps.truncate(bad.0 + 1); + let mut chunk = steps.len() / 2; + let mut runs = 0; + while chunk > 0 && runs < 400 { + let mut i = 0; + while i + chunk <= steps.len() && runs < 400 { + let mut fewer = steps.clone(); + fewer.drain(i..i + chunk); + runs += 1; + match first_stale(start, size, dpi, &fewer) { + Some(b) => { + fewer.truncate(b.0 + 1); + steps = fewer; + bad = b; + } + None => i += chunk, + } + } + chunk /= 2; + } + (steps, bad.1) +} + +/// Every seed at every DPI in a window of `size`; each seed starts in Home, the 200 files or the small folder. +fn random_sequences(size: SizeL, seeds: &[u64], n: usize) { + for dpi in [96, 120, 144] { + for &seed in seeds { + let steps = sequence(seed, n); + if first_stale(seed, size, dpi, &steps).is_some() { + let (short, at) = shrink(seed, size, dpi, steps); + panic!( + "{}x{} at {dpi} dpi, seed {seed:#x}: the window shows old pixels at {at:?} after {} steps: {short:?}", + size.w, + size.h, + short.len() + ); + } + } + } +} + +const SEEDS: [u64; 6] = [0x5EED_0001, 0x5EED_0002, 0x5EED_0003, 0x5EED_0004, 0x5EED_0005, 0x5EED_0006]; + +#[test] +fn random_sequences_keep_the_window_true_at_1000x640() { + random_sequences(SizeL { w: 1000, h: 640 }, &SEEDS, 150); +} + +#[test] +fn random_sequences_keep_the_window_true_at_760x560() { + random_sequences(SizeL { w: 760, h: 560 }, &SEEDS, 150); +} + +#[test] +fn random_sequences_keep_the_window_true_when_narrow() { + random_sequences(SizeL { w: 560, h: 480 }, &SEEDS, 150); +} + +/// Sequences the random sequences found, kept as they are: the address bar lit by a hover over a crumb, Home's +/// scrollbar hiding in a new tab, the drives' figures in the status line, the narrow toolbar's hidden search button, +/// the narrow search field closed by Tab under a Filter family (the reply to its focus event was lost), a tab's close +/// button reached without crossing the tab, which lights the whole tab. +#[test] +fn the_sequences_found_keep_the_window_true() { + let (wide, narrow) = (SizeL { w: 1000, h: 640 }, SizeL { w: 560, h: 480 }); + let cases: [(u64, SizeL, u32, Vec); 7] = [ + (1, wide, 96, vec![Step::Hover(Part::Address, 125, 528)]), + (1, SizeL { w: 760, h: 560 }, 96, vec![Step::Hover(Part::Address, 696, 424)]), + ( + 0, + narrow, + 96, + vec![Step::Drives(147), Step::Key("Ctrl+T"), Step::Wheel(Part::Body, 575, 734, -1), Step::Wait(1100)], + ), + ( + 1, + narrow, + 96, + vec![Step::Remove(32), Step::Key("Shift+Tab"), Step::Drives(202), Step::Click(Part::Body, 959, 534)], + ), + (1, narrow, 120, vec![Step::Key("Ctrl+F"), Step::Key("Tab")]), + ( + 0x5EED_0001, + narrow, + 96, + vec![Step::Key("F6"), Step::Filter(110), Step::Key("Shift+Tab"), Step::Key("Tab"), Step::Remove(769)], + ), + ( + 1, + wide, + 96, + vec![ + Step::Key("Ctrl+T"), + Step::Key("Ctrl+T"), + Step::Key("Ctrl+1"), + Step::Wait(1100), + Step::Hover(Part::Body, 500, 500), + Step::Wait(400), + Step::Hover(Part::Tabs, 394, 514), + Step::Wait(300), + ], + ), + ]; + for (start, size, dpi, steps) in cases { + if let Some((i, at)) = first_stale(start, size, dpi, &steps) { + panic!("{}x{} at {dpi} dpi: old pixels at {at:?} after step {i} of {steps:?}", size.w, size.h); + } + } +} + +/// One step of Run, then the window presented and compared with a fresh paint. +#[track_caller] +fn step(run: &mut Run, s: Step, what: &str) { + run.apply(s); + run.h.present(); + assert_eq!(run.h.stale(), None, "{what} ({s:?}): the window shows old pixels there"); +} + +/// The states the random sequences reach by chance, each once: a typed known folder and Enter (the list takes the +/// keyboard), a selection under a Filter family and a search, the notices that name a change in another folder, a +/// known name with no folder, and a change of language. +#[test] +fn typed_addresses_filters_notices_and_the_language_keep_the_window_true() { + for dpi in [96, 120, 144] { + let mut run = Run::new(2, SizeL { w: 1000, h: 640 }, dpi); + step(&mut run, Step::Go(0), "shell:Documents and Enter"); + assert_eq!(run.at(), Location::Fs(wp(BIG)), "{dpi} dpi: the known folder opens"); + assert!(run.h.focused().is_some_and(|n| n.owner() == TABLE_ID), "{dpi} dpi: the list has the keyboard"); + for k in ["Down", "Shift+Down", "Shift+Down"] { + step(&mut run, Step::Key(k), "a selection"); + } + let all = NameFamily::ALL.len() as u8; + for n in [0, 1, all, 2, all] { + step(&mut run, Step::Filter(n), "a Filter family with a selection"); + } + step(&mut run, Step::Key("Ctrl+F"), "the search"); + step(&mut run, Step::Char('1'), "a query with a selection"); + step(&mut run, Step::Wait(130), "the query narrows the list"); + step(&mut run, Step::Filter(1), "a Filter family under the query"); + step(&mut run, Step::Key("Esc"), "the query cleared"); + step(&mut run, Step::Key("Esc"), "the list takes the keyboard back"); + step(&mut run, Step::Elsewhere(0), "a change waits in another folder"); + step(&mut run, Step::Key("Ctrl+Z"), "Ctrl+Z names it"); + assert!(run.h.screen().0.status().notice().is_some(), "{dpi} dpi: the notice of a change elsewhere"); + step(&mut run, Step::Wait(6_000), "the notice's hold ends"); + step(&mut run, Step::Elsewhere(1), "an undone change waits in another folder"); + step(&mut run, Step::Key("Ctrl+Y"), "Ctrl+Y names it"); + step(&mut run, Step::Go(1), "shell:Downloads and Enter"); + assert_eq!(run.at(), Location::Fs(wp(ROOT)), "{dpi} dpi: the other known folder opens"); + step(&mut run, Step::Go(2), "a known name with no folder"); + assert_eq!(run.at(), Location::Fs(wp(ROOT)), "{dpi} dpi: the window stays where it is"); + step(&mut run, Step::Key("Esc"), "Esc"); + step(&mut run, Step::Lang(true), "the language changes to Italian"); + step(&mut run, Step::Key("Ctrl+Z"), "Ctrl+Z in Italian"); + step(&mut run, Step::Lang(false), "the language changes back"); + } +} + +fn first_row(run: &Run) -> usize { + run.h.screen().0.tabs().active().table.visible_rows().start +} + +/// A wheel turn of five notches over the list and a new tab, with the turn still under way (`early`) or once it has +/// ended; then back to the list's tab. +fn wheel_then_switch(run: &mut Run, early: bool) -> usize { + step(run, Step::Wheel(Part::Body, 500, 500, -5), "a wheel turn over the list"); + step(run, Step::Wait(if early { 16 } else { 1000 }), "time"); + step(run, Step::Key("Ctrl+T"), "a new tab"); + step(run, Step::Wait(1000), "time"); + step(run, Step::Key("Ctrl+Shift+Tab"), "back to the list's tab"); + step(run, Step::Wait(1000), "time"); + first_row(run) +} + +/// Every tab's table has the same id: a tab switch while the list's wheel scroll is under way must neither lose the +/// rest of the scroll nor keep it pending for the next turn. The list ends as after a switch once the scroll has +/// ended, and the next turn goes on from there by its own notches. +#[test] +fn a_tab_switch_during_a_wheel_scroll_neither_loses_nor_carries_it() { + for dpi in [96, 144] { + let mut ended = Run::new(1, SizeL { w: 1000, h: 640 }, dpi); + let mut early = Run::new(1, SizeL { w: 1000, h: 640 }, dpi); + let (a, b) = (wheel_then_switch(&mut ended, false), wheel_then_switch(&mut early, true)); + assert_eq!(b, a, "{dpi} dpi: the switch ends the scroll where it was going"); + for run in [&mut ended, &mut early] { + step(run, Step::Wheel(Part::Body, 500, 500, -1), "one more notch"); + step(run, Step::Wait(1000), "time"); + } + assert!(first_row(&ended) > a, "{dpi} dpi: the notch scrolls"); + assert_eq!(first_row(&early), first_row(&ended), "{dpi} dpi: the next turn goes on from there"); + } +} diff --git a/apps/files/tests/ui_icons.rs b/apps/files/tests/ui_icons.rs index f774a805..865ca201 100644 --- a/apps/files/tests/ui_icons.rs +++ b/apps/files/tests/ui_icons.rs @@ -234,6 +234,18 @@ fn a_disabled_pair_leaves_only_its_rows_out_of_a_request() { assert_eq!(asked, [ItemRef::Path(wp(r"C:\made-up\mixed\b.lnk"))], "{asked:?}"); } +/// A file without an extension draws the generic page from the first frame to the last: the class of the empty +/// extension is never asked, and an icon Windows gives for it (a folder's, on some systems) is never drawn. +#[test] +fn a_file_without_an_extension_draws_the_generic_page() { + let f = Fakes::new(); + f.icons.set_icon(b""); + let rows = [("readme", false, 58, day(1)), ("notes.txt", false, 10, day(1))]; + let h = window(&f, r"C:\made-up\plain", &rows, no_known()); + assert_eq!(art_of(&h, "readme"), Some(Art::FileGeneric), "never the class icon of the empty extension"); + assert!(f.icons.noted().iter().all(|e| !e.is_empty()), "the empty extension is never asked: {:?}", f.icons.noted()); +} + /// A window over a listing already queued on the fakes. fn window_queued(f: &Fakes, dir: &str) -> Harness { let shared = f.shared(UiLang::EN); diff --git a/apps/files/tests/ui_menu.rs b/apps/files/tests/ui_menu.rs index 364f16ac..a706e4db 100644 --- a/apps/files/tests/ui_menu.rs +++ b/apps/files/tests/ui_menu.rs @@ -167,17 +167,21 @@ fn is_disabled_with_note(items: &[MenuItem], id: u32) -> bool { #[test] fn menu_items_for_file_folder_background() { - // A file: Open first, Open with, Pin (disabled until F4.8), Copy as path, Properties, F3's Rename, Delete and - // Delete permanently (FC-OPS fills ops_ui::f3_items), then Show more options last. + // A file: Cut, Copy and Paste on top as in File Explorer, then Open, Open with, Pin (disabled until F4.8), Copy as + // path, Properties, F3's Rename, Delete and Delete permanently (FC-OPS fills ops_ui::f3_items), then Show more + // options last. let mut w = window(); let at = w.point_of("notes.txt"); w.h.right_click(at); let items = w.h.menus()[0].items.clone(); let got = ids(&items); - assert_eq!(got.first(), Some(&(Cmd::Open as u32)), "Open is the default item: {got:?}"); + assert_eq!(got.get(3), Some(&(Cmd::Open as u32)), "Open follows the clipboard commands: {got:?}"); assert_eq!( got, [ + Cmd::Cut as u32, + Cmd::Copy as u32, + Cmd::Paste as u32, Cmd::Open as u32, pick::OPEN_WITH, pick::PIN, @@ -193,7 +197,8 @@ fn menu_items_for_file_folder_background() { assert_eq!(items.last(), Some(&MenuItem::Command(CommandId(Cmd::SystemMenu as u32)))); assert_eq!(w.fs().tabs().active().table.selection().count(w.rows()), 1, "the row was selected first"); - // A folder: Open, Open in new tab (disabled until F4.2), Open in new window, then as files without Open with. + // A folder: Cut, Copy and Paste into it, Open, Open in new tab (disabled until F4.2), Open in new window, then as + // files without Open with. let mut w = window(); let at = w.point_of("invoices"); w.h.right_click(at); @@ -201,6 +206,9 @@ fn menu_items_for_file_folder_background() { assert_eq!( ids(&items), [ + Cmd::Cut as u32, + Cmd::Copy as u32, + pick::PASTE_INTO, Cmd::Open as u32, Cmd::OpenNewTab as u32, pick::OPEN_NEW_WINDOW, diff --git a/apps/files/tests/ui_path.rs b/apps/files/tests/ui_path.rs index d7dbbfd2..eaa0b4a6 100644 --- a/apps/files/tests/ui_path.rs +++ b/apps/files/tests/ui_path.rs @@ -401,6 +401,46 @@ fn enter_folder_file_shell_virtual_command_paths() { assert_eq!(w.f.shell.requests().iter().filter(|q| typed(q)).count(), 1); } +#[test] +fn enter_in_the_path_field_hands_the_keyboard_to_the_list() { + let root = tree(); + let mut w = win_at(&root); + let r = root_text(&root); + let in_list = |w: &Win| w.h.focused().is_some_and(|n| n.owner() == files_engine::tab::TABLE_ID); + let focused = |w: &Win| { + let t = &w.h.screen().tabs().active().table; + t.focused().and_then(|k| t.model().row_of(k)).map(|row| t.model().label(row).to_string()) + }; + // A folder: the list takes the keyboard, so End and the arrows move in it. + queue(&w, &wp(&format!(r"{r}\beta"))); + w.type_path(&format!(r"{r}\beta")); + w.enter(); + assert_eq!(w.at(), Location::Fs(wp(&format!(r"{r}\beta")))); + assert!(in_list(&w), "the list has the keyboard: {:?}", w.h.focused()); + w.h.key("End"); + w.h.render(); + assert_eq!(focused(&w).as_deref(), Some("note.txt"), "End reaches the last row"); + w.h.key("Up"); + w.h.render(); + assert_eq!(focused(&w).as_deref(), Some("alpha"), "Up moves in the list"); + // A file: its folder opens with the file selected, the keyboard on it. + queue(&w, &wp(&r)); + w.type_path(&format!(r#""{r}\note.txt""#)); + w.enter(); + assert!(in_list(&w), "{:?}", w.h.focused()); + assert_eq!(focused(&w).as_deref(), Some("note.txt")); + // A known folder through shell:. + w.h.screen().shared().session.borrow_mut().known.insert("downloads".into(), format!(r"{r}\Gamma")); + queue(&w, &wp(&format!(r"{r}\Gamma"))); + w.type_path("shell:Downloads"); + w.enter(); + assert!(in_list(&w), "{:?}", w.h.focused()); + // A path that is not there: the keyboard stays in the field with the error. + w.type_path(&format!(r"{r}\no-such-folder")); + w.enter(); + assert!(!in_list(&w), "the field keeps the keyboard to fix the path"); +} + #[test] fn not_found_sets_error_and_stays() { let root = tree(); diff --git a/apps/files/tests/ui_rename.rs b/apps/files/tests/ui_rename.rs index d5d3a3c4..407757cd 100644 --- a/apps/files/tests/ui_rename.rs +++ b/apps/files/tests/ui_rename.rs @@ -135,6 +135,28 @@ fn win() -> Win { // ---- F3.7 +/// While the field is open its caret blinks by the field's own damage: the window shows every blink, and no blink +/// repaints the whole window. +#[test] +fn the_caret_blinks_without_repainting_the_whole_window() { + let mut w = win(); + w.begin("notes.txt"); + assert!(w.renaming()); + w.h.present(); + let client = oled_ui::RectP::wh(0, 0, 800, 500); + let mut blinks = 0; + for n in 0..8 { + w.h.advance(265); + let damage = w.h.pending_damage(); + assert!(!damage.contains(&client), "blink {n} repaints the whole window"); + blinks += usize::from(!damage.is_empty()); + assert_eq!(w.h.stale(), None, "blink {n}"); + } + assert!(blinks >= 2, "the caret blinks ({blinks})"); + w.h.key("Esc"); + assert!(!w.renaming()); +} + #[test] fn stem_preselected() { let mut w = win(); diff --git a/apps/files/tests/ui_search.rs b/apps/files/tests/ui_search.rs index 25264330..d3e6a5ea 100644 --- a/apps/files/tests/ui_search.rs +++ b/apps/files/tests/ui_search.rs @@ -396,3 +396,56 @@ fn back_to_a_cached_folder_shows_it_whole() { assert_eq!(w.rows(), 5, "and after the revalidation"); assert_eq!(w.fs().toolbar().search().text(), ""); } + +/// What the filter or the search hides is not selected: the details pane, the status line and the commands follow +/// what is visible (Rename, Delete and Open never reach a hidden item). +#[test] +fn a_hidden_row_leaves_the_selection_the_pane_and_the_commands() { + let rows = [("clip.mp4", false, 50, day(1)), ("photo.png", false, 246, day(2)), ("notes.txt", false, 6, day(3))]; + let mut w = window(&rows, 1100); + w.fs().toolbar().force_changes(Some(true)); + let select = |w: &mut Win, name: &str| { + w.h.key("Home"); + for _ in 0..rows.len() { + if w.focused_label().as_deref() == Some(name) { + break; + } + w.h.key("Down"); + } + w.h.render(); + assert_eq!(w.focused_label().as_deref(), Some(name)); + }; + let selected = |w: &Win| { + let t = &w.fs().tabs().active().table; + t.selection().count(ListModel::len(t.model())) + }; + let pane_title = |w: &Win| w.fs().pane().content().map(|c| c.title.clone()); + // The Images family hides the video that was selected. + select(&mut w, "clip.mp4"); + assert_eq!(selected(&w), 1); + assert_eq!(pane_title(&w).as_deref(), Some("clip.mp4")); + let images = NameFamily::ALL.iter().position(|f| *f == NameFamily::Images).unwrap() as u32; + w.pick(filter_pick::BASE + images); + assert_eq!(w.labels(), ["photo.png"]); + assert_eq!(selected(&w), 0, "the hidden row is not selected"); + assert_eq!(pane_title(&w).as_deref(), Some("reports"), "the pane shows the folder"); + let a = files_engine::toolmenus::avail(w.fs()); + assert!(a.rename.is_some() && a.delete.is_some() && a.cut.is_some(), "{a:?}"); + assert!(!w.h.a11y_dump().contains("1 selected"), "{}", w.h.a11y_dump()); + let before = w.f.shell.requests().len(); + w.h.key("Enter"); + w.h.render(); + let opened = w.f.shell.requests().into_iter().skip(before).any(|r| format!("{r:?}").contains("clip.mp4")); + assert!(!opened, "Open never reaches the hidden row"); + // Show all, then the search hides the selected text file. + w.pick(filter_pick::SHOW_ALL); + select(&mut w, "notes.txt"); + assert_eq!(pane_title(&w).as_deref(), Some("notes.txt")); + w.type_in("clip"); + w.settle_search(); + assert_eq!(w.labels(), ["clip.mp4"]); + assert_eq!(selected(&w), 0, "the row the search hides is not selected"); + assert_eq!(pane_title(&w).as_deref(), Some("reports")); + let a = files_engine::toolmenus::avail(w.fs()); + assert!(a.rename.is_some() && a.delete.is_some(), "{a:?}"); +} diff --git a/apps/files/tests/undo.rs b/apps/files/tests/undo.rs index 147eaefd..0d0b03e2 100644 --- a/apps/files/tests/undo.rs +++ b/apps/files/tests/undo.rs @@ -15,6 +15,7 @@ use files_engine::listing::WidePath; use files_engine::ops::classify::{NoBin, Recyclability}; use files_engine::ops_client::{OpsError, OpsEvent, UndoRecord}; use files_engine::ops_ui::{self, MutReq}; +use files_engine::status::{self, NoticeAct}; use files_engine::undo::{UndoEntry, UndoStack, UNDO_CAP}; use files_engine::window::{FilesScreen, Shared, WinKind, WinRec}; use oled_trust::frame::files::{ @@ -32,6 +33,8 @@ fn wp(s: &str) -> WidePath { enum Op { Req(MutReq), Select(Vec<&'static str>), + /// What a click on the status notice's button runs. + Act(NoticeAct), } struct Wrap(FilesScreen); @@ -63,6 +66,9 @@ impl Screen for Wrap { } t.table.set_selection(cx, Selection::Keys(keys)); } + Op::Act(a) => { + status::on_notice_action(&mut self.0, cx, a); + } } Reply::Relayout } @@ -95,6 +101,10 @@ fn listing() -> files_engine::listing::Batch { } fn screen_for(shared: &Rc, f: &Fakes, win: u32, dir: &WidePath) -> Harness { + screen_sized(shared, f, win, dir, 800) +} + +fn screen_sized(shared: &Rc, f: &Fakes, win: u32, dir: &WidePath, width: i32) -> Harness { f.enumr.queue(dir, listing()); shared.windows.borrow_mut().push(WinRec { win, @@ -105,7 +115,7 @@ fn screen_for(shared: &Rc, f: &Fakes, win: u32, dir: &WidePath) -> Harne }); let tab = shared.new_tab(); let screen = FilesScreen::new(Rc::clone(shared), win, Location::Fs(dir.clone()), None, tab); - let mut h = Harness::new(Wrap(screen), SizeL { w: 800, h: 500 }, 96, Tokens::oled()); + let mut h = Harness::new(Wrap(screen), SizeL { w: width, h: 500 }, 96, Tokens::oled()); h.render(); f.pump(&mut h, win); h.render(); @@ -113,13 +123,17 @@ fn screen_for(shared: &Rc, f: &Fakes, win: u32, dir: &WidePath) -> Harne } fn in_root(tag: &str) -> Win { + in_root_sized(tag, 800) +} + +fn in_root_sized(tag: &str, width: i32) -> Win { let root = TempRoot::new(tag); let dir = wp(&root.path().to_string_lossy()); let f = Fakes::new(); let shared = f.shared(UiLang::EN); *shared.fmt.borrow_mut() = Rc::new(Fmt::fixed_en()); assert_eq!(shared.new_win(), 1); - let h = screen_for(&shared, &f, 1, &dir); + let h = screen_sized(&shared, &f, 1, &dir, width); Win { f, shared, h, dir, _root: root } } @@ -261,9 +275,10 @@ fn refusal_texts() { let mut w = in_root("undo_refusals"); w.key("Ctrl+Z"); assert!(w.has_label("Nothing to undo"), "{}", w.h.a11y_dump()); - let cases: [(Refusal, &str, u32, &str); 3] = [ + let cases: [(Refusal, &str, u32, &str); 4] = [ (Refusal::Changed, "b-notes.txt", 0, "Can't undo: b-notes.txt changed since"), (Refusal::Replaced, "", 3, "Can't undo: 3 items replaced older files"), + (Refusal::Replaced, "", 1, "Can't undo: 1 item replaced an older file"), (Refusal::NotEmpty, "plans", 0, "Can't undo: plans isn't empty any more"), ]; for (i, (why, detail, replaced, text)) in cases.into_iter().enumerate() { @@ -416,8 +431,12 @@ fn refused_redo_leaves_no_mark() { w.shared.ops.borrow_mut().set_facts(Arc::new(|items: &[(WidePath, u64)]| { items.iter().map(|(p, _)| (p.clone(), Recyclability::No(NoBin::Disabled))).collect() })); + // The items lie in another folder: Ctrl+Y stops there, and the notice's button goes on. w.key("Ctrl+Y"); w.pump(); + assert!(!bar::bar_of(&w.h.screen().0).is_open(), "nothing is done again out of sight"); + w.h.send(Box::new(Op::Act(NoticeAct::Redo(OpId(8))))); + w.pump(); assert!(bar::bar_of(&w.h.screen().0).is_open()); w.f.ops.set_fail(Some(OpsError::Refused(Refusal::Root))); w.key("Enter"); @@ -471,3 +490,154 @@ fn shared_across_windows() { assert_eq!(r, Some(2), "the undo belongs to the window that asked"); drop(c2); } + +/// A paste that replaced an older file cannot be undone: the notice that says so is read whole, even in a narrow +/// window where the chip of the finished paste stands in the middle of the line. +#[test] +fn a_refused_undo_is_read_whole_beside_the_chip() { + let mut w = in_root_sized("undo_whole", 600); + rename_a_to_b(&mut w); + let rec = UndoRecord { + of: OpId(1), + kind: UndoKind::RenameBack, + replaced: 1, + entries: vec![entry(w.path("a-notes.txt"), w.path("b-notes.txt"))], + }; + w.emit(OpsEvent::Undo(rec)); + w.emit(done(1, Some(UndoKind::RenameBack))); + w.pump(); + assert!(ops_ui::flyout_of(&w.h.screen().0).chip().is_some(), "the finished rename is held in the chip"); + w.key("Ctrl+Z"); + w.emit(OpsEvent::Evt(OpEvt::Refused { op: OpId(2), why: Refusal::Replaced, detail: "1".into() })); + w.pump(); + assert!(w.has_label("Can't undo: 1 item replaced an older file"), "{}", w.h.a11y_dump()); + let s = &w.h.screen().0; + let placed = s.status().placed(); + assert!(placed.notice_whole, "the notice is laid out whole: {placed:?}"); + if let Some(back) = ops_ui::flyout_of(s).chip_back() { + assert!(back.l >= placed.notice.r, "the chip stands clear of the notice: {back:?} {placed:?}"); + } +} + +/// Ctrl+Z never reaches a change in a folder that is not on screen: it stops there, and the notice names the change +/// and its folder, with a button that undoes it there. +#[test] +fn ctrl_z_stops_at_the_folder_on_screen_and_says_where_the_last_change_is() { + let mut w = in_root("undo_elsewhere"); + let sub = w.path("sub"); + let name = |n: &str| sub.join(&n.encode_utf16().collect::>()).unwrap(); + let (from, to) = (name("a.txt"), name("b.txt")); + w.req(MutReq::Rename { item: from.clone(), to: "b.txt".into() }); + let rec = UndoRecord { of: OpId(1), kind: UndoKind::RenameBack, replaced: 0, entries: vec![entry(from, to)] }; + w.emit(OpsEvent::Undo(rec)); + w.emit(done(1, Some(UndoKind::RenameBack))); + w.pump(); + assert_eq!(w.undo_len(), 1); + let before = w.calls().len(); + w.key("Ctrl+Z"); + assert_eq!(w.calls().len(), before, "nothing is undone out of sight: {:?}", w.calls()); + assert_eq!(w.undo_len(), 1, "the change stays on the stack"); + assert!(w.has_label("Last change: Rename in sub"), "{}", w.h.a11y_dump()); + assert!(w.h.a11y_dump().contains("Button \"Undo there\""), "{}", w.h.a11y_dump()); + // The More menu names the folder too. + let more = files_engine::toolmenus::more_items(&w.h.screen().0); + let undo_id = files_engine::keys::Cmd::Undo as u32; + let label = more.iter().find_map(|i| match i { + oled_ui::MenuItem::Custom { id, label, .. } if id.0 == undo_id => Some(label.to_string()), + _ => None, + }); + assert_eq!(label.as_deref(), Some("Undo Rename in sub")); + // Ctrl+Z again: still nothing. + w.key("Ctrl+Z"); + assert_eq!(w.calls().len(), before); + // The notice's button undoes it there. + w.h.send(Box::new(Op::Act(NoticeAct::Undo(OpId(1))))); + w.h.render(); + assert_eq!(w.calls().last(), Some(&OpsCall::Undo(OpId(1)))); + assert_eq!(w.undo_len(), 0); + // A change in the folder on screen is undone at once, as before. + rename_a_to_b(&mut w); + w.renamed(3, "a-notes.txt", "b-notes.txt"); + w.key("Ctrl+Z"); + assert_eq!(w.calls().last(), Some(&OpsCall::Undo(OpId(3)))); +} + +/// Ctrl+Y and Ctrl+Shift+Z never do a change again out of sight either: the undone change stays on the redo stack, the +/// notice names it and its folder, with a button that does it again there, and the More menu names the folder. +#[test] +fn ctrl_y_stops_at_the_folder_on_screen_and_says_where_the_undone_change_is() { + let mut w = in_root("redo_elsewhere"); + let sub = w.path("sub"); + let name = |n: &str| sub.join(&n.encode_utf16().collect::>()).unwrap(); + let (from, to) = (name("a.txt"), name("b.txt")); + w.req(MutReq::Rename { item: from.clone(), to: "b.txt".into() }); + let e = entry(from.clone(), to); + let rec = UndoRecord { of: OpId(1), kind: UndoKind::RenameBack, replaced: 0, entries: vec![e] }; + w.emit(OpsEvent::Undo(rec)); + w.emit(done(1, Some(UndoKind::RenameBack))); + w.pump(); + // Undone there, by the notice's button: the rename goes on the redo stack. + w.key("Ctrl+Z"); + w.h.send(Box::new(Op::Act(NoticeAct::Undo(OpId(1))))); + w.h.render(); + assert_eq!(w.calls().last(), Some(&OpsCall::Undo(OpId(1)))); + w.emit(done(2, None)); + w.pump(); + assert_eq!(w.redo_len(), 1); + let before = w.calls().len(); + for chord in ["Ctrl+Shift+Z", "Ctrl+Y"] { + w.key(chord); + assert_eq!(w.calls().len(), before, "{chord}: nothing is done again out of sight: {:?}", w.calls()); + assert_eq!(w.redo_len(), 1, "{chord}: the change stays on the redo stack"); + assert!(w.has_label("Last undone: Rename in sub"), "{chord}: {}", w.h.a11y_dump()); + assert!(w.h.a11y_dump().contains("Button \"Redo there\""), "{chord}: {}", w.h.a11y_dump()); + } + // The More menu names the folder too. + let more = files_engine::toolmenus::more_items(&w.h.screen().0); + let redo_id = files_engine::keys::Cmd::Redo as u32; + let label = more.iter().find_map(|i| match i { + oled_ui::MenuItem::Custom { id, label, .. } if id.0 == redo_id => Some(label.to_string()), + _ => None, + }); + assert_eq!(label.as_deref(), Some("Redo Rename in sub")); + // The notice's button does it again there; once taken, the same button does nothing. + let op = w.shared.undo.borrow().redo_top().map(|e| e.op).expect("the redo entry"); + w.h.send(Box::new(Op::Act(NoticeAct::Redo(op)))); + w.h.render(); + assert_eq!(w.calls().last(), Some(&OpsCall::Rename(from, "b.txt".into()))); + assert_eq!(w.redo_len(), 0); + w.h.send(Box::new(Op::Act(NoticeAct::Redo(op)))); + w.h.render(); + assert_eq!(w.calls().len(), before + 1); + // A delete undone in another folder is not done again from here: no bar, no recycle, the notice says where. + let gone = name("c.txt"); + let bin = wp(r"C:\$Recycle.Bin\S-1-5-21-0\$R0003.txt"); + let rec = UndoRecord { + of: OpId(7), + kind: UndoKind::RestoreRecycled, + replaced: 0, + entries: vec![Entry { bin: Some(bin.clone()), ..entry(gone.clone(), bin) }], + }; + w.shared.undo.borrow_mut().push_redo(UndoEntry { op: OpId(7), kind: OpKind::Recycle, record: rec }); + w.shared.ops.borrow_mut().set_facts(Arc::new(|items: &[(WidePath, u64)]| { + items.iter().map(|(p, _)| (p.clone(), Recyclability::Yes)).collect() + })); + let before = w.calls().len(); + w.key("Ctrl+Y"); + w.pump(); + assert_eq!(w.calls().len(), before, "no recycle out of sight: {:?}", w.calls()); + assert!(!bar::bar_of(&w.h.screen().0).is_open()); + assert!(w.has_label("Last undone: Delete in sub"), "{}", w.h.a11y_dump()); + w.h.send(Box::new(Op::Act(NoticeAct::Redo(OpId(7))))); + w.pump(); + assert_eq!(w.calls().last(), Some(&OpsCall::Recycle(vec![ItemRef::Path(gone)]))); + // A change in the folder on screen is done again at once, as before. + rename_a_to_b(&mut w); + w.renamed(5, "a-notes.txt", "b-notes.txt"); + w.key("Ctrl+Z"); + assert_eq!(w.calls().last(), Some(&OpsCall::Undo(OpId(5)))); + w.emit(done(6, None)); + w.pump(); + w.key("Ctrl+Y"); + assert_eq!(w.calls().last(), Some(&OpsCall::Rename(w.path("a-notes.txt"), "b-notes.txt".into()))); +} diff --git a/apps/gallery/Cargo.toml b/apps/gallery/Cargo.toml index dd2a530b..9be9b9b9 100644 --- a/apps/gallery/Cargo.toml +++ b/apps/gallery/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gallery" -version = "1.9.0" +version = "1.9.1" edition = "2021" rust-version = "1.87" license = "MIT" diff --git a/apps/gallery/tests/golden/base/charts/en-120.png b/apps/gallery/tests/golden/base/charts/en-120.png index dd9e5b65..63dd2b00 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-120.png and b/apps/gallery/tests/golden/base/charts/en-120.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-144-contrast.png b/apps/gallery/tests/golden/base/charts/en-144-contrast.png index b74e63fb..1e525613 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-144-contrast.png and b/apps/gallery/tests/golden/base/charts/en-144-contrast.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-144-hc.png b/apps/gallery/tests/golden/base/charts/en-144-hc.png index ecc747df..dca1caa8 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-144-hc.png and b/apps/gallery/tests/golden/base/charts/en-144-hc.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-144.png b/apps/gallery/tests/golden/base/charts/en-144.png index b74e63fb..1e525613 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-144.png and b/apps/gallery/tests/golden/base/charts/en-144.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-192.png b/apps/gallery/tests/golden/base/charts/en-192.png index 07020457..9a170b5e 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-192.png and b/apps/gallery/tests/golden/base/charts/en-192.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-96-hc.png b/apps/gallery/tests/golden/base/charts/en-96-hc.png index 536f8dea..6b68bb29 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-96-hc.png and b/apps/gallery/tests/golden/base/charts/en-96-hc.png differ diff --git a/apps/gallery/tests/golden/base/charts/en-96.png b/apps/gallery/tests/golden/base/charts/en-96.png index c650a3fa..616e78fb 100644 Binary files a/apps/gallery/tests/golden/base/charts/en-96.png and b/apps/gallery/tests/golden/base/charts/en-96.png differ diff --git a/apps/gallery/tests/golden/base/charts/it-120.png b/apps/gallery/tests/golden/base/charts/it-120.png index 1f0ab361..bc476df1 100644 Binary files a/apps/gallery/tests/golden/base/charts/it-120.png and b/apps/gallery/tests/golden/base/charts/it-120.png differ diff --git a/apps/gallery/tests/golden/base/charts/it-144.png b/apps/gallery/tests/golden/base/charts/it-144.png index 1b68a84f..1e22506e 100644 Binary files a/apps/gallery/tests/golden/base/charts/it-144.png and b/apps/gallery/tests/golden/base/charts/it-144.png differ diff --git a/apps/gallery/tests/golden/base/charts/it-192.png b/apps/gallery/tests/golden/base/charts/it-192.png index 61248316..86e6760d 100644 Binary files a/apps/gallery/tests/golden/base/charts/it-192.png and b/apps/gallery/tests/golden/base/charts/it-192.png differ diff --git a/apps/gallery/tests/golden/base/charts/it-96.png b/apps/gallery/tests/golden/base/charts/it-96.png index 766cceab..8d5e9404 100644 Binary files a/apps/gallery/tests/golden/base/charts/it-96.png and b/apps/gallery/tests/golden/base/charts/it-96.png differ diff --git a/apps/gallery/tests/golden/base/charts/pseudo-144.png b/apps/gallery/tests/golden/base/charts/pseudo-144.png index 0a32bc36..cde4cf63 100644 Binary files a/apps/gallery/tests/golden/base/charts/pseudo-144.png and b/apps/gallery/tests/golden/base/charts/pseudo-144.png differ diff --git a/apps/tasks/Cargo.toml b/apps/tasks/Cargo.toml index ebb1fec9..bb54361c 100644 --- a/apps/tasks/Cargo.toml +++ b/apps/tasks/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tasks" -version = "1.9.0" +version = "1.9.1" edition = "2021" rust-version = "1.87" description = "The tasks app of the suite: every process grouped as the dock names it, safe to close and end." diff --git a/apps/tasks/src/app/mod.rs b/apps/tasks/src/app/mod.rs index aa2f02e0..fcc3f5e2 100644 --- a/apps/tasks/src/app/mod.rs +++ b/apps/tasks/src/app/mod.rs @@ -60,7 +60,8 @@ pub fn main_spec(title: String, opened_by_chord: bool) -> WindowSpec { title: title.into(), size: WINDOW_SIZE, owner: None, - esc_closes: true, + // Esc clears the search, then the selection; it never closes the window. + esc_closes: false, placement: Some(MAIN_PLACEMENT), icon_resource: Some(1), opened_by_chord, @@ -112,16 +113,25 @@ impl Deps { } } +/// Whether a command line can own anything Windows draws: only the window (its caption menu, the file dialog of Run new +/// task). The self-test, the offscreen preview, the app listing and the version line show nothing. +fn owns_system_surface(cli: &args::Cli) -> bool { + matches!(cli, args::Cli::Run(_)) +} + /// tasks.exe: the start order of F-T2. pub fn main() -> ExitCode { // (1) Every DLL loaded later comes from System32 only. // SAFETY: no pointers; sets this process's default DLL search path. let _ = unsafe { SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32) }; - // Its popup menus are drawn dark (the suite is always dark). - oled_sys::darkmenu::init(); // (2) The arguments. let raw: Vec = std::env::args().skip(1).collect(); - let show = match args::parse(&raw) { + let parsed = args::parse(&raw); + // Its popup menus and dialogs come up dark (the suite is always dark), before the first window. + if parsed.as_ref().is_ok_and(owns_system_surface) { + oled_sys::darkmenu::init(); + } + let show = match parsed { Ok(args::Cli::Run(show)) => show, // (3) Handled before anything else: no mutex, no window, no forward. Ok(args::Cli::Selftest { nonce }) => return selftest::run(&nonce), @@ -303,3 +313,26 @@ fn list_apps() -> ExitCode { console_line("tasks: built without preview"); ExitCode::from(2) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Only the window opts in to dark system menus: the other command lines show nothing. + #[test] + fn only_the_window_owns_a_system_surface() { + let cli = |v: &[&str]| args::parse(&v.iter().map(|s| (*s).to_string()).collect::>()).unwrap(); + for (line, want) in [ + (&[][..], true), + (&["--from-chord"], true), + (&["--selftest", "--signal", "ab"], false), + (&["--preview", "out"], false), + (&["--list-apps"], false), + (&["--version"], false), + ] { + assert_eq!(owns_system_surface(&cli(line)), want, "{line:?}"); + } + let src = include_str!("mod.rs").split("#[cfg(test)]").next().unwrap(); + assert_eq!(src.matches("oled_sys::darkmenu::init();").count(), 1, "one opt-in, before the window"); + } +} diff --git a/apps/tasks/src/ui/actions.rs b/apps/tasks/src/ui/actions.rs index d1e8840f..89b6a557 100644 --- a/apps/tasks/src/ui/actions.rs +++ b/apps/tasks/src/ui/actions.rs @@ -121,9 +121,17 @@ pub struct ActionState { close_armed: Option, /// The processes this session put in efficiency mode, as far as the screen has been told (the Status column). eco: std::collections::HashSet, + /// The rows are the flat Details list: a process that owns a window and responds has Close, as its group has on + /// Processes. + flat: bool, } impl ActionState { + /// The page shows the flat Details list (true) or not. + pub fn set_flat(&mut self, on: bool) { + self.flat = on; + } + /// Fixes the shell, own process and session the guard is built against (scenes and tests); the system is then /// never probed: every process counts as alive as displayed and terminable, except the fixture's limited keys. pub fn set_env(&mut self, e: HostEnv) { @@ -256,6 +264,14 @@ pub fn row_verb(st: &ActionState, v: &View, r: &RowEntry) -> Option { let verb = verb_of(r, g)?; match (r.section, r.kind) { (None, RowKind::Proc(p)) if part_of_windows(v, p, st.env().session) => Some(RowVerb::EndTask), + (None, RowKind::Proc(p)) if st.flat && verb == RowVerb::End => { + let (mut windows, mut hung) = (0, 0); + for w in v.frame().windows.iter().filter(|w| w.owner == p) { + windows += 1; + hung += u32::from(w.hung); + } + Some(if windows > 0 && hung == 0 { RowVerb::Close } else { verb }) + } _ => Some(verb), } } diff --git a/apps/tasks/src/ui/band.rs b/apps/tasks/src/ui/band.rs index 41b920c8..97fe03e3 100644 --- a/apps/tasks/src/ui/band.rs +++ b/apps/tasks/src/ui/band.rs @@ -289,6 +289,8 @@ fn tune_why(r: TuneRefusal, key: ProcKey, g: &KillGuard, lang: UiLang) -> Option /// The row's name as the menu and the band say it: a group's label without its count, a process's image name. pub fn name_of(s: &TasksScreen, kind: RowKind, key: RowKey, label: &str, members: usize) -> String { match kind { + // The label the row shows (the name of its program); the image name only when the row has none. + RowKind::Proc(_) if !label.is_empty() => label.to_string(), RowKind::Proc(p) => s.v.shown_name(key, p), _ => label.strip_suffix(&format!(" ({members})")).unwrap_or(label).to_string(), } @@ -565,6 +567,8 @@ fn more_items(p: &Plan, lang: UiLang, page: Page) -> Vec { #[derive(Default)] pub struct BandState { bar: Option, + /// The band's place after the last layout (physical px): what a new fill of the bar repaints. + rect: RectP, /// What the bar was last filled for: the selection, the frame and the tune counter. sig: Option<(Vec, u64, u64, u64)>, /// Counts the outcomes of tune batches: a change of the book is a reason to fill the bar again. @@ -584,9 +588,11 @@ impl BandState { self.bar.as_ref() } - /// The last Altro menu's own rows are built by the screen; this only tells the bar its menu closed. - pub fn on_menu_closed(&mut self) { + /// The last Altro menu's own rows are built by the screen; this only tells the bar its menu closed, and repaints + /// the button that showed it open. + pub fn on_menu_closed(&mut self, cx: &mut EventCx) { if let Some(b) = self.bar.as_mut() { + b.damage_open(cx); b.set_open(None); b.set_more_open(false); } @@ -648,6 +654,7 @@ pub fn layout(s: &mut TasksScreen, cx: &mut LayoutCx, rect: RectP) -> i32 { let bar = ensure(&mut s.p.band, lang); let r = RectP { l: rect.l + cx.px(MARGIN_L), t: rect.t, r: rect.r - cx.px(MARGIN_R), b: rect.t + cx.px(BAR_H) }; bar.layout(cx, r); + s.p.band.rect = RectP { b: rect.t + cx.px(HEIGHT), ..rect }; cx.px(HEIGHT) } @@ -727,7 +734,9 @@ pub fn sync(s: &mut TasksScreen, cx: &mut EventCx) { it.enabled = p.properties.enabled; it.tip = tip(&p.properties, t(lang, k::TASKS_BAND_TIP_PROPERTIES)); } - cx.relayout(); + // Filled again at every sample: only the band is repainted (a page switch repaints the rest). + cx.relayout_nodes(); + cx.damage(s.p.band.rect); // The Status column follows the book of the rows just read. if std::mem::take(&mut s.p.band.pipeline) { let now = cx.now_ms(); @@ -841,6 +850,7 @@ pub fn on_out(s: &mut TasksScreen, cx: &mut EventCx, out: CommandBarOut) { order::note_menu_open(&mut s.p.order); if let Some(b) = s.p.band.bar.as_mut() { b.set_open(Some(id)); + b.damage_open(cx); } } CommandBarOut::OpenMore(rect) => { @@ -852,6 +862,7 @@ pub fn on_out(s: &mut TasksScreen, cx: &mut EventCx, out: CommandBarOut) { let Some(bar) = s.p.band.bar.as_mut() else { return }; let items = bar.more_menu(more_items(&p, lang, page)); bar.set_more_open(true); + bar.damage_open(cx); cx.open_menu(items, Anchor::Below(rect)); order::note_menu_open(&mut s.p.order); } diff --git a/apps/tasks/src/ui/chrome.rs b/apps/tasks/src/ui/chrome.rs index 4c1ae866..b5c12b39 100644 --- a/apps/tasks/src/ui/chrome.rs +++ b/apps/tasks/src/ui/chrome.rs @@ -188,20 +188,25 @@ impl Chrome { cx.relayout(); } - /// The lists' totals changed. + /// The lists' totals changed (at most every sample): the head's count and the status line say them, and only they + /// are repainted. pub fn set_totals(&mut self, cx: &mut EventCx, totals: Totals) { if self.totals == totals { return; } self.totals = totals; - cx.relayout(); + cx.relayout_nodes(); + cx.damage(self.head.rect()); + cx.damage(self.line.rect); } /// The order is held (the status line says so). pub fn set_held(&mut self, cx: &mut EventCx, held: bool) { if self.held != held { self.held = held; - cx.relayout(); + // Only the status line says it: its parts are laid out again and only it is repainted. + cx.relayout_nodes(); + cx.damage(self.line.rect); } } diff --git a/apps/tasks/src/ui/details.rs b/apps/tasks/src/ui/details.rs index e8b27fb7..758f65fd 100644 --- a/apps/tasks/src/ui/details.rs +++ b/apps/tasks/src/ui/details.rs @@ -10,10 +10,11 @@ use std::ops::Range; use std::sync::Arc; use std::time::Instant; +use oled_shellmodel::identity::key_from_exe_path; use oled_sys::i18n::S; use oled_sysmon::ProcKey; use oled_ui::model::{Align, ColId, Column, ListModel, RowKey, ScrollTo, Selection, SortDir}; -use oled_ui::tokens::{RES_CPU, RES_MEM}; +use oled_ui::tokens::{COL_MIN_W, RES_CPU, RES_MEM}; use oled_ui::{Anchor, CommandId, EventCx, Ink, MenuItem, RectP, UiLang}; use super::band::{self, Level}; @@ -32,6 +33,7 @@ use crate::app::options::ColumnPref; use crate::app::procinfo::{Facts, Job, Known, ProcInfo, ProcInfoBook}; use crate::app::resolver::NameBook; use crate::model::classify::ImagePath; +use crate::model::group::IdentityId; use crate::model::view::{ColumnId, Page, ViewMode}; use crate::strings::{k, t}; @@ -145,6 +147,58 @@ pub fn columns(lang: UiLang, prefs: &[ColumnPref]) -> Vec { out } +/// Narrows the columns so that they fit `total` logical px: the others toward their minimum, then the name toward the +/// least it may have, then every column to the kit's floor. Widens the name's minimum back when there is room. True when +/// a column changed. The table has no horizontal scroll, so a column that does not fit would be cut at the edge. +pub fn fit_columns(cols: &mut [Column], total: i32) -> bool { + let before: Vec<(i32, i32)> = cols.iter().map(|c| (c.width, c.min)).collect(); + let floor = |c: &Column| c.min.max(COL_MIN_W); + let name_min = SPECS[0].min; + if let Some(f) = cols.iter_mut().find(|c| c.visible && c.flex) { + f.min = name_min; + } + // The widest columns give first: every column is cut to one level, as low as the room asks (never under its own + // minimum), so the figures keep the width they need while a command line or a path narrows. + let budget = total - name_min; + let at = |cols: &[Column], level: i32| -> i32 { + cols.iter().filter(|c| c.visible && !c.flex).map(|c| c.width.min(level).max(floor(c))).sum() + }; + let widest = cols.iter().filter(|c| c.visible && !c.flex).map(|c| c.width).max().unwrap_or(0); + let (mut lo, mut hi) = (0, widest); + while lo < hi { + let mid = lo + (hi - lo + 1) / 2; + if at(cols, mid) <= budget { + lo = mid; + } else { + hi = mid - 1; + } + } + for c in cols.iter_mut().filter(|c| c.visible && !c.flex) { + c.width = c.width.min(lo).max(c.min.max(COL_MIN_W)); + } + // Every column is at its floor and still too wide: the name gives what is left of its own minimum. + let over = at(cols, widest) + name_min - total; + if over > 0 { + if let Some(f) = cols.iter_mut().find(|c| c.visible && c.flex) { + f.min = (f.min - over).max(COL_MIN_W); + } + } + before != cols.iter().map(|c| (c.width, c.min)).collect::>() +} + +/// Fits the shown columns to the width the list has now (a column just added, a window made narrower). +pub fn refit(s: &mut TasksScreen, cx: &mut EventCx) { + let total = cx.scale().logical(s.table.viewport().w()); + if s.chrome.page() != Page::Details || total <= 0 { + return; + } + let mut cols = s.table.columns().to_vec(); + if fit_columns(&mut cols, total) { + s.table.set_columns(cx, cols); + cx.relayout(); + } +} + /// The saved form of the table's columns. pub fn prefs_of(cols: &[Column]) -> Vec { cols.iter() @@ -328,6 +382,22 @@ fn sort_by_extra(rows: &mut [RowEntry], extras: &HashMap, c: Colu } } +/// The name of the app a process shows a window for, as its group is named on Processes; None for a process with no +/// window or an app the resolver has not named yet. +fn app_name(v: &View, names: &NameBook, pk: ProcKey) -> Option { + let frame = v.frame(); + let w = frame.windows.iter().find(|w| w.owner == pk)?; + let key = match names.identity(w.hwnd, w.owner.pid) { + Some(i) => i.key.clone(), + None => match frame.paths.get(pk) { + Some(ImagePath::Path(p)) => key_from_exe_path(p), + _ => return None, + }, + }; + let id = IdentityId(v.intern(&key)); + names.name_of_identity(id, &key).map(str::to_string) +} + /// The rows of the page: every process of the newest frame, flat, with the name of its program and no tail, in the /// order of the sort. pub fn build(v: &View, names: &NameBook, book: &ProcInfoBook, rows: &mut Vec) { @@ -338,6 +408,9 @@ pub fn build(v: &View, names: &NameBook, book: &ProcInfoBook, rows: &mut Vec 0 { + fit_columns(&mut cols, total); + } s.table.set_columns(cx, cols); cx.relayout(); save_columns(s); @@ -595,6 +672,30 @@ mod tests { cols.iter().filter_map(|c| spec_of_col(c.id)).map(|s| s.id).collect() } + #[test] + fn the_columns_fit_a_width_and_the_widest_give_first() { + let mut cols = columns(UiLang::EN, &[]); + for c in cols.iter_mut().filter(|c| matches!(c.id, COL_PRIORITY | COL_COMMAND_LINE | COL_PATH)) { + c.visible = true; + } + let width_of = |cols: &[Column], id| cols.iter().find(|c| c.id == id).map_or(0, |c| c.width); + let total_of = |cols: &[Column]| -> i32 { + cols.iter().filter(|c| c.visible).map(|c| if c.flex { c.min } else { c.width.max(c.min) }).sum() + }; + assert!(total_of(&cols) > 1000); + let (cpu, pid) = (width_of(&cols, COL_CPU), width_of(&cols, COL_PID)); + assert!(fit_columns(&mut cols, 1000)); + assert!(total_of(&cols) <= 1000, "{}", total_of(&cols)); + assert_eq!((width_of(&cols, COL_CPU), width_of(&cols, COL_PID)), (cpu, pid), "the figures keep their width"); + assert!(width_of(&cols, COL_PATH) < 280 && width_of(&cols, COL_COMMAND_LINE) < 320); + // Room again: nothing changes, and the name has its minimum back. + assert!(!fit_columns(&mut cols, 2000)); + // Hopelessly narrow: every column at its floor, the name below its own minimum, nothing drawn past the edge. + assert!(fit_columns(&mut cols, 520)); + let at_floor = cols.iter().filter(|c| c.visible && !c.flex).all(|c| c.width <= c.min.max(COL_MIN_W)); + assert!(total_of(&cols) <= 520 || at_floor); + } + #[test] fn a_first_start_has_the_designed_columns() { let cols = columns(UiLang::EN, &[]); diff --git a/apps/tasks/src/ui/grouped.rs b/apps/tasks/src/ui/grouped.rs index 7cb353e6..262a3477 100644 --- a/apps/tasks/src/ui/grouped.rs +++ b/apps/tasks/src/ui/grouped.rs @@ -343,13 +343,14 @@ fn group_row( } let key = group_key(g.key); let many = g.members.len() > 1; - let open = many && (parts.all_open || parts.expanded.contains(&key)); + // A search builds every group open, a group of one process too: the filter only sees process rows. + let open = parts.all_open || (many && parts.expanded.contains(&key)); let mut e = blank(key, RowKind::Group(g.key)); e.section = Some(g.section); e.parent = Some(parent); e.vals = group_vals(v, procs, g); v.fill_heat(key, &mut e.vals); - e.expandable = many; + e.expandable = many || parts.all_open; e.expanded = open; let head = group_head(v, names, procs, g); let name = head.to_lowercase(); diff --git a/apps/tasks/src/ui/perf/layout.rs b/apps/tasks/src/ui/perf/layout.rs index e0d2fe1b..90c3d5c5 100644 --- a/apps/tasks/src/ui/perf/layout.rs +++ b/apps/tasks/src/ui/perf/layout.rs @@ -97,12 +97,14 @@ pub struct Geo { pub content_h: i64, } -/// The widths that decide the layout: the spec line, the hero's label, and each stat's label and value. +/// The widths that decide the layout: the spec line, the hero's figure (its label follows it) and label, and each +/// stat's label and value. pub fn signature(eng: &mut dyn TextEngine, scale: Scale, ts: f32, p: &Page) -> Vec { let cap = eng.font(TypeRole::Caption, None, scale, ts); let strong = eng.font(TypeRole::BodyStrong, None, scale, ts); let body = eng.font(TypeRole::Body, None, scale, ts); - let mut out = vec![eng.width(&p.spec, cap), eng.width(&p.hero_label, body)]; + let display = eng.font(TypeRole::Display, None, scale, ts); + let mut out = vec![eng.width(&p.spec, cap), eng.width(&p.hero, display), eng.width(&p.hero_label, body)]; for s in &p.stats { out.push(eng.width(&s.label, cap).max(eng.width(&s.value, strong))); } diff --git a/apps/tasks/src/ui/perf/mod.rs b/apps/tasks/src/ui/perf/mod.rs index 85dbf539..71383025 100644 --- a/apps/tasks/src/ui/perf/mod.rs +++ b/apps/tasks/src/ui/perf/mod.rs @@ -496,7 +496,9 @@ pub fn sync(s: &mut TasksScreen, cx: &mut EventCx) { None => Vec::new(), }; if sig != s.perf.sig { - cx.relayout(); + // The pane's contents move inside the page, which the list and the view below cover: its nodes are laid out + // again and nothing else is repainted. + cx.relayout_nodes(); } let (list, view) = s.perf.rects(); cx.damage(list); diff --git a/apps/tasks/src/ui/perf/paint.rs b/apps/tasks/src/ui/perf/paint.rs index 447f0196..c3fe6b34 100644 --- a/apps/tasks/src/ui/perf/paint.rs +++ b/apps/tasks/src/ui/perf/paint.rs @@ -59,7 +59,7 @@ fn paint_items(st: &PerfState, cx: &mut PaintCx, c: &ColorTokens, hc: bool) { if r.b <= g.list.t || r.t >= g.list.b { continue; } - if !cx.visible(r) { + if !cx.visible_ringed(r) { continue; } let id = PerfState::item_node(i); @@ -157,7 +157,7 @@ fn paint_pane(st: &PerfState, cx: &mut PaintCx, c: &ColorTokens, hc: bool) { } for (i, row) in page.who.iter().enumerate() { let Some(&rr) = g.who_rows.get(i) else { break }; - if !cx.visible(rr) { + if !cx.visible_ringed(rr) { continue; } let id = PerfState::who_node(i); diff --git a/apps/tasks/src/ui/rows.rs b/apps/tasks/src/ui/rows.rs index e8d33921..3b49567c 100644 --- a/apps/tasks/src/ui/rows.rs +++ b/apps/tasks/src/ui/rows.rs @@ -979,6 +979,7 @@ impl TableModel for TasksTable { out.set_text(CellKind::Text, &t(self.lang, k::TASKS_ROW_EFFICIENCY)); out.role = oled_ui::theme::TypeRole::Caption; out.fg = FgRole::Tertiary; + out.lead_glyph = Some(oled_ui::glyph::Glyph::CmdEfficiency); } } COL_CPU => self.metric(e, 0, out), @@ -1198,6 +1199,22 @@ mod tests { assert_eq!(text(&t, 1, COL_STATUS).0, "Efficiency", "and on for a process the book never saw"); } + #[test] + fn the_efficiency_status_has_its_leaf() { + let mut t = TasksTable::default(); + install(&mut t, vec![proc(1, Some(1.0), 1 << 20, None), proc(2, Some(1.0), 1 << 20, None)]); + let a = t.rows[0].key; + let mut acts = HashMap::from([(a, RowAct { eco: true, ..RowAct::default() })]); + t.set_acts(&mut acts); + let leaf = |row: usize| { + let mut out = CellOut::default(); + t.cell(row, COL_STATUS, &mut out); + out.lead_glyph + }; + assert_eq!(leaf(0), Some(oled_ui::glyph::Glyph::CmdEfficiency)); + assert_eq!(leaf(1), None, "no leaf on a row that is not in the mode"); + } + #[test] fn a_role_follows_the_name_and_never_a_label_that_has_a_tail() { let mut t = TasksTable::default(); diff --git a/apps/tasks/src/ui/run.rs b/apps/tasks/src/ui/run.rs index 51c92fed..5e195d02 100644 --- a/apps/tasks/src/ui/run.rs +++ b/apps/tasks/src/ui/run.rs @@ -107,6 +107,7 @@ impl RunState { s.field.set_text(cx, text, false); s.typed = text.to_string(); s.ok.set_enabled(!text.trim().is_empty()); + cx.damage_ringed(s.ok.rect()); } } @@ -218,6 +219,7 @@ impl Sheet { self.field.set_text(cx, text, true); self.typed = text.to_string(); self.ok.set_enabled(!text.trim().is_empty()); + cx.damage_ringed(self.ok.rect()); cx.set_focus(self.field.node_id()); } @@ -365,6 +367,7 @@ impl Sheet { FieldOut::Changed => { self.typed = self.field.text().to_string(); self.ok.set_enabled(!self.typed.trim().is_empty()); + cx.damage_ringed(self.ok.rect()); self.close_list(cx); } FieldOut::Committed(_) => return self.run_out(), @@ -379,12 +382,12 @@ impl Sheet { // ---- the screen's hooks -/// RUN_NEW (the button and Ctrl+N): opens the sheet on Processes when nothing else is open. +/// RUN_NEW (the button and Ctrl+N): opens the sheet on Processes and Details when nothing else is open. pub fn on_command(s: &mut TasksScreen, cx: &mut EventCx, id: CommandId) { if id != RUN_NEW || s.p.run.sheet.is_some() || s.notices.dialog_open() { return; } - if s.chrome.page() != crate::model::view::Page::Processes { + if !super::details::hosts_band(s.chrome.page()) { return; } let sheet = Sheet::new(cx.lang(), s.deps.state.run_history(), cx.focused()); diff --git a/apps/tasks/src/ui/screen.rs b/apps/tasks/src/ui/screen.rs index ff846294..4f5093cd 100644 --- a/apps/tasks/src/ui/screen.rs +++ b/apps/tasks/src/ui/screen.rs @@ -479,7 +479,7 @@ impl TasksScreen { // Every menu ends with a pick or a close. Event::Command(_) | Event::ListPicked { .. } | Event::MenuClosed(_) if menu_was_open => { order::on_menu_closed(&mut self.p.order); - self.p.band.on_menu_closed(); + self.p.band.on_menu_closed(cx); } Event::CloseRequested => return Reply::Close, _ => {} @@ -719,11 +719,14 @@ impl TasksScreen { } search::filter(&self.v, &mut self.p.search, &mut self.rows); self.chrome.set_count(cx, search::count(&self.p.search)); + search::sync_empty(&mut self.p.search, cx); self.chrome.set_totals(cx, self.totals()); order::apply(&self.v, &mut self.p.order, &mut self.rows, now); self.v.set_ended(order::ghost_names(&self.p.order)); + self.p.actions.set_flat(self.chrome.page() == Page::Details); actions::note_groups(&mut self.p.actions, self.p.grouped.grouping()); actions::decorate(&self.v, &mut self.p.actions, &mut self.rows, now); + details::refit(self, cx); strip::sync(self, cx); perf::sync(self, cx); // The facts the rows show beyond the sample, published with them. diff --git a/apps/tasks/src/ui/search.rs b/apps/tasks/src/ui/search.rs index 0eb4db56..40e2dc87 100644 --- a/apps/tasks/src/ui/search.rs +++ b/apps/tasks/src/ui/search.rs @@ -76,6 +76,8 @@ pub struct Matcher { /// The empty state: its two lines' rects and the button, while the list is empty under a query. empty: Option<(RectP, RectP)>, clear_button: Option