Screenshots, hung out to dry. A tiny native macOS app that hangs every screenshot on a line at the top of your screen.
Swift
Hang images copied to the clipboard (#1)
Anubhav-Rai71dffdf85e3b
diff --git a/README.md b/README.mdindex 105a119..a2dab9a 100644--- a/README.md+++ b/README.md@@ -65,6 +65,16 @@ Same shortcuts. Same muscle memory. Just less mess.<br>+## Copied images too.++Take a screenshot with <kbd>⌃</kbd> held, or copy an image in Preview, and it+hangs on the line like any other. Turn on Hang copied images in the menu bar+and the shirt fills in while it is on. Only images: anything copied along+with text or a file, and anything a password manager marks as private, is+left alone.++<br>+## Private by design.No account. No network. No analytics.@@ -124,6 +134,7 @@ so macOS asks again for access to the Desktop after each rebuild.| `PeggedView.swift` | One photo: glass frame, clip, swing and breeze || `GrabArea.swift` | Click, long press, drag and drop || `ScreenshotWatcher.swift` | Notices new screenshots |+| `ClipboardWatcher.swift` | Notices images copied to the clipboard || `Inbox.swift` | Takes over screenshot settings and puts them back || `Markup.swift` | Opens the system Markup editor and saves the result || `Trim.swift` | Trims a screen recording and saves the result |diff --git a/Sources/Tendedero/AppDelegate.swift b/Sources/Tendedero/AppDelegate.swiftindex eaae6c6..ba0dc9b 100644--- a/Sources/Tendedero/AppDelegate.swift+++ b/Sources/Tendedero/AppDelegate.swift@@ -14,6 +14,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {/// ignores the screenshot settings (macOS 27 renamed one), captures keep/// landing on the Desktop, and they still hang on the line.private var safetyWatcher: ScreenshotWatcher?+ private var clipboardWatcher: ClipboardWatcher!private var signalSources: [DispatchSourceSignal] = []private var hotKey: HotKey?private var cancellables = Set<AnyCancellable>()@@ -51,6 +52,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {if Inbox.isEnabled { Inbox.apply() }restoreSettingsOnTermination()startWatcher()+ clipboardWatcher = ClipboardWatcher { [weak self] url in self?.hangCapture(url) }+ if ClipboardWatcher.isEnabled { clipboardWatcher.start() }hotKey = HotKey(keyCode: kVK_ANSI_T, modifiers: controlKey | optionKey) { [weak self] inself?.toggle()@@ -157,6 +160,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {if alert.runModal() == .alertFirstButtonReturn { setInbox(true) }}+ /// Watching the clipboard is opt in, from the menu bar only.+ private func setClipboard(_ on: Bool) {+ ClipboardWatcher.isEnabled = on+ if on { clipboardWatcher.start() } else { clipboardWatcher.stop() }+ updateStatusIcon()+ }+/// Quitting from the menu or logging out runs applicationWillTerminate./// A plain kill does not, so settings are also restored on those signals.private func restoreSettingsOnTermination() {@@ -468,14 +478,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {private func setUpStatusItem() {statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)- let image = NSImage(systemSymbolName: "tshirt", accessibilityDescription: "Tendedero")- image?.isTemplate = true- statusItem.button?.image = image+ updateStatusIcon()let menu = NSMenu()menu.delegate = selfstatusItem.menu = menu}+ /// The shirt fills in while copied images are hung, so it shows at a+ /// glance that the clipboard is being watched.+ private func updateStatusIcon() {+ let on = ClipboardWatcher.isEnabled+ let description = on ? L("Tendedero, hanging copied images") : "Tendedero"+ let image = NSImage(systemSymbolName: on ? "tshirt.fill" : "tshirt", accessibilityDescription: description)+ image?.isTemplate = true+ statusItem.button?.image = image+ statusItem.button?.toolTip = description+ }+func menuNeedsUpdate(_ menu: NSMenu) {menu.removeAllItems()@@ -499,6 +518,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {inbox.toolTip = L("Screenshots hang instantly and skip the Desktop")menu.addItem(inbox)+ let clipboard = ClosureMenuItem(L("Hang copied images")) { [weak self] in+ self?.setClipboard(!ClipboardWatcher.isEnabled)+ }+ clipboard.state = ClipboardWatcher.isEnabled ? .on : .off+ clipboard.toolTip = L("Images you copy hang on the line too")+ menu.addItem(clipboard)+menu.addItem(ClosureMenuItem(L("Open screenshots folder")) { [weak self] inguard let self else { return }NSWorkspace.shared.open(self.watcher.folder)diff --git a/Sources/Tendedero/ClipboardWatcher.swift b/Sources/Tendedero/ClipboardWatcher.swiftnew file mode 100644index 0000000..f18b209--- /dev/null+++ b/Sources/Tendedero/ClipboardWatcher.swift@@ -0,0 +1,120 @@+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.+ guard let png, NSPasteboard.general.changeCount == count 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())+ }+}diff --git a/Sources/Tendedero/Resources/az.lproj/Localizable.strings b/Sources/Tendedero/Resources/az.lproj/Localizable.stringsindex 95055e9..eeec7ab 100644--- a/Sources/Tendedero/Resources/az.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/az.lproj/Localizable.strings@@ -18,6 +18,9 @@"Quit Tendedero" = "Tendedero-dan çıx";"Could not change the login setting" = "Giriş ayarını dəyişmək alınmadı";"Move Tendedero to the Applications folder and try again." = "Tendedero-nu Applications (Proqramlar) qovluğuna köçürün və yenidən cəhd edin.";+"Hang copied images" = "Kopyalanmış şəkilləri as";+"Images you copy hang on the line too" = "Kopyaladığınız şəkillər də ipdən asılır";+"Tendedero, hanging copied images" = "Tendedero, kopyalanmış şəkilləri asır";/* GrabArea */"Copy" = "Kopyala";diff --git a/Sources/Tendedero/Resources/en.lproj/Localizable.strings b/Sources/Tendedero/Resources/en.lproj/Localizable.stringsindex 49842ba..b91a0be 100644--- a/Sources/Tendedero/Resources/en.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/en.lproj/Localizable.strings@@ -18,6 +18,9 @@"Quit Tendedero" = "Quit Tendedero";"Could not change the login setting" = "Could not change the login setting";"Move Tendedero to the Applications folder and try again." = "Move Tendedero to the Applications folder and try again.";+"Hang copied images" = "Hang copied images";+"Images you copy hang on the line too" = "Images you copy hang on the line too";+"Tendedero, hanging copied images" = "Tendedero, hanging copied images";/* GrabArea */"Copy" = "Copy";diff --git a/Sources/Tendedero/Resources/es.lproj/Localizable.strings b/Sources/Tendedero/Resources/es.lproj/Localizable.stringsindex 5e6f768..2b1f86e 100644--- a/Sources/Tendedero/Resources/es.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/es.lproj/Localizable.strings@@ -16,6 +16,9 @@"Quit Tendedero" = "Salir de Tendedero";"Could not change the login setting" = "No se pudo cambiar el inicio de sesión";"Move Tendedero to the Applications folder and try again." = "Mueve Tendedero a la carpeta Aplicaciones y vuelve a intentarlo.";+"Hang copied images" = "Colgar imágenes copiadas";+"Images you copy hang on the line too" = "Las imágenes que copias también se cuelgan";+"Tendedero, hanging copied images" = "Tendedero, colgando imágenes copiadas";/* GrabArea */"Copy" = "Copiar";diff --git a/Sources/Tendedero/Resources/tr.lproj/Localizable.strings b/Sources/Tendedero/Resources/tr.lproj/Localizable.stringsindex 0879552..74e765e 100644--- a/Sources/Tendedero/Resources/tr.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/tr.lproj/Localizable.strings@@ -16,6 +16,9 @@"Quit Tendedero" = "Tendedero'yu kapat";"Could not change the login setting" = "Giriş ayarı değiştirilemedi";"Move Tendedero to the Applications folder and try again." = "Tendedero'yu Uygulamalar klasörüne taşıyın ve tekrar deneyin.";+"Hang copied images" = "Kopyalanan görselleri as";+"Images you copy hang on the line too" = "Kopyaladığınız görseller de ipe asılır";+"Tendedero, hanging copied images" = "Tendedero, kopyalanan görselleri asıyor";/* GrabArea */"Copy" = "Kopyala";diff --git a/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings b/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.stringsindex 4d736f8..07033d9 100644--- a/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings@@ -16,6 +16,9 @@"Quit Tendedero" = "退出 Tendedero";"Could not change the login setting" = "无法更改登录项设置";"Move Tendedero to the Applications folder and try again." = "请先把 Tendedero 移到「应用程序」文件夹,再试一次。";+"Hang copied images" = "挂上复制的图片";+"Images you copy hang on the line too" = "复制的图片也会挂上绳";+"Tendedero, hanging copied images" = "Tendedero,正在挂上复制的图片";/* GrabArea */"Copy" = "复制";diff --git a/docs/i18n/README.es.md b/docs/i18n/README.es.mdindex 88307f7..e4e7d09 100644--- a/docs/i18n/README.es.md+++ b/docs/i18n/README.es.md@@ -67,6 +67,16 @@ Los mismos atajos y las mismas costumbres. Pero sin desorden.<br>+## También las imágenes que copias.++Haz una captura con <kbd>⌃</kbd> pulsado, o copia una imagen en Vista Previa,+y se cuelga como cualquier otra. Activa Colgar imágenes copiadas en la barra+de menús; mientras está activo, la camiseta se rellena. Solo imágenes: lo que+se copia junto con texto o un archivo, y lo que un gestor de contraseñas marca+como privado, se deja tal cual.++<br>+## Privacidad de serie.Sin cuentas, sin conexión a internet, sin analíticas.@@ -129,6 +139,7 @@ vuelve a pedir acceso al Escritorio cada vez que recompilas.| `PeggedView.swift` | Cada foto: marco de cristal, pinza, balanceo y brisa || `GrabArea.swift` | Clic, pulsación larga, y arrastrar y soltar || `ScreenshotWatcher.swift` | Se da cuenta de las capturas nuevas |+| `ClipboardWatcher.swift` | Se da cuenta de las imágenes copiadas || `Inbox.swift` | Toma el control de los ajustes de captura y luego los devuelve || `Markup.swift` | Abre el editor de Marcación del sistema y guarda el resultado || `Trim.swift` | Recorta una grabación de pantalla y guarda el resultado |diff --git a/docs/i18n/README.zh-Hans.md b/docs/i18n/README.zh-Hans.mdindex 926c6b5..8a81360 100644--- a/docs/i18n/README.zh-Hans.md+++ b/docs/i18n/README.zh-Hans.md@@ -65,6 +65,14 @@<br>+## 复制的图片也一样++按住 <kbd>⌃</kbd> 截图,或在「预览」中复制图片,它就会像其他截图一样挂上绳。+在菜单栏中打开「挂上复制的图片」,开启期间图标里的衬衫会被填满。只挂图片:+与文字或文件一起复制的内容,以及密码管理器标为私密的内容,都不会被挂上。++<br>+## 隐私是设计前提没有账号。不联网。无统计。@@ -122,6 +130,7 @@ open build/Tendedero.app| `GrabArea.swift` | 单击、长按、拖放 || `ScreenshotWatcher.swift` | 发现新的截图 || `Inbox.swift` | 接管截图设置,之后再把它们放回去 |+| `ClipboardWatcher.swift` | 发现复制到剪贴板的图片 || `Markup.swift` | 打开系统「标记」编辑器并保存结果 || `Trim.swift` | 剪辑屏幕录制并保存结果 || `FullScreen.swift` | 判断何时该保持隐藏 |