From 36c6da37afe01fe3f20cd58e778cdee7ba3ddbdb Mon Sep 17 00:00:00 2001 From: Yash Bavadiya Date: Sat, 28 Nov 2026 00:53:29 +0530 Subject: [PATCH 1/3] feat(gui): drag files out of the archive --- Cargo.lock | 3 + README.md | 2 + crates/gui/Cargo.toml | 53 ++- crates/gui/README.md | 1 + crates/gui/src/backend.rs | 4 + crates/gui/src/drag.rs | 413 ++++++++++++++++++ crates/gui/src/entries.rs | 67 +++ crates/gui/src/lib.rs | 1 + crates/gui/src/main_window.rs | 134 +++++- crates/gui/src/platform/linux.rs | 12 + crates/gui/src/platform/macos.rs | 241 +++++++++- crates/gui/src/platform/windows.rs | 206 +++++++++ crates/gui/tests/ui.rs | 82 +++- .../es/LC_MESSAGES/hatchzip-gui.po | 6 + .../hi/LC_MESSAGES/hatchzip-gui.po | 6 + .../tr/LC_MESSAGES/hatchzip-gui.po | 6 + .../zh_CN/LC_MESSAGES/hatchzip-gui.po | 6 + crates/gui/ui/main-window.slint | 48 +- crates/gui/ui/messages.slint | 2 + 19 files changed, 1274 insertions(+), 19 deletions(-) create mode 100644 crates/gui/src/drag.rs diff --git a/Cargo.lock b/Cargo.lock index 85d5c2f0..d4bc6e3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2027,6 +2027,7 @@ name = "hatchzip-gui" version = "0.1.10" dependencies = [ "anyhow", + "block2 0.6.2", "clap", "hatchzip-core", "hatchzip-shell", @@ -2043,6 +2044,8 @@ dependencies = [ "slint-build", "sys-locale", "tempfile", + "windows", + "windows-core", "winresource", "zip", ] diff --git a/README.md b/README.md index ce34a826..20b3cd1e 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ HatchZip shows whether the files will fit before it changes anything. The archiv To take only some files or folders out, select them in the app's contents list (Ctrl+click or Cmd+click adds a row, Shift+click a range, Space the row under the cursor), then choose **Extract selected…** and the destination folder. Only those are extracted, and the archive is always kept. +On Windows and macOS, rows can also be dragged from the contents list into a folder in Explorer or the Finder. Dragging a selected row takes the whole selection; any other row goes alone. The archive is kept, as with **Extract selected…**. On Windows the entries are extracted when they are dropped, into a temporary folder that Explorer copies from and that is removed when HatchZip closes; up to 1 GB can be dragged at once. On macOS the Finder has each entry written straight into the folder it was dropped in. Linux has no drag out yet. + To keep the archive when there is room for both, choose **Extract here (keep archive)** in the right-click menu. To always keep archives, as other extractors do, clear **Remove the archive during extraction** in the app's [settings](#settings); every right-click entry then keeps the archive too. That is a normal extraction: the archive is not changed, and space is required for all extracted files. ### Settings diff --git a/crates/gui/Cargo.toml b/crates/gui/Cargo.toml index 866cb59f..768a9f34 100644 --- a/crates/gui/Cargo.toml +++ b/crates/gui/Cargo.toml @@ -39,12 +39,57 @@ slint = { version = "~1.18.1", default-features = false, features = [ "unstable-winit-030", ] } -# Receives the files Finder opens with HatchZip; already in the tree through -# winit, at the same versions. +# Receives the files Finder opens with HatchZip, and drags entries out of the +# contents tree as file promises; already in the tree through winit, at the +# same versions. [target."cfg(target_os = \"macos\")".dependencies] +block2 = "0.6.2" objc2 = "0.6.4" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator", "NSURL"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = [ + "std", + "block2", + "NSApplication", + "NSDragging", + "NSDraggingItem", + "NSDraggingSession", + "NSEvent", + "NSFilePromiseProvider", + "NSImage", + "NSPasteboard", + "NSResponder", + "NSView", + "NSWorkspace", +] } +objc2-foundation = { version = "0.3.2", default-features = false, features = [ + "std", + "NSArray", + "NSDictionary", + "NSEnumerator", + "NSError", + "NSGeometry", + "NSObject", + "NSOperation", + "NSString", + "NSURL", +] } + +# Drags entries out of the contents tree into Explorer through OLE; already +# in the tree through Slint's accessibility and font crates, at this version. +[target."cfg(windows)".dependencies] +windows = { version = "0.62.2", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_System_Com", + "Win32_System_Com_StructuredStorage", + "Win32_System_Memory", + "Win32_System_Ole", + "Win32_System_SystemServices", + "Win32_UI_Shell", + "Win32_UI_Shell_Common", + "Win32_UI_WindowsAndMessaging", +] } +# The `implement` macro for the drop source names this crate directly. +windows-core = "0.62.2" [features] # RAR archives, through UnRAR's C++ source and its own license; see diff --git a/crates/gui/README.md b/crates/gui/README.md index 688b4b0c..d7a228d9 100644 --- a/crates/gui/README.md +++ b/crates/gui/README.md @@ -24,6 +24,7 @@ The task forms are what file manager menus call, and installers run the two shel | Existing files | When files the archive would write already exist in the destination, the main window and the task window ask once, with the number of files, whether to replace them, before anything is touched. "Replace" extracts as `hatchzip extract --replace` does; "Cancel" stops with nothing modified. Settings, "When a file already exists" can answer for every file instead: Replace as `--replace`, Skip as `--skip-existing`. A resumed run follows its journal and does not ask again. | | Updates | Help > "Check for updates" opens the latest release page on GitHub in the browser. The app makes no network connections itself. | | Giving up | A paused or partially extracted archive offers "Restore archive", which runs `hatchzip_core::restore` on a worker thread. Not for an extraction that keeps its archive, which was never changed. | +| Dragging out | Rows of the contents tree dragged into Explorer or the Finder are extracted there, with the archive kept, through the engine as for "Extract selected…" (`src/drag.rs`). A drag starts once a press moves 5 px; a selected row takes the selection, another row goes alone, and the dragged rows are dimmed until the drop. Only for an archive nothing was extracted from, while nothing runs; a run that changes the archive waits for a drop still being written. Windows (`platform/windows.rs`): OLE `DoDragDrop` with a CF_HDROP of paths under `%TEMP%\hatchzip-drag-`, extracted when the button is released over a folder that accepts the files, before Explorer copies them; the window waits for that, so a drag is limited to 1 GB, and the folder is removed when the app closes (or a day later, after a crash). macOS (`platform/macos.rs`): one `NSFilePromiseProvider` per row; the Finder asks for each once it knows the folder, and it is extracted next to it, on a thread of its own, and moved into place. Linux: winit has no drag source, so the gesture does nothing. | | Keeping the archive | "Remove the archive during extraction", on by default. Cleared, the space plan is for every file, in bold next to what removing the archive would need, and the panel says when only removing it fits. A half-extracted archive continues the way it started. | | Settings | A window of its own (`ui/settings-window.slint`, wired in `main_window.rs`), opened from File > Settings… or the gear, one instance. Sections: General (language, appearance, after extracting, closing the progress window), Extraction (removing the archive, verifying first, reserved space, default destination, existing files), Integration (the right-click menu, where `platform::SHELL_MENU`), Advanced (the file's path, Reset). Every change applies and is saved at once, and the main window's reserve, verify and remove controls follow it both ways. Saved to `~/.config/hatchzip/settings.json`, `%APPDATA%\HatchZip\settings.json` or `~/Library/Application Support/HatchZip/settings.json`. A missing or broken file means the defaults; a value this version can't read means the default for that one setting. The right-click menu switch is hidden on macOS, where hatchzip-shell can't add Finder entries yet. | | Identity | App id and X11 class `io.github.xevrion.hatchzip`, matching the desktop file. On Windows `build.rs` embeds `assets/icon/hatchzip.ico` and the version into the exe. | diff --git a/crates/gui/src/backend.rs b/crates/gui/src/backend.rs index 30949613..65c3eba3 100644 --- a/crates/gui/src/backend.rs +++ b/crates/gui/src/backend.rs @@ -52,6 +52,10 @@ impl CustomApplicationHandler for Handler { // winit 0.30 reports dropped files on Windows, macOS and X11 only; // on Wayland nothing arrives here and the Open button is the way in. match event { + // Entries dragged out of the tree and back onto the window, from + // the folder they were extracted to; not an archive to open. + WindowEvent::DroppedFile(path) | WindowEvent::HoveredFile(path) + if crate::drag::is_ours(path) => {} WindowEvent::DroppedFile(path) => { if let Some(f) = &*self.0.on_hover.borrow() { f(false); diff --git a/crates/gui/src/drag.rs b/crates/gui/src/drag.rs new file mode 100644 index 00000000..6f2f28fe --- /dev/null +++ b/crates/gui/src/drag.rs @@ -0,0 +1,413 @@ +//! Dragging entries out of the contents tree into Explorer or the Finder. +//! +//! The entries are extracted the way "Extract selected…" extracts them: by +//! the engine, with the archive kept, so nothing here can change the archive +//! or write outside the folder it is given. What differs is where they go +//! and where the run keeps its journal: a drag never has a journal next to +//! the archive, so it can't be mistaken for a run to resume, and it never +//! starts while one is there. +//! +//! The platform code decides when the extraction runs. On Windows it is +//! when the button is released over a folder that takes the files, into a +//! folder of this process under the system's temporary folder, which the +//! file manager then copies from; those folders go when the app closes. On +//! macOS the Finder asks for each entry once it knows the folder, and the +//! entry is extracted next to it and moved into place. + +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::time::{Duration, SystemTime}; + +use anyhow::{Context, Result, bail}; +use hatchzip_core::archive::storage::Reads; +use hatchzip_core::engine::{Outcome, Progress, Run}; +use hatchzip_core::journal::Paths; +use hatchzip_core::session::{self, State}; + +/// Every folder a drag writes has a name starting with this, so a drop of +/// one of them back onto the window can be told apart from a real archive. +const PREFIX: &str = "hatchzip-drag-"; + +/// What the entries are extracted from. +#[derive(Clone)] +pub struct Source { + pub archive: PathBuf, + /// The password the window opened the archive with, if it needed one. + pub password: Option, + /// Free space the extraction leaves alone, as for any other. + pub keep_free: u64, +} + +/// One row being dragged: its path inside the archive. +pub struct Dragged { + pub path: PathBuf, + /// For the icon and the file type the Finder is promised. + #[allow(dead_code)] + pub dir: bool, +} + +pub struct Drag { + pub source: Source, + pub entries: Vec, +} + +/// The disk the entries would go to has no room for them. +#[derive(Debug)] +pub struct NoSpace; + +impl std::fmt::Display for NoSpace { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("there is not enough free space for the dragged entries") + } +} + +impl std::error::Error for NoSpace {} + +static BUSY: AtomicUsize = AtomicUsize::new(0); + +/// Held while entries are being extracted for a drop. +struct Busy; + +impl Busy { + fn start() -> Self { + BUSY.fetch_add(1, Ordering::SeqCst); + Self + } +} + +impl Drop for Busy { + fn drop(&mut self) { + BUSY.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Entries are being extracted for a drop right now. The extraction only +/// reads the archive, so a run that changes it must wait: on macOS the +/// Finder's request is served on a thread of its own, after the drag ended. +pub fn busy() -> bool { + BUSY.load(Ordering::SeqCst) > 0 +} + +/// The folder this process extracts dragged entries into, under the system's +/// temporary folder. +fn root() -> PathBuf { + std::env::temp_dir().join(format!("{PREFIX}{}", std::process::id())) +} + +/// Whether `path` lies in a folder a drag wrote. +pub fn is_ours(path: &Path) -> bool { + path.components().any(|c| match c { + Component::Normal(name) => name + .to_str() + .is_some_and(|n| n.trim_start_matches('.').starts_with(PREFIX)), + _ => false, + }) +} + +/// A new, empty folder for one drag, in this process's folder. +#[allow(dead_code)] // Only the platforms that extract before the drop use it. +pub fn new_work() -> Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let work = root().join(NEXT.fetch_add(1, Ordering::Relaxed).to_string()); + if work.exists() { + fs::remove_dir_all(&work).with_context(|| format!("emptying {}", work.display()))?; + } + fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?; + Ok(work) +} + +/// Where [`extract`] into `work` puts the entries. +pub fn output(work: &Path) -> PathBuf { + work.join("out") +} + +/// Where `entry` is once [`extract`] into `work` is done, with the +/// system's separators: Explorer takes `a/b` for a name, not a path. +pub fn extracted(work: &Path, entry: &Path) -> PathBuf { + let mut path = output(work); + path.extend(entry.components().filter_map(|c| match c { + Component::Normal(n) => Some(n), + _ => None, + })); + path +} + +/// Extracts `entries` from the archive, and everything inside the folders +/// among them, into [`output`] of `work`, keeping the archive. The run's +/// journal goes in `work` too and is gone once it is done. +pub fn extract(source: &Source, entries: &[PathBuf], work: &Path) -> Result { + let _busy = Busy::start(); + let (primary, beside) = session::locate(&source.archive)?; + // That run may be shortening the archive, and its journal is what it + // trusts; a drag must not read the one or touch the other. + if beside.exists() { + bail!( + "this archive is partially extracted. Resume or restore it first, then drag the \ + entries again. Nothing was modified" + ); + } + fs::create_dir_all(work).with_context(|| format!("creating {}", work.display()))?; + let paths = Paths { + archive: primary.clone(), + journal: work.join("journal"), + tail: work.join("tail"), + folders: work.join("folders"), + stub: None, + }; + let reads = Arc::new(Reads::default()); + // Read-only: no lock, so the window's own handle on it stays valid, + // and nothing in it can be written. + let state = session::open( + &primary, + &paths, + Some(output(work)), + Some(entries), + false, + source.password.as_deref(), + &reads, + )?; + let State::Fresh(job, out) = state else { + bail!( + "this archive is partially extracted. Resume or restore it first. Nothing was modified" + ); + }; + job.check_password()?; + let plan = session::plan(&job, &out, false, source.keep_free, true)?; + if !plan.fits { + return Err(NoSpace.into()); + } + let journal = session::begin(&job, &paths, out.clone(), true, None)?; + let stop = AtomicBool::new(false); + let run = Run { + job, + journal, + paths, + stop: &stop, + progress: Progress { + on_bytes: Box::new(|_| {}), + on_commit: Box::new(|_| {}), + }, + keep_free: source.keep_free, + }; + match run.execute()? { + Outcome::Finished(_) => Ok(out), + Outcome::Paused => bail!("the extraction of the dragged entries stopped"), + } +} + +/// Extracts the dragged entries into `work` and checks that each is where +/// the file manager was told it would be. +#[allow(dead_code)] // Only the platforms that extract before the drop use it. +pub fn extract_all(drag: &Drag, work: &Path) -> Result<()> { + let entries: Vec = drag.entries.iter().map(|e| e.path.clone()).collect(); + extract(&drag.source, &entries, work)?; + for e in &drag.entries { + let path = extracted(work, &e.path); + if !path.exists() { + bail!("{} was not extracted", e.path.display()); + } + } + Ok(()) +} + +/// Writes `entry` to `dest`, a path that does not exist yet, as the Finder +/// asks for a file promise: extracts it into a hidden folder next to `dest`, +/// on the same disk, then moves it into place and removes the folder. +#[allow(dead_code)] // Only the platforms with file promises use it. +pub fn write_promise(source: &Source, entry: &Path, dest: &Path) -> Result<()> { + static NEXT: AtomicU64 = AtomicU64::new(0); + if dest.symlink_metadata().is_ok() { + bail!("{} already exists", dest.display()); + } + let Some(parent) = dest.parent() else { + bail!("{} has no folder to go in", dest.display()); + }; + let work = parent.join(format!( + ".{PREFIX}{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let result = extract(source, &[entry.to_path_buf()], &work).and_then(|_| { + let from = extracted(&work, entry); + fs::rename(&from, dest) + .with_context(|| format!("moving {} to {}", from.display(), dest.display())) + }); + let cleaned = fs::remove_dir_all(&work); + result?; + cleaned.with_context(|| format!("removing {}", work.display())) +} + +/// Removes this process's folder of dragged entries. Called when the app +/// closes: the file manager may still be copying from it until then. +pub fn cleanup() { + let _ = fs::remove_dir_all(root()); +} + +/// Removes the folders of dragged entries an earlier run of the app could +/// not, after a crash. A day old is long past any copy from them. +pub fn clean_stale() { + clean_stale_in(&std::env::temp_dir(), Duration::from_secs(24 * 60 * 60)); +} + +fn clean_stale_in(dir: &Path, age: Duration) { + let Ok(read) = fs::read_dir(dir) else { return }; + let ours = root(); + for entry in read.flatten() { + let path = entry.path(); + let named = entry + .file_name() + .to_str() + .is_some_and(|n| n.starts_with(PREFIX)); + let old = entry + .metadata() + .and_then(|m| m.modified()) + .is_ok_and(|t| SystemTime::now().duration_since(t).unwrap_or_default() >= age); + let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); + if named && old && is_dir && path != ours { + let _ = fs::remove_dir_all(&path); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + fn make_zip(dir: &Path) -> PathBuf { + let path = dir.join("game.zip"); + let mut w = zip::ZipWriter::new(fs::File::create(&path).unwrap()); + let opts = zip::write::SimpleFileOptions::default(); + w.add_directory("game/", opts).unwrap(); + w.add_directory("game/data/", opts).unwrap(); + w.start_file("game/readme.txt", opts).unwrap(); + w.write_all(b"hello\n").unwrap(); + for i in 0..3u8 { + w.start_file(format!("game/data/{i}.bin"), opts).unwrap(); + w.write_all(&vec![i; 10_000]).unwrap(); + } + w.finish().unwrap(); + path + } + + fn source(archive: &Path) -> Source { + Source { + archive: archive.to_path_buf(), + password: None, + keep_free: 0, + } + } + + #[test] + fn extracts_only_the_dragged_entries_and_keeps_the_archive() { + let dir = tempfile::tempdir().unwrap(); + let archive = make_zip(dir.path()); + let before = fs::read(&archive).unwrap(); + let work = dir.path().join(format!("{PREFIX}test")); + let drag = Drag { + source: source(&archive), + entries: vec![ + Dragged { + path: "game/readme.txt".into(), + dir: false, + }, + Dragged { + path: "game/data".into(), + dir: true, + }, + ], + }; + extract_all(&drag, &work).unwrap(); + assert_eq!( + fs::read(extracted(&work, Path::new("game/readme.txt"))).unwrap(), + b"hello\n" + ); + for i in 0..3u8 { + assert_eq!( + fs::read(extracted(&work, Path::new(&format!("game/data/{i}.bin")))).unwrap(), + vec![i; 10_000] + ); + } + assert_eq!( + fs::read(&archive).unwrap(), + before, + "the archive is untouched" + ); + let (_, beside) = session::locate(&archive).unwrap(); + assert!(!beside.exists(), "no journal next to the archive"); + for side in ["journal", "tail", "folders"] { + assert!(!work.join(side).exists(), "{side} is removed"); + } + assert!(is_ours(&extracted(&work, Path::new("game/readme.txt")))); + assert!(!is_ours(&archive)); + } + + #[test] + fn a_promise_moves_the_entry_into_place_and_leaves_nothing_else() { + let dir = tempfile::tempdir().unwrap(); + let archive = make_zip(dir.path()); + let before = fs::read(&archive).unwrap(); + let dest_dir = dir.path().join("Desktop"); + fs::create_dir(&dest_dir).unwrap(); + let dest = dest_dir.join("data"); + write_promise(&source(&archive), Path::new("game/data"), &dest).unwrap(); + assert_eq!(fs::read(dest.join("1.bin")).unwrap(), vec![1; 10_000]); + let names: Vec<_> = fs::read_dir(&dest_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["data"], "the hidden folder is gone"); + assert_eq!(fs::read(&archive).unwrap(), before); + // Never over something already there. + let err = write_promise(&source(&archive), Path::new("game/data"), &dest).unwrap_err(); + assert!(err.to_string().contains("already exists"), "{err:#}"); + assert_eq!(fs::read(dest.join("1.bin")).unwrap(), vec![1; 10_000]); + } + + #[test] + fn an_entry_not_in_the_archive_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let archive = make_zip(dir.path()); + let work = dir.path().join("work"); + assert!(extract(&source(&archive), &["../outside".into()], &work).is_err()); + assert!(extract(&source(&archive), &["missing".into()], &work).is_err()); + assert!(!dir.path().join("outside").exists()); + } + + #[test] + fn a_partially_extracted_archive_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let archive = make_zip(dir.path()); + let (_, beside) = session::locate(&archive).unwrap(); + fs::write(&beside.journal, b"{}").unwrap(); + let err = extract(&source(&archive), &["game".into()], &dir.path().join("w")).unwrap_err(); + assert!(err.to_string().contains("partially extracted"), "{err:#}"); + assert_eq!(fs::read(&beside.journal).unwrap(), b"{}"); + } + + #[test] + fn stale_folders_go_and_recent_ones_stay() { + let dir = tempfile::tempdir().unwrap(); + let stale = dir.path().join(format!("{PREFIX}1")); + let other = dir.path().join("unrelated"); + fs::create_dir(&stale).unwrap(); + fs::create_dir(&other).unwrap(); + clean_stale_in(dir.path(), Duration::from_secs(3600)); + assert!(stale.exists(), "recent"); + assert!(other.exists()); + clean_stale_in(dir.path(), Duration::ZERO); + assert!(!stale.exists()); + assert!(other.exists(), "only the app's folders go"); + } + + #[test] + fn extracted_paths_use_the_systems_separators() { + let work = Path::new("w"); + let mut expected = output(work); + expected.push("a"); + expected.push("b.txt"); + assert_eq!(extracted(work, Path::new("a/b.txt")), expected); + } +} diff --git a/crates/gui/src/entries.rs b/crates/gui/src/entries.rs index 31f2e784..977b24de 100644 --- a/crates/gui/src/entries.rs +++ b/crates/gui/src/entries.rs @@ -259,6 +259,30 @@ impl Entries { .collect() } + /// What dragging the row at `row` takes: the whole selection when the + /// row is part of it, as file managers do, and the row alone otherwise. + /// Each path comes with whether it is a folder, then the size of it all + /// and whether it was the selection. + pub fn dragged(&self, row: usize) -> Option<(Vec<(String, bool)>, u64, bool)> { + let &(node, _) = self.visible.get(row)?; + let chosen = self.nodes[node].selected || self.inside_chosen(node); + let picked: Vec = if chosen { + (1..self.nodes.len()) + .filter(|&i| self.nodes[i].selected && !self.inside_chosen(i)) + .collect() + } else { + vec![node] + }; + let size = picked + .iter() + .fold(0u64, |sum, &i| sum.saturating_add(self.nodes[i].size)); + let paths = picked + .iter() + .map(|&i| (self.path(i), self.nodes[i].dir)) + .collect(); + Some((paths, size, chosen)) + } + fn inside_chosen(&self, mut node: usize) -> bool { while node != 0 { node = self.nodes[node].parent; @@ -355,6 +379,11 @@ impl EntriesModel { self.tree.borrow().chosen() } + /// See [`Entries::dragged`]. + pub fn dragged(&self, row: usize) -> Option<(Vec<(String, bool)>, u64, bool)> { + self.tree.borrow().dragged(row) + } + pub fn toggle(&self, row: usize, expand: Option) { let change = self.tree.borrow_mut().toggle(row, expand); if let Some((added, count)) = change { @@ -587,6 +616,44 @@ mod tests { assert!(model.chosen().is_empty()); } + #[test] + fn dragging_takes_the_selection_or_the_row_alone() { + let model = EntriesModel::new(Entries::new(vec![ + file("a.txt", 1), + file("b.txt", 2), + file("d/e.txt", 4), + ])); + // d, a.txt, b.txt; nothing chosen drags the row under the pointer. + assert_eq!( + model.dragged(1), + Some((vec![("a.txt".to_string(), false)], 1, false)) + ); + assert_eq!( + model.dragged(0), + Some((vec![("d".to_string(), true)], 4, false)) + ); + model.choose(0, 1); + model.choose(2, 1); + let (mut paths, size, chosen) = model.dragged(2).unwrap(); + paths.sort(); + assert_eq!( + paths, + [("b.txt".to_string(), false), ("d".to_string(), true)] + ); + assert_eq!((size, chosen), (6, true)); + // A row outside the selection goes alone, and leaves it as it is. + assert_eq!( + model.dragged(1), + Some((vec![("a.txt".to_string(), false)], 1, false)) + ); + assert_eq!(model.chosen().len(), 2); + // A row inside a chosen folder takes the selection with it. + model.toggle(0, Some(true)); + assert_eq!(model.row_data(1).unwrap().path, "d/e.txt"); + assert!(model.dragged(1).unwrap().2); + assert_eq!(model.dragged(99), None); + } + #[test] fn large_archive_starts_with_only_visible_rows() { let entries = (0..100_000) diff --git a/crates/gui/src/lib.rs b/crates/gui/src/lib.rs index 036acc93..5d35fd5a 100644 --- a/crates/gui/src/lib.rs +++ b/crates/gui/src/lib.rs @@ -4,6 +4,7 @@ pub mod args; pub mod backend; +mod drag; mod entries; pub mod locale; pub mod main_window; diff --git a/crates/gui/src/main_window.rs b/crates/gui/src/main_window.rs index f3ca570c..2bc273f1 100644 --- a/crates/gui/src/main_window.rs +++ b/crates/gui/src/main_window.rs @@ -12,10 +12,12 @@ use hatchzip_core::archive::storage::Reads; use hatchzip_core::engine::Job; use hatchzip_core::human; use hatchzip_core::session::{self, State, display_name}; +use slint::platform::{PointerEventButton, WindowEvent}; use slint::winit_030::WinitWindowAccessor; -use slint::{CloseRequestResponse, ComponentHandle, ModelRc, Timer, TimerMode}; +use slint::{CloseRequestResponse, ComponentHandle, LogicalPosition, ModelRc, Timer, TimerMode}; use crate::backend::Drops; +use crate::drag::{self, Drag, Dragged}; use crate::entries::{self, Entries, EntriesModel}; use crate::runner::Runner; use crate::settings::{self, AfterExtracting, Appearance, Destination, Settings}; @@ -24,8 +26,8 @@ use crate::task::Task; use crate::text::{self, gb_text, parse_gb, plan_view}; use crate::work::{Request, sentence}; use crate::{ - AboutWindow, MainWindow, Messages, Mode, Palette, PlanView, Screen, SettingsWindow, TaskView, - Theme, locale, platform, shell, + AboutWindow, MainWindow, Messages, Mode, Palette, Phase, PlanView, Screen, SettingsWindow, + TaskView, Theme, locale, platform, shell, }; const REPO: &str = "https://github.com/xevrion/hatchzip"; @@ -202,11 +204,15 @@ struct App { /// Answers the folder picker of "Extract selected…" in tests. type FolderAnswer = Box Option>; +/// Takes the paths of a drag out of the tree in tests. +type DragWatch = Box)>; thread_local! { static APP: RefCell>> = const { RefCell::new(None) }; /// Answers the folder picker of "Extract selected…" instead of a dialog. static PICKED: RefCell> = const { RefCell::new(None) }; + /// Sees a drag out of the tree instead of the system. + static DRAGGED: RefCell> = const { RefCell::new(None) }; } /// Makes "Extract selected…" take its folder from `answer` instead of @@ -215,6 +221,42 @@ pub fn answer_folder_picker(answer: impl Fn() -> Option + 'static) { PICKED.with(|p| *p.borrow_mut() = Some(Box::new(answer))); } +/// Hands the paths of every drag out of the tree to `watch` instead of +/// starting one with the system, which a test without a display can't +/// drop anywhere. +pub fn watch_drags(watch: impl Fn(Vec) + 'static) { + DRAGGED.with(|d| *d.borrow_mut() = Some(Box::new(watch))); +} + +/// The system's drag of entries out of the tree is over. It kept the +/// button's release from the window, which still holds the press, so the +/// release is given back where it can't click anything. +pub(crate) fn drag_ended() { + post(|app| { + let ui = app.ui(); + ui.set_drag_row(-1); + ui.window().dispatch_event(WindowEvent::PointerReleased { + position: LogicalPosition::new(-1.0, -1.0), + button: PointerEventButton::Left, + }); + }); +} + +/// Extracting entries dragged out of the tree failed; from any thread. +pub(crate) fn drag_failed(error: anyhow::Error) { + post(move |app| { + let ui = app.ui(); + let text = if error.is::() { + ui.global::() + .invoke_task_heading(Phase::NoSpace, false, false, "".into()) + .to_string() + } else { + sentence(&format!("{error:#}")) + }; + app.notify(&text, true); + }); +} + /// Runs `f` on the UI thread with the app, from any thread. fn post(f: impl FnOnce(&Rc) + Send + 'static) { let _ = slint::invoke_from_event_loop(move || { @@ -233,8 +275,12 @@ pub fn run(archive: Option, drops: Rc) -> Result<()> { // Opening only reads, so it needn't wait for the first frame like a // task does; this only arms the switch to software drawing. crate::backend::when_drawn(ui.window(), || {}); - ui.run()?; + std::thread::spawn(drag::clean_stale); + let ran = ui.run(); APP.with(|a| a.borrow_mut().take()); + // The file manager copies dropped entries from there; it is done by now. + drag::cleanup(); + ran?; Ok(()) } @@ -255,6 +301,7 @@ pub fn build( ui.set_remove_archive(!settings.keep_archive); ui.set_supports_rar(hatchzip_core::archive::RAR_SUPPORTED); ui.set_shell_menu_available(platform::SHELL_MENU); + ui.set_drag_out_available(platform::DRAG_OUT); show_shell_menu_label(&ui); // Left alone when it follows the system, so the style's own binding to // the system's setting stays in place. @@ -418,6 +465,8 @@ fn wire(ui: &MainWindow, app: &Rc) { ); }); let a = app.clone(); + ui.on_drag_entries(move |row| a.drag_out(row)); + let a = app.clone(); ui.on_extract_selected(move || a.extract_selected()); let a = app.clone(); ui.on_open_archive(move || a.pick_archive()); @@ -1106,6 +1155,9 @@ impl App { let Some(archive) = self.archive.borrow().clone() else { return; }; + if self.wait_for_drop() { + return; + } self.runner.clear_queue(); let ui = self.ui(); let output = self.output.borrow().clone(); @@ -1191,6 +1243,7 @@ impl App { if self.runner.running() || self.mode.get() != Mode::Fresh || self.archive.borrow().as_deref() != Some(archive) + || self.wait_for_drop() { return; } @@ -1210,6 +1263,79 @@ impl App { self.start_extraction(task, request); } + /// Entries dragged out are still being extracted from the archive, which + /// a run must not change or journal under them: says so and returns true. + fn wait_for_drop(&self) -> bool { + if !drag::busy() { + return false; + } + let text = self.ui().global::().invoke_drag_busy(); + self.notify(&text, true); + true + } + + /// The press on `row` moved far enough to be a drag: hands the rows it + /// takes to the system, to drop in a folder. Only for an archive nothing + /// was extracted from yet, while nothing runs, like "Extract selected…". + fn drag_out(&self, row: i32) { + if !platform::DRAG_OUT && DRAGGED.with(|d| d.borrow().is_none()) { + return; + } + if self.runner.running() || self.mode.get() != Mode::Fresh { + return; + } + let Some(archive) = self.archive.borrow().clone() else { + return; + }; + let picked = match (self.entries.borrow().as_ref(), usize::try_from(row)) { + (Some(tree), Ok(index)) => tree.dragged(index), + _ => None, + }; + let Some((paths, size, chosen)) = picked else { + return; + }; + let ui = self.ui(); + if let Some(limit) = platform::DRAG_LIMIT + && size > limit + { + let text = ui + .global::() + .invoke_drag_too_large(human(limit).into()); + self.notify(&text, true); + return; + } + ui.set_drag_chosen(chosen); + ui.set_drag_row(row); + let watched = DRAGGED.with(|d| match d.borrow().as_ref() { + Some(watch) => { + watch(paths.iter().map(|(p, _)| p.clone()).collect()); + true + } + None => false, + }); + if watched { + drag_ended(); + return; + } + let drag = Drag { + source: drag::Source { + archive, + password: self.password.borrow().clone(), + keep_free: self.keep_free.get(), + }, + entries: paths + .into_iter() + .map(|(path, dir)| Dragged { + path: PathBuf::from(path), + dir, + }) + .collect(), + }; + if !platform::drag_out(ui.window(), drag) { + drag_ended(); + } + } + /// Queues the archives this run left in the output, each into its own /// folder next to it. Only the files the run wrote are considered, so a /// file that was already there is never extracted as if it were new. diff --git a/crates/gui/src/platform/linux.rs b/crates/gui/src/platform/linux.rs index 46329911..11a785f4 100644 --- a/crates/gui/src/platform/linux.rs +++ b/crates/gui/src/platform/linux.rs @@ -27,3 +27,15 @@ pub fn config_dir() -> Option { /// File managers pass the files as arguments here, so there is nothing to /// listen for. pub fn forward_opened_files(_on_open: impl Fn(PathBuf) + 'static) {} + +/// winit has no way to start a drag from the window here, on X11 or +/// Wayland, so rows can't be dragged out; "Extract selected…" does it. +pub const DRAG_OUT: bool = false; + +/// Nothing is dragged, so there is nothing to limit. +pub const DRAG_LIMIT: Option = None; + +/// Never called while [`DRAG_OUT`] is false; starts nothing. +pub fn drag_out(_window: &slint::Window, _drag: crate::drag::Drag) -> bool { + false +} diff --git a/crates/gui/src/platform/macos.rs b/crates/gui/src/platform/macos.rs index 93897726..e4c0a119 100644 --- a/crates/gui/src/platform/macos.rs +++ b/crates/gui/src/platform/macos.rs @@ -1,11 +1,24 @@ use std::cell::RefCell; use std::path::PathBuf; +use block2::DynBlock; use objc2::ffi; -use objc2::runtime::{AnyClass, AnyObject, Imp, Sel}; -use objc2::sel; -use objc2_app_kit::NSApplication; -use objc2_foundation::{MainThreadMarker, NSArray, NSURL}; +use objc2::rc::Retained; +use objc2::runtime::{AnyClass, AnyObject, Imp, NSObject, NSObjectProtocol, ProtocolObject, Sel}; +use objc2::{AnyThread, DefinedClass, MainThreadOnly, define_class, msg_send, sel}; +use objc2_app_kit::{ + NSApplication, NSDragOperation, NSDraggingContext, NSDraggingItem, NSDraggingSession, + NSDraggingSource, NSEventType, NSFilePromiseProvider, NSFilePromiseProviderDelegate, NSView, + NSWorkspace, +}; +use objc2_foundation::{ + MainThreadMarker, NSArray, NSCocoaErrorDomain, NSError, NSOperationQueue, NSPoint, NSRect, + NSSize, NSString, NSURL, +}; +use slint::winit_030::WinitWindowAccessor; +use slint::winit_030::winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + +use crate::drag::{Drag, Source}; /// The settings switch, named after this system's file manager. pub const SHELL_MENU_NAME: super::ShellMenuName = super::ShellMenuName::Finder; @@ -92,3 +105,223 @@ extern "C-unwind" fn open_urls( } } } + +/// Rows dragged out go to the Finder as file promises. +pub const DRAG_OUT: bool = true; + +/// The Finder asks for each entry on a thread of its own once it knows the +/// folder, and the window keeps working meanwhile, so any size goes. +pub const DRAG_LIMIT: Option = None; + +/// One entry the Finder is promised. +struct PromiseIvars { + source: Source, + entry: PathBuf, + name: String, + /// Where the Finder's request to write it is served: not the main + /// thread, which would hang the window for as long as it takes. + queue: Retained, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and Promise + // implements no Drop. + #[unsafe(super(NSObject))] + #[name = "HatchZipFilePromise"] + #[ivars = PromiseIvars] + struct Promise; + + unsafe impl NSObjectProtocol for Promise {} + + unsafe impl NSFilePromiseProviderDelegate for Promise { + #[unsafe(method_id(filePromiseProvider:fileNameForType:))] + fn file_name( + &self, + _provider: &NSFilePromiseProvider, + _file_type: &NSString, + ) -> Retained { + NSString::from_str(&self.ivars().name) + } + + #[unsafe(method(filePromiseProvider:writePromiseToURL:completionHandler:))] + fn write_promise( + &self, + _provider: &NSFilePromiseProvider, + url: &NSURL, + done: &DynBlock, + ) { + let promise = self.ivars(); + let written = match url.to_file_path() { + Some(dest) => crate::drag::write_promise(&promise.source, &promise.entry, &dest), + None => Err(anyhow::anyhow!( + "{} was dropped somewhere that is not a folder", + promise.name + )), + }; + match written { + Ok(()) => done.call((std::ptr::null_mut(),)), + Err(e) => { + crate::main_window::drag_failed(e); + // SAFETY: a constant of Foundation's, there for the + // life of the process. 512 is NSFileWriteUnknownError. + let error = NSError::new(512, unsafe { NSCocoaErrorDomain }); + done.call((Retained::as_ptr(&error).cast_mut(),)); + } + } + } + + #[unsafe(method_id(operationQueueForFilePromiseProvider:))] + fn operation_queue(&self, _provider: &NSFilePromiseProvider) -> Retained { + self.ivars().queue.clone() + } + } +); + +impl Promise { + fn new(ivars: PromiseIvars) -> Retained { + let this = Self::alloc().set_ivars(ivars); + // SAFETY: NSObject's init, on an object just allocated. + unsafe { msg_send![super(this), init] } + } +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and DragSource + // implements no Drop. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "HatchZipDragSource"] + struct DragSource; + + unsafe impl NSObjectProtocol for DragSource {} + + unsafe impl NSDraggingSource for DragSource { + #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))] + fn operation_mask( + &self, + _session: &NSDraggingSession, + _context: NSDraggingContext, + ) -> NSDragOperation { + NSDragOperation::Copy + } + + #[unsafe(method(draggingSession:endedAtPoint:operation:))] + fn ended( + &self, + _session: &NSDraggingSession, + _point: NSPoint, + _operation: NSDragOperation, + ) { + crate::main_window::drag_ended(); + } + } +); + +impl DragSource { + fn new(mtm: MainThreadMarker) -> Retained { + let this = Self::alloc(mtm).set_ivars(()); + // SAFETY: NSObject's init, on an object just allocated. + unsafe { msg_send![super(this), init] } + } +} + +thread_local! { + /// The source of the last drag, until the next one replaces it. + static SOURCE: RefCell>> = const { RefCell::new(None) }; + /// A file promise holds its delegate weakly, and the Finder may ask for + /// the file after the drag is over, so they are kept for the process. + /// Each is a few words. + static PROMISES: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +/// Starts dragging `drag` out of `window`. AppKit only starts a drag from +/// the mouse event that moves it, which is the one being handled: Slint +/// calls this from inside winit's handling of it. +pub fn drag_out(window: &slint::Window, drag: Drag) -> bool { + window + .with_winit_window(|w| start_drag(w, &drag)) + .unwrap_or(false) +} + +fn start_drag(window: &slint::winit_030::winit::window::Window, drag: &Drag) -> bool { + let Some(mtm) = MainThreadMarker::new() else { + return false; + }; + let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else { + return false; + }; + if event.r#type() != NSEventType::LeftMouseDragged { + return false; + } + let Ok(handle) = window.window_handle() else { + return false; + }; + let RawWindowHandle::AppKit(appkit) = handle.as_raw() else { + return false; + }; + // SAFETY: winit's NSView for this window, alive as long as the window, + // borrowed here on the main thread while the window handles an event. + let view: &NSView = unsafe { appkit.ns_view.cast::().as_ref() }; + let at = view.convertPoint_fromView(event.locationInWindow(), None); + let queue = NSOperationQueue::new(); + let workspace = NSWorkspace::sharedWorkspace(); + let mut items = Vec::new(); + for (i, entry) in drag.entries.iter().enumerate() { + let Some(name) = entry.path.file_name() else { + continue; + }; + let promise = Promise::new(PromiseIvars { + source: drag.source.clone(), + entry: entry.path.clone(), + name: name.to_string_lossy().into_owned(), + queue: queue.clone(), + }); + let kind = NSString::from_str(if entry.dir { + "public.folder" + } else { + "public.data" + }); + let provider = NSFilePromiseProvider::initWithFileType_delegate( + NSFilePromiseProvider::alloc(), + &kind, + ProtocolObject::from_ref(&*promise), + ); + let item = NSDraggingItem::initWithPasteboardWriter( + NSDraggingItem::alloc(), + ProtocolObject::from_ref(&*provider), + ); + let icon_type = match entry.path.extension() { + _ if entry.dir => "public.folder".to_string(), + Some(ext) => ext.to_string_lossy().into_owned(), + None => "public.data".to_string(), + }; + // The replacement, iconForContentType:, takes a UTType, from + // bindings this app has no other use for; this one takes an + // extension or a type identifier and still works. + #[allow(deprecated)] + let icon = workspace.iconForFileType(&NSString::from_str(&icon_type)); + let contents: &AnyObject = &icon; + // A few entries fan out a little, as the Finder's own drags do. + let step = i.min(4) as f64 * 4.0; + let frame = NSRect::new( + NSPoint::new(at.x - 16.0 + step, at.y - 16.0 - step), + NSSize::new(32.0, 32.0), + ); + // SAFETY: a dragging frame's contents are an image, as this is. + unsafe { item.setDraggingFrame_contents(frame, Some(contents)) }; + PROMISES.with(|p| p.borrow_mut().push(promise)); + items.push(item); + } + if items.is_empty() { + return false; + } + let source = DragSource::new(mtm); + let items = NSArray::from_retained_slice(&items); + let _session = view.beginDraggingSessionWithItems_event_source( + &items, + &event, + ProtocolObject::from_ref(&*source), + ); + SOURCE.with(|s| *s.borrow_mut() = Some(source)); + true +} diff --git a/crates/gui/src/platform/windows.rs b/crates/gui/src/platform/windows.rs index 0854ab96..5cb923d9 100644 --- a/crates/gui/src/platform/windows.rs +++ b/crates/gui/src/platform/windows.rs @@ -1,4 +1,28 @@ +use std::cell::{Cell, RefCell}; +use std::mem::ManuallyDrop; +use std::os::windows::ffi::OsStrExt; use std::path::PathBuf; +use std::rc::Rc; + +use anyhow::{Context, Result, bail}; +use windows::Win32::Foundation::{ + DRAGDROP_S_CANCEL, DRAGDROP_S_DROP, DRAGDROP_S_USEDEFAULTCURSORS, GlobalFree, HGLOBAL, HWND, + S_OK, +}; +use windows::Win32::System::Com::{ + DVASPECT_CONTENT, FORMATETC, IDataObject, STGMEDIUM, STGMEDIUM_0, TYMED_HGLOBAL, +}; +use windows::Win32::System::Memory::{GHND, GlobalAlloc, GlobalLock, GlobalUnlock}; +use windows::Win32::System::Ole::{ + CF_HDROP, DROPEFFECT, DROPEFFECT_COPY, DROPEFFECT_NONE, DoDragDrop, IDropSource, + IDropSource_Impl, OleInitialize, OleUninitialize, +}; +use windows::Win32::System::SystemServices::{MK_LBUTTON, MODIFIERKEYS_FLAGS}; +use windows::Win32::UI::Shell::{DROPFILES, SHCreateDataObject}; +use windows::Win32::UI::WindowsAndMessaging::{KillTimer, SetTimer}; +use windows_core::{BOOL, HRESULT, implement}; + +use crate::drag::Drag; /// The settings switch, named after this system's file manager. pub const SHELL_MENU_NAME: super::ShellMenuName = super::ShellMenuName::Explorer; @@ -29,3 +53,185 @@ pub fn config_dir() -> Option { /// Explorer passes the files as arguments here, so there is nothing to /// listen for. pub fn forward_opened_files(_on_open: impl Fn(PathBuf) + 'static) {} + +/// Rows dragged out go to Explorer through OLE, as files. +pub const DRAG_OUT: bool = true; + +/// Explorer is handed files that exist, so the entries are extracted when +/// the button is released over a folder that takes them, and the window +/// waits for that. Beyond this much, "Extract selected…", which shows its +/// progress, is the way. +pub const DRAG_LIMIT: Option = Some(1_000_000_000); + +thread_local! { + static PENDING: RefCell> = const { RefCell::new(None) }; +} + +/// Starts dragging `drag` out once the current event is handled. DoDragDrop +/// runs a message loop of its own until the drop. Called from inside winit's +/// event handler, as Slint's callbacks are, that loop would hand winit a +/// repaint while the handler is busy, which winit refuses with a panic. A +/// thread timer's callback is called by the message loop itself, between +/// events, so the window keeps drawing while the drag is on. +pub fn drag_out(_window: &slint::Window, drag: Drag) -> bool { + PENDING.with(|p| *p.borrow_mut() = Some(drag)); + // SAFETY: a thread timer, owned by no window, whose callback has the + // signature TIMERPROC requires. + let id = unsafe { SetTimer(None, 0, 0, Some(start_pending)) }; + if id == 0 { + PENDING.with(|p| p.borrow_mut().take()); + return false; + } + true +} + +unsafe extern "system" fn start_pending(_window: HWND, _message: u32, id: usize, _time: u32) { + // SAFETY: the thread timer this call is for; it fires once. + let _ = unsafe { KillTimer(None, id) }; + let Some(drag) = PENDING.with(|p| p.borrow_mut().take()) else { + return; + }; + if let Err(e) = drag_files(drag) { + crate::main_window::drag_failed(e); + } + crate::main_window::drag_ended(); +} + +fn drag_files(drag: Drag) -> Result<()> { + let work = crate::drag::new_work()?; + let files: Vec = drag + .entries + .iter() + .map(|e| crate::drag::extracted(&work, &e.path)) + .collect(); + // SAFETY: on the UI thread, where winit already initialized OLE for its + // own drop target, in the same apartment; this only counts up, and is + // matched below. + unsafe { OleInitialize(None) }.context("starting OLE to drag the entries")?; + let result = drag_with_ole(drag, work, &files); + // SAFETY: matches the OleInitialize above, which succeeded. + unsafe { OleUninitialize() }; + result +} + +/// What the drag shares with the drop source's callbacks. +struct State { + drag: Drag, + work: PathBuf, + /// What the window under the pointer said it would do with the files. + effect: Cell, + error: RefCell>, +} + +#[implement(IDropSource)] +struct DropSource(Rc); + +impl IDropSource_Impl for DropSource_Impl { + fn QueryContinueDrag(&self, escape: BOOL, keys: MODIFIERKEYS_FLAGS) -> HRESULT { + if escape.as_bool() { + return DRAGDROP_S_CANCEL; + } + if keys.0 & MK_LBUTTON.0 != 0 { + return S_OK; + } + // Released. Over somewhere that refuses the files, nothing is + // extracted; otherwise they are, before the target hears of the drop. + if self.0.effect.get() == DROPEFFECT_NONE { + return DRAGDROP_S_CANCEL; + } + match crate::drag::extract_all(&self.0.drag, &self.0.work) { + Ok(()) => DRAGDROP_S_DROP, + Err(e) => { + *self.0.error.borrow_mut() = Some(e); + DRAGDROP_S_CANCEL + } + } + } + + fn GiveFeedback(&self, effect: DROPEFFECT) -> HRESULT { + self.0.effect.set(effect); + DRAGDROP_S_USEDEFAULTCURSORS + } +} + +fn drag_with_ole(drag: Drag, work: PathBuf, files: &[PathBuf]) -> Result<()> { + // SAFETY: no folder, no items and no inner object: an empty data object + // of the shell's, which takes any format set on it and answers the ones + // Explorer sets on it during the drag. + let data: IDataObject = unsafe { SHCreateDataObject(None, None, None::<&IDataObject>) } + .context("creating the data to drag")?; + let names = file_list(files)?; + let format = FORMATETC { + cfFormat: CF_HDROP.0, + ptd: std::ptr::null_mut(), + dwAspect: DVASPECT_CONTENT.0, + lindex: -1, + tymed: TYMED_HGLOBAL.0 as u32, + }; + let medium = STGMEDIUM { + tymed: TYMED_HGLOBAL.0 as u32, + u: STGMEDIUM_0 { hGlobal: names }, + pUnkForRelease: ManuallyDrop::new(None), + }; + // SAFETY: the format and the medium describe the same block; with + // `release` set the data object owns it once this succeeds. + if let Err(e) = unsafe { data.SetData(&format, &medium, true) } { + // SAFETY: refused, so the block is still ours to free. + let _ = unsafe { GlobalFree(Some(names)) }; + return Err(e).context("setting the files to drag"); + } + let state = Rc::new(State { + drag, + work, + effect: Cell::new(DROPEFFECT_NONE), + error: RefCell::new(None), + }); + let source: IDropSource = DropSource(state.clone()).into(); + let mut effect = DROPEFFECT_NONE; + // Copy only: Explorer would otherwise move the files out of the + // temporary folder on the same disk, which is fine, but a target that + // moves by deleting after its copy would race the cleanup. + // SAFETY: both objects outlive the call, which runs on this thread, + // where OLE is initialized. + let hr = unsafe { DoDragDrop(&data, &source, DROPEFFECT_COPY, &mut effect) }; + if let Some(e) = state.error.borrow_mut().take() { + return Err(e); + } + hr.ok().context("dragging the entries")?; + Ok(()) +} + +/// The paths as CF_HDROP has them: a DROPFILES header, then each path in +/// UTF-16 ending in a zero, then one more zero. +fn file_list(files: &[PathBuf]) -> Result { + let mut wide: Vec = Vec::new(); + for f in files { + wide.extend(f.as_os_str().encode_wide()); + wide.push(0); + } + wide.push(0); + let header = std::mem::size_of::(); + let size = header + wide.len() * 2; + // SAFETY: a plain allocation, zeroed by GHND. + let block = unsafe { GlobalAlloc(GHND, size) }.context("allocating the file list")?; + // SAFETY: `block` is the movable block just allocated. + let p = unsafe { GlobalLock(block) }.cast::(); + if p.is_null() { + // SAFETY: ours, and given to nobody yet. + let _ = unsafe { GlobalFree(Some(block)) }; + bail!("locking the file list"); + } + let head = DROPFILES { + pFiles: header as u32, + fWide: true.into(), + ..Default::default() + }; + // SAFETY: the block holds `size` bytes, the header and then the names; + // DROPFILES is packed, so it is written unaligned. + unsafe { + std::ptr::write_unaligned(p.cast::(), head); + std::ptr::copy_nonoverlapping(wide.as_ptr().cast::(), p.add(header), wide.len() * 2); + let _ = GlobalUnlock(block); + } + Ok(block) +} diff --git a/crates/gui/tests/ui.rs b/crates/gui/tests/ui.rs index a155ff4d..1298e2ac 100644 --- a/crates/gui/tests/ui.rs +++ b/crates/gui/tests/ui.rs @@ -9,7 +9,7 @@ //! //! The backend can be installed once per process, so this is one test. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::io::Write; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -794,6 +794,66 @@ fn selection_flow(scheme: ColorScheme, tag: &str) { inside_window(&ui, "Extract all"); shot(ui.window(), &format!("{tag}-21-selection")); + // Dragging a chosen row out takes the whole selection, and any other + // row goes alone. The system's drag can't run here, and Linux has none, + // so the window is told it has one and the paths are watched instead. + let dragged = Rc::new(RefCell::new(Vec::>::new())); + let d = dragged.clone(); + main_window::watch_drags(move |mut paths| { + paths.sort(); + d.borrow_mut().push(paths); + }); + ui.set_drag_out_available(true); + for label in ["Northwind/README.txt", "Northwind/bin"] { + drag_row(&ui, label); + let w = ui.as_weak(); + wait_until("the drag to end", move || w.unwrap().get_drag_row() < 0); + } + assert_eq!( + *dragged.borrow(), + [ + vec![ + "Northwind/README.txt".to_string(), + "Northwind/data".to_string() + ], + vec!["Northwind/bin".to_string()], + ] + ); + assert_eq!( + ui.get_selection_count(), + 2, + "a drag's release chooses nothing" + ); + assert_eq!( + inside_window(&ui, "Northwind/bin").accessible_expanded(), + Some(true), + "nor closes the folder it started on" + ); + // A move within the threshold is still a click. + let row = inside_window(&ui, "Northwind/bin"); + let (p, s) = (row.absolute_position(), row.size()); + let at = slint::LogicalPosition::new(p.x + s.width / 2.0, p.y + s.height / 2.0); + let near = slint::LogicalPosition::new(at.x + 3.0, at.y); + ui.window() + .dispatch_event(WindowEvent::PointerMoved { position: at }); + ui.window().dispatch_event(WindowEvent::PointerPressed { + position: at, + button: PointerEventButton::Left, + }); + ui.window() + .dispatch_event(WindowEvent::PointerMoved { position: near }); + ui.window().dispatch_event(WindowEvent::PointerReleased { + position: near, + button: PointerEventButton::Left, + }); + assert_eq!(dragged.borrow().len(), 2, "no drag"); + assert_eq!( + inside_window(&ui, "Northwind/bin").accessible_expanded(), + Some(false) + ); + click_control(&ui, "Northwind/bin"); + ui.set_drag_out_available(false); + let picked = dir.path().join("picked"); let answer = picked.clone(); main_window::answer_folder_picker(move || Some(answer.clone())); @@ -1415,6 +1475,26 @@ fn inside_window(ui: &MainWindow, label: &str) -> ElementHandle { element } +/// Presses on the row, moves well past the drag threshold and releases. +fn drag_row(ui: &MainWindow, label: &str) { + let row = inside_window(ui, label); + let p = row.absolute_position(); + let s = row.size(); + let from = slint::LogicalPosition::new(p.x + s.width / 2.0, p.y + s.height / 2.0); + let to = slint::LogicalPosition::new(from.x + 30.0, from.y); + let window = ui.window(); + window.dispatch_event(WindowEvent::PointerMoved { position: from }); + window.dispatch_event(WindowEvent::PointerPressed { + position: from, + button: PointerEventButton::Left, + }); + window.dispatch_event(WindowEvent::PointerMoved { position: to }); + window.dispatch_event(WindowEvent::PointerReleased { + position: to, + button: PointerEventButton::Left, + }); +} + fn click_control(ui: &MainWindow, label: &str) { let button = inside_window(ui, label); let p = button.absolute_position(); diff --git a/crates/gui/translations/es/LC_MESSAGES/hatchzip-gui.po b/crates/gui/translations/es/LC_MESSAGES/hatchzip-gui.po index f8f150a5..a54b6d18 100644 --- a/crates/gui/translations/es/LC_MESSAGES/hatchzip-gui.po +++ b/crates/gui/translations/es/LC_MESSAGES/hatchzip-gui.po @@ -609,3 +609,9 @@ msgstr[1] "Extraer y eliminar los {} archivos que contiene" msgid "Only the files this run wrote were checked for archives." msgstr "Solo se comprobaron los archivos que escribió esta ejecución." + +msgid "Up to {} can be dragged out at once. Use Extract selected… for more." +msgstr "Se pueden arrastrar hasta {} a la vez. Usa Extraer selección… para más." + +msgid "Entries dragged out of the archive are still being extracted. Try again when they are done." +msgstr "Las entradas arrastradas fuera del archivo todavía se están extrayendo. Inténtalo de nuevo cuando terminen." diff --git a/crates/gui/translations/hi/LC_MESSAGES/hatchzip-gui.po b/crates/gui/translations/hi/LC_MESSAGES/hatchzip-gui.po index 099ea5e0..13a860b8 100644 --- a/crates/gui/translations/hi/LC_MESSAGES/hatchzip-gui.po +++ b/crates/gui/translations/hi/LC_MESSAGES/hatchzip-gui.po @@ -609,3 +609,9 @@ msgstr[1] "अंदर के {} आर्काइव एक्सट्रै msgid "Only the files this run wrote were checked for archives." msgstr "इस रन में लिखी गई फ़ाइलों में ही आर्काइव खोजे गए।" + +msgid "Up to {} can be dragged out at once. Use Extract selected… for more." +msgstr "एक बार में अधिकतम {} बाहर खींचा जा सकता है। इससे अधिक के लिए चयनित एक्सट्रैक्ट करें… का उपयोग करें।" + +msgid "Entries dragged out of the archive are still being extracted. Try again when they are done." +msgstr "आर्काइव से बाहर खींची गई प्रविष्टियाँ अभी एक्सट्रैक्ट हो रही हैं। उनके पूरा होने पर फिर से प्रयास करें।" diff --git a/crates/gui/translations/tr/LC_MESSAGES/hatchzip-gui.po b/crates/gui/translations/tr/LC_MESSAGES/hatchzip-gui.po index bc1b0932..4bdb6916 100644 --- a/crates/gui/translations/tr/LC_MESSAGES/hatchzip-gui.po +++ b/crates/gui/translations/tr/LC_MESSAGES/hatchzip-gui.po @@ -609,3 +609,9 @@ msgstr "Yalnızca bu çalıştırmanın yazdığı dosyalarda arşiv arandı." msgid "Not started: {}." msgstr "Başlatılmadı: {}." + +msgid "Up to {} can be dragged out at once. Use Extract selected… for more." +msgstr "Tek seferde en fazla {} dışarı sürüklenebilir. Daha fazlası için Seçimi çıkar… seçeneğini kullanın." + +msgid "Entries dragged out of the archive are still being extracted. Try again when they are done." +msgstr "Arşivden dışarı sürüklenen öğeler hâlâ çıkarılıyor. Bittiğinde tekrar deneyin." diff --git a/crates/gui/translations/zh_CN/LC_MESSAGES/hatchzip-gui.po b/crates/gui/translations/zh_CN/LC_MESSAGES/hatchzip-gui.po index 3c2802db..31a0f66e 100644 --- a/crates/gui/translations/zh_CN/LC_MESSAGES/hatchzip-gui.po +++ b/crates/gui/translations/zh_CN/LC_MESSAGES/hatchzip-gui.po @@ -597,3 +597,9 @@ msgstr[0] "解压并删除里面的 {} 个压缩包" msgid "Only the files this run wrote were checked for archives." msgstr "只检查了本次运行写出的文件。" + +msgid "Up to {} can be dragged out at once. Use Extract selected… for more." +msgstr "一次最多可拖出 {}。更多内容请使用“解压所选项…”。" + +msgid "Entries dragged out of the archive are still being extracted. Try again when they are done." +msgstr "从压缩包拖出的条目仍在解压。完成后请重试。" diff --git a/crates/gui/ui/main-window.slint b/crates/gui/ui/main-window.slint index 121dadc7..e23f83b9 100644 --- a/crates/gui/ui/main-window.slint +++ b/crates/gui/ui/main-window.slint @@ -80,11 +80,21 @@ component EntryList inherits VerticalLayout { // range from the last row clicked (Shift). Read from the press, which // carries the keys. property click-mode: 0; + // Rows can be dragged out to a folder in the file manager. + in property drag-out; + // The row being dragged out, or -1; with `drag-chosen`, every chosen + // row goes with it. Dimmed until the drop. + in property drag-row: -1; + in property drag-chosen; + // The press being made has turned into a drag, so its release is no click. + property dragged; init => { scope.focus(); } callback toggle(int, int); callback navigate(int, bool) -> int; // Changes the rows "Extract selected…" takes, with a mode as above. callback choose(int, int); + // The press on this row moved far enough to start dragging it out. + callback drag(int); function show-selection() { let y = list.content-y + root.selected * root.row-height; if y < 0px { list.content-y -= y; } @@ -143,6 +153,7 @@ component EntryList inherits VerticalLayout { // Rows chosen for "Extract selected…" keep the selection colour, // and the cursor bar is drawn on them too, in their text colour. background: row.selected ? Palette.selection-background : root.selected != index ? transparent : scope.has-focus ? Theme.selected : Theme.track; + opacity: root.drag-row >= 0 && (root.drag-chosen ? row.selected : root.drag-row == index) ? 0.5 : 1; if root.selected == index && scope.has-focus: Rectangle { x: 4px; y: (parent.height - self.height) / 2; @@ -191,16 +202,28 @@ component EntryList inherits VerticalLayout { TouchArea { pointer-event(event) => { if event.kind == PointerEventKind.down { + root.dragged = false; root.click-mode = event.modifiers.shift ? 2 : (event.modifiers.control || event.modifiers.meta) ? 1 : 0; } } + // A few pixels, as the systems' own drag thresholds. + moved => { + if root.drag-out && self.pressed && !root.dragged && root.drag-row < 0 && (abs(self.mouse-x - self.pressed-x) > 5px || abs(self.mouse-y - self.pressed-y) > 5px) { + root.dragged = true; + root.drag(index); + } + } clicked => { - root.selected = index; - scope.focus(); - root.choose(index, root.click-mode); - // A plain click opens or closes a folder and chooses - // nothing; adding one to the selection leaves it as it is. - if row.dir && root.click-mode == 0 { root.toggle(index, 0); } + if root.dragged { + root.dragged = false; + } else { + root.selected = index; + scope.focus(); + root.choose(index, root.click-mode); + // A plain click opens or closes a folder and chooses + // nothing; adding one to the selection leaves it as it is. + if row.dir && root.click-mode == 0 { root.toggle(index, 0); } + } } } } @@ -255,6 +278,11 @@ export component MainWindow inherits Window { in property <[EntryRow]> entries; // Rows chosen in the tree for "Extract selected…". in property selection-count; + // This system can take rows dragged out of the tree. + in property drag-out-available; + // The row being dragged out, or -1, and whether the chosen rows go too. + in property drag-row: -1; + in property drag-chosen; // "2 items selected. ...", said after what Extract does, which a // selection does not change. in property selection-text; @@ -297,6 +325,8 @@ export component MainWindow inherits Window { callback toggle-entry(int, int); callback navigate-entry(int, bool) -> int; callback choose-entry(int, int); + // The press on this row became a drag out of the window. + callback drag-entries(int); callback extract-selected(); callback password-ok(string); callback password-cancel(); @@ -555,6 +585,12 @@ export component MainWindow inherits Window { toggle(row, action) => { root.toggle-entry(row, action); } navigate(row, right) => { return root.navigate-entry(row, right); } choose(row, mode) => { root.choose-entry(row, mode); } + // Like "Extract selected…": only before anything was + // extracted, while nothing runs. + drag-out: root.drag-out-available && root.mode == Mode.fresh && root.task.phase == Phase.idle; + drag-row: root.drag-row; + drag-chosen: root.drag-chosen; + drag(row) => { root.drag-entries(row); } } VLine { } // The plan can outgrow a small window; its content must not diff --git a/crates/gui/ui/messages.slint b/crates/gui/ui/messages.slint index 44443b00..d906656a 100644 --- a/crates/gui/ui/messages.slint +++ b/crates/gui/ui/messages.slint @@ -27,6 +27,8 @@ export global Messages { public function inside-count-remove(n: int, count: string) -> string { return @tr("Extract and remove {} archive inside" | "Extract and remove {} archives inside" % n, count); } public function inside-partial() -> string { return @tr("Only the files this run wrote were checked for archives."); } public function waiting-disk() -> string { return @tr("Waiting for disk"); } + public function drag-too-large(size: string) -> string { return @tr("Up to {} can be dragged out at once. Use Extract selected… for more.", size); } + public function drag-busy() -> string { return @tr("Entries dragged out of the archive are still being extracted. Try again when they are done."); } public function reading-archive(percent: int) -> string { return @tr("Reading archive… {}%", percent); } public function archive-kind(name: string) -> string { return @tr("{} archive", name); } From 88eb99f5a03b1656c1b6ae5ef2dda58e7a763795 Mon Sep 17 00:00:00 2001 From: Yash Bavadiya Date: Sat, 28 Nov 2026 01:00:33 +0530 Subject: [PATCH 2/3] fix(gui): satisfy clippy for the drag-out code --- crates/gui/src/entries.rs | 8 ++++++-- crates/gui/src/main_window.rs | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/gui/src/entries.rs b/crates/gui/src/entries.rs index 977b24de..11a4fc78 100644 --- a/crates/gui/src/entries.rs +++ b/crates/gui/src/entries.rs @@ -41,6 +41,10 @@ struct Node { children: Vec, } +/// What a drag out of the tree takes: each path with whether it is a +/// folder, the size of it all, and whether it is the selection. +pub type DragRows = (Vec<(String, bool)>, u64, bool); + pub struct Entries { nodes: Vec, visible: Vec<(usize, i32)>, @@ -263,7 +267,7 @@ impl Entries { /// row is part of it, as file managers do, and the row alone otherwise. /// Each path comes with whether it is a folder, then the size of it all /// and whether it was the selection. - pub fn dragged(&self, row: usize) -> Option<(Vec<(String, bool)>, u64, bool)> { + pub fn dragged(&self, row: usize) -> Option { let &(node, _) = self.visible.get(row)?; let chosen = self.nodes[node].selected || self.inside_chosen(node); let picked: Vec = if chosen { @@ -380,7 +384,7 @@ impl EntriesModel { } /// See [`Entries::dragged`]. - pub fn dragged(&self, row: usize) -> Option<(Vec<(String, bool)>, u64, bool)> { + pub fn dragged(&self, row: usize) -> Option { self.tree.borrow().dragged(row) } diff --git a/crates/gui/src/main_window.rs b/crates/gui/src/main_window.rs index 2bc273f1..5bc6c635 100644 --- a/crates/gui/src/main_window.rs +++ b/crates/gui/src/main_window.rs @@ -243,6 +243,7 @@ pub(crate) fn drag_ended() { } /// Extracting entries dragged out of the tree failed; from any thread. +#[allow(dead_code)] // Linux starts no drag, so nothing fails there. pub(crate) fn drag_failed(error: anyhow::Error) { post(move |app| { let ui = app.ui(); From c9bc906b9152752958491e5af4781a7a22a934fa Mon Sep 17 00:00:00 2001 From: Yash Bavadiya Date: Sat, 28 Nov 2026 01:20:34 +0530 Subject: [PATCH 3/3] test(gui): compare the folder with its state before the drag --- crates/gui/tests/ui.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/gui/tests/ui.rs b/crates/gui/tests/ui.rs index 1298e2ac..397b4579 100644 --- a/crates/gui/tests/ui.rs +++ b/crates/gui/tests/ui.rs @@ -804,6 +804,7 @@ fn selection_flow(scheme: ColorScheme, tag: &str) { d.borrow_mut().push(paths); }); ui.set_drag_out_available(true); + let open = inside_window(&ui, "Northwind/bin").accessible_expanded(); for label in ["Northwind/README.txt", "Northwind/bin"] { drag_row(&ui, label); let w = ui.as_weak(); @@ -826,8 +827,8 @@ fn selection_flow(scheme: ColorScheme, tag: &str) { ); assert_eq!( inside_window(&ui, "Northwind/bin").accessible_expanded(), - Some(true), - "nor closes the folder it started on" + open, + "nor opens or closes the folder it started on" ); // A move within the threshold is still a click. let row = inside_window(&ui, "Northwind/bin"); @@ -849,7 +850,7 @@ fn selection_flow(scheme: ColorScheme, tag: &str) { assert_eq!(dragged.borrow().len(), 2, "no drag"); assert_eq!( inside_window(&ui, "Northwind/bin").accessible_expanded(), - Some(false) + open.map(|o| !o) ); click_control(&ui, "Northwind/bin"); ui.set_drag_out_available(false);