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 screen recordings on the line in inbox mode
Alejandro Bujánddf1579ac81d
diff --git a/README.md b/README.mdindex 77d38ce..105a119 100644--- a/README.md+++ b/README.md@@ -58,6 +58,9 @@ Hand Tendedero your screenshots<sup>1</sup> and they skip the Desktopentirely. No floating thumbnail. No five-second wait. Each capture hangsthe instant you take it, and only what you drag out is kept.+Screen recordings hang there too, with a play button over them.+Press and hold one to trim it.+Same shortcuts. Same muscle memory. Just less mess.<br>@@ -123,6 +126,7 @@ so macOS asks again for access to the Desktop after each rebuild.| `ScreenshotWatcher.swift` | Notices new screenshots || `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 || `FullScreen.swift` | Knows when to stay hidden || `Line.swift` | What is hanging, and what you can do with it |diff --git a/Sources/Tendedero/AppDelegate.swift b/Sources/Tendedero/AppDelegate.swiftindex 99bd677..eaae6c6 100644--- a/Sources/Tendedero/AppDelegate.swift+++ b/Sources/Tendedero/AppDelegate.swift@@ -60,6 +60,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {watchMenuBarClicks()Markup.shared.onSaved = { [weak self] url in self?.line.reloadThumbnail(for: url) }+ Trim.shared.onSaved = { [weak self] url in self?.line.reloadThumbnail(for: url) }line.onFall = { [weak self] item in self?.fall(item) }line.$itemsdiff --git a/Sources/Tendedero/GrabArea.swift b/Sources/Tendedero/GrabArea.swiftindex 2d6c4bf..b5fb3df 100644--- a/Sources/Tendedero/GrabArea.swift+++ b/Sources/Tendedero/GrabArea.swift@@ -27,6 +27,7 @@ struct GrabArea: NSViewRepresentable {private func configure(_ view: GrabView) {let id = item.idlet line = line+ let isRecording = item.isRecordingview.url = item.urlview.dragImage = item.thumbview.onClick = { line.copy(id) }@@ -45,7 +46,9 @@ struct GrabArea: NSViewRepresentable {let menu = NSMenu()menu.addItem(ClosureMenuItem(L("Copy")) { line.copy(id) })menu.addItem(ClosureMenuItem(L("Open")) { line.open(id) })- menu.addItem(ClosureMenuItem(L("Markup")) { line.markup(id) })+ if !isRecording {+ menu.addItem(ClosureMenuItem(L("Markup")) { line.markup(id) })+ }menu.addItem(ClosureMenuItem(L("Show in Finder")) { line.reveal(id) })let inInbox = line.isInInbox(id)if inInbox {diff --git a/Sources/Tendedero/Inbox.swift b/Sources/Tendedero/Inbox.swiftindex 7280474..b6a115f 100644--- a/Sources/Tendedero/Inbox.swift+++ b/Sources/Tendedero/Inbox.swift@@ -6,6 +6,7 @@ import Foundation/// menu of Cmd+Shift+5: the floating thumbnail is turned off, so the file is/// written at once instead of five seconds later, and the save location/// becomes Tendedero's own folder, so the Desktop only gets what you keep.+/// Screen recordings go there too, and hang on the line like screenshots.////// The previous values are saved first and put back when the mode is turned/// off or the app quits, so macOS is never left pointing at a folder nobody@@ -16,6 +17,9 @@ enum Inbox {/// "location-screenshot" and ignores the old key, so both are written.private static let locationKey = "location" as CFStringprivate static let screenshotLocationKey = "location-screenshot" as CFString+ /// macOS 27 keeps screen recordings apart, in "location-screenrecording".+ /// Earlier versions send them wherever "location" points.+ private static let recordingLocationKey = "location-screenrecording" as CFStringprivate static let thumbnailKey = "show-thumbnail" as CFStringprivate static let enabledKey = "inboxEnabled"@@ -50,16 +54,23 @@ enum Inbox {try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)// Never save our own values as the "previous" ones, for example after// a crash left them applied.+ var saved = UserDefaults.standard.dictionary(forKey: savedKey) ?? [:]if !isApplied {- let saved: [String: Any] = [- "location": CFPreferencesCopyAppValue(locationKey, domain) as? String ?? NSNull(),- "locationScreenshot": CFPreferencesCopyAppValue(screenshotLocationKey, domain) as? String ?? NSNull(),- "thumbnail": CFPreferencesCopyAppValue(thumbnailKey, domain) as? Bool ?? NSNull(),- ]- UserDefaults.standard.set(saved.compactMapValues { $0 is NSNull ? nil : $0 }, forKey: savedKey)+ saved = [:]+ saved["location"] = CFPreferencesCopyAppValue(locationKey, domain) as? String+ saved["locationScreenshot"] = CFPreferencesCopyAppValue(screenshotLocationKey, domain) as? String+ saved["thumbnail"] = CFPreferencesCopyAppValue(thumbnailKey, domain) as? Bool}+ // Recordings came later: settings saved by an earlier version lack+ // them, and the value macOS has now is still the user's own.+ if saved["recordingSaved"] == nil {+ saved["locationRecording"] = CFPreferencesCopyAppValue(recordingLocationKey, domain) as? String+ saved["recordingSaved"] = true+ }+ UserDefaults.standard.set(saved, forKey: savedKey)set(locationKey, folder.path)set(screenshotLocationKey, folder.path)+ set(recordingLocationKey, folder.path)set(thumbnailKey, false)}@@ -68,6 +79,7 @@ enum Inbox {let saved = UserDefaults.standard.dictionary(forKey: savedKey) ?? [:]set(locationKey, saved["location"])set(screenshotLocationKey, saved["locationScreenshot"])+ set(recordingLocationKey, saved["locationRecording"])set(thumbnailKey, saved["thumbnail"])UserDefaults.standard.removeObject(forKey: savedKey)}diff --git a/Sources/Tendedero/Line.swift b/Sources/Tendedero/Line.swiftindex 9487c7e..4b7ce87 100644--- a/Sources/Tendedero/Line.swift+++ b/Sources/Tendedero/Line.swift@@ -1,4 +1,5 @@import AppKit+import AVFoundationimport Combineimport os@@ -14,6 +15,8 @@ struct Pegged: Identifiable, Equatable {var falling = false/// Still flying in from where it was captured; the card waits hidden.var flying = false+ /// A screen recording rather than a screenshot.+ var isRecording: Bool { Tendedero.isRecording(url) }static func == (a: Pegged, b: Pegged) -> Bool {a.id == b.id && a.falling == b.falling && a.flying == b.flying && a.thumb === b.thumb@@ -117,7 +120,8 @@ final class Line: ObservableObject {func copy(_ id: UUID) {guard let item = items.first(where: { $0.id == id }) else { return }let entry = NSPasteboardItem()- if let png = pngData(item.url) { entry.setData(png, forType: .png) }+ // A recording is copied as the file, which apps paste as the video.+ if !item.isRecording, let png = pngData(item.url) { entry.setData(png, forType: .png) }entry.setString(item.url.absoluteString, forType: .fileURL)let pb = NSPasteboard.generalpb.clearContents()@@ -204,10 +208,15 @@ final class Line: ObservableObject {return candidate}- /// Long press: open the photo in the system Markup editor.+ /// Long press: open the photo in the system Markup editor. Markup does+ /// not edit video, so a recording opens in the trimming editor instead.func markup(_ id: UUID) {guard let item = items.first(where: { $0.id == id }) else { return }- Markup.shared.edit(item.url)+ if item.isRecording {+ Trim.shared.edit(item.url, size: item.thumb.size)+ } else {+ Markup.shared.edit(item.url)+ }}/// After editing, the photo on the line shows the new version.@@ -269,7 +278,13 @@ final class Line: ObservableObject {}}+/// Screen recordings, as macOS saves them.+func isRecording(_ url: URL) -> Bool {+ ["mov", "mp4"].contains(url.pathExtension.lowercased())+}+func makeThumbnail(_ url: URL, maxPixels: Int = 480) -> NSImage? {+ if isRecording(url) { return firstFrame(url, maxPixels: maxPixels) }guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,@@ -279,3 +294,12 @@ func makeThumbnail(_ url: URL, maxPixels: Int = 480) -> NSImage? {guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }return NSImage(cgImage: cg, size: NSSize(width: cg.width, height: cg.height))}++/// A recording shows its first frame.+private func firstFrame(_ url: URL, maxPixels: Int) -> NSImage? {+ let generator = AVAssetImageGenerator(asset: AVURLAsset(url: url))+ generator.appliesPreferredTrackTransform = true+ generator.maximumSize = CGSize(width: maxPixels, height: maxPixels)+ guard let cg = try? generator.copyCGImage(at: .zero, actualTime: nil) else { return nil }+ return NSImage(cgImage: cg, size: NSSize(width: cg.width, height: cg.height))+}diff --git a/Sources/Tendedero/PeggedView.swift b/Sources/Tendedero/PeggedView.swiftindex ee6eeab..548716f 100644--- a/Sources/Tendedero/PeggedView.swift+++ b/Sources/Tendedero/PeggedView.swift@@ -65,6 +65,17 @@ struct PeggedView: View {RoundedRectangle(cornerRadius: Frame.radius - Frame.inset, style: .continuous).strokeBorder(Color.white.opacity(0.18), lineWidth: 0.5))+ .overlay {+ // A recording says so with a play button over its first frame.+ if item.isRecording {+ Image(systemName: "play.fill")+ .font(.system(size: 11, weight: .bold))+ .foregroundStyle(.primary)+ .frame(width: 28, height: 28)+ .glassFrame(circle: true)+ .allowsHitTesting(false)+ }+ }.padding(Frame.inset).glassFrame(cornerRadius: Frame.radius).shadow(color: .black.opacity(hovering ? 0.26 : 0.18), radius: hovering ? 14 : 10, y: hovering ? 8 : 5)diff --git a/Sources/Tendedero/ScreenshotWatcher.swift b/Sources/Tendedero/ScreenshotWatcher.swiftindex 9462fe7..0852505 100644--- a/Sources/Tendedero/ScreenshotWatcher.swift+++ b/Sources/Tendedero/ScreenshotWatcher.swift@@ -8,6 +8,9 @@ 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+ /// Screen recordings carry no tag, so they are only picked up in+ /// Tendedero's own folder, where nothing else is saved.+ private let acceptsRecordings: Boolprivate var known: Set<String>?private var source: DispatchSourceFileSystemObject?private var pending: DispatchWorkItem?@@ -32,6 +35,7 @@ final class ScreenshotWatcher {self.onChange = onChangeself.folder = folder ?? Self.screenshotFolder()onlyTaggedScreenshots = self.folder.standardizedFileURL.path == Self.desktop.standardizedFileURL.path+ acceptsRecordings = self.folder.standardizedFileURL.path == Inbox.folder.standardizedFileURL.path}static func screenshotFolder() -> URL {@@ -162,6 +166,7 @@ final class ScreenshotWatcher {}private func isCandidate(_ url: URL) -> Bool {+ if isRecording(url) { return acceptsRecordings }guard Self.imageExtensions.contains(url.pathExtension.lowercased()) else { return false }return onlyTaggedScreenshots ? isScreenCapture(url) : true}diff --git a/Sources/Tendedero/Trim.swift b/Sources/Tendedero/Trim.swiftnew file mode 100644index 0000000..6f85623--- /dev/null+++ b/Sources/Tendedero/Trim.swift@@ -0,0 +1,99 @@+import AppKit+import AVKit+import Combine++/// Trims a screen recording in place, with the same trimming bar QuickTime+/// shows. It is to recordings what Markup is to screenshots: press and hold,+/// edit, and the result is written over the original file.+@MainActor+final class Trim: NSObject, NSWindowDelegate {+ static let shared = Trim()++ /// Called with the file once the trimmed recording has replaced it.+ var onSaved: (URL) -> Void = { _ in }++ private var window: NSWindow?+ private var ready: AnyCancellable?++ func edit(_ url: URL, size: CGSize) {+ window?.close()++ let item = AVPlayerItem(url: url)+ let playerView = AVPlayerView()+ playerView.player = AVPlayer(playerItem: item)+ playerView.controlsStyle = .inline++ let window = NSWindow(contentRect: NSRect(origin: .zero, size: Self.windowSize(for: size)),+ styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)+ window.title = url.lastPathComponent+ window.contentView = playerView+ window.isReleasedWhenClosed = false+ window.delegate = self+ window.center()+ self.window = window+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)++ // The trimming bar can only come up once the recording has loaded.+ ready = item.publisher(for: \.status)+ .first { $0 != .unknown }+ .receive(on: RunLoop.main)+ .sink { [weak self, weak playerView] status in+ guard let self, let playerView, status == .readyToPlay, playerView.canBeginTrimming else {+ log.error("Could not trim \(url.lastPathComponent, privacy: .public)")+ return+ }+ playerView.beginTrimming { result in+ DispatchQueue.main.async {+ if result == .okButton { self.save(item, to: url) }+ self.window?.close()+ }+ }+ }+ }++ /// The recording at its own proportions, as large as fits comfortably.+ private static func windowSize(for size: CGSize) -> CGSize {+ guard size.width > 0, size.height > 0 else { return CGSize(width: 720, height: 450) }+ let scale = min(720 / size.width, 520 / size.height)+ return CGSize(width: (size.width * scale).rounded(), height: (size.height * scale).rounded())+ }++ func windowWillClose(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ (window?.contentView as? AVPlayerView)?.player?.pause()+ ready = nil+ window = nil+ }++ // MARK: Writing back++ /// Copies the kept part without re-encoding, to a hidden file next to the+ /// original so the watcher ignores it, then swaps it in.+ private func save(_ item: AVPlayerItem, to target: URL) {+ let start = item.reversePlaybackEndTime.isValid ? item.reversePlaybackEndTime : .zero+ let end = item.forwardPlaybackEndTime.isValid ? item.forwardPlaybackEndTime : item.duration+ guard let export = AVAssetExportSession(asset: item.asset, presetName: AVAssetExportPresetPassthrough) else {+ NSSound.beep()+ return+ }+ let temp = target.deletingLastPathComponent()+ .appendingPathComponent(".trimming-\(UUID().uuidString)")+ .appendingPathExtension(target.pathExtension)+ export.outputURL = temp+ export.outputFileType = target.pathExtension.lowercased() == "mp4" ? .mp4 : .mov+ export.timeRange = CMTimeRange(start: start, end: end)+ Task {+ await export.export()+ if export.status == .completed,+ (try? FileManager.default.replaceItemAt(target, withItemAt: temp)) != nil {+ log.notice("Trimmed \(target.lastPathComponent, privacy: .public)")+ onSaved(target)+ } else {+ log.error("Could not trim \(target.lastPathComponent, privacy: .public): \(export.error?.localizedDescription ?? "", privacy: .public)")+ try? FileManager.default.removeItem(at: temp)+ NSSound.beep()+ }+ }+ }+}diff --git a/docs/i18n/README.es.md b/docs/i18n/README.es.mdindex 079662f..88307f7 100644--- a/docs/i18n/README.es.md+++ b/docs/i18n/README.es.md@@ -60,6 +60,9 @@ Deja que Tendedero se encargue de tus capturas<sup>1</sup> y dejarán de pasarpor el Escritorio. Sin miniatura flotante ni cinco segundos de espera: cadacaptura se cuelga al momento, y solo se queda lo que tú saques de la cuerda.+Las grabaciones de pantalla también se cuelgan, con un botón de play encima.+Mantén pulsada una para recortarla.+Los mismos atajos y las mismas costumbres. Pero sin desorden.<br>@@ -128,6 +131,7 @@ vuelve a pedir acceso al Escritorio cada vez que recompilas.| `ScreenshotWatcher.swift` | Se da cuenta de las capturas nuevas || `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 || `FullScreen.swift` | Sabe cuándo tiene que quedarse oculto || `Line.swift` | Qué hay colgado y qué puedes hacer con ello |diff --git a/docs/i18n/README.zh-Hans.md b/docs/i18n/README.zh-Hans.mdindex e6611e5..926c6b5 100644--- a/docs/i18n/README.zh-Hans.md+++ b/docs/i18n/README.zh-Hans.md@@ -59,6 +59,8 @@把截图交给 Tendedero<sup>1</sup>,它们就完全跳过桌面。没有浮动缩略图。不用等五秒。拍下的瞬间即挂上绳,只有你拖出去的才会留下。+屏幕录制也会挂上绳,上面带一个播放按钮。按住即可剪辑。+同样的快捷键。同样的肌肉记忆。只是少了乱。<br>@@ -121,6 +123,7 @@ open build/Tendedero.app| `ScreenshotWatcher.swift` | 发现新的截图 || `Inbox.swift` | 接管截图设置,之后再把它们放回去 || `Markup.swift` | 打开系统「标记」编辑器并保存结果 |+| `Trim.swift` | 剪辑屏幕录制并保存结果 || `FullScreen.swift` | 判断何时该保持隐藏 || `Line.swift` | 绳上挂着什么,以及你能对它做什么 |