A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
Cancel macOS disk usage scans when leaving the page
sunzhaozheng8c1eb993fe7c
diff --git a/crates/rf-mac/src/diskusage.rs b/crates/rf-mac/src/diskusage.rsindex c4a5af97..0bb3942e 100644--- a/crates/rf-mac/src/diskusage.rs+++ b/crates/rf-mac/src/diskusage.rs@@ -73,7 +73,7 @@ impl DiskScan {bytes: Arc::new(AtomicU64::new(0)),});let (tree, done, cancelled, entries, bytes) = (scan.tree.clone(), scan.done.clone(), scan.cancelled.clone(), scan.entries.clone(), scan.bytes.clone());- std::thread::Builder::new()+ if std::thread::Builder::new().name("rf-diskusage".into()).spawn(move || {let root = Path::new(&root);@@ -82,12 +82,18 @@ impl DiskScan {let name = root.file_name().map_or_else(|| root.display().to_string(), |n| n.to_string_lossy().into_owned());let mut node = w.dir(root, name);if !w.cancelled.load(Ordering::Relaxed) {- sort(&mut node);- *tree.lock().unwrap() = Some(node);+ sort(&mut node, &w.cancelled);+ let mut result = tree.lock().unwrap();+ if !w.cancelled.load(Ordering::Relaxed) {+ *result = Some(node);+ }}done.store(true, Ordering::Release);})- .ok();+ .is_err()+ {+ scan.done.store(true, Ordering::Release);+ }scan}@@ -104,6 +110,10 @@ impl DiskScan {self.bytes.load(Ordering::Relaxed)}+ pub fn is_cancelled(&self) -> bool {+ self.cancelled.load(Ordering::Relaxed)+ }+pub fn cancel(&self) {self.cancelled.store(true, Ordering::Relaxed);}@@ -131,6 +141,18 @@ impl DiskScan {}}+impl Drop for DiskScan {+ fn drop(&mut self) {+ self.cancel();+ // A completed tree can be large; don't tear it down on the UI thread.+ if let Some(tree) = self.tree.lock().unwrap().take() {+ let _ = std::thread::Builder::new()+ .name("rf-diskusage-cleanup".into())+ .spawn(move || drop(tree));+ }+ }+}+/// Squarified treemap rectangles for `weights` (biggest first) in a `w` × `h` box.#[uniffi::export]pub fn treemap_layout(weights: Vec<u64>, w: f64, h: f64) -> Vec<DiskRect> {@@ -165,9 +187,10 @@ fn find<'a>(root: &'a Node, root_path: &Path, id: &[u32]) -> Option<(&'a Node, PSome((n, p))}-fn sort(n: &mut Node) {+fn sort(n: &mut Node, cancelled: &AtomicBool) {+ if cancelled.load(Ordering::Relaxed) { return; }n.children.sort_by(|a, b| b.size.cmp(&a.size));- n.children.par_iter_mut().for_each(sort);+ n.children.par_iter_mut().for_each(|child| sort(child, cancelled));}struct Walk {@@ -187,6 +210,7 @@ impl Walk {let mut files = Vec::new();let mut dirs = Vec::new();for e in rd.flatten() {+ if self.cancelled.load(Ordering::Relaxed) { return node; }let Ok(m) = std::fs::symlink_metadata(e.path()) else { continue };let n = e.file_name().to_string_lossy().into_owned();if m.is_dir() {@@ -219,6 +243,29 @@ impl Walk {mod tests {use super::*;+ #[test]+ fn cancelling_a_scan_stops_the_worker_and_does_not_publish_partial_results() {+ let d = std::env::temp_dir().join(format!("rf-mac-du-cancel-{}", std::process::id()));+ std::fs::create_dir(&d).unwrap();+ for n in 0..2_000 {+ std::fs::write(d.join(n.to_string()), b"x").unwrap();+ }+ let scan = DiskScan::start(d.display().to_string());+ scan.cancel();+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while !scan.is_done() && std::time::Instant::now() < deadline {+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(scan.is_done());+ assert!(scan.is_cancelled());+ // A scheduler may let the walk finish before cancel() runs. In that case the+ // published tree must be complete, never a partially walked directory.+ if let Some(root) = scan.item(vec![]) {+ assert_eq!(root.files, 2_000);+ }+ std::fs::remove_dir_all(&d).unwrap();+ }+#[test]fn sizes_add_up_and_children_come_biggest_first() {let d = std::env::temp_dir().join(format!("rf-mac-du-{}", std::process::id()));diff --git a/macos/Localization/zh-Hans.json b/macos/Localization/zh-Hans.jsonindex 2b48e6ab..d6c8ce1e 100644--- a/macos/Localization/zh-Hans.json+++ b/macos/Localization/zh-Hans.json@@ -907,5 +907,9 @@"just now": "刚刚","{n} min ago": "{n} 分钟前","{n} h ago": "{n} 小时前",-"{n} d ago": "{n} 天前"-}\ No newline at end of file+"{n} d ago": "{n} 天前",+"Alternating row colors": "交替行颜色",+"In Details, List and Columns, every other row is lightly shaded, so that rows next to each other are easier to tell apart.": "在详细信息、列表和分栏视图中,每隔一行使用浅色底纹,让相邻行更容易区分。",+"Stop scan": "停止分析",+"Scan stopped": "分析已停止"+}diff --git a/macos/Localization/zh-Hant.json b/macos/Localization/zh-Hant.jsonindex 1f9217b2..1118c622 100644--- a/macos/Localization/zh-Hant.json+++ b/macos/Localization/zh-Hant.json@@ -907,5 +907,9 @@"just now": "剛剛","{n} min ago": "{n} 分鐘前","{n} h ago": "{n} 小時前",-"{n} d ago": "{n} 天前"+"{n} d ago": "{n} 天前",+"Alternating row colors": "交替列色",+"In Details, List and Columns, every other row is lightly shaded, so that rows next to each other are easier to tell apart.": "在詳細資料、列表和分欄檢視中,每隔一列使用淺色底紋,讓相鄰列更容易區分。",+"Stop scan": "停止分析",+"Scan stopped": "分析已停止"}\ No newline at end of filediff --git a/macos/Sources/RustyFiles/BrowserWindowController.swift b/macos/Sources/RustyFiles/BrowserWindowController.swiftindex d06982b2..19e1ae81 100644--- a/macos/Sources/RustyFiles/BrowserWindowController.swift+++ b/macos/Sources/RustyFiles/BrowserWindowController.swift@@ -3,7 +3,19 @@ import AppKit/// One tab: its folder, its own back/forward history, and what to restore when it comes back.@MainActorfinal class BrowserTab {- var url: URL+ var url: URL {+ didSet { if url != oldValue { stopDiskScan() } }+ }++ func stopDiskScan() {+ disk?.cancel()+ disk = nil+ }++ func stopDiskScansInBothPanes() {+ stopDiskScan()+ right?.stopDiskScan()+ }var back: [URL] = []var forward: [URL] = []var folder: Folder?@@ -294,7 +306,10 @@ final class BrowserWindowController: NSWindowController, NSWindowDelegate, NSMen/// Edit › Undo and Redo, ⌘Z and ⇧⌘Z, work on file operations (text being edited keeps its own).func windowWillReturnUndoManager(_ window: NSWindow) -> UndoManager? { FileUndo.shared.manager }- func windowWillClose(_ notification: Notification) { onClose?(self) }+ func windowWillClose(_ notification: Notification) {+ tabs.forEach { $0.stopDiskScansInBothPanes() }+ onClose?(self)+ }/// A setting changed: the list takes what concerns it; colours redraw everywhere (and/// lenses find their places again, or go, when the material changed).@@ -494,6 +509,7 @@ final class BrowserWindowController: NSWindowController, NSWindowDelegate, NSMenif t.right != nil {saveTabState()t.right?.search?.cancel()+ t.right?.stopDiskScan()t.right = nilrightActive = falseleftList.card.isActivePane = false@@ -628,6 +644,7 @@ final class BrowserWindowController: NSWindowController, NSWindowDelegate, NSMenfunc restore(_ addresses: [String], active a: Int) {let urls = addresses.compactMap(Sessions.url)guard !urls.isEmpty else { return }+ tabs.forEach { $0.stopDiskScansInBothPanes() }tabs = urls.map { BrowserTab(url: $0) }active = min(max(a, 0), tabs.count - 1)load(tab)@@ -687,6 +704,7 @@ final class BrowserWindowController: NSWindowController, NSWindowDelegate, NSMensaveTabState()let current = tabs[active]closedTabs += indices.map { tabs[$0].url }+ indices.forEach { tabs[$0].stopDiskScansInBothPanes() }tabs = keep.map { tabs[$0] }active = tabs.firstIndex { $0 === current } ?? min(keep.firstIndex { $0 > indices.min()! } ?? 0, tabs.count - 1)showTab()@@ -806,6 +824,7 @@ final class BrowserWindowController: NSWindowController, NSWindowDelegate, NSMen}if i == active { saveTabState() }closedTabs.append(tabs[i].url)+ tabs[i].stopDiskScansInBothPanes()tabs.remove(at: i)if i < active || active >= tabs.count { active = max(active - 1, 0) }showTab()diff --git a/macos/Sources/RustyFiles/DiskUsage.swift b/macos/Sources/RustyFiles/DiskUsage.swiftindex 84fe9300..3296477c 100644--- a/macos/Sources/RustyFiles/DiskUsage.swift+++ b/macos/Sources/RustyFiles/DiskUsage.swift@@ -16,6 +16,7 @@ final class DiskUsageView: FlippedView {private var cells: [(rect: NSRect, item: DiskItem, head: Bool)] = []private var hot: [UInt32]?private var timer: Timer?+ private var stopped = falseprivate let up = IconButton(icon: "arrow-up", size: NSSize(width: 28, height: 28), iconSize: 15, tooltip: String(localized: "Up"))private let rescan = PlainButton(String(localized: "Scan again"), action: nil)@@ -26,7 +27,16 @@ final class DiskUsageView: FlippedView {override init(frame: NSRect) {super.init(frame: frame)up.action = { [weak self] _ in self?.goUp() }- rescan.action = { [weak self] in self?.restart() }+ rescan.action = { [weak self] in+ guard let self else { return }+ if let scan = self.scan, !self.stopped, !scan.isDone() {+ scan.cancel()+ self.stopped = true+ self.refresh()+ } else {+ self.restart()+ }+ }list.owner = selfmap.owner = selflistScroll.documentView = list@@ -43,8 +53,9 @@ final class DiskUsageView: FlippedView {/// Shows the disk usage of `root`, with the walk the tab keeps (made when it has none).func show(_ root: URL, scan existing: DiskScan?) -> DiskScan {- if self.root != root || scan !== existing {+ if scan == nil || self.root != root || scan !== existing {self.root = root+ stopped = existing?.isCancelled() == truecur = []scan = existing ?? DiskScan.start(root: root.path)}@@ -56,6 +67,7 @@ final class DiskUsageView: FlippedView {guard let root else { return }scan?.cancel()scan = DiskScan.start(root: root.path)+ stopped = falsecur = []onRescan?(scan!)refresh()@@ -70,10 +82,14 @@ final class DiskUsageView: FlippedView {version += 1timer?.invalidate()guard let scan else { return }- if !scan.isDone() {+ let scanning = !stopped && !scan.isDone()+ rescan.title = scanning ? String(localized: "Stop scan") : String(localized: "Scan again")+ if stopped || scanning {items = []current = nil- timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false) { [weak self] _ in MainActor.assumeIsolated { self?.refresh() } }+ if scanning {+ timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false) { [weak self] _ in MainActor.assumeIsolated { self?.refresh() } }+ }} else {current = scan.item(id: cur)items = scan.children(id: cur)@@ -88,6 +104,12 @@ final class DiskUsageView: FlippedView {override func viewDidHide() {super.viewDidHide()timer?.invalidate()+ timer = nil+ scan = nil+ items = []+ current = nil+ cells = []+ hot = nil}override func viewDidUnhide() {@@ -158,7 +180,10 @@ final class DiskUsageView: FlippedView {let x: CGFloat = 52let title: Stringlet detail: String- if let scan, !scan.isDone() {+ if stopped {+ title = String(localized: "Disk usage — \(root?.lastPathComponent ?? "")")+ detail = String(localized: "Scan stopped")+ } else if let scan, !scan.isDone() {title = String(localized: "Disk usage — \(root?.lastPathComponent ?? "")")detail = String(localized: "Looking through… \(Int(scan.entries()).formatted()) items, \(formatSize(bytes: scan.bytes()))")} else if let current {