Skip to content

Screenshots, hung out to dry. A tiny native macOS app that hangs every screenshot on a line at the top of your screen.

Swift
5.1 KB
Raw Blame
import AppKit

/// Hangs images copied to the clipboard, like a screenshot taken with Control
/// held or an image copied in Preview. Each one is saved as a PNG in
/// Tendedero's own folder, so on the line it behaves like any screenshot.
///
/// Off until the user turns it on. The pasteboard has no change notification,
/// so its change count is checked twice a second; what was copied is only read
/// once its types say it is a picture and nothing else.
@MainActor
final class ClipboardWatcher {
    private let onImage: (URL) -> Void
    private var timer: Timer?
    private var lastCount = NSPasteboard.general.changeCount
    /// The last image saved. Some apps put the same image on the clipboard
    /// again; it hangs once, unless it has been taken down since.
    private var last: (png: Data, url: URL)?

    private static let enabledKey = "clipboardEnabled"

    static var isEnabled: Bool {
        get { UserDefaults.standard.bool(forKey: enabledKey) }
        set { UserDefaults.standard.set(newValue, forKey: enabledKey) }
    }

    /// Copies that carry a picture but are not one. Text from a spreadsheet
    /// or a document also comes as an image of itself. A file copied in
    /// Finder brings its icon, and a photo copied from the line brings its
    /// file. Password managers and similar apps mark private or temporary
    /// copies, following nspasteboard.org.
    private static let ignoredTypes: Set<NSPasteboard.PasteboardType> = [
        .string, .fileURL,
        .init("org.nspasteboard.ConcealedType"),
        .init("org.nspasteboard.TransientType"),
        .init("org.nspasteboard.AutoGeneratedType"),
    ]

    /// Anything bigger is not a screenshot.
    private static let maxBytes = 64 * 1024 * 1024
    nonisolated private static let maxPixels = 80_000_000

    init(onImage: @escaping (URL) -> Void) {
        self.onImage = onImage
    }

    func start() {
        guard timer == nil else { return }
        // Whatever is on the clipboard already is old news.
        lastCount = NSPasteboard.general.changeCount
        let timer = Timer(timeInterval: 0.5, repeats: true) { [weak self] _ in
            MainActor.assumeIsolated { self?.check() }
        }
        RunLoop.main.add(timer, forMode: .common)
        self.timer = timer
    }

    func stop() {
        timer?.invalidate()
        timer = nil
    }

    private func check() {
        let pb = NSPasteboard.general
        let count = pb.changeCount
        guard count != lastCount else { return }
        lastCount = count
        guard let items = pb.pasteboardItems, !items.isEmpty,
              items.allSatisfy({ Self.ignoredTypes.isDisjoint(with: $0.types) }),
              let type = pb.availableType(from: [.png, .tiff]),
              let data = pb.data(forType: type), data.count <= Self.maxBytes,
              pb.changeCount == count else { return }
        // Decoding a large image takes a moment, so it happens off the main thread.
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let png = ClipboardWatcher.png(from: data, type: type)
            DispatchQueue.main.async {
                // Copied over again in the meantime: that copy is the one that
                // counts. Turned off in the meantime: nothing hangs.
                guard let png, NSPasteboard.general.changeCount == count,
                      let self, self.timer != nil else { return }
                self.save(png)
            }
        }
    }

    /// PNG bytes are kept as they are; TIFF becomes PNG. Either way the image
    /// must decode and have a sane size.
    nonisolated private static func png(from data: Data, type: NSPasteboard.PasteboardType) -> Data? {
        guard let rep = NSBitmapImageRep(data: data),
              rep.pixelsWide > 0, rep.pixelsHigh > 0,
              rep.pixelsWide <= maxPixels / rep.pixelsHigh else { return nil }
        return type == .png ? data : rep.representation(using: .png, properties: [:])
    }

    private func save(_ png: Data) {
        if let last, last.png == png, FileManager.default.fileExists(atPath: last.url.path) { return }
        let fm = FileManager.default
        var url = Inbox.folder.appendingPathComponent("Clipboard \(Self.stamp()).png")
        var n = 2
        while fm.fileExists(atPath: url.path) {
            url = Inbox.folder.appendingPathComponent("Clipboard \(Self.stamp()) \(n).png")
            n += 1
        }
        do {
            try fm.createDirectory(at: Inbox.folder, withIntermediateDirectories: true)
            try png.write(to: url, options: .atomic)
            // What people copy can be private: only they can read it.
            try fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
            last = (png, url)
            onImage(url)
        } catch {
            try? fm.removeItem(at: url)
            log.error("Could not save a copied image: \(error.localizedDescription, privacy: .public)")
        }
    }

    private static func stamp() -> String {
        let f = DateFormatter()
        f.locale = Locale(identifier: "en_US_POSIX")
        f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
        return f.string(from: Date())
    }
}