Repository Public License
1// ORIX Convert — App/Sources/Features/Shared/SystemIntegration.swift2// Description: Finder actions, Quick Look panel, Dock badge and progress, and the local "batch finished"3// notification (permission asked lazily; nothing leaves the Mac).4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import AppKit6import Quartz7import UserNotifications89enum FileActions {10 static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }1112 /// Selects the items in the Finder; items that no longer exist are ignored. Returns `false` when none exists.13 @discardableResult14 static func reveal(_ urls: [URL]) -> Bool {15 let present = urls.filter(exists)16 guard !present.isEmpty else { return false }17 NSWorkspace.shared.activateFileViewerSelecting(present)18 return true19 }2021 @discardableResult22 static func open(_ url: URL) -> Bool {23 guard exists(url) else { return false }24 return NSWorkspace.shared.open(url)25 }2627 static func copy(_ text: String) {28 NSPasteboard.general.clearContents()29 NSPasteboard.general.setString(text, forType: .string)30 }31}3233/// Quick Look panel for a list of files.34final class QuickLook: NSObject, QLPreviewPanelDataSource {35 static let shared = QuickLook()36 /// Read by the panel on the main thread only.37 nonisolated(unsafe) private var urls: [NSURL] = []3839 static func show(_ items: [URL]) {40 let present = items.filter(FileActions.exists)41 guard !present.isEmpty, let panel = QLPreviewPanel.shared() else { return }42 shared.urls = present.map { $0 as NSURL }43 panel.dataSource = shared44 panel.reloadData()45 if panel.isVisible { panel.currentPreviewItemIndex = 0 } else { panel.makeKeyAndOrderFront(nil) }46 }4748 static func toggle(_ items: [URL]) {49 if let panel = QLPreviewPanel.shared(), panel.isVisible { panel.orderOut(nil) } else { show(items) }50 }5152 nonisolated func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { urls.count }53 nonisolated func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! {54 index < urls.count ? urls[index] : nil55 }56}5758/// Dock tile: a badge with the number of jobs left and a progress bar under the icon while a batch runs.59final class DockProgress {60 private var view: DockTileView?61 private var lastKey = ""6263 func update(progress: (fraction: Double?, done: Int, total: Int)?, remaining: Int, needsDecision: Int) {64 let key = "\(progress.map { "\(Int(($0.fraction ?? -1) * 100))" } ?? "none")|\(remaining)|\(needsDecision)"65 guard key != lastKey else { return }66 lastKey = key67 let tile = NSApp.dockTile68 tile.badgeLabel = needsDecision > 0 ? "?" : (remaining > 0 ? Fmt.count(remaining) : nil)69 if let progress {70 let view = view ?? DockTileView(frame: NSRect(x: 0, y: 0, width: 128, height: 128))71 self.view = view72 view.fraction = progress.fraction73 if tile.contentView !== view { tile.contentView = view }74 } else {75 tile.contentView = nil76 view = nil77 }78 tile.display()79 }80}8182private final class DockTileView: NSView {83 /// `nil`: running without a measured fraction (hatched bar instead of a made-up fill).84 var fraction: Double?8586 override func draw(_ dirtyRect: NSRect) {87 NSApp.applicationIconImage.draw(in: bounds)88 let track = NSRect(x: 14, y: 10, width: bounds.width - 28, height: 12)89 let path = NSBezierPath(roundedRect: track, xRadius: 6, yRadius: 6)90 NSColor.black.withAlphaComponent(0.65).setFill()91 path.fill()92 let inner = track.insetBy(dx: 2, dy: 2)93 if let fraction {94 let fill = NSRect(x: inner.minX, y: inner.minY, width: max(inner.height, inner.width * min(1, max(0, fraction))), height: inner.height)95 NSGradient(colors: [NSColor(hex: 0xFB7A5C), NSColor(hex: 0x8B5CF6), NSColor(hex: 0x22D3EE)])?96 .draw(in: NSBezierPath(roundedRect: fill, xRadius: 4, yRadius: 4), angle: 0)97 } else {98 NSGraphicsContext.saveGraphicsState()99 NSBezierPath(roundedRect: inner, xRadius: 4, yRadius: 4).addClip()100 NSColor.white.withAlphaComponent(0.8).setStroke()101 var x = inner.minX - inner.height102 while x < inner.maxX {103 let line = NSBezierPath()104 line.move(to: NSPoint(x: x, y: inner.minY))105 line.line(to: NSPoint(x: x + inner.height, y: inner.maxY))106 line.lineWidth = 2107 line.stroke()108 x += 7109 }110 NSGraphicsContext.restoreGraphicsState()111 }112 }113}114115/// Local notification when a batch ends while the app is in the background.116enum Notifier {117 static func runFinished(_ summary: RunSummary, awaitingDecisions: Int) {118 var parts: [String] = []119 if summary.finished > 0 { parts.append(L("%lld converted", summary.finished)) }120 if summary.failed > 0 { parts.append(L("%lld failed", summary.failed)) }121 if summary.skipped > 0 { parts.append(L("%lld skipped", summary.skipped)) }122 if summary.cancelled > 0 { parts.append(L("%lld cancelled", summary.cancelled)) }123 if awaitingDecisions > 0 { parts.append(L("%lld waiting for your decision", awaitingDecisions)) }124 let title = summary.failed > 0 ? L("Conversion finished with errors") : L("Conversion finished")125 let body = parts.joined(separator: " · ")126 let center = UNUserNotificationCenter.current()127 Task {128 // Asked the first time a batch ends in the background, not at launch.129 guard (try? await center.requestAuthorization(options: [.alert, .sound])) == true else { return }130 let content = UNMutableNotificationContent()131 content.title = title132 content.body = body133 content.sound = .default134 try? await center.add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil))135 }136 }137}138