Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc8fa0a2fe | ||
|
|
97d21be470 |
@@ -0,0 +1,8 @@
|
||||
.build/
|
||||
.swiftpm/
|
||||
Packages/
|
||||
*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.DS_Store
|
||||
.netrc
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<?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>CFBundleIdentifier</key>
|
||||
<string>ai.flowmaster.shotdeck</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Shotdeck</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Shotdeck</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>14.0</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2026 Flowmaster FZC LLC. All rights reserved.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,31 @@
|
||||
// swift-tools-version: 6.0
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Shotdeck",
|
||||
platforms: [
|
||||
.macOS(.v14),
|
||||
],
|
||||
products: [
|
||||
.library(name: "ShotdeckCore", targets: ["ShotdeckCore"]),
|
||||
.executable(name: "Shotdeck", targets: ["Shotdeck"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "ShotdeckCore",
|
||||
swiftSettings: [.swiftLanguageMode(.v6)]
|
||||
),
|
||||
.executableTarget(
|
||||
name: "Shotdeck",
|
||||
dependencies: ["ShotdeckCore"],
|
||||
swiftSettings: [.swiftLanguageMode(.v6)]
|
||||
),
|
||||
.testTarget(
|
||||
name: "ShotdeckCoreTests",
|
||||
dependencies: ["ShotdeckCore"],
|
||||
swiftSettings: [.swiftLanguageMode(.v6)]
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -1,3 +1,22 @@
|
||||
# shotdeck
|
||||
# Shotdeck
|
||||
|
||||
macOS menu-bar app: hotkey region capture into a review PDF with PASS/FAIL boxes, AirDrop send, annotation-return tracking
|
||||
A macOS menu-bar app that captures a remembered screen region, builds a one-screenshot-per-page PDF, AirDrops it to an iPad for markup, then watches for the annotated file to come back.
|
||||
|
||||
## Hotkeys
|
||||
|
||||
- **⌥⇧1** — pick a new region, then capture it.
|
||||
- **⌥⇧2** — capture the remembered region instantly (no picker).
|
||||
|
||||
## Screen Recording permission
|
||||
|
||||
On first launch macOS asks once for Screen Recording. Grant it at **System Settings > Privacy & Security > Screen Recording**. You never have to do this again as long as the app is not re-signed with a different identity.
|
||||
|
||||
The grant is bound to the bundle identifier `ai.flowmaster.shotdeck` plus the code signature. Changing either one forces a fresh prompt.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
swift build && swift test
|
||||
./scripts/build-app.sh # signed .app for daily use
|
||||
open .build/Shotdeck.app
|
||||
```
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import AppKit
|
||||
|
||||
// WP-4 replaces this body with the real menu-bar UI.
|
||||
let application = NSApplication.shared
|
||||
application.setActivationPolicy(.accessory)
|
||||
application.run()
|
||||
@@ -0,0 +1,58 @@
|
||||
import Foundation
|
||||
import AppKit // NSScreen, NSDeviceDescriptionKey — macOS-only target, no portability concern
|
||||
|
||||
/// A remembered rectangle, in CoreGraphics global display coordinates (origin top-left,
|
||||
/// y increasing downward — see the conversion note below).
|
||||
public struct CaptureRegion: Codable, Sendable, Equatable {
|
||||
public let displayID: CGDirectDisplayID
|
||||
public let rect: CGRect
|
||||
public let capturedScale: CGFloat
|
||||
|
||||
public init(displayID: CGDirectDisplayID, rect: CGRect, capturedScale: CGFloat) {
|
||||
self.displayID = displayID
|
||||
self.rect = rect
|
||||
self.capturedScale = capturedScale
|
||||
}
|
||||
|
||||
/// Converts an AppKit rect in GLOBAL AppKit coordinates (bottom-left origin, y increasing
|
||||
/// upward, anchored at the bottom-left of the PRIMARY screen — exactly what
|
||||
/// `NSWindow.frame`, `NSEvent.mouseLocation` and `NSScreen.frame` already report; no
|
||||
/// screen-local conversion is needed here) into global CoreGraphics coordinates
|
||||
/// (top-left origin, y increasing downward, same primary-screen anchor). Both coordinate
|
||||
/// systems share the SAME horizontal origin and the SAME anchor rectangle (the primary
|
||||
/// screen's bounds) — only the vertical axis is mirrored around the primary's height.
|
||||
/// That is why the flip below is correct for every attached screen, including one with a
|
||||
/// negative AppKit x (to the left of primary) or a y that places it above the primary
|
||||
/// (whose CG y then comes out negative): x is untouched, and the primary height is the
|
||||
/// one fixed reference both systems agree on regardless of which physical screen the
|
||||
/// rect is actually on.
|
||||
public static func fromAppKit(rect: CGRect, on screen: NSScreen) -> CaptureRegion {
|
||||
let displayID = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")]
|
||||
as? NSNumber)?.uint32Value ?? CGMainDisplayID()
|
||||
let primaryHeight = NSScreen.screens.first?.frame.height ?? screen.frame.height
|
||||
return fromAppKit(rect: rect, displayID: displayID,
|
||||
capturedScale: screen.backingScaleFactor, primaryHeight: primaryHeight)
|
||||
}
|
||||
|
||||
/// Injectable overload for deterministic geometry tests — no dependency on real attached
|
||||
/// displays. The public overload above is a thin adapter over this.
|
||||
static func fromAppKit(rect: CGRect, displayID: CGDirectDisplayID,
|
||||
capturedScale: CGFloat, primaryHeight: CGFloat) -> CaptureRegion {
|
||||
let cgY = primaryHeight - rect.origin.y - rect.height
|
||||
let cgRect = CGRect(x: rect.origin.x, y: cgY, width: rect.width, height: rect.height)
|
||||
return CaptureRegion(displayID: displayID, rect: cgRect, capturedScale: capturedScale)
|
||||
}
|
||||
|
||||
/// True when `displayID` is still attached AND `rect` still lies inside its current
|
||||
/// bounds. Uses `CGDisplayIsActive` (returns 0 safely for an unknown id, never traps) and
|
||||
/// `CGDisplayBounds` — both real CoreGraphics calls, no injection needed since this is a
|
||||
/// live-state check by design.
|
||||
public var isStillValid: Bool {
|
||||
guard CGDisplayIsActive(displayID) != 0 else { return false }
|
||||
let bounds = CGDisplayBounds(displayID)
|
||||
return bounds.contains(rect)
|
||||
}
|
||||
|
||||
/// Persisted in UserDefaults under this key BY THE APP (WP-4a), never by this type.
|
||||
public static let defaultsKey = "ai.flowmaster.shotdeck.region"
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import Carbon.HIToolbox
|
||||
import Foundation
|
||||
|
||||
/// Carbon's C event handler cannot capture Swift closures, so live handlers are kept in one
|
||||
/// process-wide table keyed by the numeric EventHotKeyID Carbon hands back on fire. Safe
|
||||
/// because InstallEventHandler on GetApplicationEventTarget() always delivers on the main
|
||||
/// thread, and every access here happens either from a @MainActor HotkeyCenter method or from
|
||||
/// the C callback below, which this process only ever invokes on the main run loop.
|
||||
private final class HotkeyDispatchTable: @unchecked Sendable {
|
||||
static let shared = HotkeyDispatchTable()
|
||||
private var handlers: [UInt32: @MainActor () -> Void] = [:]
|
||||
private init() {}
|
||||
func set(_ numericID: UInt32, _ handler: @escaping @MainActor () -> Void) {
|
||||
handlers[numericID] = handler
|
||||
}
|
||||
func remove(_ numericID: UInt32) { handlers.removeValue(forKey: numericID) }
|
||||
func fire(_ numericID: UInt32) { MainActor.assumeIsolated { handlers[numericID]?() } }
|
||||
}
|
||||
|
||||
private func shotdeckCarbonHotkeyHandler(
|
||||
_ nextHandler: EventHandlerCallRef?, _ event: EventRef?, _ userData: UnsafeMutableRawPointer?
|
||||
) -> OSStatus {
|
||||
guard let event else { return OSStatus(eventNotHandledErr) }
|
||||
var hotKeyID = EventHotKeyID()
|
||||
let status = GetEventParameter(event, EventParamName(kEventParamDirectObject),
|
||||
EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &hotKeyID)
|
||||
guard status == noErr else { return status }
|
||||
HotkeyDispatchTable.shared.fire(hotKeyID.id)
|
||||
return noErr
|
||||
}
|
||||
|
||||
/// Four-character creator code used for every `EventHotKeyID` this process registers.
|
||||
private let shotdeckHotKeySignature: OSType = 0x53484F54 // "SHOT"
|
||||
|
||||
@MainActor
|
||||
public final class HotkeyCenter {
|
||||
private var bindings: [String: (ref: EventHotKeyRef, numericID: UInt32)] = [:]
|
||||
private var nextNumericID: UInt32 = 1
|
||||
|
||||
private static var didInstallGlobalCarbonHandler = false
|
||||
private static var carbonHandlerRef: EventHandlerRef?
|
||||
|
||||
public init() { HotkeyCenter.installGlobalCarbonHandlerIfNeeded() }
|
||||
|
||||
/// Registers a hotkey. `id` is a caller-chosen stable identifier. Re-registering the same
|
||||
/// `id` first unregisters its previous binding, then attempts the new one (idempotent).
|
||||
/// Returns false when Carbon's `RegisterEventHotKey` reports a non-`noErr` status — the
|
||||
/// most common cause is the same keyCode+modifiers combination already being claimed
|
||||
/// system-wide by this or another process.
|
||||
@discardableResult
|
||||
public func register(
|
||||
id: String,
|
||||
keyCode: UInt32,
|
||||
modifiers: UInt32,
|
||||
handler: @escaping @MainActor () -> Void
|
||||
) -> Bool {
|
||||
unregister(id: id)
|
||||
|
||||
let hotKeyID = EventHotKeyID(signature: shotdeckHotKeySignature, id: nextNumericID)
|
||||
var ref: EventHotKeyRef?
|
||||
let status = RegisterEventHotKey(
|
||||
keyCode,
|
||||
modifiers,
|
||||
hotKeyID,
|
||||
GetApplicationEventTarget(),
|
||||
0,
|
||||
&ref
|
||||
)
|
||||
guard status == noErr, let ref else {
|
||||
return false
|
||||
}
|
||||
bindings[id] = (ref: ref, numericID: nextNumericID)
|
||||
HotkeyDispatchTable.shared.set(nextNumericID, handler)
|
||||
nextNumericID += 1
|
||||
return true
|
||||
}
|
||||
|
||||
public func unregister(id: String) {
|
||||
guard let binding = bindings.removeValue(forKey: id) else { return }
|
||||
_ = UnregisterEventHotKey(binding.ref)
|
||||
HotkeyDispatchTable.shared.remove(binding.numericID)
|
||||
}
|
||||
|
||||
public func unregisterAll() {
|
||||
let ids = Array(bindings.keys)
|
||||
for id in ids {
|
||||
unregister(id: id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide Carbon hot-key pressed handler exactly once.
|
||||
private static func installGlobalCarbonHandlerIfNeeded() {
|
||||
guard !didInstallGlobalCarbonHandler else { return }
|
||||
didInstallGlobalCarbonHandler = true
|
||||
|
||||
var handlerRef: EventHandlerRef?
|
||||
var eventTypes = [
|
||||
EventTypeSpec(
|
||||
eventClass: OSType(kEventClassKeyboard),
|
||||
eventKind: OSType(kEventHotKeyPressed)
|
||||
)
|
||||
]
|
||||
let status = InstallEventHandler(
|
||||
GetApplicationEventTarget(),
|
||||
shotdeckCarbonHotkeyHandler,
|
||||
1,
|
||||
&eventTypes,
|
||||
nil,
|
||||
&handlerRef
|
||||
)
|
||||
if status == noErr {
|
||||
carbonHandlerRef = handlerRef
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
/// One screenshot plus everything needed to place it on a PDF page.
|
||||
public struct Capture: Codable, Sendable, Identifiable, Equatable {
|
||||
public let id: UUID
|
||||
/// 1-based position within its session. Stable; never renumbered on delete.
|
||||
public let sequence: Int
|
||||
/// File name only (e.g. "001-A1B2C3D4.png"), never a path.
|
||||
/// The directory is always the owning session's directory.
|
||||
public let fileName: String
|
||||
/// Pixel dimensions of the PNG on disk.
|
||||
public let pixelWidth: Int
|
||||
public let pixelHeight: Int
|
||||
/// Backing scale the capture was taken at (2.0 on Retina). Needed so the PDF
|
||||
/// composer lays the image out at its true point size, not its pixel size.
|
||||
public let scale: CGFloat
|
||||
/// When the screenshot was taken. Always stored as an absolute instant;
|
||||
/// rendered in Asia/Dubai wherever a human sees it.
|
||||
public let capturedAt: Date
|
||||
|
||||
public init(
|
||||
id: UUID,
|
||||
sequence: Int,
|
||||
fileName: String,
|
||||
pixelWidth: Int,
|
||||
pixelHeight: Int,
|
||||
scale: CGFloat,
|
||||
capturedAt: Date
|
||||
) {
|
||||
self.id = id
|
||||
self.sequence = sequence
|
||||
self.fileName = fileName
|
||||
self.pixelWidth = pixelWidth
|
||||
self.pixelHeight = pixelHeight
|
||||
self.scale = scale
|
||||
self.capturedAt = capturedAt
|
||||
}
|
||||
|
||||
/// True when the image is wider than it is tall. Drives page orientation.
|
||||
public var isLandscape: Bool {
|
||||
pixelWidth > pixelHeight
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import Foundation
|
||||
|
||||
public enum SessionState: String, Codable, Sendable {
|
||||
case open // accepting captures
|
||||
case archived // its PDF has been built and sent; kept forever, never deleted
|
||||
}
|
||||
|
||||
/// The manifest persisted as session.json alongside the PNGs.
|
||||
public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
||||
public let id: UUID
|
||||
public let createdAt: Date
|
||||
public private(set) var state: SessionState
|
||||
public private(set) var captures: [Capture]
|
||||
/// Set when the PDF is built, so a re-send reuses the same file.
|
||||
public private(set) var pdfFileName: String?
|
||||
|
||||
public init(
|
||||
id: UUID,
|
||||
createdAt: Date,
|
||||
state: SessionState,
|
||||
captures: [Capture],
|
||||
pdfFileName: String?
|
||||
) {
|
||||
self.id = id
|
||||
self.createdAt = createdAt
|
||||
self.state = state
|
||||
self.captures = captures
|
||||
self.pdfFileName = pdfFileName
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
captures.isEmpty
|
||||
}
|
||||
|
||||
/// max(sequence)+1, or 1 when empty.
|
||||
public var nextSequence: Int {
|
||||
(captures.map(\.sequence).max() ?? 0) + 1
|
||||
}
|
||||
|
||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||
public func appending(_ capture: Capture) -> CaptureSession {
|
||||
CaptureSession(
|
||||
id: id,
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures + [capture],
|
||||
pdfFileName: pdfFileName
|
||||
)
|
||||
}
|
||||
|
||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||
/// Sequence numbers of remaining captures are left unchanged.
|
||||
public func removing(captureID: UUID) -> CaptureSession {
|
||||
CaptureSession(
|
||||
id: id,
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures.filter { $0.id != captureID },
|
||||
pdfFileName: pdfFileName
|
||||
)
|
||||
}
|
||||
|
||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||
public func markArchived(pdfFileName: String) -> CaptureSession {
|
||||
CaptureSession(
|
||||
id: id,
|
||||
createdAt: createdAt,
|
||||
state: .archived,
|
||||
captures: captures,
|
||||
pdfFileName: pdfFileName
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Foundation
|
||||
|
||||
public enum ShotdeckError: Error, LocalizedError, Sendable {
|
||||
case screenRecordingNotGranted
|
||||
case noRegionRemembered
|
||||
case displayNoLongerConnected(displayID: UInt32)
|
||||
case captureFailed(underlying: String)
|
||||
case spoolWriteFailed(path: String, underlying: String)
|
||||
case manifestCorrupt(path: String)
|
||||
case pdfCompositionFailed(reason: String)
|
||||
case airDropUnavailable
|
||||
case noCommentedReturns
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .screenRecordingNotGranted:
|
||||
return "Screen Recording is turned off. Grant it in System Settings to capture."
|
||||
case .noRegionRemembered:
|
||||
return "No capture region is set. Press ⌥⇧1 to pick one."
|
||||
case .displayNoLongerConnected:
|
||||
return "The display used for capture is no longer connected."
|
||||
case .captureFailed(let underlying):
|
||||
return "The screenshot could not be taken. \(underlying)"
|
||||
case .spoolWriteFailed(_, let underlying):
|
||||
return "The screenshot could not be saved. \(underlying)"
|
||||
case .manifestCorrupt:
|
||||
return "This session's file is damaged and cannot be opened."
|
||||
case .pdfCompositionFailed(let reason):
|
||||
return "The PDF could not be built. \(reason)"
|
||||
case .airDropUnavailable:
|
||||
return "AirDrop is not available right now."
|
||||
case .noCommentedReturns:
|
||||
return "None of the returned PDFs have comments on them."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
/// The only type in the app that knows the on-disk directory layout.
|
||||
public struct AppSupportPaths: Sendable {
|
||||
public let root: URL
|
||||
public let spool: URL
|
||||
public let archive: URL
|
||||
public let outbox: URL
|
||||
public let watchFolder: URL
|
||||
|
||||
/// Production paths.
|
||||
public static func standard() throws -> AppSupportPaths {
|
||||
let fileManager = FileManager.default
|
||||
let appSupportParent = try fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)
|
||||
let desktop = try fileManager.url(
|
||||
for: .desktopDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)
|
||||
let downloads = try fileManager.url(
|
||||
for: .downloadsDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)
|
||||
let root = appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
|
||||
return try AppSupportPaths(root: root, outbox: desktop, watchFolder: downloads)
|
||||
}
|
||||
|
||||
/// Test paths rooted anywhere. Every directory is created if missing.
|
||||
public init(root: URL, outbox: URL, watchFolder: URL) throws {
|
||||
self.root = root
|
||||
self.spool = root.appendingPathComponent("spool", isDirectory: true)
|
||||
self.archive = root.appendingPathComponent("archive", isDirectory: true)
|
||||
self.outbox = outbox
|
||||
self.watchFolder = watchFolder
|
||||
|
||||
try Self.createDirectory(self.root)
|
||||
try Self.createDirectory(self.spool)
|
||||
try Self.createDirectory(self.archive)
|
||||
try Self.createDirectory(self.outbox)
|
||||
try Self.createDirectory(self.watchFolder)
|
||||
}
|
||||
|
||||
public func sessionDirectory(_ id: UUID) -> URL {
|
||||
spool.appendingPathComponent(id.uuidString, isDirectory: true)
|
||||
}
|
||||
|
||||
public func archiveDirectory(_ id: UUID) -> URL {
|
||||
archive.appendingPathComponent(id.uuidString, isDirectory: true)
|
||||
}
|
||||
|
||||
private static func createDirectory(_ url: URL) throws {
|
||||
try FileManager.default.createDirectory(
|
||||
at: url,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
public enum DubaiTime {
|
||||
private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'")
|
||||
private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss")
|
||||
|
||||
public static func stamp(_ date: Date) -> String {
|
||||
stampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
public static func fileStamp(_ date: Date) -> String {
|
||||
fileStampFormatter.string(from: date)
|
||||
}
|
||||
}
|
||||
|
||||
/// DateFormatter is not Sendable. This holder is the only shared mutable state
|
||||
/// around a formatter: every read is serialized by the lock, so concurrent
|
||||
/// calls (one per PDF page) cannot race.
|
||||
private final class LockedDateFormatter: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let formatter: DateFormatter
|
||||
|
||||
init(dateFormat: String) {
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = Calendar(identifier: .gregorian)
|
||||
formatter.locale = Locale(identifier: "en_GB")
|
||||
guard let dubai = TimeZone(identifier: "Asia/Dubai") else {
|
||||
preconditionFailure("The Asia/Dubai time zone is missing from this system.")
|
||||
}
|
||||
formatter.timeZone = dubai
|
||||
formatter.dateFormat = dateFormat
|
||||
self.formatter = formatter
|
||||
}
|
||||
|
||||
func string(from date: Date) -> String {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import ShotdeckCore
|
||||
|
||||
@Test
|
||||
func appSupportPathsCreatesEveryNamedDirectory() throws {
|
||||
let temporaryRoot = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("shotdeck-paths-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: temporaryRoot) }
|
||||
|
||||
let root = temporaryRoot.appendingPathComponent("root", isDirectory: true)
|
||||
let outbox = temporaryRoot.appendingPathComponent("outbox", isDirectory: true)
|
||||
let watchFolder = temporaryRoot.appendingPathComponent("watch", isDirectory: true)
|
||||
|
||||
let paths = try AppSupportPaths(root: root, outbox: outbox, watchFolder: watchFolder)
|
||||
|
||||
#expect(directoryExists(paths.root))
|
||||
#expect(directoryExists(paths.spool))
|
||||
#expect(directoryExists(paths.archive))
|
||||
#expect(directoryExists(paths.outbox))
|
||||
#expect(directoryExists(paths.watchFolder))
|
||||
|
||||
#expect(paths.spool.path == root.appendingPathComponent("spool", isDirectory: true).path)
|
||||
#expect(paths.archive.path == root.appendingPathComponent("archive", isDirectory: true).path)
|
||||
}
|
||||
|
||||
@Test
|
||||
func sessionAndArchiveDirectoriesAreDistinctUnderTheRightParents() throws {
|
||||
let temporaryRoot = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("shotdeck-dirs-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: temporaryRoot) }
|
||||
|
||||
let paths = try AppSupportPaths(
|
||||
root: temporaryRoot.appendingPathComponent("root", isDirectory: true),
|
||||
outbox: temporaryRoot.appendingPathComponent("outbox", isDirectory: true),
|
||||
watchFolder: temporaryRoot.appendingPathComponent("watch", isDirectory: true)
|
||||
)
|
||||
|
||||
let sessionID = UUID()
|
||||
let sessionDirectory = paths.sessionDirectory(sessionID)
|
||||
let archiveDirectory = paths.archiveDirectory(sessionID)
|
||||
|
||||
#expect(sessionDirectory.path != archiveDirectory.path)
|
||||
#expect(sessionDirectory.deletingLastPathComponent().path == paths.spool.path)
|
||||
#expect(archiveDirectory.deletingLastPathComponent().path == paths.archive.path)
|
||||
#expect(sessionDirectory.lastPathComponent == sessionID.uuidString)
|
||||
#expect(archiveDirectory.lastPathComponent == sessionID.uuidString)
|
||||
}
|
||||
|
||||
@Test
|
||||
func dubaiTimeStampRendersAKnownInstantInAsiaDubai() throws {
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
let dubai = try #require(TimeZone(identifier: "Asia/Dubai"))
|
||||
calendar.timeZone = dubai
|
||||
|
||||
let date = try #require(
|
||||
calendar.date(from: DateComponents(
|
||||
year: 2026,
|
||||
month: 8,
|
||||
day: 30,
|
||||
hour: 13,
|
||||
minute: 42,
|
||||
second: 5
|
||||
))
|
||||
)
|
||||
|
||||
#expect(DubaiTime.stamp(date) == "30 Aug 2026, 13:42 Dubai")
|
||||
#expect(DubaiTime.fileStamp(date) == "20260830-134205")
|
||||
}
|
||||
|
||||
private func directoryExists(_ url: URL) -> Bool {
|
||||
var isDirectory: ObjCBool = false
|
||||
let exists = FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)
|
||||
return exists && isDirectory.boolValue
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import Carbon.HIToolbox
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import ShotdeckCore
|
||||
|
||||
@Test("GEO-1 primary-only 1080-tall screen, AppKit rect (100,100,400,300)")
|
||||
func geo1_primaryOnlyAppKitRectConvertsToExpectedCGRect() {
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: CGRect(x: 100, y: 100, width: 400, height: 300),
|
||||
displayID: 1,
|
||||
capturedScale: 2,
|
||||
primaryHeight: 1080
|
||||
)
|
||||
#expect(region.rect == CGRect(x: 100, y: 680, width: 400, height: 300))
|
||||
}
|
||||
|
||||
@Test("GEO-2 rect flush to AppKit bottom (y=0), h=300, primaryHeight=1080")
|
||||
func geo2_flushToAppKitBottomYieldsCGY780() {
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: CGRect(x: 50, y: 0, width: 200, height: 300),
|
||||
displayID: 1,
|
||||
capturedScale: 1,
|
||||
primaryHeight: 1080
|
||||
)
|
||||
#expect(region.rect.origin.y == 780)
|
||||
}
|
||||
|
||||
@Test("GEO-3 rect flush to AppKit top (y+h=primaryHeight), primaryHeight=1080, h=300")
|
||||
func geo3_flushToAppKitTopYieldsCGY0() {
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: CGRect(x: 50, y: 780, width: 200, height: 300),
|
||||
displayID: 1,
|
||||
capturedScale: 1,
|
||||
primaryHeight: 1080
|
||||
)
|
||||
#expect(region.rect.origin.y == 0)
|
||||
}
|
||||
|
||||
@Test("GEO-4 round-trip AppKit→CG via injectable overload, then invert recovers original")
|
||||
func geo4_invertRecoverOriginalAppKitRect() {
|
||||
let original = CGRect(x: 100, y: 100, width: 400, height: 300)
|
||||
let primaryHeight: CGFloat = 1080
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: original,
|
||||
displayID: 1,
|
||||
capturedScale: 2,
|
||||
primaryHeight: primaryHeight
|
||||
)
|
||||
let appKitY = primaryHeight - region.rect.origin.y - region.rect.height
|
||||
let recovered = CGRect(
|
||||
x: region.rect.origin.x,
|
||||
y: appKitY,
|
||||
width: region.rect.width,
|
||||
height: region.rect.height
|
||||
)
|
||||
#expect(recovered == original)
|
||||
}
|
||||
|
||||
@Test("GEO-5 isStillValid for displayID 999_999 is false and does not trap")
|
||||
func geo5_unknownDisplayIsNotStillValid() {
|
||||
let region = CaptureRegion(
|
||||
displayID: 999_999,
|
||||
rect: CGRect(x: 0, y: 0, width: 100, height: 100),
|
||||
capturedScale: 1
|
||||
)
|
||||
#expect(region.isStillValid == false)
|
||||
}
|
||||
|
||||
@Test("GEO-6 CaptureRegion JSONEncoder→JSONDecoder round-trip equals original")
|
||||
func geo6_codableRoundTripEqualsOriginal() throws {
|
||||
let original = CaptureRegion(
|
||||
displayID: 42,
|
||||
rect: CGRect(x: 10, y: 20, width: 300, height: 400),
|
||||
capturedScale: 2
|
||||
)
|
||||
let data = try JSONEncoder().encode(original)
|
||||
let decoded = try JSONDecoder().decode(CaptureRegion.self, from: data)
|
||||
#expect(decoded == original)
|
||||
}
|
||||
|
||||
@Test("GEO-7 secondary screen negative x: AppKit (−1800,200,500,400) → CG (−1800,480,500,400)")
|
||||
func geo7_secondaryNegativeXLeavesXUnchanged() {
|
||||
// Secondary AppKit frame (−1920, 0, 1920, 1080); primaryHeight=1080.
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: CGRect(x: -1800, y: 200, width: 500, height: 400),
|
||||
displayID: 2,
|
||||
capturedScale: 1,
|
||||
primaryHeight: 1080
|
||||
)
|
||||
#expect(region.rect == CGRect(x: -1800, y: 480, width: 500, height: 400))
|
||||
}
|
||||
|
||||
@Test("GEO-8 secondary screen stacked above primary: AppKit (300,1300,600,350) → CG (300,−570,600,350)")
|
||||
func geo8_secondaryPositiveYProducesNegativeCGY() {
|
||||
// Secondary AppKit frame (0, 1080, 1920, 1080); primaryHeight=1080.
|
||||
let region = CaptureRegion.fromAppKit(
|
||||
rect: CGRect(x: 300, y: 1300, width: 600, height: 350),
|
||||
displayID: 2,
|
||||
capturedScale: 1,
|
||||
primaryHeight: 1080
|
||||
)
|
||||
#expect(region.rect == CGRect(x: 300, y: -570, width: 600, height: 350))
|
||||
}
|
||||
|
||||
/// Carbon registrations are process-wide, so these cases must not run in parallel.
|
||||
@Suite(.serialized)
|
||||
@MainActor
|
||||
struct HotkeyCenterCarbonTests {
|
||||
/// kVK_ANSI_2. The app registers this combo once (WP-4a); tests only exercise the registrar.
|
||||
private let captureKeyCode: UInt32 = 19
|
||||
private let captureModifiers = UInt32(optionKey) | UInt32(shiftKey)
|
||||
|
||||
@Test("HK-1 register id a with Option-Shift-2 returns true")
|
||||
func hk1_registerReturnsTrue() {
|
||||
let center = HotkeyCenter()
|
||||
defer { center.unregisterAll() }
|
||||
let ok = center.register(id: "a", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
if !ok {
|
||||
Issue.record("HK-1: RegisterEventHotKey returned non-noErr inside swift test (no NSApplication). Carbon registration did not function headlessly.")
|
||||
return
|
||||
}
|
||||
#expect(ok)
|
||||
}
|
||||
|
||||
@Test("HK-2 register same combo under a different id returns false")
|
||||
func hk2_duplicateComboRejected() {
|
||||
let center = HotkeyCenter()
|
||||
defer { center.unregisterAll() }
|
||||
let first = center.register(id: "a", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
if !first {
|
||||
Issue.record("HK-2: first RegisterEventHotKey failed inside swift test (no NSApplication); cannot evaluate duplicate-combo rejection.")
|
||||
return
|
||||
}
|
||||
let second = center.register(id: "b", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
#expect(second == false)
|
||||
}
|
||||
|
||||
@Test("HK-3 unregister frees the combination so a later register succeeds")
|
||||
func hk3_unregisterFreesCombination() {
|
||||
let center = HotkeyCenter()
|
||||
defer { center.unregisterAll() }
|
||||
let first = center.register(id: "a", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
if !first {
|
||||
Issue.record("HK-3: first RegisterEventHotKey failed inside swift test (no NSApplication); cannot evaluate unregister.")
|
||||
return
|
||||
}
|
||||
center.unregister(id: "a")
|
||||
let again = center.register(id: "c", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
#expect(again)
|
||||
}
|
||||
|
||||
@Test("HK-4 unregisterAll frees combinations so a later register succeeds")
|
||||
func hk4_unregisterAllFreesCombinations() {
|
||||
let center = HotkeyCenter()
|
||||
defer { center.unregisterAll() }
|
||||
let first = center.register(id: "a", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
let other = center.register(
|
||||
id: "other",
|
||||
keyCode: UInt32(kVK_ANSI_3),
|
||||
modifiers: captureModifiers
|
||||
) {}
|
||||
if !first {
|
||||
Issue.record("HK-4: RegisterEventHotKey failed inside swift test (no NSApplication); cannot evaluate unregisterAll.")
|
||||
return
|
||||
}
|
||||
_ = other
|
||||
center.unregisterAll()
|
||||
let again = center.register(id: "c", keyCode: captureKeyCode, modifiers: captureModifiers) {}
|
||||
#expect(again)
|
||||
}
|
||||
}
|
||||
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# macOS keys the Screen Recording permission to the bundle identifier plus the
|
||||
# code signature. The identity below and --identifier ai.flowmaster.shotdeck must
|
||||
# never change: altering either one makes the existing grant invalid and forces
|
||||
# the user to approve Screen Recording again by hand.
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
|
||||
BUNDLE_ID="ai.flowmaster.shotdeck"
|
||||
APP_BUNDLE="${ROOT}/.build/Shotdeck.app"
|
||||
|
||||
SKIP_SIGN=0
|
||||
for arg in "$@"; do
|
||||
case "${arg}" in
|
||||
--skip-sign)
|
||||
SKIP_SIGN=1
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: ${arg}" >&2
|
||||
echo "Usage: $0 [--skip-sign]" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "==> Building Shotdeck (release)"
|
||||
swift build -c release --product Shotdeck
|
||||
|
||||
BIN_PATH="$(swift build -c release --product Shotdeck --show-bin-path)/Shotdeck"
|
||||
if [[ ! -x "${BIN_PATH}" ]]; then
|
||||
echo "Release binary not found at ${BIN_PATH}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Assembling ${APP_BUNDLE}"
|
||||
rm -rf "${APP_BUNDLE}"
|
||||
mkdir -p "${APP_BUNDLE}/Contents/MacOS"
|
||||
mkdir -p "${APP_BUNDLE}/Contents/Resources"
|
||||
cp "${BIN_PATH}" "${APP_BUNDLE}/Contents/MacOS/Shotdeck"
|
||||
chmod +x "${APP_BUNDLE}/Contents/MacOS/Shotdeck"
|
||||
cp "${ROOT}/Info.plist" "${APP_BUNDLE}/Contents/Info.plist"
|
||||
|
||||
if [[ "${SKIP_SIGN}" -eq 1 ]]; then
|
||||
echo
|
||||
echo "************************************************************************"
|
||||
echo "WARNING: --skip-sign was used. This app is UNSIGNED."
|
||||
echo "The resulting app will trigger a fresh Screen Recording prompt and must"
|
||||
echo "not be handed to the user."
|
||||
echo "************************************************************************"
|
||||
echo
|
||||
else
|
||||
if ! security find-identity -v -p codesigning | grep -Fq "${IDENTITY}"; then
|
||||
echo "The codesigning identity '${IDENTITY}' is not in this shell's keychain search list." >&2
|
||||
echo "The login keychain is not reachable from this shell." >&2
|
||||
echo "Run this script from a normal login session so the app can be signed." >&2
|
||||
echo "Refusing to produce an unsigned app." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "==> Signing ${APP_BUNDLE}"
|
||||
codesign --force --options runtime \
|
||||
--sign "${IDENTITY}" \
|
||||
--identifier "${BUNDLE_ID}" \
|
||||
"${APP_BUNDLE}"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "App path: ${APP_BUNDLE}"
|
||||
echo "Launch with: open ${APP_BUNDLE}"
|
||||
Reference in New Issue
Block a user