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

Initial commit

Alejandro Buján0e4dc0087cf9
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8b80f2f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+.build/
+build/
+.DS_Store
+*.xcodeproj
+.swiftpm/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..16ccaec
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,34 @@
+MIT License
+
+Copyright (c) 2026 Alejandro Buján
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+---
+
+Name and icon
+
+The MIT License above covers the source code. It does not grant any rights
+to the Tendedero name or the Tendedero icon, including the icon artwork drawn
+by scripts/make-icon.swift and the images in the docs folder.
+
+You may build and use the app as published, and you may refer to Tendedero
+to say where your work comes from. Modified or redistributed versions must
+use a different name and a different icon, and must not suggest that they
+are Tendedero or are endorsed by its author.
diff --git a/Package.swift b/Package.swift
new file mode 100644
index 0000000..61de070
--- /dev/null
+++ b/Package.swift
@@ -0,0 +1,10 @@
+// swift-tools-version:5.9
+import PackageDescription
+
+let package = Package(
+ name: "Tendedero",
+ platforms: [.macOS(.v14)],
+ targets: [
+ .executableTarget(name: "Tendedero", path: "Sources/Tendedero")
+ ]
+)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4a71f60
--- /dev/null
+++ b/README.md
@@ -0,0 +1,147 @@
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/hero-dark.png">
+ <img src="docs/hero-light.png" alt="Tendedero. Screenshots, hung out to dry. Three screenshots in glass frames hang from a thin line under the macOS menu bar.">
+</picture>
+
+<p align="center">
+ Free and open source. For macOS 14 and later.
+ <br>
+ <a href="../../releases/latest">Download&nbsp;&rsaquo;</a>
+ &nbsp;&nbsp;
+ <a href="#build-from-source">Build from source&nbsp;&rsaquo;</a>
+</p>
+
+<br>
+
+## Out of sight. Within reach.
+
+Every screenshot you take hangs on a line just above your screen.
+Rest the pointer in the menu bar and it glides down. Move away and it's gone.
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/demo-dark.gif">
+ <img src="docs/demo-light.gif" alt="The pointer rests against the top edge, the line slides down with three screenshots swinging gently, a click copies one, and the line tucks away when the pointer leaves.">
+</picture>
+
+<br>
+<br>
+
+## A gesture for everything.
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/bento-dark.png">
+ <img src="docs/bento-light.png" alt="Click to copy. Hold to mark up. Drag to share. Let it go.">
+</picture>
+
+<br>
+<br>
+
+| | |
+|:--|:--|
+| Click | Copy the image. |
+| Press and hold | Open it in Markup. |
+| Double click | Open it in Preview. |
+| Drag into an app | Send a copy. It stays on the line. |
+| Drag into a folder | Keep it there. It leaves the line. |
+| Drag to the Trash, or click the cross | Let it go. |
+| Rest the pointer in the menu bar | Bring the line down on that screen. |
+| Click anything in the menu bar | Put it away. |
+| <kbd>⌃</kbd>&thinsp;<kbd>⌥</kbd>&thinsp;<kbd>T</kbd> | Show or hide the line. |
+
+<br>
+
+## Your Desktop. Finally clear.
+
+Hand Tendedero your screenshots<sup>1</sup> and they skip the Desktop
+entirely. No floating thumbnail. No five-second wait. Each capture hangs
+the instant you take it, and only what you drag out is kept.
+
+Same shortcuts. Same muscle memory. Just less mess.
+
+<br>
+
+## Private by design.
+
+No account. No network. No analytics.
+Tendedero runs entirely on your Mac, and your screenshots never leave it.
+
+<br>
+
+## Tech Specs
+
+| | |
+|:--|:--|
+| **Compatibility** | macOS 14 Sonoma or later, on Apple silicon and Intel. Designed for macOS 27. |
+| **Size** | 1.7 MB |
+| **Languages** | English, Spanish |
+| **Built with** | Swift, AppKit and SwiftUI |
+| **Network access** | None |
+| **Price** | Free |
+| **License** | MIT for the code. The name and icon are not included. |
+
+<br>
+
+## Install
+
+Download the disk image from the [latest release](../../releases/latest),
+open it and drag Tendedero to Applications.
+
+Tendedero is not notarized by Apple yet, so the first time macOS will say it
+cannot verify it. Open System Settings, go to Privacy & Security, and click
+Open Anyway next to the message about Tendedero. You only need to do this once.
+
+<br>
+
+## Build from source
+
+```sh
+git clone [email protected]:alejandrobujan/tendedero.git
+cd tendedero
+scripts/build-app.sh
+open build/Tendedero.app
+```
+
+Requires the Swift toolchain. Xcode is optional. With the Command Line Tools for macOS 27, the script falls back to the macOS 26 SDK they install alongside, because the new SDK needs a SwiftUI macro plugin only Xcode includes. Local builds are signed ad hoc,
+so macOS asks again for access to the Desktop after each rebuild.
+
+<details>
+<summary>Inside the app</summary>
+<br>
+
+| File | Role |
+|:--|:--|
+| `AppDelegate.swift` | Menu bar, shortcut, revealing and tucking away the line |
+| `LinePanel.swift` | The transparent strip along the top of the screen |
+| `LineView.swift` | The line and where each photo hangs |
+| `PeggedView.swift` | One photo: glass frame, clip, swing and breeze |
+| `GrabArea.swift` | Click, long press, drag and drop |
+| `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 |
+| `FullScreen.swift` | Knows when to stay hidden |
+| `Line.swift` | What is hanging, and what you can do with it |
+
+Every image here, the icon included, is drawn in code by
+`scripts/make-icon.swift` and `scripts/make-readme-art.swift`.
+`scripts/make-dmg.sh` builds the disk image for releases.
+
+</details>
+
+<br>
+
+---
+
+<sub>
+1. On first launch, Tendedero offers to handle your screenshots. If you accept, it turns off the floating thumbnail and saves new screenshots to its own folder, two settings also found under Options in Cmd+Shift+5. Your previous settings are saved and restored when Tendedero quits or the option is turned off from the menu bar. Tendedero hides automatically while an app is in full screen.
+</sub>
+
+<br>
+<br>
+
+<p align="center">
+ <img src="docs/icon.png" width="64" height="64" alt="">
+ <br>
+ <sub>The code is MIT licensed. The Tendedero name and icon are not, so forks need their own. See <a href="LICENSE">LICENSE</a>.</sub>
+ <br>
+ <sub>Designed and built by <a href="https://alejandrobujan.com">Alejandro Buján</a>.</sub>
+</p>
diff --git a/Sources/Tendedero/AppDelegate.swift b/Sources/Tendedero/AppDelegate.swift
new file mode 100644
index 0000000..45e30fe
--- /dev/null
+++ b/Sources/Tendedero/AppDelegate.swift
@@ -0,0 +1,527 @@
+import AppKit
+import Carbon
+import Combine
+import ServiceManagement
+import SwiftUI
+
+@MainActor
+final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
+ private let line = Line()
+ private var panel: LinePanel!
+ private var statusItem: NSStatusItem!
+ private var watcher: ScreenshotWatcher!
+ /// In inbox mode, a second watcher on the Desktop. If a macOS version
+ /// 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 signalSources: [DispatchSourceSignal] = []
+ private var hotKey: HotKey?
+ private var cancellables = Set<AnyCancellable>()
+ private var mouseTimer: Timer?
+
+ /// Whether the panel is ordered in. It can be in and still tucked away
+ /// above the top edge, like an auto-hiding Dock.
+ private var isPresent = false
+ /// Whether the line has slid down into view.
+ private var isRevealed = false
+ /// Opened on purpose with the shortcut or the menu: it stays down until
+ /// the cursor has visited it and left, or the shortcut is pressed again.
+ private var pinned = false
+ /// A new screenshot shows itself for a moment, then tucks away.
+ private var peekUntil = Date.distantPast
+ private var hotZoneSince: Date?
+ /// After a click in the menu bar the line stays up there hidden until the
+ /// pointer leaves the menu bar, so it does not come back over a menu.
+ private var menuBarSuppressed = false
+ private var clickMonitors: [Any] = []
+ private var awaySince: Date?
+ /// Whether the line should be up, if nothing prevents it. A full screen
+ /// app on that screen does: the line waits until you leave full screen.
+ private var wanted = false
+ /// Set when you open the line on purpose, so it stays up while empty.
+ private var keepOpen = false
+ private var lastLiveCount = 0
+ /// The screen a new capture was taken on: the line goes there.
+ private var pendingScreen: NSScreen?
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ let host = NSHostingView(rootView: LineView(line: line))
+ host.sizingOptions = []
+ panel = LinePanel(content: host)
+ panel.placeOnScreen()
+ updateCapacity()
+
+ if Inbox.isEnabled { Inbox.apply() }
+ restoreSettingsOnTermination()
+ startWatcher()
+
+ hotKey = HotKey(keyCode: kVK_ANSI_T, modifiers: controlKey | optionKey) { [weak self] in
+ self?.toggle()
+ }
+
+ setUpStatusItem()
+ watchMenuBarClicks()
+
+ Markup.shared.onSaved = { [weak self] url in self?.line.reloadThumbnail(for: url) }
+ line.onFall = { [weak self] item in self?.fall(item) }
+
+ line.$items
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in self?.itemsChanged() }
+ .store(in: &cancellables)
+
+ // Entering or leaving full screen switches Space. Check again once the
+ // switch animation has settled.
+ let workspace = NSWorkspace.shared.notificationCenter
+ for name in [NSWorkspace.activeSpaceDidChangeNotification, NSWorkspace.didActivateApplicationNotification] {
+ workspace.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated {
+ self?.refresh()
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self?.refresh() }
+ }
+ }
+ }
+
+ NotificationCenter.default.addObserver(
+ forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main
+ ) { [weak self] _ in
+ MainActor.assumeIsolated {
+ self?.panel.placeOnScreen()
+ self?.updateCapacity()
+ }
+ }
+
+ if !Inbox.wasOffered {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in self?.offerInbox() }
+ }
+
+ if !UserDefaults.standard.bool(forKey: "welcomed") {
+ UserDefaults.standard.set(true, forKey: "welcomed")
+ keepOpen = true
+ wanted = true
+ refresh()
+ reveal(pinned: true)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
+ guard let self, self.line.liveCount == 0 else { return }
+ self.keepOpen = false
+ self.wanted = false
+ self.refresh()
+ }
+ }
+ }
+
+ func applicationWillTerminate(_ notification: Notification) {
+ if Inbox.isEnabled { Inbox.restore() }
+ }
+
+ // MARK: Inbox mode
+
+ private func startWatcher() {
+ watcher?.stop()
+ safetyWatcher?.stop()
+ safetyWatcher = nil
+ watcher = ScreenshotWatcher(
+ onNew: { [weak self] url in self?.hangCapture(url) },
+ onChange: { [weak self] in self?.line.prune() })
+ watcher.start()
+ if Inbox.isEnabled, watcher.folder.standardizedFileURL != ScreenshotWatcher.desktop.standardizedFileURL {
+ let safety = ScreenshotWatcher(
+ folder: ScreenshotWatcher.desktop,
+ onNew: { [weak self] url in
+ log.notice("Screenshot landed on the Desktop despite inbox mode: \(url.lastPathComponent, privacy: .public)")
+ self?.hangCapture(url)
+ },
+ onChange: { [weak self] in self?.line.prune() })
+ safety.start()
+ safetyWatcher = safety
+ }
+ }
+
+ private func setInbox(_ on: Bool) {
+ Inbox.isEnabled = on
+ if on { Inbox.apply() } else { Inbox.restore() }
+ startWatcher()
+ }
+
+ /// Asked once. Changing system settings is the user's call, never ours.
+ private func offerInbox() {
+ Inbox.wasOffered = true
+ let alert = NSAlert()
+ alert.messageText = L("Let Tendedero handle your screenshots?",
+ "¿Quieres que Tendedero se encargue de tus capturas?")
+ alert.informativeText = L(
+ "Screenshots will hang on the line the instant you take them, without the floating thumbnail, and will not pile up on your Desktop. Drag one to a folder to keep it, or discard it with the cross. You can turn this off from the menu bar, and your settings come back when Tendedero quits.",
+ "Las capturas se colgarán al instante, sin la miniatura flotante, y no se acumularán en el Escritorio. Arrastra una a una carpeta para guardarla, o descártala con la cruz. Puedes desactivarlo desde la barra de menús, y tus ajustes vuelven a ser los de antes al salir de Tendedero.")
+ alert.addButton(withTitle: L("Turn on", "Activar"))
+ alert.addButton(withTitle: L("Not now", "Ahora no"))
+ if let icon = NSImage(named: "Tendedero") ?? NSApp.applicationIconImage { alert.icon = icon }
+ NSApp.activate(ignoringOtherApps: true)
+ if alert.runModal() == .alertFirstButtonReturn { setInbox(true) }
+ }
+
+ /// 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() {
+ for sig in [SIGTERM, SIGINT, SIGHUP] {
+ signal(sig, SIG_IGN)
+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)
+ source.setEventHandler {
+ if Inbox.isEnabled { Inbox.restore() }
+ exit(0)
+ }
+ source.resume()
+ signalSources.append(source)
+ }
+ }
+
+ // MARK: Showing and hiding
+
+ private func itemsChanged() {
+ let live = line.liveCount
+ if live > lastLiveCount {
+ panel.placeOnScreen(pendingScreen)
+ pendingScreen = nil
+ updateCapacity()
+ wanted = true
+ refresh()
+ reveal(peekFor: 2.5)
+ } else if live == 0 && !keepOpen {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { [weak self] in
+ guard let self, self.line.liveCount == 0, !self.keepOpen else { return }
+ self.wanted = false
+ self.refresh()
+ }
+ }
+ lastLiveCount = live
+ }
+
+ // MARK: The capture flying to the line
+
+ /// A new screenshot lifts off from where it was taken and flies to its
+ /// place on the line. Without a known capture area it simply drops in.
+ private func hangCapture(_ url: URL) {
+ let from = captureRect(of: url)
+ if let from {
+ let center = CGPoint(x: from.midX, y: from.midY)
+ pendingScreen = NSScreen.screens.first { NSMouseInRect(center, $0.frame, false) }
+ }
+ guard let id = line.hang(url, flying: from != nil), let from else { return }
+ // Let the line come down and lay out before measuring the landing spot.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [weak self] in
+ self?.fly(id, from: from)
+ }
+ }
+
+ private func fly(_ id: UUID, from: CGRect) {
+ guard isPresent, isRevealed, let screen = panel.screen,
+ let to = cardFrame(for: id),
+ let item = line.items.first(where: { $0.id == id }) else {
+ line.land(id)
+ return
+ }
+ let pixels = Int(max(from.width, from.height) * screen.backingScaleFactor)
+ guard let image = makeThumbnail(item.url, maxPixels: min(3000, max(400, pixels)))?
+ .cgImage(forProposedRect: nil, context: nil, hints: nil) else {
+ line.land(id)
+ return
+ }
+ CaptureFlight.fly(image: image, from: from, to: to, tilt: CGFloat(item.tilt), on: screen) { [weak self] in
+ self?.line.land(id)
+ }
+ }
+
+ /// A discarded card falls over the whole screen, from where it hangs.
+ private func fall(_ item: Pegged) {
+ guard isPresent, isRevealed, !item.flying, let screen = panel.screen,
+ let card = cardFrame(for: item.id),
+ let image = item.thumb.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return }
+ CaptureFlight.fall(image: image, card: card, tilt: CGFloat(item.tilt), on: screen)
+ }
+
+ /// Where a card will hang, in screen coordinates, using the same layout
+ /// as the line view.
+ private func cardFrame(for id: UUID) -> CGRect? {
+ guard let index = line.items.firstIndex(where: { $0.id == id }) else { return nil }
+ let width = panel.frame.width
+ let x = Layout.x(index: index, count: line.items.count, width: width)
+ let viewTop = Layout.ropeY(x: x, width: width) - Layout.pinAbove
+ let cardTop = viewTop + PeggedView.cardOffsetBelowTop
+ let size = PeggedView.cardSize(for: line.items[index].thumb.size)
+ return CGRect(x: panel.frame.minX + x - size.width / 2,
+ y: panel.frame.maxY - cardTop - size.height,
+ width: size.width, height: size.height)
+ }
+
+ /// Decides whether the panel is ordered in at all: something to show,
+ /// and no full screen app on that screen.
+ private func refresh() {
+ let blocked = panel.screen.map(FullScreen.isActive(on:))
+ ?? LinePanel.screenUnderPointer().map(FullScreen.isActive(on:)) ?? false
+ if wanted && !blocked {
+ present()
+ } else {
+ dismiss()
+ }
+ // The cursor is watched while there is a line, even tucked away,
+ // to notice it pushing against the top edge.
+ if wanted { startMouseTracking() } else { stopMouseTracking() }
+ }
+
+ private func present() {
+ guard !isPresent else { return }
+ isPresent = true
+ panel.alphaValue = 1
+ panel.orderFrontRegardless()
+ }
+
+ private func dismiss() {
+ guard isPresent else { return }
+ isPresent = false
+ setRevealed(false)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in
+ guard let self, !self.isPresent else { return }
+ self.panel.orderOut(nil)
+ }
+ }
+
+ private func reveal(pinned: Bool = false, peekFor seconds: TimeInterval = 0) {
+ guard isPresent else { return }
+ if pinned { self.pinned = true }
+ if seconds > 0 { peekUntil = Date().addingTimeInterval(seconds) }
+ awaySince = nil
+ setRevealed(true)
+ }
+
+ private func setRevealed(_ on: Bool) {
+ guard on != isRevealed else { return }
+ isRevealed = on
+ line.revealed = on
+ if !on {
+ pinned = false
+ peekUntil = .distantPast
+ panel.ignoresMouseEvents = true
+ }
+ }
+
+ @objc private func toggle() {
+ if isRevealed {
+ setRevealed(false)
+ if line.liveCount == 0 {
+ keepOpen = false
+ wanted = false
+ refresh()
+ }
+ } else {
+ keepOpen = true
+ wanted = true
+ panel.placeOnScreen()
+ updateCapacity()
+ refresh()
+ reveal(pinned: true)
+ }
+ }
+
+ private func startMouseTracking() {
+ guard mouseTimer == nil else { return }
+ let timer = Timer(timeInterval: 1.0 / 30.0, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.tick() }
+ }
+ RunLoop.main.add(timer, forMode: .common)
+ mouseTimer = timer
+ }
+
+ private func stopMouseTracking() {
+ mouseTimer?.invalidate()
+ mouseTimer = nil
+ panel.ignoresMouseEvents = true
+ }
+
+ /// How long the cursor rests against the top edge before the line comes
+ /// down. Short enough to feel instant, long enough that a quick trip to
+ /// the menu bar does not trigger it.
+ private static let revealDelay: TimeInterval = 0.25
+
+ /// The menu bar strip at the top of a screen. With an auto-hiding menu
+ /// bar the visible frame reaches the top, so the system thickness is used.
+ static func menuBarBand(of screen: NSScreen) -> NSRect {
+ var h = screen.frame.maxY - screen.visibleFrame.maxY
+ if h < 1 { h = max(NSStatusBar.system.thickness, screen.safeAreaInsets.top) }
+ return NSRect(x: screen.frame.minX, y: screen.frame.maxY - h, width: screen.frame.width, height: h)
+ }
+
+ /// A click anywhere in the top bar of any screen, a menu or an icon, puts the line away.
+ private func watchMenuBarClicks() {
+ let handler: (NSEvent?) -> Void = { [weak self] _ in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ let p = NSEvent.mouseLocation
+ guard NSScreen.screens.contains(where: { Self.menuBarBand(of: $0).contains(p) }) else { return }
+ self.menuBarSuppressed = true
+ self.hotZoneSince = nil
+ if self.isRevealed {
+ self.pinned = false
+ self.setRevealed(false)
+ }
+ }
+ }
+ if let global = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown], handler: handler) {
+ clickMonitors.append(global)
+ }
+ if let local = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown], handler: { e in handler(e); return e }) {
+ clickMonitors.append(local)
+ }
+ }
+ /// How long the cursor is away before the line tucks back up.
+ private static let retractDelay: TimeInterval = 0.5
+
+ private func tick() {
+ let mouse = NSEvent.mouseLocation
+ let now = Date()
+
+ let screenUnderPointer = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) }
+ let inMenuBar = screenUnderPointer.map { Self.menuBarBand(of: $0).contains(mouse) } ?? false
+ if !inMenuBar { menuBarSuppressed = false }
+
+ guard isRevealed else {
+ // Resting in the menu bar brings the line down on that screen.
+ // Pushing against the top edge is part of it, and it also works
+ // when another display sits above and the pointer never stops.
+ if let screen = screenUnderPointer, inMenuBar, !menuBarSuppressed,
+ !FullScreen.isActive(on: screen) {
+ let since = hotZoneSince ?? now
+ hotZoneSince = since
+ if now.timeIntervalSince(since) >= Self.revealDelay {
+ hotZoneSince = nil
+ if panel.screen != screen {
+ panel.placeOnScreen()
+ updateCapacity()
+ }
+ refresh()
+ reveal()
+ }
+ } else {
+ hotZoneSince = nil
+ }
+ return
+ }
+
+ updateMousePassThrough(mouse)
+
+ // The line's zone runs from its lowest point up to the top of the
+ // screen, menu bar included, so moving up never hides it.
+ var zone = panel.frame
+ if let screen = panel.screen { zone.size.height = screen.frame.maxY - zone.minY }
+ let inside = NSMouseInRect(mouse, zone, false)
+ if inside && pinned { pinned = false }
+
+ let busy = pinned || GrabView.isDragging || line.pressedID != nil || now < peekUntil
+ if inside || busy {
+ awaySince = nil
+ } else {
+ let since = awaySince ?? now
+ awaySince = since
+ if now.timeIntervalSince(since) >= Self.retractDelay {
+ awaySince = nil
+ setRevealed(false)
+ }
+ }
+ }
+
+ /// The panel spans the whole width of the screen, so it only accepts the
+ /// mouse while the cursor is over a photo. Everywhere else, clicks go to
+ /// whatever is underneath.
+ private func updateMousePassThrough(_ mouse: NSPoint) {
+ guard !GrabView.isDragging else { return }
+ let local = panel.convertPoint(fromScreen: mouse)
+ let flipped = CGPoint(x: local.x, y: panel.frame.height - local.y)
+ let overPhoto = line.hitRects.values.contains { $0.insetBy(dx: -4, dy: -4).contains(flipped) }
+ if panel.ignoresMouseEvents == overPhoto {
+ panel.ignoresMouseEvents = !overPhoto
+ }
+ }
+
+ private func updateCapacity() {
+ let usable = panel.frame.width - 200
+ line.maxItems = max(3, min(12, Int(usable / Layout.spacing)))
+ }
+
+ // MARK: Menu bar
+
+ private func setUpStatusItem() {
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
+ let image = NSImage(systemSymbolName: "tshirt", accessibilityDescription: "Tendedero")
+ image?.isTemplate = true
+ statusItem.button?.image = image
+ let menu = NSMenu()
+ menu.delegate = self
+ statusItem.menu = menu
+ }
+
+ func menuNeedsUpdate(_ menu: NSMenu) {
+ menu.removeAllItems()
+
+ let toggleItem = ClosureMenuItem(isRevealed ? L("Hide line", "Ocultar tendedero")
+ : L("Show line", "Mostrar tendedero")) { [weak self] in
+ self?.toggle()
+ }
+ toggleItem.keyEquivalent = "t"
+ toggleItem.keyEquivalentModifierMask = [.control, .option]
+ menu.addItem(toggleItem)
+
+ let clearItem = ClosureMenuItem(L("Take everything down", "Descolgar todo")) { [weak self] in
+ self?.line.clear()
+ }
+ clearItem.isEnabled = line.liveCount > 0
+ menu.addItem(clearItem)
+
+ let inbox = ClosureMenuItem(L("Handle screenshots", "Encargarse de las capturas")) { [weak self] in
+ self?.setInbox(!Inbox.isEnabled)
+ }
+ inbox.state = Inbox.isEnabled ? .on : .off
+ inbox.toolTip = L("Screenshots hang instantly and skip the Desktop",
+ "Las capturas se cuelgan al instante y no pasan por el Escritorio")
+ menu.addItem(inbox)
+
+ menu.addItem(ClosureMenuItem(L("Open screenshots folder", "Abrir carpeta de capturas")) { [weak self] in
+ guard let self else { return }
+ NSWorkspace.shared.open(self.watcher.folder)
+ })
+
+ menu.addItem(.separator())
+
+ let sound = ClosureMenuItem(L("Sounds", "Sonidos")) { [weak self] in
+ guard let self else { return }
+ self.line.soundOn.toggle()
+ }
+ sound.state = line.soundOn ? .on : .off
+ menu.addItem(sound)
+
+ let login = ClosureMenuItem(L("Open at login", "Abrir al iniciar sesión")) {
+ AppDelegate.toggleLaunchAtLogin()
+ }
+ login.state = SMAppService.mainApp.status == .enabled ? .on : .off
+ menu.addItem(login)
+
+ menu.addItem(.separator())
+ menu.addItem(ClosureMenuItem(L("Quit Tendedero", "Salir de Tendedero"), key: "q") {
+ NSApp.terminate(nil)
+ })
+ }
+
+ private static func toggleLaunchAtLogin() {
+ do {
+ if SMAppService.mainApp.status == .enabled {
+ try SMAppService.mainApp.unregister()
+ } else {
+ try SMAppService.mainApp.register()
+ }
+ } catch {
+ let alert = NSAlert()
+ alert.messageText = L("Could not change the login setting", "No se pudo cambiar el inicio de sesión")
+ alert.informativeText = L("Move Tendedero to the Applications folder and try again.",
+ "Mueve Tendedero a la carpeta Aplicaciones y vuelve a intentarlo.")
+ NSApp.activate(ignoringOtherApps: true)
+ alert.runModal()
+ }
+ }
+}
diff --git a/Sources/Tendedero/CaptureFlight.swift b/Sources/Tendedero/CaptureFlight.swift
new file mode 100644
index 0000000..0916730
--- /dev/null
+++ b/Sources/Tendedero/CaptureFlight.swift
@@ -0,0 +1,220 @@
+import AppKit
+import QuartzCore
+
+/// Reads where on screen a screenshot was taken. macOS stores the captured
+/// area on the file, in global points with the origin at the top left of
+/// the main display. Returned in AppKit screen coordinates.
+func captureRect(of url: URL) -> CGRect? {
+ let name = "com.apple.metadata:kMDItemScreenCaptureGlobalRect"
+ let data: Data? = url.withUnsafeFileSystemRepresentation { path in
+ guard let path else { return nil }
+ let size = getxattr(path, name, nil, 0, 0, 0)
+ guard size > 0 else { return nil }
+ var buffer = Data(count: size)
+ let read = buffer.withUnsafeMutableBytes { getxattr(path, name, $0.baseAddress, size, 0, 0) }
+ return read == size ? buffer : nil
+ }
+ guard let data,
+ let values = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [NSNumber],
+ values.count == 4, let main = NSScreen.screens.first else { return nil }
+ let x = CGFloat(truncating: values[0]), y = CGFloat(truncating: values[1])
+ let w = CGFloat(truncating: values[2]), h = CGFloat(truncating: values[3])
+ guard w > 2, h > 2 else { return nil }
+ return CGRect(x: x, y: main.frame.maxY - y - h, width: w, height: h)
+}
+
+/// The capture lifting off the screen and flying up to the line. It turns
+/// into the hanging card on the way: it shrinks, tilts into place and grows
+/// its glass frame and clip, so there is nothing left to change on landing.
+@MainActor
+final class CaptureFlight {
+ static let duration: CFTimeInterval = 0.65
+ /// How high the gentle arc rises halfway, in points.
+ private static let arc: CGFloat = 30
+
+ private let window: NSWindow
+ private let container = CALayer()
+ private let glass = CALayer()
+ private let edge = CAGradientLayer()
+ private let edgeMask = CAShapeLayer()
+ private let photo = CALayer()
+ private let clip = CAGradientLayer()
+
+ private let from: CGRect
+ private let to: CGRect
+ private let tilt: CGFloat
+ private var falling = false
+ private var duration: CFTimeInterval = CaptureFlight.duration
+ private var start: CFTimeInterval = 0
+ private var timer: Timer?
+ private var completion: () -> Void = {}
+
+ private static var current: [CaptureFlight] = []
+
+ /// - Parameters:
+ /// - from: the captured area, in screen coordinates.
+ /// - to: the card's frame on the line, in screen coordinates, unrotated.
+ /// - tilt: the card's resting tilt in degrees, clockwise, as SwiftUI uses.
+ static func fly(image: CGImage, from: CGRect, to: CGRect, tilt: CGFloat, on screen: NSScreen,
+ completion: @escaping () -> Void) {
+ let flight = CaptureFlight(image: image, from: from, to: to, tilt: tilt, screen: screen)
+ current.append(flight)
+ flight.completion = { [weak flight] in
+ completion()
+ current.removeAll { $0 === flight }
+ }
+ flight.run()
+ }
+
+ /// A discarded card falling off the line, drawn over the whole screen so
+ /// it is never cut by the line's strip. Same motion as the app always had:
+ /// 520 points down, tilting further, fading, 0.55 s ease in.
+ static func fall(image: CGImage, card: CGRect, tilt: CGFloat, on screen: NSScreen) {
+ let flight = CaptureFlight(image: image, from: card, to: card, tilt: tilt, screen: screen)
+ flight.falling = true
+ flight.duration = 0.55
+ current.append(flight)
+ flight.completion = { [weak flight] in current.removeAll { $0 === flight } }
+ flight.run()
+ }
+
+ private init(image: CGImage, from: CGRect, to: CGRect, tilt: CGFloat, screen: NSScreen) {
+ self.from = from
+ self.to = to
+ self.tilt = tilt
+ window = NSPanel(contentRect: screen.frame, styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false)
+ window.isOpaque = false
+ window.backgroundColor = .clear
+ window.hasShadow = false
+ window.ignoresMouseEvents = true
+ window.level = NSWindow.Level(rawValue: NSWindow.Level.floating.rawValue + 1)
+ window.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
+
+ let host = NSView(frame: NSRect(origin: .zero, size: screen.frame.size))
+ host.wantsLayer = true
+ window.contentView = host
+ let scale = screen.backingScaleFactor
+
+ container.anchorPoint = CGPoint(x: 0.5, y: 1) // the card's top center
+ container.shadowColor = NSColor.black.cgColor
+ container.shadowOpacity = 0.24
+ container.shadowRadius = 10
+ container.shadowOffset = CGSize(width: 0, height: -5)
+
+ glass.backgroundColor = NSColor(white: 0.97, alpha: 0.72).cgColor
+ edge.colors = [NSColor(white: 1, alpha: 0.9).cgColor, NSColor(white: 1, alpha: 0.25).cgColor]
+ edge.startPoint = CGPoint(x: 0.5, y: 1); edge.endPoint = CGPoint(x: 0.5, y: 0)
+ edgeMask.fillColor = nil
+ edgeMask.strokeColor = NSColor.black.cgColor
+ edgeMask.lineWidth = 1.5
+ edge.mask = edgeMask
+
+ photo.contents = image
+ photo.contentsGravity = .resizeAspectFill
+ photo.masksToBounds = true
+ photo.contentsScale = scale
+
+ clip.colors = [NSColor(white: 0.70, alpha: 1).cgColor, NSColor(white: 0.93, alpha: 1).cgColor,
+ NSColor(white: 0.82, alpha: 1).cgColor, NSColor(white: 0.62, alpha: 1).cgColor]
+ clip.locations = [0, 0.35, 0.65, 1]
+ clip.startPoint = CGPoint(x: 0, y: 0.5); clip.endPoint = CGPoint(x: 1, y: 0.5)
+ clip.cornerRadius = 3.5
+ clip.borderColor = NSColor(white: 1, alpha: 0.7).cgColor
+ clip.borderWidth = 0.6
+
+ for layer in [container, glass, edge, photo, clip] as [CALayer] { layer.contentsScale = scale }
+ container.addSublayer(glass)
+ container.addSublayer(photo)
+ container.addSublayer(edge)
+ container.addSublayer(clip)
+ host.layer?.addSublayer(container)
+ }
+
+ private func run() {
+ if falling { update(1); updateFall(0) } else { update(0) }
+ window.orderFrontRegardless()
+ start = CACurrentMediaTime()
+ let timer = Timer(timeInterval: 1.0 / 120.0, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.tick() }
+ }
+ RunLoop.main.add(timer, forMode: .common)
+ self.timer = timer
+ }
+
+ private func tick() {
+ let k = min(1, (CACurrentMediaTime() - start) / duration)
+ if falling { updateFall(k) } else { update(k) }
+ guard k >= 1 else { return }
+ timer?.invalidate()
+ timer = nil
+ completion()
+ if falling {
+ window.orderOut(nil)
+ return
+ }
+ // The real card fades in underneath; this one fades out over it.
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.16
+ window.animator().alphaValue = 0
+ }, completionHandler: { [window] in
+ MainActor.assumeIsolated { window.orderOut(nil) }
+ })
+ }
+
+ private func updateFall(_ raw: Double) {
+ let e = CGFloat(raw * raw * raw)
+ let origin = window.frame.origin
+ let angle = tilt + (tilt * 7 + 20) * e
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ container.position = CGPoint(x: to.midX - origin.x, y: to.maxY - origin.y - 520 * e)
+ container.setAffineTransform(CGAffineTransform(rotationAngle: -angle * .pi / 180))
+ container.opacity = Float(1 - e)
+ CATransaction.commit()
+ }
+
+ private static func easeInOutCubic(_ x: Double) -> Double {
+ x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2
+ }
+
+ private static func smooth(_ x: Double, _ a: Double, _ b: Double) -> Double {
+ let t = max(0, min(1, (x - a) / (b - a)))
+ return t * t * (3 - 2 * t)
+ }
+
+ private func update(_ raw: Double) {
+ let k = CGFloat(Self.easeInOutCubic(raw))
+ let chrome = Float(Self.smooth(Double(k), 0.35, 1))
+ let origin = window.frame.origin
+ func lerp(_ a: CGFloat, _ b: CGFloat) -> CGFloat { a + (b - a) * k }
+
+ let w = lerp(from.width, to.width), h = lerp(from.height, to.height)
+ let topX = lerp(from.midX, to.midX) - origin.x
+ let topY = lerp(from.maxY, to.maxY) - origin.y + sin(.pi * k) * Self.arc
+ let inset = 4 * k
+ let radius = lerp(0, 16)
+
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ container.bounds = CGRect(x: 0, y: 0, width: w, height: h)
+ container.position = CGPoint(x: topX, y: topY)
+ // SwiftUI tilts clockwise for positive angles; Core Animation the other way.
+ container.setAffineTransform(CGAffineTransform(rotationAngle: -tilt * .pi / 180 * k))
+ container.shadowPath = CGPath(roundedRect: container.bounds, cornerWidth: radius, cornerHeight: radius, transform: nil)
+
+ glass.frame = container.bounds
+ glass.cornerRadius = radius
+ glass.opacity = chrome
+ edge.frame = container.bounds
+ edgeMask.path = CGPath(roundedRect: container.bounds.insetBy(dx: 0.75, dy: 0.75),
+ cornerWidth: max(0, radius - 0.75), cornerHeight: max(0, radius - 0.75), transform: nil)
+ edge.opacity = chrome
+ photo.frame = container.bounds.insetBy(dx: inset, dy: inset)
+ photo.cornerRadius = max(0, radius - inset)
+ // The clip grips the top edge: 26 points tall, 12 of them over the card.
+ clip.frame = CGRect(x: w / 2 - 4.5, y: h - 12, width: 9, height: 26)
+ clip.opacity = chrome
+ CATransaction.commit()
+ }
+}
diff --git a/Sources/Tendedero/FullScreen.swift b/Sources/Tendedero/FullScreen.swift
new file mode 100644
index 0000000..ab68248
--- /dev/null
+++ b/Sources/Tendedero/FullScreen.swift
@@ -0,0 +1,39 @@
+import AppKit
+
+// The window server knows the type of the Space each display is showing.
+// These calls are private but stable for a decade, need no permission, and
+// are what window managers like yabai rely on. A full screen Space is type 4.
+@_silgen_name("CGSMainConnectionID")
+private func CGSMainConnectionID() -> Int32
+
+@_silgen_name("CGSCopyManagedDisplaySpaces")
+private func CGSCopyManagedDisplaySpaces(_ connection: Int32) -> CFArray
+
+enum FullScreen {
+ private static let fullScreenSpaceType = 4
+
+ /// True when the given screen is currently showing a full screen app,
+ /// like a video or a presentation.
+ static func isActive(on screen: NSScreen) -> Bool {
+ guard let displays = CGSCopyManagedDisplaySpaces(CGSMainConnectionID()) as? [[String: Any]],
+ !displays.isEmpty else { return false }
+
+ // With "Displays have separate Spaces" off there is a single entry
+ // that covers every screen.
+ let entry: [String: Any]?
+ if displays.count == 1 {
+ entry = displays.first
+ } else {
+ let uuid = uuidString(for: screen)
+ entry = displays.first { ($0["Display Identifier"] as? String) == uuid }
+ }
+ let current = entry?["Current Space"] as? [String: Any]
+ return (current?["type"] as? Int) == fullScreenSpaceType
+ }
+
+ private static func uuidString(for screen: NSScreen) -> String? {
+ guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID,
+ let uuid = CGDisplayCreateUUIDFromDisplayID(number)?.takeRetainedValue() else { return nil }
+ return CFUUIDCreateString(nil, uuid) as String?
+ }
+}
diff --git a/Sources/Tendedero/GrabArea.swift b/Sources/Tendedero/GrabArea.swift
new file mode 100644
index 0000000..eabab21
--- /dev/null
+++ b/Sources/Tendedero/GrabArea.swift
@@ -0,0 +1,212 @@
+import AppKit
+import SwiftUI
+
+/// Bridges each photo to AppKit's drag and drop, so it can be dragged into
+/// any app as a real file. Each destination means one thing:
+///
+/// - An app gets a copy, and the photo stays on the line.
+/// - A folder or the Desktop keeps the file, and the photo leaves the line.
+/// - The Trash discards it.
+/// - Nowhere that accepts it: the photo flies back to the line.
+///
+/// Click copies, press and hold opens Markup, the corner cross discards.
+struct GrabArea: NSViewRepresentable {
+ let item: Pegged
+ let line: Line
+
+ func makeNSView(context: Context) -> GrabView {
+ let view = GrabView()
+ configure(view)
+ return view
+ }
+
+ func updateNSView(_ view: GrabView, context: Context) {
+ configure(view)
+ }
+
+ private func configure(_ view: GrabView) {
+ let id = item.id
+ let line = line
+ view.url = item.url
+ view.dragImage = item.thumb
+ view.onClick = { line.copy(id) }
+ view.onDoubleClick = { line.open(id) }
+ view.onDragStart = { line.draggingID = id }
+ view.onDragEnd = {
+ line.draggingID = nil
+ // Moved into a folder: it is saved where you wanted it.
+ line.prune()
+ }
+ view.onTrash = { line.trash(id) }
+ view.onDiscard = { line.discard(id) }
+ view.onLongPress = { line.markup(id) }
+ view.onPressChange = { pressed in line.pressedID = pressed ? id : nil }
+ view.menuProvider = {
+ let menu = NSMenu()
+ menu.addItem(ClosureMenuItem(L("Copy", "Copiar")) { line.copy(id) })
+ menu.addItem(ClosureMenuItem(L("Open", "Abrir")) { line.open(id) })
+ menu.addItem(ClosureMenuItem(L("Markup", "Marcación")) { line.markup(id) })
+ menu.addItem(ClosureMenuItem(L("Show in Finder", "Mostrar en Finder")) { line.reveal(id) })
+ let inInbox = line.isInInbox(id)
+ if inInbox {
+ menu.addItem(ClosureMenuItem(L("Save to Desktop", "Guardar en el Escritorio")) { line.saveToDesktop(id) })
+ }
+ menu.addItem(.separator())
+ if inInbox {
+ menu.addItem(ClosureMenuItem(L("Discard", "Descartar")) { line.discard(id) })
+ } else {
+ menu.addItem(ClosureMenuItem(L("Take down", "Descolgar")) { line.discard(id) })
+ menu.addItem(ClosureMenuItem(L("Move to Trash", "Mover a la Papelera")) { line.trash(id) })
+ }
+ return menu
+ }
+ }
+}
+
+final class GrabView: NSView, NSDraggingSource {
+ static var isDragging = false
+
+ var url: URL?
+ var dragImage: NSImage?
+ var onClick: () -> Void = {}
+ var onDoubleClick: () -> Void = {}
+ var onDragStart: () -> Void = {}
+ var onDragEnd: () -> Void = {}
+ var onTrash: () -> Void = {}
+ var onDiscard: () -> Void = {}
+ var onLongPress: () -> Void = {}
+ var onPressChange: (Bool) -> Void = { _ in }
+ var menuProvider: () -> NSMenu = { NSMenu() }
+
+ private var downPoint: NSPoint?
+ private var startedDrag = false
+ private var holdTimer: Timer?
+ private var didLongPress = false
+
+ /// How long you hold before Markup opens. Long enough not to fire on a
+ /// slow click, short enough to feel deliberate.
+ private static let holdDuration: TimeInterval = 0.45
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ /// The discard cross drawn in the top left corner of the card. It is
+ /// handled here because this view sits on top of the SwiftUI card.
+ static let crossHitSize: CGFloat = 26
+
+ private func isInCross(_ event: NSEvent) -> Bool {
+ let p = convert(event.locationInWindow, from: nil)
+ let corner = NSRect(x: 0, y: isFlipped ? 0 : bounds.height - Self.crossHitSize,
+ width: Self.crossHitSize, height: Self.crossHitSize)
+ return corner.contains(p)
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ if isInCross(event) {
+ downPoint = nil
+ onDiscard()
+ return
+ }
+ if event.clickCount == 2 {
+ downPoint = nil
+ onDoubleClick()
+ return
+ }
+ downPoint = event.locationInWindow
+ startedDrag = false
+ didLongPress = false
+ onPressChange(true)
+ holdTimer?.invalidate()
+ holdTimer = Timer.scheduledTimer(withTimeInterval: Self.holdDuration, repeats: false) { [weak self] _ in
+ MainActor.assumeIsolated {
+ guard let self, self.downPoint != nil, !self.startedDrag else { return }
+ self.didLongPress = true
+ self.onPressChange(false)
+ self.onLongPress()
+ }
+ }
+ }
+
+ private func endPress() {
+ holdTimer?.invalidate()
+ holdTimer = nil
+ onPressChange(false)
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard let start = downPoint, !startedDrag, let url else { return }
+ let p = event.locationInWindow
+ guard hypot(p.x - start.x, p.y - start.y) > 4, !didLongPress else { return }
+ startedDrag = true
+ endPress()
+
+ let item = NSDraggingItem(pasteboardWriter: url as NSURL)
+ item.setDraggingFrame(imageFrame(), contents: dragImage)
+ let session = beginDraggingSession(with: [item], event: event, source: self)
+ // Released where nothing accepts it: it flies back to the line.
+ session.animatesToStartingPositionsOnCancelOrFail = true
+ GrabView.isDragging = true
+ onDragStart()
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ endPress()
+ if downPoint != nil && !startedDrag && !didLongPress && event.clickCount == 1 { onClick() }
+ downPoint = nil
+ didLongPress = false
+ }
+
+ override func rightMouseDown(with event: NSEvent) {
+ NSMenu.popUpContextMenu(menuProvider(), with: event, for: self)
+ }
+
+ // MARK: NSDraggingSource
+
+ func draggingSession(_ session: NSDraggingSession,
+ sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ // Apps pick copy. Finder picks move, so a folder or the Desktop keeps
+ // the file. Delete is what lets the Dock's Trash accept it.
+ context == .outsideApplication ? [.copy, .move, .delete] : []
+ }
+
+ func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
+ GrabView.isDragging = false
+ startedDrag = false
+ downPoint = nil
+ log.notice("Drag ended with operation \(operation.rawValue, privacy: .public)")
+ // Dropped on the Trash: macOS only tells us, we move the file.
+ if operation.contains(.delete) {
+ onDragEnd()
+ onTrash()
+ return
+ }
+ onDragEnd()
+ // Finder finishes a move a moment later. Check again then, so a photo
+ // saved into a folder leaves the line.
+ if operation.contains(.move) {
+ let done = onDragEnd
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { done() }
+ }
+ }
+
+ /// The drag preview keeps the photo's aspect ratio inside the card.
+ private func imageFrame() -> NSRect {
+ guard let size = dragImage?.size, size.width > 0, size.height > 0 else { return bounds }
+ let scale = min(bounds.width / size.width, bounds.height / size.height)
+ let w = size.width * scale, h = size.height * scale
+ return NSRect(x: (bounds.width - w) / 2, y: (bounds.height - h) / 2, width: w, height: h)
+ }
+}
+
+final class ClosureMenuItem: NSMenuItem {
+ private let handler: () -> Void
+
+ init(_ title: String, key: String = "", handler: @escaping () -> Void) {
+ self.handler = handler
+ super.init(title: title, action: #selector(fire), keyEquivalent: key)
+ target = self
+ }
+
+ required init(coder: NSCoder) { fatalError() }
+
+ @objc private func fire() { handler() }
+}
diff --git a/Sources/Tendedero/HotKey.swift b/Sources/Tendedero/HotKey.swift
new file mode 100644
index 0000000..236fbda
--- /dev/null
+++ b/Sources/Tendedero/HotKey.swift
@@ -0,0 +1,23 @@
+import Carbon
+
+/// A single global shortcut through the Carbon hot key API. Unlike a global
+/// key monitor, it needs no Accessibility permission.
+final class HotKey {
+ private var ref: EventHotKeyRef?
+ private static var action: (() -> Void)?
+
+ init(keyCode: Int, modifiers: Int, action: @escaping () -> Void) {
+ HotKey.action = action
+ var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
+ InstallEventHandler(GetApplicationEventTarget(), { _, _, _ in
+ DispatchQueue.main.async { HotKey.action?() }
+ return noErr
+ }, 1, &spec, nil, nil)
+ let id = EventHotKeyID(signature: OSType(0x5445_4E44), id: 1) // "TEND"
+ RegisterEventHotKey(UInt32(keyCode), UInt32(modifiers), id, GetApplicationEventTarget(), 0, &ref)
+ }
+
+ deinit {
+ if let ref { UnregisterEventHotKey(ref) }
+ }
+}
diff --git a/Sources/Tendedero/Inbox.swift b/Sources/Tendedero/Inbox.swift
new file mode 100644
index 0000000..7280474
--- /dev/null
+++ b/Sources/Tendedero/Inbox.swift
@@ -0,0 +1,81 @@
+import Foundation
+
+/// Inbox mode: Tendedero takes over where screenshots go.
+///
+/// It changes two macOS screenshot settings, the same ones in the Options
+/// 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.
+///
+/// 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
+/// is watching.
+enum Inbox {
+ private static let domain = "com.apple.screencapture" as CFString
+ /// macOS 26 and earlier read "location". macOS 27 reads
+ /// "location-screenshot" and ignores the old key, so both are written.
+ private static let locationKey = "location" as CFString
+ private static let screenshotLocationKey = "location-screenshot" as CFString
+ private static let thumbnailKey = "show-thumbnail" as CFString
+
+ private static let enabledKey = "inboxEnabled"
+ private static let offeredKey = "inboxOffered"
+ private static let savedKey = "inboxSavedSettings"
+
+ static let folder: URL = {
+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ return base.appendingPathComponent("Tendedero/Screenshots", isDirectory: true)
+ }()
+
+ /// The user's choice, kept across launches.
+ static var isEnabled: Bool {
+ get { UserDefaults.standard.bool(forKey: enabledKey) }
+ set { UserDefaults.standard.set(newValue, forKey: enabledKey) }
+ }
+
+ /// Whether we already asked, so the offer appears only once.
+ static var wasOffered: Bool {
+ get { UserDefaults.standard.bool(forKey: offeredKey) }
+ set { UserDefaults.standard.set(newValue, forKey: offeredKey) }
+ }
+
+ /// Whether macOS is currently sending screenshots to our folder.
+ static var isApplied: Bool {
+ guard let current = CFPreferencesCopyAppValue(locationKey, domain) as? String else { return false }
+ return URL(fileURLWithPath: (current as NSString).expandingTildeInPath).standardizedFileURL
+ == folder.standardizedFileURL
+ }
+
+ static func apply() {
+ 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.
+ 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)
+ }
+ set(locationKey, folder.path)
+ set(screenshotLocationKey, folder.path)
+ set(thumbnailKey, false)
+ }
+
+ static func restore() {
+ guard isApplied else { return }
+ let saved = UserDefaults.standard.dictionary(forKey: savedKey) ?? [:]
+ set(locationKey, saved["location"])
+ set(screenshotLocationKey, saved["locationScreenshot"])
+ set(thumbnailKey, saved["thumbnail"])
+ UserDefaults.standard.removeObject(forKey: savedKey)
+ }
+
+ /// Writes through cfprefsd, so the screenshot service sees it at once.
+ /// A nil value removes the key and returns it to the macOS default.
+ private static func set(_ key: CFString, _ value: Any?) {
+ CFPreferencesSetAppValue(key, value as CFPropertyList?, domain)
+ CFPreferencesAppSynchronize(domain)
+ }
+}
diff --git a/Sources/Tendedero/Line.swift b/Sources/Tendedero/Line.swift
new file mode 100644
index 0000000..98eaf0a
--- /dev/null
+++ b/Sources/Tendedero/Line.swift
@@ -0,0 +1,262 @@
+import AppKit
+import Combine
+import os
+
+let log = Logger(subsystem: "app.tendedero.Tendedero", category: "line")
+
+/// One screenshot hanging on the line.
+struct Pegged: Identifiable, Equatable {
+ let id = UUID()
+ let url: URL
+ var thumb: NSImage
+ /// Every photo hangs a little crooked, like on a real line.
+ let tilt = Double.random(in: -2.5...2.5)
+ var falling = false
+ /// Still flying in from where it was captured; the card waits hidden.
+ var flying = false
+
+ static func == (a: Pegged, b: Pegged) -> Bool {
+ a.id == b.id && a.falling == b.falling && a.flying == b.flying && a.thumb === b.thumb
+ }
+}
+
+/// The line itself: what hangs on it and what you can do with each item.
+/// The files never move. The line is only a view onto them.
+@MainActor
+final class Line: ObservableObject {
+ @Published private(set) var items: [Pegged] = []
+ @Published private(set) var gust = 0
+ @Published var copiedID: UUID?
+ @Published var draggingID: UUID?
+ @Published var pressedID: UUID?
+ /// Whether the line has slid down into view.
+ @Published var revealed = false
+
+ /// Card frames in window coordinates, reported by the views. The panel
+ /// uses them to only catch clicks over photos and let the rest through.
+ var hitRects: [UUID: CGRect] = [:]
+
+ var maxItems = 8
+
+
+ var soundOn: Bool {
+ get { !UserDefaults.standard.bool(forKey: "soundOff") }
+ set { UserDefaults.standard.set(!newValue, forKey: "soundOff") }
+ }
+
+ var liveCount: Int { items.filter { !$0.falling }.count }
+
+ private let storeKey = "pegged"
+
+ init() {
+ restore()
+ scheduleGust()
+ }
+
+ // MARK: Hanging and dropping
+
+ @discardableResult
+ func hang(_ url: URL, quietly: Bool = false, flying: Bool = false) -> UUID? {
+ guard !items.contains(where: { $0.url == url && !$0.falling }),
+ let thumb = makeThumbnail(url) else { return nil }
+ var item = Pegged(url: url, thumb: thumb)
+ item.flying = flying
+ items.append(item)
+ // A full line lets the oldest photo fall off the far end.
+ while liveCount > maxItems, let oldest = items.first(where: { !$0.falling }) {
+ drop(oldest.id, quietly: true)
+ }
+ save()
+ if !quietly { play("Tink", volume: 0.35) }
+ return item.id
+ }
+
+ /// The capture has reached the line: the real card takes over.
+ func land(_ id: UUID) {
+ guard let i = items.firstIndex(where: { $0.id == id }) else { return }
+ items[i].flying = false
+ }
+
+ /// Called just before a photo starts falling, so the fall can be drawn
+ /// over the whole screen.
+ var onFall: ((Pegged) -> Void)?
+
+ func drop(_ id: UUID, quietly: Bool = false) {
+ guard let i = items.firstIndex(where: { $0.id == id }), !items[i].falling else { return }
+ onFall?(items[i])
+ items[i].falling = true
+ hitRects[id] = nil
+ save()
+ if !quietly { play("Pop", volume: 0.25) }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
+ self?.items.removeAll { $0.id == id }
+ }
+ }
+
+ func clear() {
+ let live = items.filter { !$0.falling }
+ for (n, item) in live.enumerated() {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.06 * Double(n)) { [weak self] in
+ self?.drop(item.id, quietly: n > 0)
+ }
+ }
+ }
+
+ /// Photos whose file was deleted or moved away fall off by themselves.
+ func prune() {
+ for item in items where !item.falling && !FileManager.default.fileExists(atPath: item.url.path) {
+ drop(item.id, quietly: true)
+ }
+ }
+
+ // MARK: Actions on one photo
+
+ 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) }
+ entry.setString(item.url.absoluteString, forType: .fileURL)
+ let pb = NSPasteboard.general
+ pb.clearContents()
+ pb.writeObjects([entry])
+
+ copiedID = id
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in
+ if self?.copiedID == id { self?.copiedID = nil }
+ }
+ }
+
+ func open(_ id: UUID) {
+ guard let item = items.first(where: { $0.id == id }) else { return }
+ NSWorkspace.shared.open(item.url)
+ }
+
+ /// Moves the file to the Trash and takes the photo off the line. When a
+ /// drag ends on the Dock's Trash, macOS only reports it: deleting the file
+ /// is the source app's job, as Finder does.
+ func trash(_ id: UUID) {
+ guard let item = items.first(where: { $0.id == id }) else { return }
+ do {
+ try FileManager.default.trashItem(at: item.url, resultingItemURL: nil)
+ log.notice("Trashed \(item.url.lastPathComponent, privacy: .public)")
+ if soundOn { Line.trashSound?.play() }
+ drop(id, quietly: true)
+ } catch {
+ log.error("Could not trash \(item.url.path, privacy: .public): \(error.localizedDescription, privacy: .public)")
+ NSSound.beep()
+ }
+ }
+
+ private static let trashSound = NSSound(
+ contentsOfFile: "/System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds/dock/drag to trash.aif",
+ byReference: true)
+
+ /// Whether the file lives in Tendedero's own folder. Those are discarded
+ /// to the Trash, or the folder would fill up with forgotten screenshots.
+ /// Files anywhere else, like the Desktop, stay where they are.
+ func isInInbox(_ id: UUID) -> Bool {
+ guard let item = items.first(where: { $0.id == id }) else { return false }
+ return item.url.standardizedFileURL.path.hasPrefix(Inbox.folder.standardizedFileURL.path + "/")
+ }
+
+ /// The corner cross and "Take down" both end up here.
+ func discard(_ id: UUID) {
+ if isInInbox(id) { trash(id) } else { drop(id) }
+ }
+
+ /// Inbox mode: keep a screenshot by moving it to the Desktop.
+ func saveToDesktop(_ id: UUID) {
+ guard let item = items.first(where: { $0.id == id }) else { return }
+ let desktop = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")
+ let target = uniqueURL(in: desktop, for: item.url.lastPathComponent)
+ do {
+ try FileManager.default.moveItem(at: item.url, to: target)
+ drop(id, quietly: true)
+ } catch {
+ log.error("Could not save to Desktop: \(error.localizedDescription, privacy: .public)")
+ NSSound.beep()
+ }
+ }
+
+ private func uniqueURL(in folder: URL, for name: String) -> URL {
+ let base = (name as NSString).deletingPathExtension
+ let ext = (name as NSString).pathExtension
+ var candidate = folder.appendingPathComponent(name)
+ var n = 2
+ while FileManager.default.fileExists(atPath: candidate.path) {
+ candidate = folder.appendingPathComponent("\(base) \(n)").appendingPathExtension(ext)
+ n += 1
+ }
+ return candidate
+ }
+
+ /// Long press: open the photo in the system Markup editor.
+ func markup(_ id: UUID) {
+ guard let item = items.first(where: { $0.id == id }) else { return }
+ Markup.shared.edit(item.url)
+ }
+
+ /// After editing, the photo on the line shows the new version.
+ func reloadThumbnail(for url: URL) {
+ guard let i = items.firstIndex(where: { $0.url == url && !$0.falling }),
+ let thumb = makeThumbnail(url) else { return }
+ items[i].thumb = thumb
+ }
+
+ func reveal(_ id: UUID) {
+ guard let item = items.first(where: { $0.id == id }) else { return }
+ NSWorkspace.shared.activateFileViewerSelecting([item.url])
+ }
+
+ // MARK: Breeze
+
+ /// Every so often a little wind moves the line. It is the detail that
+ /// makes it feel like an object and not a widget.
+ private func scheduleGust() {
+ DispatchQueue.main.asyncAfter(deadline: .now() + .random(in: 7...16)) { [weak self] in
+ guard let self else { return }
+ if !self.items.isEmpty && self.draggingID == nil { self.gust += 1 }
+ self.scheduleGust()
+ }
+ }
+
+ // MARK: Persistence
+
+ private func save() {
+ let paths = items.filter { !$0.falling }.map(\.url.path)
+ UserDefaults.standard.set(paths, forKey: storeKey)
+ }
+
+ private func restore() {
+ let paths = UserDefaults.standard.stringArray(forKey: storeKey) ?? []
+ for path in paths where FileManager.default.fileExists(atPath: path) {
+ hang(URL(fileURLWithPath: path), quietly: true)
+ }
+ }
+
+ // MARK: Helpers
+
+ private func play(_ name: String, volume: Float) {
+ guard soundOn, let sound = NSSound(named: name)?.copy() as? NSSound else { return }
+ sound.volume = volume
+ sound.play()
+ }
+
+ private func pngData(_ url: URL) -> Data? {
+ if url.pathExtension.lowercased() == "png" { return try? Data(contentsOf: url) }
+ guard let tiff = NSImage(contentsOf: url)?.tiffRepresentation,
+ let rep = NSBitmapImageRep(data: tiff) else { return nil }
+ return rep.representation(using: .png, properties: [:])
+ }
+}
+
+func makeThumbnail(_ url: URL, maxPixels: Int = 480) -> NSImage? {
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxPixels,
+ ]
+ guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
+ return NSImage(cgImage: cg, size: NSSize(width: cg.width, height: cg.height))
+}
diff --git a/Sources/Tendedero/LinePanel.swift b/Sources/Tendedero/LinePanel.swift
new file mode 100644
index 0000000..613de7f
--- /dev/null
+++ b/Sources/Tendedero/LinePanel.swift
@@ -0,0 +1,41 @@
+import AppKit
+
+/// A transparent strip along the top of the screen that floats over every
+/// app and every Space except full screen ones, never takes focus, and lets clicks pass through
+/// everywhere except over the photos.
+final class LinePanel: NSPanel {
+ init(content: NSView) {
+ super.init(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false)
+ isOpaque = false
+ backgroundColor = .clear
+ hasShadow = false
+ level = .floating
+ // Every Space except full screen ones: a video or a presentation in full
+ // screen should never get a clothesline across the top.
+ collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
+ hidesOnDeactivate = false
+ isMovable = false
+ becomesKeyOnlyIfNeeded = true
+ ignoresMouseEvents = true
+ contentView = content
+ }
+
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+
+ /// The line hangs on the screen you are using, which is the one with the
+ /// pointer: that is where you just took the screenshot.
+ static func screenUnderPointer() -> NSScreen? {
+ let mouse = NSEvent.mouseLocation
+ return NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) }
+ ?? NSScreen.main ?? NSScreen.screens.first
+ }
+
+ func placeOnScreen(_ screen: NSScreen? = nil) {
+ guard let visible = (screen ?? LinePanel.screenUnderPointer())?.visibleFrame else { return }
+ let target = NSRect(x: visible.minX, y: visible.maxY - Layout.panelHeight,
+ width: visible.width, height: Layout.panelHeight)
+ if frame != target { setFrame(target, display: true) }
+ }
+}
diff --git a/Sources/Tendedero/LineView.swift b/Sources/Tendedero/LineView.swift
new file mode 100644
index 0000000..8892255
--- /dev/null
+++ b/Sources/Tendedero/LineView.swift
@@ -0,0 +1,112 @@
+import SwiftUI
+
+enum Layout {
+ static let panelHeight: CGFloat = 210
+ static let ropeTop: CGFloat = 10
+ static let spacing: CGFloat = 174
+ static let cardWidth: CGFloat = 150
+ static let pinAbove: CGFloat = 9.5
+
+ /// The rope hangs as a parabola from edge to edge of the screen.
+ static func sag(width: CGFloat) -> CGFloat { min(30, width * 0.018) }
+
+ static func ropeY(x: CGFloat, width: CGFloat) -> CGFloat {
+ guard width > 0 else { return ropeTop }
+ let f = x / width
+ return ropeTop + 4 * sag(width: width) * f * (1 - f)
+ }
+
+ static func x(index: Int, count: Int, width: CGFloat) -> CGFloat {
+ let total = CGFloat(max(count - 1, 0)) * spacing
+ return width / 2 - total / 2 + CGFloat(index) * spacing
+ }
+}
+
+struct LineView: View {
+ @ObservedObject var line: Line
+
+ var body: some View {
+ GeometryReader { geo in
+ let width = geo.size.width
+ ZStack(alignment: .topLeading) {
+ Rope(width: width)
+
+ if line.items.isEmpty {
+ Hint()
+ .position(x: width / 2, y: Layout.ropeY(x: width / 2, width: width) + 34)
+ .transition(.opacity)
+ }
+
+ ForEach(Array(line.items.enumerated()), id: \.element.id) { index, item in
+ let x = Layout.x(index: index, count: line.items.count, width: width)
+ let ropeY = Layout.ropeY(x: x, width: width)
+ PeggedView(item: item, line: line)
+ .frame(width: Layout.cardWidth, height: Layout.panelHeight - ropeY, alignment: .top)
+ .position(x: x, y: ropeY - Layout.pinAbove + (Layout.panelHeight - ropeY) / 2)
+ }
+ }
+ .animation(.spring(response: 0.55, dampingFraction: 0.78), value: line.items.map(\.id))
+ .animation(.easeInOut(duration: 0.3), value: line.items.isEmpty)
+ // Tucked away, the whole line waits above the top edge and slides
+ // out from under the menu bar, the way an auto-hiding Dock does.
+ .offset(y: line.revealed ? 0 : -(Layout.panelHeight + 12))
+ .animation(line.revealed ? .spring(response: 0.42, dampingFraction: 0.82)
+ : .easeIn(duration: 0.22), value: line.revealed)
+ }
+ .onPreferenceChange(HitRectsKey.self) { rects in
+ line.hitRects = rects
+ }
+ }
+}
+
+private struct Hint: View {
+ var body: some View {
+ Text(L("Take a screenshot and it will hang here", "Haz una captura y se quedará colgada aquí"))
+ .font(.system(size: 12, weight: .medium, design: .rounded))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(.regularMaterial, in: Capsule())
+ }
+}
+
+/// A thin, neutral line: a mid gray core with a faint highlight and a soft
+/// shadow, so it reads on light and dark backgrounds alike. It fades out at
+/// both ends so it seems to come from beyond the screen.
+struct Rope: View {
+ let width: CGFloat
+
+ private var path: Path {
+ Path { p in
+ let top = Layout.ropeTop
+ p.move(to: CGPoint(x: -20, y: top))
+ p.addQuadCurve(
+ to: CGPoint(x: width + 20, y: top),
+ control: CGPoint(x: width / 2, y: top + 2 * Layout.sag(width: width)))
+ }
+ }
+
+ var body: some View {
+ ZStack {
+ path.stroke(Color.black.opacity(0.22), lineWidth: 1.4).offset(y: 1.2).blur(radius: 1.2)
+ path.stroke(Color(white: 0.55), lineWidth: 1.2)
+ path.stroke(Color.white.opacity(0.45), lineWidth: 0.4).offset(y: -0.35)
+ }
+ .mask(
+ LinearGradient(stops: [
+ .init(color: .clear, location: 0),
+ .init(color: .black, location: 0.08),
+ .init(color: .black, location: 0.92),
+ .init(color: .clear, location: 1),
+ ], startPoint: .leading, endPoint: .trailing)
+ )
+ .allowsHitTesting(false)
+ }
+}
+
+struct HitRectsKey: PreferenceKey {
+ static var defaultValue: [UUID: CGRect] = [:]
+ static func reduce(value: inout [UUID: CGRect], nextValue: () -> [UUID: CGRect]) {
+ value.merge(nextValue()) { $1 }
+ }
+}
diff --git a/Sources/Tendedero/Localization.swift b/Sources/Tendedero/Localization.swift
new file mode 100644
index 0000000..8cd02bf
--- /dev/null
+++ b/Sources/Tendedero/Localization.swift
@@ -0,0 +1,9 @@
+import Foundation
+
+private let isSpanish = Locale.preferredLanguages.first?.hasPrefix("es") ?? false
+
+/// Tiny two-language helper. The app has a handful of strings, so a full
+/// .strings setup would be more ceremony than content.
+func L(_ english: String, _ spanish: String) -> String {
+ isSpanish ? spanish : english
+}
diff --git a/Sources/Tendedero/Markup.swift b/Sources/Tendedero/Markup.swift
new file mode 100644
index 0000000..db126e6
--- /dev/null
+++ b/Sources/Tendedero/Markup.swift
@@ -0,0 +1,105 @@
+import AppKit
+import UniformTypeIdentifiers
+
+/// Opens a screenshot in the system Markup editor, the window macOS shows
+/// when you click the thumbnail of a screenshot you just took. It is a
+/// system extension, reached through the sharing service it registers.
+@MainActor
+final class Markup: NSObject, NSSharingServiceDelegate {
+ static let shared = Markup()
+
+ /// Called with the file once the edited image has been written back.
+ var onSaved: (URL) -> Void = { _ in }
+
+ private var editing: URL?
+ private static let serviceName = NSSharingService.Name("com.apple.MarkupUI.Markup")
+
+ func edit(_ url: URL) {
+ guard let service = NSSharingService(named: Markup.serviceName),
+ service.canPerform(withItems: [url]) else {
+ // Without the extension, Preview is the closest thing.
+ NSWorkspace.shared.open(url)
+ return
+ }
+ editing = url
+ service.delegate = self
+ NSApp.activate(ignoringOtherApps: true)
+ service.perform(withItems: [url])
+ }
+
+ // MARK: NSSharingServiceDelegate
+
+ /// Done was pressed. The extension hands back the edited image and the
+ /// host app is the one that writes it over the original file.
+ nonisolated func sharingService(_ sharingService: NSSharingService, didShareItems items: [Any]) {
+ MainActor.assumeIsolated { self.save(items) }
+ }
+
+ nonisolated func sharingService(_ sharingService: NSSharingService,
+ didFailToShareItems items: [Any], error: Error) {
+ log.notice("Markup ended without saving: \(error.localizedDescription, privacy: .public)")
+ }
+
+ // MARK: Writing back
+
+ private func save(_ items: [Any]) {
+ guard let target = editing, let item = items.first else { return }
+ editing = nil
+ log.notice("Markup returned \(String(describing: type(of: item)), privacy: .public)")
+
+ switch item {
+ case let url as URL:
+ write(from: url, to: target)
+ case let image as NSImage:
+ write(data: pngData(image), to: target)
+ case let provider as NSItemProvider:
+ load(provider, into: target)
+ default:
+ log.error("Markup returned an unexpected item")
+ }
+ }
+
+ private func load(_ provider: NSItemProvider, into target: URL) {
+ let types = provider.registeredTypeIdentifiers
+ log.notice("Markup provider types: \(types.joined(separator: ", "), privacy: .public)")
+
+ if types.contains(UTType.fileURL.identifier) {
+ _ = provider.loadObject(ofClass: URL.self) { url, _ in
+ DispatchQueue.main.async { if let url { self.write(from: url, to: target) } }
+ }
+ return
+ }
+ // Prefer the original format, then any image format.
+ let original = UTType(filenameExtension: target.pathExtension)?.identifier
+ let imageType = types.first { $0 == original }
+ ?? types.first { UTType($0)?.conforms(to: .image) == true }
+ guard let imageType else { return }
+ provider.loadDataRepresentation(forTypeIdentifier: imageType) { data, _ in
+ DispatchQueue.main.async { self.write(data: data, to: target) }
+ }
+ }
+
+ private func write(from source: URL, to target: URL) {
+ if source.standardizedFileURL == target.standardizedFileURL {
+ onSaved(target)
+ } else {
+ write(data: try? Data(contentsOf: source), to: target)
+ }
+ }
+
+ private func write(data: Data?, to target: URL) {
+ guard let data else { return }
+ do {
+ try data.write(to: target, options: .atomic)
+ onSaved(target)
+ } catch {
+ log.error("Could not save markup: \(error.localizedDescription, privacy: .public)")
+ NSSound.beep()
+ }
+ }
+
+ private func pngData(_ image: NSImage) -> Data? {
+ guard let tiff = image.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return nil }
+ return rep.representation(using: .png, properties: [:])
+ }
+}
diff --git a/Sources/Tendedero/PeggedView.swift b/Sources/Tendedero/PeggedView.swift
new file mode 100644
index 0000000..344ee4e
--- /dev/null
+++ b/Sources/Tendedero/PeggedView.swift
@@ -0,0 +1,199 @@
+import SwiftUI
+
+/// One photo with its clothespin. All the charm lives here: it drops onto
+/// the line, swings, sways with the breeze and falls when you pull it off.
+struct PeggedView: View {
+ let item: Pegged
+ @ObservedObject var line: Line
+
+ @State private var swing: Double = 0
+ @State private var arrived = false
+ @State private var hovering = false
+
+ private var copied: Bool { line.copiedID == item.id }
+ private var dragging: Bool { line.draggingID == item.id }
+ private var pressed: Bool { line.pressedID == item.id }
+
+ var body: some View {
+ VStack(spacing: -12) {
+ Clothespin()
+ .zIndex(1)
+ card
+ }
+ .rotationEffect(.degrees(swing + item.tilt), anchor: .top)
+ .offset(y: arrived ? 0 : -46)
+ // The fall itself is drawn over the whole screen by CaptureFlight, so
+ // the card here just steps aside at once.
+ .opacity(item.falling || item.flying ? 0 : (arrived ? 1 : 0))
+ .transaction { t in if item.falling { t.animation = nil } }
+ .animation(.easeOut(duration: 0.16), value: item.flying)
+ .onAppear(perform: arrive)
+ .onChange(of: item.flying) { was, now in if was && !now { land() } }
+ .onChange(of: line.gust) { _, _ in breeze() }
+ .onChange(of: copied) { _, isCopied in if isCopied { nudge(3) } }
+ }
+
+ /// The photo fits inside the card area keeping its proportions, so the
+ /// white border hugs it whether the screenshot is wide or tall.
+ static func photoSize(for size: CGSize) -> CGSize {
+ let maxW = Layout.cardWidth - 14, maxH: CGFloat = 104
+ guard size.width > 0, size.height > 0 else { return CGSize(width: maxW, height: maxH) }
+ let scale = min(maxW / size.width, maxH / size.height)
+ return CGSize(width: size.width * scale, height: size.height * scale)
+ }
+
+ /// The card around the photo: the photo plus the glass inset.
+ static func cardSize(for size: CGSize) -> CGSize {
+ let p = photoSize(for: size)
+ return CGSize(width: p.width + Frame.inset * 2, height: p.height + Frame.inset * 2)
+ }
+
+ /// Distance from the top of the hanging view (the clip) to the card.
+ static let cardOffsetBelowTop: CGFloat = 26 - 12
+
+ private var photoSize: CGSize { Self.photoSize(for: item.thumb.size) }
+
+ private var card: some View {
+ Image(nsImage: item.thumb)
+ .resizable()
+ .interpolation(.high)
+ .frame(width: photoSize.width, height: photoSize.height)
+ // Concentric corners: the photo's radius is the frame's minus the
+ // inset, the way macOS rounds nested shapes.
+ .clipShape(RoundedRectangle(cornerRadius: Frame.radius - Frame.inset, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: Frame.radius - Frame.inset, style: .continuous)
+ .strokeBorder(Color.white.opacity(0.18), lineWidth: 0.5)
+ )
+ .padding(Frame.inset)
+ .glassFrame(cornerRadius: Frame.radius)
+ .shadow(color: .black.opacity(hovering ? 0.26 : 0.18), radius: hovering ? 14 : 10, y: hovering ? 8 : 5)
+ // Holding presses the photo in slowly, so a long press feels like
+ // it is building up to something.
+ .scaleEffect(pressed ? 0.95 : (hovering ? 1.035 : 1), anchor: .top)
+ .animation(pressed ? .easeInOut(duration: 0.45) : .spring(response: 0.3, dampingFraction: 0.6), value: pressed)
+ .opacity(dragging ? 0.45 : 1)
+ .overlay(alignment: .topLeading) {
+ // Drawn here, clicked through GrabView, which sits on top.
+ Image(systemName: "xmark")
+ .font(.system(size: 8, weight: .bold))
+ .foregroundStyle(.primary)
+ .frame(width: 20, height: 20)
+ .glassFrame(circle: true)
+ .padding(3)
+ .opacity(hovering && !dragging ? 1 : 0)
+ .scaleEffect(hovering ? 1 : 0.6)
+ .allowsHitTesting(false)
+ }
+ .overlay(GrabArea(item: item, line: line))
+ .overlay(alignment: .bottom) {
+ if copied {
+ Label(L("Copied", "Copiado"), systemImage: "checkmark")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.primary)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .glassFrame(capsule: true)
+ .offset(y: 16)
+ .transition(.opacity.combined(with: .offset(y: -4)))
+ }
+ }
+ .animation(.easeOut(duration: 0.18), value: hovering)
+ .animation(.easeOut(duration: 0.2), value: copied)
+ .onHover { hovering = $0 }
+ .background(
+ GeometryReader { g in
+ Color.clear.preference(key: HitRectsKey.self,
+ value: item.falling ? [:] : [item.id: g.frame(in: .global)])
+ }
+ )
+ }
+
+ private func arrive() {
+ // A capture that flew in is already in place; the flight did the arriving.
+ if item.flying {
+ arrived = true
+ return
+ }
+ swing = 16
+ withAnimation(.spring(response: 0.42, dampingFraction: 0.72)) { arrived = true }
+ withAnimation(.interpolatingSpring(stiffness: 46, damping: 2.6)) { swing = 0 }
+ }
+
+ /// Landing after the flight: no jump, just a small sway from rest.
+ private func land() {
+ nudge(2.2)
+ }
+
+ private func breeze() {
+ let delay = Double.random(in: 0...0.35)
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
+ nudge(Double.random(in: 1.6...3.4))
+ }
+ }
+
+ private func nudge(_ degrees: Double) {
+ withAnimation(.easeOut(duration: 0.3)) { swing = degrees }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
+ withAnimation(.interpolatingSpring(stiffness: 38, damping: 2.4)) { swing = 0 }
+ }
+ }
+}
+
+enum Frame {
+ static let radius: CGFloat = 16
+ static let inset: CGFloat = 4
+}
+
+extension View {
+ /// A crisp glass: the system's blurred material with a thin specular
+ /// edge, lit from above. No refraction, so the background stays sharp
+ /// around the frame instead of bending like gel.
+ func glassFrame(cornerRadius: CGFloat = 0, circle: Bool = false, capsule: Bool = false) -> some View {
+ let shape: AnyShape = circle ? AnyShape(Circle())
+ : capsule ? AnyShape(Capsule())
+ : AnyShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
+ return background(.ultraThinMaterial, in: shape)
+ .overlay(
+ shape.stroke(
+ LinearGradient(colors: [Color.white.opacity(0.55), Color.white.opacity(0.12)],
+ startPoint: .top, endPoint: .bottom),
+ lineWidth: 0.75)
+ )
+ .overlay(shape.stroke(Color.black.opacity(0.10), lineWidth: 0.5).padding(-0.5))
+ }
+}
+
+/// A minimal aluminium clip: a brushed metal pill with a slot where it
+/// grips the line, and a soft shadow so it reads on any background.
+struct Clothespin: View {
+ private let metal = LinearGradient(
+ stops: [
+ .init(color: Color(white: 0.70), location: 0),
+ .init(color: Color(white: 0.93), location: 0.35),
+ .init(color: Color(white: 0.82), location: 0.65),
+ .init(color: Color(white: 0.62), location: 1),
+ ],
+ startPoint: .leading, endPoint: .trailing)
+
+ var body: some View {
+ RoundedRectangle(cornerRadius: 3.5, style: .continuous)
+ .fill(metal)
+ .frame(width: 9, height: 26)
+ .overlay(
+ RoundedRectangle(cornerRadius: 3.5, style: .continuous)
+ .stroke(LinearGradient(colors: [Color.white.opacity(0.9), Color.black.opacity(0.18)],
+ startPoint: .top, endPoint: .bottom),
+ lineWidth: 0.6)
+ )
+ .overlay(alignment: .top) {
+ // The slot the line passes through.
+ Capsule()
+ .fill(Color.black.opacity(0.32))
+ .frame(width: 5, height: 1.4)
+ .padding(.top, 8.5)
+ }
+ .shadow(color: .black.opacity(0.30), radius: 2, y: 1.5)
+ .allowsHitTesting(false)
+ }
+}
diff --git a/Sources/Tendedero/ScreenshotWatcher.swift b/Sources/Tendedero/ScreenshotWatcher.swift
new file mode 100644
index 0000000..b90eaf6
--- /dev/null
+++ b/Sources/Tendedero/ScreenshotWatcher.swift
@@ -0,0 +1,114 @@
+import Foundation
+
+/// Watches the folder macOS saves screenshots to and reports new ones.
+/// Tendedero never takes screenshots itself: you keep your usual shortcut
+/// (or CleanShot, or anything else) and the line just picks them up.
+final class ScreenshotWatcher {
+ let folder: URL
+ /// 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 source: DispatchSourceFileSystemObject?
+ private var pending: DispatchWorkItem?
+ private let onNew: (URL) -> Void
+ private let onChange: () -> Void
+
+ private static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "heic", "tif", "tiff", "gif", "webp"]
+
+ static let desktop = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")
+
+ /// Watches the folder macOS saves screenshots to, or a given folder.
+ init(folder: URL? = nil, onNew: @escaping (URL) -> Void, onChange: @escaping () -> Void) {
+ self.onNew = onNew
+ self.onChange = onChange
+ self.folder = folder ?? Self.screenshotFolder()
+ onlyTaggedScreenshots = self.folder.standardizedFileURL.path == Self.desktop.standardizedFileURL.path
+ }
+
+ static func screenshotFolder() -> URL {
+ let fm = FileManager.default
+ // Read fresh through cfprefsd: inbox mode changes this value at runtime.
+ CFPreferencesAppSynchronize("com.apple.screencapture" as CFString)
+ // macOS 27 keeps it in "location-screenshot"; earlier versions in "location".
+ let domain = "com.apple.screencapture" as CFString
+ let raw = (CFPreferencesCopyAppValue("location-screenshot" as CFString, domain) as? String)
+ ?? (CFPreferencesCopyAppValue("location" as CFString, domain) as? String)
+ if let raw, !raw.isEmpty {
+ let url = URL(fileURLWithPath: (raw as NSString).expandingTildeInPath, isDirectory: true)
+ var isDir: ObjCBool = false
+ if fm.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue { return url }
+ }
+ return fm.homeDirectoryForCurrentUser.appendingPathComponent("Desktop", isDirectory: true)
+ }
+
+ /// Anything created after the app launched counts as new, even if it
+ /// landed before the watcher was ready (macOS may be asking for Desktop
+ /// access at that moment).
+ private let launchDate = Date()
+
+ 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)
+ }
+ known = Set(files.map(\.path))
+ let fd = open(folder.path, O_EVTONLY)
+ guard fd >= 0 else {
+ NSLog("Tendedero: cannot watch \(folder.path)")
+ return
+ }
+ let src = DispatchSource.makeFileSystemObjectSource(
+ fileDescriptor: fd, eventMask: [.write, .rename, .delete], queue: .main)
+ src.setEventHandler { [weak self] in self?.scheduleScan() }
+ src.setCancelHandler { close(fd) }
+ src.resume()
+ source = src
+ }
+
+ func stop() {
+ pending?.cancel()
+ source?.cancel()
+ source = nil
+ }
+
+ private func scheduleScan() {
+ pending?.cancel()
+ let work = DispatchWorkItem { [weak self] in self?.scan() }
+ 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) {
+ onNew(url)
+ }
+ known = Set(files.map(\.path))
+ onChange()
+ }
+
+ private func listing() -> [URL] {
+ let urls = (try? FileManager.default.contentsOfDirectory(
+ at: folder, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles])) ?? []
+ return urls.sorted { creationDate($0) < creationDate($1) }
+ }
+
+ private func creationDate(_ url: URL) -> Date {
+ (try? url.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast
+ }
+
+ private func isCandidate(_ url: URL) -> Bool {
+ guard Self.imageExtensions.contains(url.pathExtension.lowercased()) else { return false }
+ return onlyTaggedScreenshots ? isScreenCapture(url) : true
+ }
+
+ private func isScreenCapture(_ url: URL) -> Bool {
+ url.withUnsafeFileSystemRepresentation { path in
+ guard let path else { return false }
+ return getxattr(path, "com.apple.metadata:kMDItemIsScreenCapture", nil, 0, 0, 0) >= 0
+ }
+ }
+}
diff --git a/Sources/Tendedero/main.swift b/Sources/Tendedero/main.swift
new file mode 100644
index 0000000..7363ca6
--- /dev/null
+++ b/Sources/Tendedero/main.swift
@@ -0,0 +1,9 @@
+import AppKit
+
+MainActor.assumeIsolated {
+ let app = NSApplication.shared
+ let delegate = AppDelegate()
+ app.delegate = delegate
+ app.setActivationPolicy(.accessory)
+ withExtendedLifetime(delegate) { app.run() }
+}
diff --git a/docs/bento-dark.png b/docs/bento-dark.png
new file mode 100644
index 0000000..b278c64
Binary files /dev/null and b/docs/bento-dark.png differ
diff --git a/docs/bento-light.png b/docs/bento-light.png
new file mode 100644
index 0000000..8f167a7
Binary files /dev/null and b/docs/bento-light.png differ
diff --git a/docs/demo-dark.gif b/docs/demo-dark.gif
new file mode 100644
index 0000000..05271b8
Binary files /dev/null and b/docs/demo-dark.gif differ
diff --git a/docs/demo-light.gif b/docs/demo-light.gif
new file mode 100644
index 0000000..d84de14
Binary files /dev/null and b/docs/demo-light.gif differ
diff --git a/docs/hero-dark.png b/docs/hero-dark.png
new file mode 100644
index 0000000..17533c3
Binary files /dev/null and b/docs/hero-dark.png differ
diff --git a/docs/hero-light.png b/docs/hero-light.png
new file mode 100644
index 0000000..e47a5f6
Binary files /dev/null and b/docs/hero-light.png differ
diff --git a/docs/icon.png b/docs/icon.png
new file mode 100644
index 0000000..3a1e34a
Binary files /dev/null and b/docs/icon.png differ
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
new file mode 100755
index 0000000..3241995
--- /dev/null
+++ b/scripts/build-app.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+# Builds Tendedero.app into ./build without needing Xcode.
+# Usage: scripts/build-app.sh [debug|release]
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+CONFIG="${1:-release}"
+APP="build/Tendedero.app"
+VERSION="1.0.0"
+
+# Builds one architecture and prints the binary's path.
+# The Command Line Tools for macOS 27 ship an SDK whose SwiftUI needs a macro
+# plugin they do not include. If the default SDK fails, fall back to the
+# newest macOS 26 SDK installed alongside it.
+build_arch() {
+ local triple="$1-apple-macosx14.0"
+ if [ -z "${SDKROOT:-}" ] && ! swift build -c "$CONFIG" --triple "$triple" >&2; then
+ FALLBACK="$(ls -d /Library/Developer/CommandLineTools/SDKs/MacOSX26*.sdk 2>/dev/null | sort -V | tail -1)"
+ if [ -z "$FALLBACK" ]; then exit 1; fi
+ echo "Retrying with $FALLBACK" >&2
+ export SDKROOT="$FALLBACK"
+ fi
+ if [ -n "${SDKROOT:-}" ]; then swift build -c "$CONFIG" --triple "$triple" >&2; fi
+ cp "$(swift build -c "$CONFIG" --triple "$triple" --show-bin-path)/Tendedero" "$OUT/Tendedero-$1"
+}
+
+# A universal binary, so it runs on Apple silicon and on Intel Macs, from
+# macOS 14 Sonoma onwards.
+OUT="$(mktemp -d)"
+build_arch arm64
+build_arch x86_64
+lipo -create "$OUT/Tendedero-arm64" "$OUT/Tendedero-x86_64" -output "$OUT/Tendedero"
+BIN="$OUT/Tendedero"
+
+rm -rf "$APP"
+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
+cp "$BIN" "$APP/Contents/MacOS/Tendedero"
+
+# Icon
+WORK="$(mktemp -d)"
+swift scripts/make-icon.swift "$WORK/icon.png"
+ICONSET="$WORK/Tendedero.iconset"
+mkdir -p "$ICONSET"
+for s in 16 32 128 256 512; do
+ sips -z $s $s "$WORK/icon.png" --out "$ICONSET/icon_${s}x${s}.png" >/dev/null
+ sips -z $((s*2)) $((s*2)) "$WORK/icon.png" --out "$ICONSET/icon_${s}x${s}@2x.png" >/dev/null
+done
+iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/Tendedero.icns"
+rm -rf "$WORK"
+
+cat > "$APP/Contents/Info.plist" <<PLIST
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleName</key><string>Tendedero</string>
+ <key>CFBundleDisplayName</key><string>Tendedero</string>
+ <key>CFBundleIdentifier</key><string>app.tendedero.Tendedero</string>
+ <key>CFBundleExecutable</key><string>Tendedero</string>
+ <key>CFBundleIconFile</key><string>Tendedero</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>CFBundleShortVersionString</key><string>${VERSION}</string>
+ <key>CFBundleVersion</key><string>1</string>
+ <key>LSMinimumSystemVersion</key><string>14.0</string>
+ <key>LSUIElement</key><true/>
+ <key>NSHighResolutionCapable</key><true/>
+ <key>NSDesktopFolderUsageDescription</key>
+ <string>Tendedero watches the folder where macOS saves your screenshots so it can hang them on the line.</string>
+</dict>
+</plist>
+PLIST
+
+# Ad-hoc signature so it runs locally. Releases should use a Developer ID.
+codesign --force --deep --sign - "$APP" >/dev/null
+echo "Built $APP"
diff --git a/scripts/make-dmg-background.swift b/scripts/make-dmg-background.swift
new file mode 100644
index 0000000..ac5dfef
--- /dev/null
+++ b/scripts/make-dmg-background.swift
@@ -0,0 +1,58 @@
+// Draws the background of the Tendedero disk image window.
+// Usage: swift scripts/make-dmg-background.swift out.png [scale]
+import AppKit
+
+let out = CommandLine.arguments.dropFirst().first ?? "background.png"
+let scale = CGFloat(Double(CommandLine.arguments.dropFirst(2).first ?? "1") ?? 1)
+let W: CGFloat = 600, H: CGFloat = 380
+
+func color(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> NSColor {
+ NSColor(srgbRed: r / 255, green: g / 255, blue: b / 255, alpha: a)
+}
+
+let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(W * scale), pixelsHigh: Int(H * scale),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+rep.size = NSSize(width: W, height: H)
+NSGraphicsContext.saveGraphicsState()
+NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+
+// The same soft sky as the icon, kept light so Finder labels stay legible.
+NSGradient(colors: [color(232, 238, 255), color(242, 236, 252), color(255, 238, 236)],
+ atLocations: [0, 0.55, 1], colorSpace: .sRGB)!.draw(in: NSRect(x: 0, y: 0, width: W, height: H), angle: -35)
+
+// A thin line hanging across the top, like the app.
+let line = NSBezierPath()
+line.move(to: NSPoint(x: -10, y: H - 34))
+line.curve(to: NSPoint(x: W + 10, y: H - 34), controlPoint1: NSPoint(x: W * 0.3, y: H - 70), controlPoint2: NSPoint(x: W * 0.7, y: H - 70))
+line.lineWidth = 1.4
+color(130, 134, 150, 0.7).setStroke()
+line.stroke()
+
+// Arrow from the app to Applications.
+let arrow = NSBezierPath()
+arrow.move(to: NSPoint(x: 248, y: 190))
+arrow.line(to: NSPoint(x: 344, y: 190))
+arrow.lineWidth = 2.5
+arrow.lineCapStyle = .round
+color(110, 116, 140, 0.55).setStroke()
+arrow.stroke()
+let head = NSBezierPath()
+head.move(to: NSPoint(x: 334, y: 199))
+head.line(to: NSPoint(x: 346, y: 190))
+head.line(to: NSPoint(x: 334, y: 181))
+head.lineWidth = 2.5
+head.lineCapStyle = .round
+head.lineJoinStyle = .round
+head.stroke()
+
+let style = NSMutableParagraphStyle(); style.alignment = .center
+let text = NSAttributedString(string: "Drag Tendedero to Applications", attributes: [
+ .font: NSFont.systemFont(ofSize: 13, weight: .medium),
+ .foregroundColor: color(80, 84, 100),
+ .paragraphStyle: style,
+])
+text.draw(in: NSRect(x: 0, y: 54, width: W, height: 20))
+
+NSGraphicsContext.restoreGraphicsState()
+try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: out))
diff --git a/scripts/make-dmg.sh b/scripts/make-dmg.sh
new file mode 100755
index 0000000..ea47e5c
--- /dev/null
+++ b/scripts/make-dmg.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# Builds Tendedero.app and packs it into a disk image for releases.
+# Usage: scripts/make-dmg.sh
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+scripts/build-app.sh release
+VERSION="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' build/Tendedero.app/Contents/Info.plist)"
+DMG="build/Tendedero-$VERSION.dmg"
+NAME="Tendedero"
+
+WORK="$(mktemp -d)"
+STAGE="$WORK/stage"
+mkdir -p "$STAGE/.background"
+cp -R build/Tendedero.app "$STAGE/"
+ln -s /Applications "$STAGE/Applications"
+swift scripts/make-dmg-background.swift "$WORK/bg1x.png" 1
+swift scripts/make-dmg-background.swift "$WORK/bg2x.png" 2
+# One TIFF holding both resolutions, so the window is sharp on Retina.
+tiffutil -cathidpicheck "$WORK/bg1x.png" "$WORK/bg2x.png" -out "$STAGE/.background/background.tiff" >/dev/null
+
+RW="$WORK/rw.dmg"
+hdiutil create -quiet -srcfolder "$STAGE" -volname "$NAME" -fs HFS+ -format UDRW -size 60m "$RW"
+MOUNT="$(hdiutil attach -readwrite -noverify -noautoopen "$RW" | awk -F'\t' '/\/Volumes\//{print $NF}')"
+
+# Tiling window managers resize the window, and Finder would save that size
+# into the image. Pause AeroSpace while laying it out, if it is running.
+if command -v aerospace >/dev/null && pgrep -qx AeroSpace; then
+ aerospace enable off
+ trap 'aerospace enable on' EXIT
+fi
+
+# Lay out the window. Needs permission to control Finder; without it the
+# image still works, just with Finder's default layout.
+osascript <<OSA || echo "Finder layout skipped"
+tell application "Finder"
+ tell disk "$NAME"
+ open
+ set current view of container window to icon view
+ set toolbar visible of container window to false
+ set statusbar visible of container window to false
+ set the bounds of container window to {200, 120, 800, 528}
+ set opts to the icon view options of container window
+ set arrangement of opts to not arranged
+ set icon size of opts to 112
+ set text size of opts to 13
+ set background picture of opts to file ".background:background.tiff"
+ set position of item "Tendedero.app" of container window to {160, 178}
+ set position of item "Applications" of container window to {440, 178}
+ -- Size last: Finder can resize the window while it applies the options.
+ set the bounds of container window to {200, 120, 800, 528}
+ update without registering applications
+ delay 1
+ set the bounds of container window to {200, 120, 800, 528}
+ delay 1
+ close
+ end tell
+end tell
+OSA
+
+chmod -Rf go-w "$MOUNT" || true
+sync
+hdiutil detach -quiet "$MOUNT"
+rm -f "$DMG"
+hdiutil convert -quiet "$RW" -format UDZO -imagekey zlib-level=9 -o "$DMG"
+rm -rf "$WORK"
+echo "Built $DMG"
diff --git a/scripts/make-icon.swift b/scripts/make-icon.swift
new file mode 100644
index 0000000..b7eded9
--- /dev/null
+++ b/scripts/make-icon.swift
@@ -0,0 +1,172 @@
+// Draws the Tendedero app icon: two screenshots in crisp glass frames,
+// held by aluminium clips on a thin line, over a soft gradient.
+// Usage: swift scripts/make-icon.swift out.png
+import AppKit
+
+let size: CGFloat = 1024
+let out = CommandLine.arguments.dropFirst().first ?? "icon.png"
+
+let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size), pixelsHigh: Int(size),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+NSGraphicsContext.saveGraphicsState()
+NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+let ctx = NSGraphicsContext.current!.cgContext
+
+func color(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> NSColor {
+ NSColor(srgbRed: r / 255, green: g / 255, blue: b / 255, alpha: a)
+}
+
+func shadow(_ alpha: CGFloat, blur: CGFloat, y: CGFloat) {
+ let s = NSShadow()
+ s.shadowColor = color(20, 24, 48, alpha)
+ s.shadowBlurRadius = blur
+ s.shadowOffset = NSSize(width: 0, height: y)
+ s.set()
+}
+
+// Body, following the macOS icon grid: 824pt square, 100pt margin.
+let body = NSRect(x: 100, y: 100, width: 824, height: 824)
+let shape = NSBezierPath(roundedRect: body, xRadius: 185, yRadius: 185)
+
+ctx.saveGState()
+shadow(0.30, blur: 26, y: -12)
+color(200, 210, 240).setFill()
+shape.fill()
+ctx.restoreGState()
+
+ctx.saveGState()
+shape.addClip()
+NSGradient(colors: [color(132, 170, 255), color(176, 160, 250), color(255, 190, 196)],
+ atLocations: [0, 0.55, 1], colorSpace: .sRGB)!
+ .draw(in: body, angle: -60)
+// Soft light from the top.
+NSGradient(colors: [color(255, 255, 255, 0.35), color(255, 255, 255, 0)])!
+ .draw(in: NSRect(x: body.minX, y: body.midY, width: body.width, height: body.height / 2), angle: -90)
+
+// The line
+let left = NSPoint(x: 60, y: 700), right = NSPoint(x: 964, y: 700)
+let control = NSPoint(x: 512, y: 590)
+func lineY(_ x: CGFloat) -> CGFloat {
+ let t = (x - left.x) / (right.x - left.x)
+ return (1 - t) * (1 - t) * left.y + 2 * (1 - t) * t * control.y + t * t * right.y
+}
+func linePath() -> NSBezierPath {
+ let p = NSBezierPath()
+ p.move(to: left)
+ p.curve(to: right,
+ controlPoint1: NSPoint(x: left.x + (control.x - left.x) * 2 / 3, y: left.y + (control.y - left.y) * 2 / 3),
+ controlPoint2: NSPoint(x: right.x + (control.x - right.x) * 2 / 3, y: right.y + (control.y - right.y) * 2 / 3))
+ return p
+}
+ctx.saveGState()
+shadow(0.25, blur: 8, y: -5)
+let line = linePath()
+line.lineWidth = 9
+color(110, 116, 140).setStroke()
+line.stroke()
+ctx.restoreGState()
+let highlight = linePath()
+highlight.lineWidth = 3
+highlight.transform(using: AffineTransform(translationByX: 0, byY: 2))
+color(255, 255, 255, 0.55).setStroke()
+highlight.stroke()
+
+// A screenshot in a glass frame, hanging from a clip.
+func hang(centerX: CGFloat, width: CGFloat, height: CGFloat, angle: CGFloat, content: (NSRect) -> Void) {
+ let top = lineY(centerX) + 34
+ ctx.saveGState()
+ ctx.translateBy(x: centerX, y: top)
+ ctx.rotate(by: angle * .pi / 180)
+
+ let radius: CGFloat = 64, inset: CGFloat = 18
+ let frame = NSRect(x: -width / 2, y: -height, width: width, height: height)
+ let framePath = NSBezierPath(roundedRect: frame, xRadius: radius, yRadius: radius)
+
+ // Glass: translucent white body, soft shadow, top-lit edge.
+ ctx.saveGState()
+ shadow(0.28, blur: 40, y: -22)
+ color(255, 255, 255, 0.42).setFill()
+ framePath.fill()
+ ctx.restoreGState()
+ NSGradient(colors: [color(255, 255, 255, 0.30), color(255, 255, 255, 0.05)])!
+ .draw(in: framePath, angle: -90)
+
+ let photoRect = frame.insetBy(dx: inset, dy: inset)
+ let photoPath = NSBezierPath(roundedRect: photoRect, xRadius: radius - inset, yRadius: radius - inset)
+ ctx.saveGState()
+ photoPath.addClip()
+ content(photoRect)
+ ctx.restoreGState()
+
+ // Top-lit edge: a thin ring, brighter at the top.
+ ctx.saveGState()
+ let ring = NSBezierPath(roundedRect: frame, xRadius: radius, yRadius: radius)
+ ring.append(NSBezierPath(roundedRect: frame.insetBy(dx: 4, dy: 4), xRadius: radius - 4, yRadius: radius - 4))
+ ring.windingRule = .evenOdd
+ ring.addClip()
+ NSGradient(colors: [color(255, 255, 255, 0.95), color(255, 255, 255, 0.30)])!.draw(in: frame, angle: -90)
+ ctx.restoreGState()
+
+ // Aluminium clip
+ let clip = NSRect(x: -15, y: -58, width: 30, height: 86)
+ let clipPath = NSBezierPath(roundedRect: clip, xRadius: 11, yRadius: 11)
+ ctx.saveGState()
+ shadow(0.35, blur: 8, y: -5)
+ color(200, 200, 205).setFill()
+ clipPath.fill()
+ ctx.restoreGState()
+ NSGradient(colors: [color(170, 172, 180), color(240, 241, 245), color(212, 214, 220), color(150, 152, 160)],
+ atLocations: [0, 0.35, 0.65, 1], colorSpace: .sRGB)!
+ .draw(in: clipPath, angle: 0)
+ color(40, 40, 50, 0.35).setFill()
+ NSBezierPath(roundedRect: NSRect(x: -9, y: -6, width: 18, height: 5), xRadius: 2.5, yRadius: 2.5).fill()
+ clipPath.lineWidth = 2
+ color(255, 255, 255, 0.7).setStroke()
+ clipPath.stroke()
+
+ ctx.restoreGState()
+}
+
+// Left: a small app window.
+hang(centerX: 330, width: 340, height: 400, angle: 3) { r in
+ color(248, 249, 252).setFill(); r.fill()
+ let bar = NSRect(x: r.minX, y: r.maxY - 56, width: r.width, height: 56)
+ color(232, 234, 240).setFill(); bar.fill()
+ for (i, c) in [color(255, 95, 87), color(254, 188, 46), color(40, 200, 64)].enumerated() {
+ c.setFill()
+ NSBezierPath(ovalIn: NSRect(x: r.minX + 26 + CGFloat(i) * 30, y: bar.midY - 9, width: 18, height: 18)).fill()
+ }
+ color(100, 120, 255).setFill()
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 26, y: bar.minY - 70, width: r.width * 0.55, height: 26), xRadius: 8, yRadius: 8).fill()
+ color(200, 204, 216).setFill()
+ for i in 0..<5 {
+ let w = r.width * [0.78, 0.66, 0.72, 0.5, 0.62][i]
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 26, y: bar.minY - 120 - CGFloat(i) * 38, width: w, height: 16), xRadius: 8, yRadius: 8).fill()
+ }
+}
+
+// Right: a sunset photo.
+hang(centerX: 695, width: 320, height: 270, angle: -3) { r in
+ NSGradient(colors: [color(255, 150, 90), color(255, 110, 130), color(120, 90, 200)])!.draw(in: r, angle: 90)
+ color(255, 230, 160).setFill()
+ NSBezierPath(ovalIn: NSRect(x: r.midX - 40, y: r.minY + 60, width: 80, height: 80)).fill()
+ let hills = NSBezierPath()
+ hills.move(to: NSPoint(x: r.minX, y: r.minY + 70))
+ hills.curve(to: NSPoint(x: r.maxX, y: r.minY + 50), controlPoint1: NSPoint(x: r.minX + r.width * 0.3, y: r.minY + 130),
+ controlPoint2: NSPoint(x: r.minX + r.width * 0.6, y: r.minY + 10))
+ hills.line(to: NSPoint(x: r.maxX, y: r.minY)); hills.line(to: NSPoint(x: r.minX, y: r.minY)); hills.close()
+ color(70, 50, 130).setFill(); hills.fill()
+}
+ctx.restoreGState()
+
+// Top-lit rim on the icon body.
+shape.lineWidth = 4
+ctx.saveGState()
+shape.addClip()
+color(255, 255, 255, 0.35).setStroke()
+shape.stroke()
+ctx.restoreGState()
+
+NSGraphicsContext.restoreGraphicsState()
+try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: out))
diff --git a/scripts/make-readme-art.swift b/scripts/make-readme-art.swift
new file mode 100644
index 0000000..80eaf3d
--- /dev/null
+++ b/scripts/make-readme-art.swift
@@ -0,0 +1,411 @@
+// Renders every image in the README, in light and dark:
+// hero-*.png headline and the line hanging under the menu bar
+// demo-*.gif the reveal: pointer to the top edge, line slides down, a
+// click copies, the pointer leaves and the line tucks away
+// bento-*.png four gestures as tiles with SF Symbols
+// Usage: swift scripts/make-readme-art.swift docs/
+import AppKit
+import ImageIO
+import UniformTypeIdentifiers
+
+let outDir = CommandLine.arguments.dropFirst().first ?? "docs"
+
+func color(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> NSColor {
+ NSColor(srgbRed: r / 255, green: g / 255, blue: b / 255, alpha: a)
+}
+
+// MARK: Themes
+
+struct Theme {
+ let name: String
+ let page: NSColor // README background behind everything
+ let ink: NSColor
+ let secondaryInk: NSColor
+ let wallpaper: [NSColor]
+ let glow: NSColor
+ let menuBar: NSColor
+ let menuInk: NSColor
+ let line: NSColor
+ let glassFill: NSColor
+ let edgeTop: NSColor
+ let edgeBottom: NSColor
+ let shadow: NSColor
+ let tile: NSColor
+ let tileInk: NSColor
+}
+
+let light = Theme(
+ name: "light",
+ page: color(255, 255, 255), ink: color(29, 29, 31), secondaryInk: color(110, 110, 115),
+ wallpaper: [color(214, 224, 255), color(232, 222, 252), color(255, 226, 222)],
+ glow: color(255, 255, 255, 0.35),
+ menuBar: color(255, 255, 255, 0.55), menuInk: color(30, 32, 48, 0.5),
+ line: color(120, 124, 145), glassFill: color(255, 255, 255, 0.5),
+ edgeTop: color(255, 255, 255, 0.95), edgeBottom: color(255, 255, 255, 0.35),
+ shadow: color(40, 40, 80, 0.22),
+ tile: color(245, 245, 247), tileInk: color(29, 29, 31))
+
+let dark = Theme(
+ name: "dark",
+ page: color(13, 17, 23), ink: color(245, 245, 247), secondaryInk: color(161, 161, 166),
+ wallpaper: [color(22, 26, 52), color(40, 30, 72), color(70, 36, 70)],
+ glow: color(140, 120, 255, 0.22),
+ menuBar: color(20, 20, 30, 0.55), menuInk: color(255, 255, 255, 0.5),
+ line: color(150, 154, 175), glassFill: color(255, 255, 255, 0.12),
+ edgeTop: color(255, 255, 255, 0.45), edgeBottom: color(255, 255, 255, 0.08),
+ shadow: color(0, 0, 0, 0.5),
+ tile: color(28, 28, 30), tileInk: color(245, 245, 247))
+
+// MARK: Canvas
+
+func makeBitmap(_ w: CGFloat, _ h: CGFloat, scale: CGFloat) -> NSBitmapImageRep {
+ NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(w * scale), pixelsHigh: Int(h * scale),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+}
+
+func draw(_ rep: NSBitmapImageRep, scale: CGFloat, _ body: (CGContext) -> Void) {
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ let ctx = NSGraphicsContext.current!.cgContext
+ ctx.scaleBy(x: scale, y: scale)
+ body(ctx)
+ NSGraphicsContext.restoreGraphicsState()
+}
+
+func savePNG(_ rep: NSBitmapImageRep, _ path: String) {
+ try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: path))
+}
+
+func shadow(_ t: Theme, _ alpha: CGFloat, blur: CGFloat, y: CGFloat) {
+ let s = NSShadow()
+ s.shadowColor = t.shadow.withAlphaComponent(t.shadow.alphaComponent * alpha)
+ s.shadowBlurRadius = blur
+ s.shadowOffset = NSSize(width: 0, height: y)
+ s.set()
+}
+
+func text(_ string: String, size: CGFloat, weight: NSFont.Weight, color: NSColor,
+ tracking: CGFloat = 0, centerX: CGFloat, baselineY: CGFloat, rounded: Bool = false) {
+ var font = NSFont.systemFont(ofSize: size, weight: weight)
+ if rounded, let d = font.fontDescriptor.withDesign(.rounded) { font = NSFont(descriptor: d, size: size) ?? font }
+ let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color, .kern: tracking]
+ let s = NSAttributedString(string: string, attributes: attrs)
+ let w = s.size().width
+ s.draw(at: NSPoint(x: centerX - w / 2, y: baselineY + font.descender))
+}
+
+func leftText(_ string: String, size: CGFloat, weight: NSFont.Weight, color: NSColor,
+ tracking: CGFloat = 0, x: CGFloat, baselineY: CGFloat) {
+ let font = NSFont.systemFont(ofSize: size, weight: weight)
+ let s = NSAttributedString(string: string, attributes: [.font: font, .foregroundColor: color, .kern: tracking])
+ s.draw(at: NSPoint(x: x, y: baselineY + font.descender))
+}
+
+// MARK: The scene
+
+struct Frame { let x: CGFloat; let w: CGFloat; let h: CGFloat; let tilt: CGFloat; let kind: Int }
+
+struct SceneState {
+ var reveal: CGFloat = 1 // 0 tucked away, 1 down
+ var swing: [CGFloat] = [0, 0, 0] // extra degrees per photo
+ var cursor: NSPoint? = nil
+ var hover: Int? = nil
+ var pressed: CGFloat = 0
+ var copied: CGFloat = 0 // 0...1 opacity of the Copied label
+}
+
+func drawScene(_ ctx: CGContext, _ t: Theme, rect: NSRect, frames: [Frame], state: SceneState, cornerRadius: CGFloat) {
+ ctx.saveGState()
+ let W = rect.width, H = rect.height
+ ctx.translateBy(x: rect.minX, y: rect.minY)
+ let canvas = NSRect(x: 0, y: 0, width: W, height: H)
+ NSBezierPath(roundedRect: canvas, xRadius: cornerRadius, yRadius: cornerRadius).addClip()
+
+ NSGradient(colors: t.wallpaper, atLocations: [0, 0.55, 1], colorSpace: .sRGB)!.draw(in: canvas, angle: -35)
+ NSGradient(colors: [t.glow, t.glow.withAlphaComponent(0)])!
+ .draw(fromCenter: NSPoint(x: W * 0.5, y: H * 0.45), radius: 0,
+ toCenter: NSPoint(x: W * 0.5, y: H * 0.45), radius: W * 0.6, options: [])
+
+ let barH: CGFloat = 26
+ // The line lives under the menu bar and slides out from beneath it.
+ let hidden: CGFloat = 260
+ let dy = (1 - state.reveal) * hidden
+ let top = H - barH - 20 + dy
+ let sag: CGFloat = 22
+ func lineY(_ x: CGFloat) -> CGFloat { let f = x / W; return top - 4 * sag * f * (1 - f) }
+
+ ctx.saveGState()
+ NSRect(x: 0, y: 0, width: W, height: H - barH).clip()
+ let linePath = NSBezierPath()
+ linePath.move(to: NSPoint(x: -10, y: top))
+ let c = NSPoint(x: W / 2, y: top - 2 * sag)
+ linePath.curve(to: NSPoint(x: W + 10, y: top),
+ controlPoint1: NSPoint(x: -10 + (c.x + 10) * 2 / 3, y: top + (c.y - top) * 2 / 3),
+ controlPoint2: NSPoint(x: W + 10 + (c.x - W - 10) * 2 / 3, y: top + (c.y - top) * 2 / 3))
+ ctx.saveGState(); shadow(t, 0.8, blur: 3, y: -2)
+ linePath.lineWidth = 1.8; t.line.setStroke(); linePath.stroke()
+ ctx.restoreGState()
+
+ for (i, f) in frames.enumerated() {
+ let hover = state.hover == i
+ let scale: CGFloat = hover ? (1.03 - 0.06 * state.pressed) : 1
+ ctx.saveGState()
+ ctx.translateBy(x: f.x, y: lineY(f.x) + 7)
+ ctx.rotate(by: (f.tilt + state.swing[i]) * .pi / 180)
+ ctx.scaleBy(x: scale, y: scale)
+ drawGlassPhoto(ctx, t, w: f.w, h: f.h, kind: f.kind, lift: hover)
+ if hover && state.copied > 0 {
+ drawCopied(ctx, t, y: -f.h - 18, alpha: state.copied)
+ }
+ ctx.restoreGState()
+ }
+ ctx.restoreGState()
+
+ // Menu bar on top of everything.
+ t.menuBar.setFill()
+ NSRect(x: 0, y: H - barH, width: W, height: barH).fill()
+ t.menuInk.setFill()
+ NSBezierPath(ovalIn: NSRect(x: 18, y: H - barH / 2 - 5, width: 10, height: 10)).fill()
+ for (i, w) in [CGFloat(46), 32, 28, 40, 34].enumerated() {
+ let x = 42 + CGFloat(i) * 52
+ NSBezierPath(roundedRect: NSRect(x: x, y: H - barH / 2 - 3.5, width: w, height: 7), xRadius: 3.5, yRadius: 3.5).fill()
+ }
+ for i in 0..<4 {
+ NSBezierPath(roundedRect: NSRect(x: W - 34 - CGFloat(i) * 30, y: H - barH / 2 - 5, width: 16, height: 10), xRadius: 3, yRadius: 3).fill()
+ }
+
+ if let p = state.cursor { drawCursor(ctx, t, at: NSPoint(x: p.x, y: min(p.y, H - 1))) }
+ ctx.restoreGState()
+}
+
+func drawGlassPhoto(_ ctx: CGContext, _ t: Theme, w: CGFloat, h: CGFloat, kind: Int, lift: Bool) {
+ let radius: CGFloat = 16, inset: CGFloat = 4.5
+ let frame = NSRect(x: -w / 2, y: -h, width: w, height: h)
+ let path = NSBezierPath(roundedRect: frame, xRadius: radius, yRadius: radius)
+ ctx.saveGState(); shadow(t, lift ? 1.3 : 1, blur: lift ? 30 : 22, y: lift ? -16 : -12)
+ t.glassFill.setFill(); path.fill()
+ ctx.restoreGState()
+
+ let photo = frame.insetBy(dx: inset, dy: inset)
+ ctx.saveGState()
+ NSBezierPath(roundedRect: photo, xRadius: radius - inset, yRadius: radius - inset).addClip()
+ drawContent(kind, photo)
+ ctx.restoreGState()
+
+ ctx.saveGState()
+ let ring = NSBezierPath(roundedRect: frame, xRadius: radius, yRadius: radius)
+ ring.append(NSBezierPath(roundedRect: frame.insetBy(dx: 1, dy: 1), xRadius: radius - 1, yRadius: radius - 1))
+ ring.windingRule = .evenOdd
+ ring.addClip()
+ NSGradient(colors: [t.edgeTop, t.edgeBottom])!.draw(in: frame, angle: -90)
+ ctx.restoreGState()
+
+ let clip = NSRect(x: -4.5, y: -15, width: 9, height: 25)
+ let clipPath = NSBezierPath(roundedRect: clip, xRadius: 3.5, yRadius: 3.5)
+ ctx.saveGState(); shadow(t, 0.9, blur: 3, y: -1.5)
+ color(200, 200, 205).setFill(); clipPath.fill()
+ ctx.restoreGState()
+ NSGradient(colors: [color(178, 179, 186), color(238, 239, 243), color(209, 210, 216), color(158, 159, 166)],
+ atLocations: [0, 0.35, 0.65, 1], colorSpace: .sRGB)!.draw(in: clipPath, angle: 0)
+ color(30, 30, 40, 0.35).setFill()
+ NSBezierPath(roundedRect: NSRect(x: -2.5, y: -0.7, width: 5, height: 1.4), xRadius: 0.7, yRadius: 0.7).fill()
+}
+
+func drawContent(_ kind: Int, _ r: NSRect) {
+ switch kind {
+ case 0:
+ color(250, 250, 252).setFill(); r.fill()
+ let bar = NSRect(x: r.minX, y: r.maxY - 20, width: r.width, height: 20)
+ color(236, 237, 242).setFill(); bar.fill()
+ for (i, c) in [color(255, 95, 87), color(254, 188, 46), color(40, 200, 64)].enumerated() {
+ c.setFill()
+ NSBezierPath(ovalIn: NSRect(x: r.minX + 8 + CGFloat(i) * 11, y: bar.midY - 3, width: 6.5, height: 6.5)).fill()
+ }
+ color(98, 120, 255).setFill()
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 12, y: bar.minY - 24, width: r.width * 0.45, height: 9), xRadius: 3, yRadius: 3).fill()
+ color(214, 217, 226).setFill()
+ for i in 0..<6 {
+ let y = bar.minY - 42 - CGFloat(i) * 14
+ if y < r.minY + 8 { break }
+ let w = r.width * [0.8, 0.62, 0.72, 0.5, 0.66, 0.58][i]
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 12, y: y, width: w, height: 5.5), xRadius: 2.75, yRadius: 2.75).fill()
+ }
+ case 1:
+ NSGradient(colors: [color(255, 156, 96), color(255, 108, 132), color(118, 88, 204)])!.draw(in: r, angle: 90)
+ color(255, 232, 166).setFill()
+ let s = r.height * 0.26
+ NSBezierPath(ovalIn: NSRect(x: r.midX - s / 2, y: r.minY + r.height * 0.3, width: s, height: s)).fill()
+ let hills = NSBezierPath()
+ hills.move(to: NSPoint(x: r.minX, y: r.minY + r.height * 0.3))
+ hills.curve(to: NSPoint(x: r.maxX, y: r.minY + r.height * 0.2),
+ controlPoint1: NSPoint(x: r.minX + r.width * 0.3, y: r.minY + r.height * 0.55),
+ controlPoint2: NSPoint(x: r.minX + r.width * 0.62, y: r.minY + r.height * 0.05))
+ hills.line(to: NSPoint(x: r.maxX, y: r.minY)); hills.line(to: NSPoint(x: r.minX, y: r.minY)); hills.close()
+ color(66, 48, 128).setFill(); hills.fill()
+ default:
+ color(24, 26, 36).setFill(); r.fill()
+ let bars: [CGFloat] = [0.35, 0.55, 0.42, 0.7, 0.6, 0.85, 0.74]
+ let bw = (r.width - 36) / CGFloat(bars.count)
+ for (i, v) in bars.enumerated() {
+ (i == bars.count - 2 ? color(120, 140, 255) : color(120, 140, 255, 0.45)).setFill()
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 18 + CGFloat(i) * bw + 3, y: r.minY + 16,
+ width: bw - 6, height: (r.height - 42) * v), xRadius: 3, yRadius: 3).fill()
+ }
+ color(255, 255, 255, 0.7).setFill()
+ NSBezierPath(roundedRect: NSRect(x: r.minX + 18, y: r.maxY - 18, width: 54, height: 5.5), xRadius: 2.75, yRadius: 2.75).fill()
+ }
+}
+
+func drawCopied(_ ctx: CGContext, _ t: Theme, y: CGFloat, alpha: CGFloat) {
+ let w: CGFloat = 84, h: CGFloat = 24
+ let r = NSRect(x: -w / 2, y: y - h / 2 + (1 - alpha) * 4, width: w, height: h)
+ let p = NSBezierPath(roundedRect: r, xRadius: h / 2, yRadius: h / 2)
+ ctx.saveGState()
+ ctx.setAlpha(alpha)
+ ctx.saveGState(); shadow(t, 0.8, blur: 10, y: -4)
+ (t.name == "light" ? color(255, 255, 255, 0.92) : color(50, 50, 60, 0.92)).setFill(); p.fill()
+ ctx.restoreGState()
+ text("\u{2713} Copied", size: 11.5, weight: .semibold, color: t.ink, centerX: 0, baselineY: r.midY - 4)
+ ctx.restoreGState()
+}
+
+func drawCursor(_ ctx: CGContext, _ t: Theme, at p: NSPoint) {
+ let a = NSBezierPath()
+ a.move(to: p)
+ a.line(to: NSPoint(x: p.x, y: p.y - 20))
+ a.line(to: NSPoint(x: p.x + 5, y: p.y - 15.5))
+ a.line(to: NSPoint(x: p.x + 8.6, y: p.y - 23.5))
+ a.line(to: NSPoint(x: p.x + 11.8, y: p.y - 22.1))
+ a.line(to: NSPoint(x: p.x + 8.2, y: p.y - 14.1))
+ a.line(to: NSPoint(x: p.x + 14.5, y: p.y - 14.1))
+ a.close()
+ ctx.saveGState(); shadow(t, 0.9, blur: 3, y: -1.5)
+ NSColor.black.setFill(); a.fill()
+ ctx.restoreGState()
+ a.lineWidth = 1.3; NSColor.white.setStroke(); a.stroke()
+}
+
+// MARK: Hero
+
+func hero(_ t: Theme) {
+ let W: CGFloat = 1200, H: CGFloat = 640, s: CGFloat = 2
+ let rep = makeBitmap(W, H, scale: s)
+ draw(rep, scale: s) { ctx in
+ t.page.setFill(); NSRect(x: 0, y: 0, width: W, height: H).fill()
+ text("Tendedero", size: 84, weight: .semibold, color: t.ink, tracking: -2.4, centerX: W / 2, baselineY: H - 128)
+ text("Screenshots, hung out to dry.", size: 30, weight: .regular, color: t.secondaryInk,
+ tracking: -0.4, centerX: W / 2, baselineY: H - 182)
+ let frames = [Frame(x: 290, w: 250, h: 172, tilt: 2.5, kind: 0),
+ Frame(x: 560, w: 270, h: 186, tilt: -1.2, kind: 1),
+ Frame(x: 830, w: 220, h: 160, tilt: 3, kind: 2)]
+ let scene = NSRect(x: 60, y: 40, width: W - 120, height: 330)
+ ctx.saveGState(); shadow(t, 0.6, blur: 40, y: -18)
+ t.page.setFill(); NSBezierPath(roundedRect: scene, xRadius: 26, yRadius: 26).fill()
+ ctx.restoreGState()
+ drawScene(ctx, t, rect: scene,
+ frames: frames.map { Frame(x: $0.x - 60 + 60, w: $0.w, h: $0.h, tilt: $0.tilt, kind: $0.kind) },
+ state: SceneState(cursor: NSPoint(x: 690, y: 330)), cornerRadius: 26)
+ }
+ savePNG(rep, "\(outDir)/hero-\(t.name).png")
+}
+
+// MARK: Demo loop
+
+func easeInOut(_ x: CGFloat) -> CGFloat { let x = max(0, min(1, x)); return x * x * (3 - 2 * x) }
+func lerp(_ a: CGFloat, _ b: CGFloat, _ x: CGFloat) -> CGFloat { a + (b - a) * x }
+func lerp(_ a: NSPoint, _ b: NSPoint, _ x: CGFloat) -> NSPoint { NSPoint(x: lerp(a.x, b.x, x), y: lerp(a.y, b.y, x)) }
+
+func demo(_ t: Theme) {
+ let W: CGFloat = 960, H: CGFloat = 340, s: CGFloat = 1
+ let fps: CGFloat = 25, duration: CGFloat = 5.2
+ let frames = [Frame(x: 250, w: 210, h: 146, tilt: 2.5, kind: 0),
+ Frame(x: 480, w: 230, h: 158, tilt: -1.2, kind: 1),
+ Frame(x: 705, w: 190, h: 136, tilt: 3, kind: 2)]
+ let rest = NSPoint(x: 620, y: 90), edge = NSPoint(x: 560, y: H), onPhoto = NSPoint(x: 492, y: 175)
+ let away = NSPoint(x: 760, y: 70)
+
+ let url = URL(fileURLWithPath: "\(outDir)/demo-\(t.name).gif")
+ let count = Int(fps * duration)
+ let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.gif.identifier as CFString, count, nil)!
+ CGImageDestinationSetProperties(dest, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: 0]] as CFDictionary)
+ let frameProps = [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFDelayTime: 1 / fps,
+ kCGImagePropertyGIFUnclampedDelayTime: 1 / fps]] as CFDictionary
+
+ for i in 0..<count {
+ let time = CGFloat(i) / fps
+ var st = SceneState(reveal: 0)
+
+ // Pointer travels to the top edge and rests there.
+ if time < 1.0 { st.cursor = lerp(rest, edge, easeInOut((time - 0.2) / 0.8)) }
+ else if time < 1.9 { st.cursor = edge }
+ else if time < 2.7 { st.cursor = lerp(edge, onPhoto, easeInOut((time - 1.9) / 0.8)) }
+ else if time < 3.9 { st.cursor = onPhoto }
+ else { st.cursor = lerp(onPhoto, away, easeInOut((time - 3.9) / 0.7)) }
+
+ // The line slides down with a soft spring, photos swing as it lands.
+ let downAt: CGFloat = 1.25, upAt: CGFloat = 4.75
+ if time >= downAt && time < upAt {
+ let d = time - downAt
+ st.reveal = 1 - exp(-7 * d) * cos(9 * d)
+ for k in 0..<3 {
+ let dk = max(0, d - 0.05 * CGFloat(k))
+ st.swing[k] = 9 * exp(-2.6 * dk) * sin(8.5 * dk + 0.6) * (k % 2 == 0 ? 1 : -1)
+ }
+ } else if time >= upAt {
+ st.reveal = 1 - easeInOut((time - upAt) / 0.28)
+ }
+
+ // Hover, press and copy on the middle photo.
+ if time >= 2.55 && time < 4.0 { st.hover = 1 }
+ if time >= 2.95 && time < 3.15 { st.pressed = easeInOut((time - 2.95) / 0.1) * (1 - easeInOut((time - 3.05) / 0.1)) }
+ if time >= 3.1 && time < 4.0 { st.copied = min(1, (time - 3.1) / 0.15) * (time > 3.8 ? max(0, 1 - (time - 3.8) / 0.2) : 1) }
+
+ let rep = makeBitmap(W, H, scale: s)
+ draw(rep, scale: s) { ctx in
+ t.page.setFill(); NSRect(x: 0, y: 0, width: W, height: H).fill()
+ drawScene(ctx, t, rect: NSRect(x: 0, y: 0, width: W, height: H), frames: frames, state: st, cornerRadius: 22)
+ }
+ CGImageDestinationAddImage(dest, rep.cgImage!, frameProps)
+ }
+ CGImageDestinationFinalize(dest)
+}
+
+// MARK: Bento
+
+func bento(_ t: Theme) {
+ let W: CGFloat = 1200, H: CGFloat = 700, s: CGFloat = 2, gap: CGFloat = 20
+ let tiles: [(String, String, String)] = [
+ ("doc.on.doc", "Click to copy.", "Paste it anywhere, instantly."),
+ ("pencil.tip.crop.circle", "Hold to mark up.", "Annotate, crop or sign in place."),
+ ("arrow.up.forward.app", "Drag to share.", "Apps get a copy. Folders keep it."),
+ ("xmark.circle", "Let it go.", "The cross or the Trash. That\u{2019}s it."),
+ ]
+ let rep = makeBitmap(W, H, scale: s)
+ draw(rep, scale: s) { ctx in
+ t.page.setFill(); NSRect(x: 0, y: 0, width: W, height: H).fill()
+ let tw = (W - gap * 3) / 2, th = (H - gap * 3) / 2
+ for (i, tile) in tiles.enumerated() {
+ let col = CGFloat(i % 2), row = CGFloat(1 - i / 2)
+ let r = NSRect(x: gap + col * (tw + gap), y: gap + row * (th + gap), width: tw, height: th)
+ t.tile.setFill()
+ NSBezierPath(roundedRect: r, xRadius: 28, yRadius: 28).fill()
+
+ let config = NSImage.SymbolConfiguration(pointSize: 46, weight: .regular)
+ .applying(.init(paletteColors: [color(98, 120, 255)]))
+ if let symbol = NSImage(systemSymbolName: tile.0, accessibilityDescription: nil)?.withSymbolConfiguration(config) {
+ let sz = symbol.size
+ symbol.draw(in: NSRect(x: r.minX + 44, y: r.maxY - 52 - sz.height, width: sz.width, height: sz.height))
+ }
+ leftText(tile.1, size: 36, weight: .semibold, color: t.tileInk, tracking: -0.8, x: r.minX + 44, baselineY: r.minY + 92)
+ leftText(tile.2, size: 21, weight: .regular, color: t.secondaryInk, tracking: -0.2, x: r.minX + 44, baselineY: r.minY + 52)
+ }
+ }
+ savePNG(rep, "\(outDir)/bento-\(t.name).png")
+}
+
+for t in [light, dark] {
+ hero(t)
+ bento(t)
+ demo(t)
+}