Skip to content

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.

30.1 KB
Raw Blame
import AppKit

/// Development aid (RF_SELFTEST): the file operation engine and its undo, run for real in a
/// scratch folder, each step checked; prints PASS or FAIL lines and quits.
@MainActor
enum SelfTest {
    private static var failures = 0

    private static func check(_ ok: Bool, _ what: String) {
        print((ok ? "PASS " : "FAIL ") + what)
        if !ok { failures += 1 }
    }

    private static func finish(_ root: URL) {
        try? FileManager.default.removeItem(at: root)
        print(failures == 0 ? "ALL PASSED" : "\(failures) FAILED")
        exit(failures == 0 ? 0 : 1)
    }

    static func run() {
        let fm = FileManager.default
        let root = fm.temporaryDirectory.appendingPathComponent("rf-selftest-\(UUID().uuidString)")
        let a = root.appendingPathComponent("a"), b = root.appendingPathComponent("b")
        try? fm.createDirectory(at: a.appendingPathComponent("folder/inner"), withIntermediateDirectories: true)
        try? fm.createDirectory(at: b, withIntermediateDirectories: true)
        try? Data(repeating: 7, count: 3_000_000).write(to: a.appendingPathComponent("big.bin"))
        try? "hello".write(to: a.appendingPathComponent("folder/inner/note.txt"), atomically: true, encoding: .utf8)
        let um = FileUndo.shared.manager

        let tileItem = TileItem()
        tileItem.tile.hoverPoint = NSPoint(x: 10, y: 10)
        tileItem.tile.hovered = true
        tileItem.prepareForReuse()
        check(!tileItem.tile.hovered && tileItem.tile.hoverPoint == nil, "a reused grid tile forgets the old item's hover")

        var crc = CRC32()
        crc.update(Data("123456789".utf8))
        check(crc.value == 0xCBF4_3926, "CRC32 gives the standard check value")
        check(PropertiesWindow.normalizedHash(" 0xAB-CD:ef 12 ") == "abcdef12", "a pasted hash is compared without spaces, dashes and 0x")
        let sample = """
            <!DOCTYPE NETSCAPE-Bookmark-file-1>
            <DL><p>
                <DT><H3 ADD_DATE="1" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
                <DL><p>
                    <DT><A HREF="file:///Users/me/My%20Folder" ICON="data:x">My Folder</A>
                    <DT><H3>More</H3>
                    <DL><p>
                        <DT><A HREF="https://example.com/a?b=1&amp;c=2">Web &amp; more</A>
                    </DL><p>
                </DL><p>
                <DT><A HREF="file:///Applications">Apps</A>
            </DL><p>
            """
        let marks = Bookmarks.parse(sample)
        check(marks == [
            .link(name: "My Folder", target: "/Users/me/My Folder"),
            .folder(name: "More", children: [.link(name: "Web & more", target: "https://example.com/a?b=1&c=2")]),
            .link(name: "Apps", target: "/Applications"),
        ], "a browser's bookmark file is read, its toolbar folder first")
        check(Bookmarks.parse(Bookmarks.toHTML(marks)) == marks, "the bookmarks bar is written as a bookmark file that reads back the same")
        check(GitRepo.isValidBranchName("feature/new-look") && !GitRepo.isValidBranchName("bad name")
              && !GitRepo.isValidBranchName("a..b") && !GitRepo.isValidBranchName("-x") && !GitRepo.isValidBranchName("x.lock"),
              "a branch name is checked as git does")
        let tagged: [String: Set<String>] = ["red": ["/a", "/b"], "work": ["/b", "/c"], "done": ["/c"]]
        let tq = { (q: String) in TagQuery.eval(TagQuery.parse(TagQuery.expression(q) ?? ""), with: { tagged[$0] ?? [] }, all: { ["/a", "/b", "/c"] }) }
        check(tq("tag:red AND work") == ["/b"] && tq("tag:red OR work NOT done") == ["/a", "/b"] && tq("etiket:değil done") == ["/a", "/b"],
              "tag searches with AND, OR and NOT read left to right")
        let held = root.appendingPathComponent("held.txt")
        try? "x".write(to: held, atomically: true, encoding: .utf8)
        let holder = Process()
        holder.executableURL = URL(fileURLWithPath: "/usr/bin/tail")
        holder.arguments = ["-f", held.path]
        holder.standardOutput = FileHandle.nullDevice
        try? holder.run()
        Thread.sleep(forTimeInterval: 0.3)
        check(Lockers.holders([held]).contains { $0.pid == holder.processIdentifier }, "\"Programs using it\" finds a program that has the file open")
        holder.terminate()
        let qa = QuickCommands.arguments("--open \"two words\" {selection} -C {folder}", folder: URL(fileURLWithPath: "/tmp/d"),
                                         selection: [URL(fileURLWithPath: "/a b"), URL(fileURLWithPath: "/c")])
        check((try? qa.get()) == ["--open", "two words", "/a b", "/c", "-C", "/tmp/d"], "a command's arguments get the folder and the selection")
        if case .failure(.noSelection) = QuickCommands.arguments("{selection}", folder: nil, selection: []) {
            check(true, "a command that needs a selection says so when there is none")
        } else { check(false, "a command that needs a selection says so when there is none") }

        // 0. the Git look-up ends at the disk's root and finds a repository from inside it (issue 429)
        check(GitRepo.repoRoot(URL(fileURLWithPath: "/")) == nil, "no repository above the root")
        check(GitRepo.repoRoot(URL(string: "file:///../")!) == nil, "a URL above the root ends too")
        let repo = root.appendingPathComponent("repo")
        try? fm.createDirectory(at: repo.appendingPathComponent(".git"), withIntermediateDirectories: true)
        try? fm.createDirectory(at: repo.appendingPathComponent("src/deep"), withIntermediateDirectories: true)
        check(GitRepo.repoRoot(repo.appendingPathComponent("src/deep"))?.standardizedFileURL.path == repo.standardizedFileURL.path,
              "a folder in a repository finds its root")

        // 0b. a two-finger swipe as macOS 26 sends it: a .began with no movement, movement on
        // .changed, the end as .cancelled (issue 430); and a vertical scroll that is not one
        func scroll(_ v: SwipeScrollView, _ phase: Int64, dx: Int32, dy: Int32 = 0) {
            guard let cg = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0) else { return }
            cg.setIntegerValueField(.scrollWheelEventIsContinuous, value: 1)
            cg.setIntegerValueField(.scrollWheelEventScrollPhase, value: phase)
            if let e = NSEvent(cgEvent: cg) { v.scrollWheel(with: e) }
        }
        let sv = SwipeScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 300))
        sv.documentView = FlippedView(frame: NSRect(x: 0, y: 0, width: 400, height: 2000))
        var swiped: [Bool] = []
        sv.onSwipe = { swiped.append($0) }
        sv.canSwipe = { _ in true }
        let began: Int64 = 1, changed: Int64 = 2, ended: Int64 = 4, cancelled: Int64 = 8
        scroll(sv, began, dx: 0)
        for _ in 0..<5 { scroll(sv, changed, dx: 30) }
        scroll(sv, cancelled, dx: 0)
        check(swiped.count == 1, "a swipe that starts still and ends cancelled counts (\(swiped))")
        swiped = []
        scroll(sv, began, dx: 0)
        for _ in 0..<5 { scroll(sv, changed, dx: 4, dy: -40) }
        scroll(sv, ended, dx: 0)
        check(swiped.isEmpty, "a vertical scroll is not a swipe")
        scroll(sv, began, dx: 0)
        for _ in 0..<2 { scroll(sv, changed, dx: 20) }
        scroll(sv, ended, dx: 0)
        check(swiped.isEmpty, "a short sideways nudge is not a swipe")

        // 0c. a full folder keeps room under its last row whose right click opens the
        // folder's own menu (Open in Terminal…): the inset below the document
        let room = SwipeScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 300))
        room.documentView = FlippedView(frame: NSRect(x: 0, y: 0, width: 400, height: 2000))
        room.automaticallyAdjustsContentInsets = false
        room.contentInsets = NSEdgeInsets(top: 4, left: 0, bottom: 4 + FileListController.tailRoom, right: 0)
        let roomWin = NSWindow(contentRect: room.frame, styleMask: [.borderless], backing: .buffered, defer: true)
        roomWin.contentView = room
        room.contentView.scroll(to: NSPoint(x: 0, y: 2000 - 300 + 4 + FileListController.tailRoom))
        room.reflectScrolledClipView(room.contentView)
        let below = room.hitTest(NSPoint(x: 200, y: 20))
        check(below != nil && below !== room.documentView, "the room under the last row is not a row (\(String(describing: below)))")
        let marker = NSMenu(title: "folder")
        room.emptyMenu = { marker }
        let click = NSEvent.mouseEvent(with: .rightMouseDown, location: NSPoint(x: 200, y: 20), modifierFlags: [], timestamp: 0,
            windowNumber: roomWin.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)
        check(click.map { room.menu(for: $0) === marker } ?? false, "a right click there opens the folder's menu")
        // 0d. light mode contrast and glass appearance (issue 682): active tabs, lenses and option
        // labels stay readable in light mode across Liquid Glass, Translucent and Solid materials
        do {
            let d = UserDefaults.standard
            let savedMaterial = d.object(forKey: "material")
            let savedWash = d.object(forKey: "surfaceWash")
            let savedAccent = d.object(forKey: "accent")
            defer {
                if let savedMaterial { d.set(savedMaterial, forKey: "material") } else { d.removeObject(forKey: "material") }
                if let savedWash { d.set(savedWash, forKey: "surfaceWash") } else { d.removeObject(forKey: "surfaceWash") }
                if let savedAccent { d.set(savedAccent, forKey: "accent") } else { d.removeObject(forKey: "accent") }
                Palette.invalidate()
            }
            d.set(50, forKey: "surfaceWash")
            d.set("", forKey: "accent")
            let lightHost = NSView()
            lightHost.appearance = NSAppearance(named: .aqua)
            let darkHost = NSView()
            darkHost.appearance = NSAppearance(named: .darkAqua)
            let darkWallpaper = Palette.hex(0x1E1E1E)
            let whiteBg = Palette.hex(0xFFFFFF)

            for mat in AppSettings.Material.allCases {
                d.set(mat.rawValue, forKey: "material")
                Palette.invalidate()
                let p = Palette.of(lightHost)
                check(!p.dark, "aqua view resolves light palette (\(mat.rawValue))")
                let baseBg: NSColor
                switch mat {
                case .glass:
                    baseBg = Palette.composite(p.windowBg, over: darkWallpaper)
                case .finder:
                    baseBg = Palette.hex(0xE6E6E6)
                case .solid:
                    baseBg = Palette.composite(p.windowBg, over: darkWallpaper)
                }
                let contentSurface = Palette.composite(p.contentBg, over: baseBg)
                let tabSurface = Palette.composite(mat == .glass ? p.tabActive.withAlphaComponent(0.65) : p.tabActive, over: baseBg)
                check(Palette.contrastRatio(p.text, over: tabSurface) >= 7.0, "light active tab text contrast (\(mat.rawValue))")
                check(Palette.contrastRatio(p.text, over: contentSurface) >= 7.0, "light option title contrast (\(mat.rawValue))")
                check(Palette.contrastRatio(p.textSecondary, over: contentSurface) >= 4.5, "light option detail contrast (\(mat.rawValue))")
                check(Palette.contrastRatio(p.textTertiary, over: whiteBg) >= 4.5, "light tertiary label contrast on white (\(mat.rawValue))")
            }

            d.set("glass", forKey: "material")
            Palette.invalidate()
            for hex in AppSettings.swatches {
                d.set(String(format: "#%06X", hex), forKey: "accent")
                Palette.invalidate()
                let p = Palette.of(lightHost)
                check(Palette.contrastRatio(p.accentText, over: p.accent) >= 4.5, String(format: "light accentText contrast on #%06X", hex))
            }

            let lightLens = LensView(cornerRadius: 8)
            lightLens.appearance = NSAppearance(named: .aqua)
            lightLens.applyAppearance()
            let darkLens = LensView(cornerRadius: 8)
            darkLens.appearance = NSAppearance(named: .darkAqua)
            darkLens.applyAppearance()
            check(lightLens.style == .regular, "light lens uses frosted regular glass")
            check(darkLens.style == .clear, "dark lens keeps clear glass")
            check(Palette.of(darkHost).dark, "darkAqua view resolves dark palette")
        }

        // 1. copy a file and a folder: both arrive whole
        Transfer(.copy, [a.appendingPathComponent("big.bin"), a.appendingPathComponent("folder")], into: b).start(window: nil) { made in
            check(made.count == 2, "copy reports two new items")
            check((try? Data(contentsOf: b.appendingPathComponent("big.bin")).count) == 3_000_000, "copied file is whole")
            check(fm.fileExists(atPath: b.appendingPathComponent("folder/inner/note.txt").path), "copied folder keeps its inside")
            // 2. undo the copy: the copies go to the Trash, the originals stay
            um.undo()
            check(!fm.fileExists(atPath: b.appendingPathComponent("big.bin").path), "undo copy removes the copy")
            check(fm.fileExists(atPath: a.appendingPathComponent("big.bin").path), "undo copy keeps the original")
            // 3. redo: they come back
            um.redo()
            check(fm.fileExists(atPath: b.appendingPathComponent("folder/inner/note.txt").path), "redo copy brings the copies back")
            // 4. a copy into its own folder is "name - Copy"
            Transfer(.copy, [a.appendingPathComponent("big.bin")], into: a).start(window: nil) { made in
                check(made.first?.lastPathComponent == "big - Copy.bin", "copy into its own folder is named “- Copy”")
                // 5. move within the volume, then undo it
                let note = b.appendingPathComponent("folder/inner/note.txt")
                Transfer(.move, [note], into: b).start(window: nil) { made in
                    check(fm.fileExists(atPath: b.appendingPathComponent("note.txt").path) && !fm.fileExists(atPath: note.path), "move puts it in its new place")
                    um.undo()
                    check(fm.fileExists(atPath: note.path) && !fm.fileExists(atPath: b.appendingPathComponent("note.txt").path), "undo move puts it back")
                    // 6. Trash and back
                    let pairs = (try? FileOps.trash([b.appendingPathComponent("big.bin")])) ?? []
                    FileUndo.shared.record(.moves(pairs), title: "Move to Trash")
                    check(!fm.fileExists(atPath: b.appendingPathComponent("big.bin").path), "trash takes it away")
                    um.undo()
                    check(fm.fileExists(atPath: b.appendingPathComponent("big.bin").path), "undo trash brings it back")
                    // 7. rename and back
                    let renamed = try? FileOps.rename(b.appendingPathComponent("big.bin"), to: "huge.bin")
                    if let renamed { FileUndo.shared.record(.moves([(from: renamed, to: b.appendingPathComponent("big.bin"))]), title: "Rename") }
                    check(um.undoMenuItemTitle.contains("Rename"), "Edit says what undo does (\(um.undoMenuItemTitle))")
                    um.undo()
                    check(fm.fileExists(atPath: b.appendingPathComponent("big.bin").path), "undo rename gives the old name back")
                    // 8. the Trash remembers where things came from, and puts them back
                    let pb = (try? FileOps.trash([b.appendingPathComponent("big.bin")])) ?? []
                    check(pb.count == 1 && TrashBin.origin(of: pb[0].from) == b.appendingPathComponent("big.bin"), "Trash remembers the origin")
                    if let t = pb.first { _ = try? TrashBin.putBack([(trashed: t.from, origin: t.to)]) }
                    check(fm.fileExists(atPath: b.appendingPathComponent("big.bin").path), "Put Back returns it")
                    // 9. the organizer: pictures into Pictures/, then ⌘Z brings them back
                    let inbox = root.appendingPathComponent("inbox")
                    try? fm.createDirectory(at: inbox, withIntermediateDirectories: true)
                    for n in ["one.jpg", "two.png", "note.txt"] { fm.createFile(atPath: inbox.appendingPathComponent(n).path, contents: Data("x".utf8)) }
                    let rule = Organizer.Rule(id: 1, name: "Pictures", enabled: true, folder: inbox.path, subfolders: false, join: "all",
                                              conditions: [.init(type: "kind", kinds: ["image"])], action: .init(type: "move_to", folder: "Pictures"), auto: false)
                    let plan = Organizer.plan(Organizer.json([rule]), only: nil)
                    check(plan?.steps.count == 2, "organizer plans the two pictures (\(plan?.steps.count ?? -1))")
                    if let plan { Organizer.execute(plan, quiet: true) }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        check(fm.fileExists(atPath: inbox.appendingPathComponent("Pictures/one.jpg").path), "organizer moved the pictures")
                        check(fm.fileExists(atPath: inbox.appendingPathComponent("note.txt").path), "organizer left the text file")
                        um.undo()
                        check(fm.fileExists(atPath: inbox.appendingPathComponent("one.jpg").path), "undo puts the pictures back")
                        // 10. a paused copy writes nothing until it is resumed (issue 322)
                        let c = root.appendingPathComponent("c")
                        try? fm.createDirectory(at: c, withIntermediateDirectories: true)
                        let paused = Transfer(.copy, [a.appendingPathComponent("big.bin")], into: c)
                        paused.paused = true
                        paused.start(window: nil) { made in
                            check(made.count == 1 && fm.fileExists(atPath: c.appendingPathComponent("big.bin").path), "a resumed copy finishes")
                            // 11. dragged out of an archive: to another app (a promise) and within the app
                            let zip = root.appendingPathComponent("drag.zip")
                            let p = Process()
                            p.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
                            p.arguments = ["-c", "-k", a.appendingPathComponent("folder").path, zip.path]
                            try? p.run()
                            p.waitUntilExit()
                            guard let arc = try? Archive.open(path: zip.path, password: nil) else {
                                check(false, "a test archive opens")
                                return finish(root)
                            }
                            let out = root.appendingPathComponent("out"), d = root.appendingPathComponent("d")
                            try? fm.createDirectory(at: out, withIntermediateDirectories: true)
                            try? fm.createDirectory(at: d, withIntermediateDirectories: true)
                            let promise = ArchiveDrag.provider(arc, inner: "inner/note.txt", isDir: false)
                            var promiseError: Error? = CocoaError(.fileWriteUnknown)
                            ArchivePromises.shared.filePromiseProvider(promise, writePromiseTo: out.appendingPathComponent("note.txt")) { promiseError = $0 }
                            check(promiseError == nil && (try? String(contentsOf: out.appendingPathComponent("note.txt"), encoding: .utf8)) == "hello",
                                  "a member dragged to another app is written there")
                            ArchiveDrag.current = .init(archive: arc, inner: ["inner"])
                            ArchiveDrag.drop(into: d, window: nil)
                            ArchiveDrag.current = nil
                            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                                check(fm.fileExists(atPath: d.appendingPathComponent("inner/note.txt").path), "a folder dragged out of an archive arrives whole")
                                unreadable(root) { links(root) { inside(root) { finish(root) } } }
                            }
                        }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            check(!fm.fileExists(atPath: c.appendingPathComponent("big.bin").path), "a paused copy writes nothing")
                            paused.paused = false
                        }
                    }
                }
            }
        }
    }

    /// Runs hdiutil (a test disk image: another volume, so moves copy and then delete).
    private static func hdiutil(_ args: [String]) -> Bool {
        let p = Process()
        p.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
        p.arguments = args
        p.standardOutput = FileHandle.nullDevice
        p.standardError = FileHandle.nullDevice
        guard (try? p.run()) != nil else { return false }
        p.waitUntilExit()
        return p.terminationStatus == 0
    }

    /// 12. what can't be copied stops the copy, and a move to another disk keeps its source
    /// (issue 712): a folder holding a file nobody may read, copied, then moved onto an exFAT
    /// disk image; readable again, the move goes through.
    private static func unreadable(_ root: URL, then done: @escaping () -> Void) {
        let fm = FileManager.default
        let src = root.appendingPathComponent("locked"), to = root.appendingPathComponent("e")
        let secret = src.appendingPathComponent("sub/secret.txt")
        try? fm.createDirectory(at: secret.deletingLastPathComponent(), withIntermediateDirectories: true)
        try? fm.createDirectory(at: to, withIntermediateDirectories: true)
        fm.createFile(atPath: src.appendingPathComponent("a.txt").path, contents: Data("a".utf8))
        fm.createFile(atPath: secret.path, contents: Data("s".utf8), attributes: [.posixPermissions: 0])
        func readable() { try? fm.setAttributes([.posixPermissions: 0o644], ofItemAtPath: secret.path) }
        var copied = false
        Transfer(.copy, [src], into: to).start(window: nil) { _ in copied = true }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            check(!copied, "a copy that can't read a file does not finish as done")
            let image = root.appendingPathComponent("disk.dmg"), volume = root.appendingPathComponent("volume")
            guard hdiutil(["create", "-size", "8m", "-fs", "ExFAT", "-volname", "RFTEST", image.path]),
                  hdiutil(["attach", "-nobrowse", "-mountpoint", volume.path, image.path]) else {
                check(false, "a test disk image mounts")
                readable()
                return done()
            }
            var moved = false
            Transfer(.move, [src], into: volume).start(window: nil) { _ in moved = true }
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                check(!moved && fm.fileExists(atPath: secret.path), "a move to another disk that can't copy a file keeps its source")
                readable()
                try? fm.removeItem(at: volume.appendingPathComponent("locked"))
                var made: [URL] = []
                Transfer(.move, [src], into: volume).start(window: nil) { made = $0 }
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    check(made.count == 1 && !fm.fileExists(atPath: src.path)
                          && (try? String(contentsOf: volume.appendingPathComponent("locked/sub/secret.txt"), encoding: .utf8)) == "s",
                          "a move to another disk that copied everything deletes its source")
                    _ = hdiutil(["detach", volume.path])
                    done()
                }
            }
        }
    }

    /// 13. links are checked as links: a folder holding a link to nothing arrives whole on an
    /// APFS image, so its move removes the source, and a copy of it back passes Check copies.
    private static func links(_ root: URL, then done: @escaping () -> Void) {
        let fm = FileManager.default
        let src = root.appendingPathComponent("links")
        try? fm.createDirectory(at: src, withIntermediateDirectories: true)
        fm.createFile(atPath: src.appendingPathComponent("f.txt").path, contents: Data("f".utf8))
        try? fm.createSymbolicLink(atPath: src.appendingPathComponent("to-f").path, withDestinationPath: "f.txt")
        try? fm.createSymbolicLink(atPath: src.appendingPathComponent("to-nothing").path, withDestinationPath: "/nonexistent")
        let image = root.appendingPathComponent("apfs.dmg"), volume = root.appendingPathComponent("apfs")
        guard hdiutil(["create", "-size", "20m", "-fs", "APFS", "-volname", "RFTEST2", image.path]),
              hdiutil(["attach", "-nobrowse", "-mountpoint", volume.path, image.path]) else {
            check(false, "a test APFS image mounts")
            return done()
        }
        var made: [URL] = []
        Transfer(.move, [src], into: volume).start(window: nil) { made = $0 }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            let link = try? fm.destinationOfSymbolicLink(atPath: volume.appendingPathComponent("links/to-nothing").path)
            check(made.count == 1 && !fm.fileExists(atPath: src.path) && link == "/nonexistent",
                  "a move to another disk of a folder holding a link to nothing goes through")
            // Check copies (full) on for this one copy back: the copy is read through, the links compared as links
            let d = UserDefaults.standard, was = d.object(forKey: "verifyCopies")
            d.set("full", forKey: "verifyCopies")
            var back: [URL] = []
            Transfer(.copy, [volume.appendingPathComponent("links")], into: root).start(window: nil) { back = $0 }
            if let was { d.set(was, forKey: "verifyCopies") } else { d.removeObject(forKey: "verifyCopies") }
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                check(back.count == 1 && fm.fileExists(atPath: src.appendingPathComponent("f.txt").path),
                      "a checked copy of a folder holding a link to nothing goes through")
                _ = hdiutil(["detach", volume.path])
                done()
            }
        }
    }

    /// 14. a folder can't be put inside itself by another spelling of the way in (issue 759):
    /// through a link to its own subfolder, or in other letter case on a disk that ignores it.
    private static func inside(_ root: URL, then done: @escaping () -> Void) {
        let fm = FileManager.default
        let box = root.appendingPathComponent("Box"), sub = box.appendingPathComponent("sub")
        let link = root.appendingPathComponent("to-sub"), other = root.appendingPathComponent("box/sub")
        try? fm.createDirectory(at: sub, withIntermediateDirectories: true)
        fm.createFile(atPath: box.appendingPathComponent("f.txt").path, contents: Data("f".utf8))
        try? fm.createSymbolicLink(at: link, withDestinationURL: sub)
        let caseless = fm.fileExists(atPath: other.path)
        var done1 = false, done2 = false
        Transfer(.copy, [box], into: link).start(window: nil) { _ in done1 = true }
        if caseless { Transfer(.copy, [box], into: other).start(window: nil) { _ in done2 = true } }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            check(!done1 && !fm.fileExists(atPath: sub.appendingPathComponent("Box").path),
                  "a copy into a link to its own subfolder is refused")
            if caseless {
                check(!done2 && !fm.fileExists(atPath: sub.appendingPathComponent("Box").path),
                      "a copy into its own subfolder in other letter case is refused")
            }
            check((try? FileOps.paste([box], into: link, move: false)) == nil
                  && !fm.fileExists(atPath: sub.appendingPathComponent("Box").path),
                  "a paste into a link to its own subfolder is refused")
            if caseless {
                check((try? FileOps.paste([box], into: other, move: false)) == nil
                      && !fm.fileExists(atPath: sub.appendingPathComponent("Box").path),
                      "a paste into its own subfolder in other letter case is refused")
            }
            let toBox = root.appendingPathComponent("to-box")
            try? fm.createSymbolicLink(at: toBox, withDestinationURL: box)
            let pasted = (try? FileOps.paste([toBox], into: sub, move: false))?.first
            check(pasted.flatMap { try? fm.destinationOfSymbolicLink(atPath: $0.path) } != nil,
                  "a link to a folder pastes into that folder as a link")
            // the same two ways in on exFAT, a disk without APFS's file identities of its own
            let image = root.appendingPathComponent("inside.dmg"), volume = root.appendingPathComponent("inside")
            guard hdiutil(["create", "-size", "8m", "-fs", "ExFAT", "-volname", "RFTEST3", image.path]),
                  hdiutil(["attach", "-nobrowse", "-mountpoint", volume.path, image.path]) else {
                check(false, "a test exFAT image mounts")
                return done()
            }
            let xbox = volume.appendingPathComponent("Box"), xsub = xbox.appendingPathComponent("sub")
            let xlink = volume.appendingPathComponent("to-sub")
            try? fm.createDirectory(at: xsub, withIntermediateDirectories: true)
            fm.createFile(atPath: xbox.appendingPathComponent("f.txt").path, contents: Data("f".utf8))
            try? fm.createSymbolicLink(at: xlink, withDestinationURL: xsub)
            var xdone1 = false, xdone2 = false
            Transfer(.copy, [xbox], into: xlink).start(window: nil) { _ in xdone1 = true }
            Transfer(.copy, [xbox], into: volume.appendingPathComponent("box/sub")).start(window: nil) { _ in xdone2 = true }
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                check(!xdone1 && !xdone2 && !fm.fileExists(atPath: xsub.appendingPathComponent("Box").path),
                      "on exFAT a copy into its own subfolder by a link or other letter case is refused")
                let vol = try? volume.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey])
                check(vol.map { HomeView.freeBytes($0) > 0 } ?? false, "an exFAT disk's free space is not 0 (issue 758)")
                _ = hdiutil(["detach", volume.path])
                done()
            }
        }
    }
}