import Foundation import Darwin public enum TransferKind: String, Codable { case copy, move, trash, delete } public struct TransferJob: Identifiable { public let id = UUID() public let kind: TransferKind public let sources: [URL] /// Cartella di destinazione (copia e sposta). public let destination: URL? /// Nuovo nome, solo con un elemento. public let newName: String? public init(kind: TransferKind, sources: [URL], destination: URL? = nil, newName: String? = nil) { self.kind = kind self.sources = sources self.destination = destination self.newName = sources.count == 1 ? newName : nil } public var title: String { let what = sources.count == 1 ? "\"\(newName ?? sources[0].lastPathComponent)\"" : "\(sources.count) elementi" let dest = destination.map { Format.path($0) } ?? "" switch kind { case .copy: return "Copia di \(what) in \(dest)" case .move: return "Spostamento di \(what) in \(dest)" case .trash: return "Cestino: \(what)" case .delete: return "Eliminazione di \(what)" } } } public enum ConflictChoice { case overwrite, overwriteAll, skip, skipAll, cancel } public enum ErrorChoice { case skip, cancel } public enum TrashFallback { case deletePermanently, deleteAllPermanently, skip, cancel } public struct TransferError: LocalizedError { public let message: String public init(_ message: String) { self.message = message } public var errorDescription: String? { message } } /// Chiamate dal thread di lavoro: chi risponde a conflitti ed errori può bloccare. public protocol TransferEngineDelegate: AnyObject { func engine(_ engine: TransferEngine, progress done: Int64, of total: Int64, current: String) func engine(_ engine: TransferEngine, conflictAt destination: URL, source: URL) -> ConflictChoice func engine(_ engine: TransferEngine, error: Error, at url: URL) -> ErrorChoice func engine(_ engine: TransferEngine, trashFailedFor url: URL, error: Error) -> TrashFallback } /// Esegue un'operazione alla volta, in modo sincrono, sul thread che la chiama. public final class TransferEngine { public weak var delegate: TransferEngineDelegate? private let lock = NSLock() private var cancelled = false private let fm = FileManager() private var totalBytes: Int64 = 0 private var doneBytes: Int64 = 0 private var currentName = "" private var conflictPolicy: ConflictChoice? private var trashPolicy: TrashFallback? public init() {} public var isCancelled: Bool { lock.lock(); defer { lock.unlock() } return cancelled } public func cancel() { lock.lock(); cancelled = true; lock.unlock() } public enum Outcome { case completed, cancelled } @discardableResult public func run(_ job: TransferJob) -> Outcome { switch job.kind { case .trash, .delete: runDelete(job) case .copy, .move: runTransfer(job) } return isCancelled ? .cancelled : .completed } // MARK: - Elimina private func runDelete(_ job: TransferJob) { totalBytes = Int64(job.sources.count) for (i, src) in job.sources.enumerated() { if isCancelled { return } currentName = src.lastPathComponent report(Int64(i)) if job.kind == .trash && trashPolicy != .deleteAllPermanently { do { try fm.trashItem(at: src, resultingItemURL: nil) continue } catch { let choice = delegate?.engine(self, trashFailedFor: src, error: error) ?? .skip switch choice { case .skip: continue case .cancel: cancel(); return case .deleteAllPermanently: trashPolicy = .deleteAllPermanently case .deletePermanently: break } } } do { try fm.removeItem(at: src) } catch { if ask(error, src) == .cancel { return } } } report(totalBytes) } // MARK: - Copia e sposta private func runTransfer(_ job: TransferJob) { guard let destDir = job.destination?.standardizedFileURL else { return } if !lexists(destDir) { do { try fm.createDirectory(at: destDir, withIntermediateDirectories: true) } catch { _ = ask(error, destDir) return } } let move = job.kind == .move var plan: [(src: URL, dst: URL, rename: Bool)] = [] for src in job.sources { let src = src.standardizedFileURL let dst = destDir.appendingPathComponent(job.newName ?? src.lastPathComponent) if src.path == dst.path { if ask(TransferError("Origine e destinazione coincidono: \(src.lastPathComponent)"), src) == .cancel { return } continue } if isRealDir(src) && dst.path.hasPrefix(src.path + "/") { if ask(TransferError("Non si può copiare una cartella dentro se stessa: \(src.lastPathComponent)"), src) == .cancel { return } continue } plan.append((src, dst, move && sameVolume(src, destDir))) } totalBytes = plan.filter { !$0.rename }.reduce(0) { $0 + DirectoryLister.totalSize(of: $1.src, isCancelled: { self.isCancelled }).bytes } doneBytes = 0 for step in plan { if isCancelled { return } if step.rename { currentName = step.src.lastPathComponent report(doneBytes) _ = moveSameVolume(step.src, step.dst) } else { let ok = copyRecursive(step.src, step.dst) if ok && move && !isCancelled { do { try fm.removeItem(at: step.src) } catch { if ask(error, step.src) == .cancel { return } } } } } report(totalBytes) } private func moveSameVolume(_ src: URL, _ dst: URL) -> Bool { if isCancelled { return false } if lexists(dst) { if isRealDir(src) && isRealDir(dst) { // Unisce le cartelle, chiedendo per ogni file che esiste già. var all = true let children = (try? fm.contentsOfDirectory(at: src, includingPropertiesForKeys: nil)) ?? [] for c in children where !moveSameVolume(c, dst.appendingPathComponent(c.lastPathComponent)) { all = false } if all && !isCancelled { try? fm.removeItem(at: src) } return all } switch resolveConflict(src, dst) { case .overwrite: do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false } default: return false } } do { try fm.moveItem(at: src, to: dst) return true } catch { _ = ask(error, src) return false } } /// true se l'elemento è stato copiato tutto (serve per lo spostamento tra dischi). private func copyRecursive(_ src: URL, _ dst: URL) -> Bool { if isCancelled { return false } if isRealDir(src) { if lexists(dst) && !isRealDir(dst) { guard resolveConflict(src, dst) == .overwrite else { return false } do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false } } if !lexists(dst) { do { try fm.createDirectory(at: dst, withIntermediateDirectories: false) } catch { _ = ask(error, dst) return false } } let children: [URL] do { children = try fm.contentsOfDirectory(at: src, includingPropertiesForKeys: nil) } catch { _ = ask(error, src) return false } var all = true for c in children { if !copyRecursive(c, dst.appendingPathComponent(c.lastPathComponent)) { all = false } if isCancelled { return false } } // Date, permessi e attributi della cartella, dopo averla riempita. copyfile(src.path, dst.path, nil, copyfile_flags_t(CF.metadata)) return all } if lexists(dst) { guard resolveConflict(src, dst) == .overwrite else { return false } do { try fm.removeItem(at: dst) } catch { _ = ask(error, dst); return false } } return copyFile(src, dst) } private func copyFile(_ src: URL, _ dst: URL) -> Bool { var st = stat() let size: Int64 = lstat(src.path, &st) == 0 ? Int64(st.st_size) : 0 currentName = src.lastPathComponent report(doneBytes) let state = copyfile_state_alloc() defer { copyfile_state_free(state) } copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CB), unsafeBitCast(TransferEngine.callback, to: UnsafeRawPointer.self)) copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CTX), Unmanaged.passUnretained(self).toOpaque()) let flags = CF.all | CF.excl | CF.nofollowSrc | CF.clone let r = copyfile(src.path, dst.path, state, copyfile_flags_t(flags)) if r != 0 { let code = errno if lexists(dst) { try? fm.removeItem(at: dst) } if isCancelled { return false } _ = ask(NSError(domain: NSPOSIXErrorDomain, code: Int(code)), src) return false } doneBytes += size report(doneBytes) return true } fileprivate func fileProgress(_ copied: Int64) { report(doneBytes + copied) } private static let callback: copyfile_callback_t = { what, stage, state, _, _, ctx in guard let ctx else { return COPYFILE_CONTINUE } let engine = Unmanaged.fromOpaque(ctx).takeUnretainedValue() if engine.isCancelled { return COPYFILE_QUIT } if what == COPYFILE_COPY_DATA && stage == COPYFILE_PROGRESS { var copied: off_t = 0 copyfile_state_get(state, UInt32(COPYFILE_STATE_COPIED), &copied) engine.fileProgress(Int64(copied)) } return COPYFILE_CONTINUE } // MARK: - Aiuti private func report(_ done: Int64) { delegate?.engine(self, progress: done, of: totalBytes, current: currentName) } private func resolveConflict(_ src: URL, _ dst: URL) -> ConflictChoice { if let p = conflictPolicy { return p == .overwriteAll ? .overwrite : .skip } let c = delegate?.engine(self, conflictAt: dst, source: src) ?? .skip switch c { case .overwriteAll: conflictPolicy = .overwriteAll; return .overwrite case .skipAll: conflictPolicy = .skipAll; return .skip case .cancel: cancel(); return .cancel default: return c } } private func ask(_ error: Error, _ url: URL) -> ErrorChoice { let c = delegate?.engine(self, error: error, at: url) ?? .skip if c == .cancel { cancel() } return c } private func lexists(_ u: URL) -> Bool { var st = stat() return lstat(u.path, &st) == 0 } private func isRealDir(_ u: URL) -> Bool { var st = stat() return lstat(u.path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR } private func sameVolume(_ a: URL, _ b: URL) -> Bool { var sa = stat(), sb = stat() guard lstat(a.path, &sa) == 0, stat(b.path, &sb) == 0 else { return false } return sa.st_dev == sb.st_dev } } /// Valori di copyfile.h (alcuni sono macro composte che Swift non importa). enum CF { static let acl: UInt32 = 1 << 0 static let stat: UInt32 = 1 << 1 static let xattr: UInt32 = 1 << 2 static let data: UInt32 = 1 << 3 static let metadata: UInt32 = acl | stat | xattr static let all: UInt32 = metadata | data static let excl: UInt32 = 1 << 17 static let nofollowSrc: UInt32 = 1 << 18 static let clone: UInt32 = 1 << 24 }