Screenshots, hung out to dry. A tiny native macOS app that hangs every screenshot on a line at the top of your screen.
Swift
Start the watchers without blocking launch (#22)
Zacka84568e15b10
diff --git a/Sources/Tendedero/ScreenshotWatcher.swift b/Sources/Tendedero/ScreenshotWatcher.swiftindex b90eaf6..9462fe7 100644--- a/Sources/Tendedero/ScreenshotWatcher.swift+++ b/Sources/Tendedero/ScreenshotWatcher.swift@@ -8,9 +8,17 @@ final class ScreenshotWatcher {/// On the Desktop we only accept real screenshots, tagged by macOS with an/// extended attribute. In a dedicated folder, any image counts.private let onlyTaggedScreenshots: Bool- private var known = Set<String>()+ private var known: Set<String>?private var source: DispatchSourceFileSystemObject?private var pending: DispatchWorkItem?+ /// A `start()` that is still waiting on the folder, off the main thread.+ private var starting = false+ /// A folder listing that is still on its way, off the main thread.+ private var listing = false+ /// A capture landed while that listing was in flight.+ private var missed = false+ /// `stop()` arrived while one of the two was still pending.+ private var stopped = falseprivate let onNew: (URL) -> Voidprivate let onChange: () -> Void@@ -47,14 +55,31 @@ final class ScreenshotWatcher {/// access at that moment).private let launchDate = Date()+ /// The folder is opened off the main thread, because `open()` blocks while+ /// macOS asks whether Tendedero may look inside it. On the Desktop that is+ /// the consent prompt, and it waits for an answer. Asking from+ /// `applicationDidFinishLaunching` meant the app had not finished launching+ /// while that was pending: no status item appeared, and the signal sources+ /// that put the screenshot settings back never ran.func start() {- let files = listing()- known = Set(files.filter { creationDate($0) < launchDate }.map(\.path))- for url in files where !known.contains(url.path) && isCandidate(url) {- onNew(url)+ stopped = false+ guard source == nil, !starting else { return }+ starting = true+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in+ guard let self else { return }+ let fd = open(self.folder.path, O_EVTONLY)+ DispatchQueue.main.async { self.watch(fd) }+ }+ }++ /// Starts watching, then reads the folder. The watcher is live before the+ /// listing begins, so a capture that lands in between is not lost.+ private func watch(_ fd: Int32) {+ starting = false+ guard !stopped else {+ if fd >= 0 { close(fd) }+ return}- known = Set(files.map(\.path))- let fd = open(folder.path, O_EVTONLY)guard fd >= 0 else {NSLog("Tendedero: cannot watch \(folder.path)")return@@ -65,32 +90,68 @@ final class ScreenshotWatcher {src.setCancelHandler { close(fd) }src.resume()source = src+ refresh()}+ /// Safe to call while `start()` or a listing is still pending: the file+ /// descriptor is closed as soon as it arrives, and a listing that lands+ /// afterwards is dropped.func stop() {+ stopped = true+ missed = falsepending?.cancel()+ pending = nilsource?.cancel()source = nil}private func scheduleScan() {pending?.cancel()- let work = DispatchWorkItem { [weak self] in self?.scan() }+ let work = DispatchWorkItem { [weak self] in self?.refresh() }pending = work// macOS writes a hidden temp file and renames it; give it a moment.DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: work)}- private func scan() {- let files = listing()- for url in files where !known.contains(url.path) && isCandidate(url) {+ /// Reads the folder off the main thread. Sorting by creation date and+ /// reading it back costs one filesystem call per file, and this folder can+ /// be the Desktop, so none of it belongs on the main thread.+ private func refresh() {+ guard !listing else {+ missed = true+ return+ }+ listing = true+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in+ guard let self else { return }+ let files = self.listFolder()+ let settled = files.filter { self.creationDate($0) < self.launchDate }+ let candidates = files.filter { self.isCandidate($0) }+ DispatchQueue.main.async { self.adopt(files, settled, candidates) }+ }+ }++ /// Takes a finished listing, reports what is new, then runs the listing+ /// that was asked for while this one was in flight.+ private func adopt(_ files: [URL], _ settled: [URL], _ candidates: [URL]) {+ listing = false+ guard !stopped else { return }+ // The first listing adopts everything that was already there when the+ // app launched. Later ones compare against the previous listing.+ let first = known == nil+ let base = known ?? Set(settled.map(\.path))+ for url in candidates where !base.contains(url.path) {onNew(url)}known = Set(files.map(\.path))- onChange()+ if !first { onChange() }+ if missed {+ missed = false+ refresh()+ }}- private func listing() -> [URL] {+ private func listFolder() -> [URL] {let urls = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles])) ?? []return urls.sorted { creationDate($0) < creationDate($1) }