diff --git a/Info.plist b/Info.plist index dfdebfb..44215de 100644 --- a/Info.plist +++ b/Info.plist @@ -13,9 +13,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 0.5.0 + 0.6.0 CFBundleVersion - 7 + 8 LSMinimumSystemVersion 14.0 LSUIElement diff --git a/README.md b/README.md index 06ad46f..1c4a08c 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,19 @@ 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. +## What Capture takes + +Four scopes, chosen in the popover (or the window's capture menu) and kept with the session: + +- **Area** — the saved rectangle. `Choose Area…` picks a new one at any time. +- **Window** — the window under the pointer. Redline hides itself, dims the screen, names + the app under the cursor and highlights its window; click to capture it, Escape cancels. +- **Browser** — the front browser window (Safari, Chrome, Edge, Brave, Arc, Firefox, + Vivaldi, Opera). +- **Screen** — the whole display your saved area is on. + +Window and Browser capture a single window, so nothing overlapping it ends up in the shot. + ## Hotkeys - **⌥⇧1** — pick a new region, then capture it. @@ -18,13 +31,19 @@ Two surfaces, two jobs: by day, the selected session's pages in the middle, and its review details, PDF facts and session facts in the inspector. History, text entry and file facts live here because they need room and a window that stays open. -- **Settings** (⌘, in the popover's … menu) — capture, sending, and the session age limit. +- **Settings** — one door: the gear in the popover header, or ⌘,. Capture, sending, +- sessions and updates all live there. +- **Updates are automatic.** A downloaded update installs the next time nothing is +- waiting to be sent; turn it off in Settings › Updates. ## Sessions Every review is a session. Captures go into the open session; "New Session" closes it and keeps it in the sidebar, named and dated, whether or not it was sent. +- **New Session** keeps the current captures in their own folder, starts a fresh +- session, and immediately asks where to capture (Return keeps the saved area, a drag +- picks a new one). Turn that question off in Settings › Capture. - **Nothing is deleted by default.** A session is kept until you delete it. - **Settings > Sessions > Delete after** sets an age limit (7 days … 1 year). Sessions older than the limit are removed on the next launch and by **Clean up now**. @@ -64,7 +83,7 @@ The grant is bound to the bundle identifier `ai.flowmaster.shotdeck` plus the co ```bash swift build && swift test ./scripts/build-app.sh # signed .app for daily use -open .build/Redline.app +./scripts/install-local.sh # install it into /Applications and relaunch ``` ## Verification scripts diff --git a/Sources/Shotdeck/AppModel.swift b/Sources/Shotdeck/AppModel.swift index ca6cee2..0646162 100644 --- a/Sources/Shotdeck/AppModel.swift +++ b/Sources/Shotdeck/AppModel.swift @@ -44,6 +44,13 @@ public final class AppModel { /// The user's age limit for kept sessions (Settings > Sessions). `.never` until /// the user chooses otherwise, so every session is saved by default. public private(set) var retention: SessionRetention = .never + /// What Capture takes: the saved area, the front window, a browser window, or a + /// whole display. Kept across sessions; changing it never clears the saved area. + public private(set) var captureScope: CaptureScope = .area + /// Whether "New Session…" asks what to capture before starting. + public private(set) var askWhatToCaptureOnNewSession = true + /// Whether a downloaded update installs itself the next time nothing is unsent. + public private(set) var autoInstallUpdates = true /// How many archived sessions the current age limit would delete right now. /// Recomputed on launch, on a policy change and after every cleanup. public private(set) var expiredSessionCount: Int = 0 @@ -84,6 +91,7 @@ public final class AppModel { let capturer: ScreenCapturer let hotkeys: HotkeyCenter let picker: RegionPickerController + let windowPicker = WindowPickerController() let ledger: ReturnLedger let watcher: ReturnWatcher let updateChecker: UpdateChecker @@ -136,6 +144,7 @@ public final class AppModel { guard let self else { return } self.updateAvailable = self.updateChecker.availableUpdate self.setUpdateStatus(self.updateChecker.statusMessage) + self.installStagedUpdateIfIdle() } self.updateChecker.onCheckingChanged = { [weak self] checking in self?.isCheckingForUpdates = checking @@ -171,6 +180,7 @@ public final class AppModel { } } func setSelectedSessionID(_ value: UUID?) { selectedSessionID = value } + func setCaptureScope(_ scope: CaptureScope) { captureScope = scope } func requestLaneFocus() { laneFocusRequest += 1 } func setFolderDisplayNames(outbox: String, watch: String) { outboxDisplayName = outbox @@ -502,6 +512,9 @@ public final class AppModel { public func bootstrap() async { retention = RetentionSettings.load(defaults: retentionDefaults) + captureScope = CaptureSettings.scope(defaults: retentionDefaults) + askWhatToCaptureOnNewSession = CaptureSettings.askOnNewSession(defaults: retentionDefaults) + autoInstallUpdates = UpdateSettings.autoInstall(defaults: retentionDefaults) await spool.setRetention(retention) if let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey), @@ -605,6 +618,28 @@ public final class AppModel { } } + /// Turning automatic updates on/off. On is the default: a staged update installs as + /// soon as the app has nothing unsent. + public func setAutoInstallUpdates(_ value: Bool) { + autoInstallUpdates = value + UpdateSettings.setAutoInstall(value, defaults: retentionDefaults) + installStagedUpdateIfIdle() + } + + /// Installs a staged update when it is safe to restart: nothing captured in the open + /// session is waiting to be sent, and no capture or send is in flight. Called after + /// every update check, after a send, and after a new session starts — the moments + /// the app becomes idle. + func installStagedUpdateIfIdle() { + guard autoInstallUpdates, + updateAvailable != nil, + session.isEmpty, + !isSending, + !isCapturing + else { return } + updateChecker.installStaged() + } + /// Installs the staged update over `/Applications/Redline.app` and relaunches. /// Does nothing unless the user clicked the menu row. public func installUpdate() { @@ -652,26 +687,44 @@ public final class AppModel { } } + /// The line shown under the capture control: what the next capture will take. + public var captureTargetDescription: String { + captureScope.targetDescription(savedArea: region) + } + + /// Picks the scope for the session being captured into and persists it. Choosing a + /// scope other than Area keeps the saved area untouched. + public func chooseCaptureScope(_ scope: CaptureScope) async { + captureScope = scope + CaptureSettings.setScope(scope, defaults: retentionDefaults) + setStatus(nil) + if scope == .area, region == nil { + await rePickRegion() + } + } + + public func setAskWhatToCaptureOnNewSession(_ value: Bool) { + askWhatToCaptureOnNewSession = value + CaptureSettings.setAskOnNewSession(value, defaults: retentionDefaults) + } + public func captureNow() async { + await capture(scope: captureScope) + } + + /// Captures whatever the chosen scope points at. + /// + /// Any picker runs with Redline's own windows hidden, so the panel never covers — + /// or ends up inside — the thing being captured. + public func capture(scope: CaptureScope) async { guard !isCapturing else { return } setCapturing(true) defer { setCapturing(false) } - var target = region - if target == nil { - target = await withCheckedContinuation { (cont: CheckedContinuation) in - picker.pick { picked in cont.resume(returning: picked) } - } - guard let picked = target else { - setStatus("No region selected.") - return - } - persistRegion(picked) - } - guard let region = target else { return } - do { - let image = try await capturer.capture(region) + let target = try await resolveTarget(for: scope) + guard let target else { return } + let image = try await capturer.capture(target) let capture = try await spool.append( pngData: image.pngData, pixelWidth: image.pixelWidth, @@ -687,13 +740,71 @@ public final class AppModel { } } - public func rePickRegion() async { - let picked = await withCheckedContinuation { (cont: CheckedContinuation) in - picker.pick { cont.resume(returning: $0) } + /// Works out what to capture, presenting the area or window picker when the scope + /// needs one. nil means the user backed out — nothing to say about it. + private func resolveTarget(for scope: CaptureScope) async throws -> CaptureTarget? { + switch scope { + case .area: + var area = region + if area == nil { + area = await pickArea(confirming: nil) + guard let picked = area else { return nil } + persistRegion(picked) + } + guard let area else { return nil } + return .region(area) + + case .window, .browser: + return await pickWindow(onlyBrowsers: scope == .browser) + + case .screen: + if let area = region { + return .display(displayID: area.displayID) + } + return .display(displayID: CGMainDisplayID()) } - guard let picked else { return } + } + + /// Hides Redline, runs the area picker, then restores Redline's windows. + private func pickArea(confirming saved: CaptureRegion?) async -> CaptureRegion? { + RedlineWindows.hideForPicking() + defer { RedlineWindows.restoreAfterPicking() } + return await withCheckedContinuation { (continuation: CheckedContinuation) in + picker.pick(confirming: saved) { picked in + continuation.resume(returning: picked) + } + } + } + + /// Hides Redline, runs the window picker (hover highlights, click chooses), then + /// restores Redline's windows. + private func pickWindow(onlyBrowsers: Bool) async -> CaptureTarget? { + RedlineWindows.hideForPicking() + defer { RedlineWindows.restoreAfterPicking() } + return await withCheckedContinuation { (continuation: CheckedContinuation) in + windowPicker.pick(onlyBrowsers: onlyBrowsers) { picked in + continuation.resume(returning: picked) + } + } + } + + /// Picks a new area and remembers it (the "Choose Area…" action). + public func rePickRegion() async { + guard let picked = await pickArea(confirming: region) else { return } persistRegion(picked) - setStatus("Region set: \(Int(picked.rect.width)) × \(Int(picked.rect.height)).") + setStatus("\(picked.summary) saved.") + } + + /// One-click "New Session": the current session is kept as a past session (its + /// screenshots stay in their own folder and its PDF keeps its name), a fresh one + /// opens, and — when the user asked to be asked — the area picker comes straight up + /// so the next capture starts with the right area. Return keeps the saved area. + public func newSession() async { + await startNewSession() + guard askWhatToCaptureOnNewSession, captureScope == .area else { return } + if let picked = await pickArea(confirming: region) { + persistRegion(picked) + } } public func removeCapture(id: UUID) async { diff --git a/Sources/Shotdeck/MenuBarView.swift b/Sources/Shotdeck/MenuBarView.swift index d6b92b5..0e9a59c 100644 --- a/Sources/Shotdeck/MenuBarView.swift +++ b/Sources/Shotdeck/MenuBarView.swift @@ -2,26 +2,22 @@ import AppKit import SwiftUI import ShotdeckCore -/// The menu-bar popover: the current session, and the two things you do with it. -/// -/// Everything else — history, review details, PDF facts — lives in the Redline -/// window, which stays open and has room for it. +/// The menu-bar popover: decide what to capture, see the pages, then capture or send. +/// History, editable details and file facts live in the Redline window; Settings has +/// exactly one door — the gear here (⌘, works anywhere). struct MenuBarView: View { @Environment(AppModel.self) private var model var body: some View { VStack(alignment: .leading, spacing: 8) { if model.screenRecordingGranted { - sessionHeader - thumbnailRow - statusRow - actionRows - Divider() - footer + header + scopeControl + pageStrip + newsRow + verbs } else { permissionBlock - Divider() - footer } } .padding(10) @@ -31,7 +27,7 @@ struct MenuBarView: View { // MARK: - Header - private var sessionHeader: some View { + private var header: some View { HStack(alignment: .top, spacing: 8) { VStack(alignment: .leading, spacing: 1) { HStack(spacing: 5) { @@ -50,18 +46,8 @@ struct MenuBarView: View { .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.tail) - .help(detailLine) } Spacer(minLength: 4) - if !model.session.isEmpty { - Text("\(model.session.captures.count) page\(model.session.captures.count == 1 ? "" : "s")") - .font(.caption) - .foregroundStyle(.secondary) - .monospacedDigit() - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(.quaternary, in: Capsule()) - } Button { presentWindow(focusLane: true) } label: { @@ -71,6 +57,17 @@ struct MenuBarView: View { .buttonStyle(.borderless) .help("Edit review details") .accessibilityLabel("Edit review details") + + Button { + (model as? SettingsWindowPresenting)?.presentSettingsWindow() + } label: { + Image(systemName: "gearshape") + .font(.system(size: 12, weight: .semibold)) + } + .buttonStyle(.borderless) + .keyboardShortcut(",", modifiers: .command) + .help("Settings (⌘,)") + .accessibilityLabel("Settings") } } @@ -89,20 +86,55 @@ struct MenuBarView: View { var parts: [String] = [] if !context.commit.isEmpty { parts.append(context.commit) } if !context.reviewer.isEmpty { parts.append(context.reviewer) } - let started = DubaiTime.checkTime(model.session.createdAt) - if parts.isEmpty { - return "No review details yet · started \(started)" - } - return parts.joined(separator: " · ") + " · started \(started)" + let pages = model.session.captures.count + parts.append(pages == 0 ? "no pages" : "\(pages) page\(pages == 1 ? "" : "s")") + return parts.joined(separator: " · ") } - // MARK: - Body + // MARK: - What to capture + + private var scopeControl: some View { + VStack(alignment: .leading, spacing: 4) { + Picker("Capture", selection: scopeBinding) { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Text(scope.displayName).tag(scope) + } + } + .pickerStyle(.segmented) + .labelsHidden() + .accessibilityLabel("Capture") + + HStack(spacing: 6) { + Text(model.captureTargetDescription) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 4) + if model.captureScope == .area { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + .buttonStyle(.link) + } + } + } + } + + private var scopeBinding: Binding { + Binding( + get: { model.captureScope }, + set: { scope in Task { await model.chooseCaptureScope(scope) } } + ) + } + + // MARK: - Pages @ViewBuilder - private var thumbnailRow: some View { + private var pageStrip: some View { if model.session.isEmpty { VStack(spacing: 2) { - Text("Nothing captured yet") + Text("No pages yet") .font(.callout) .foregroundStyle(.secondary) Text(emptyHint) @@ -117,28 +149,26 @@ struct MenuBarView: View { } private var emptyHint: String { - guard let region = model.region else { - return "\(model.hotkeyDisplayString) picks an area, then captures it" - } - return "\(model.hotkeyDisplayString) captures \(Int(region.rect.width)) × \(Int(region.rect.height)) on \(displayName(for: region))" + "\(model.hotkeyDisplayString) captures the \(model.captureScope.displayName.lowercased())" } - private func displayName(for region: CaptureRegion) -> String { - for (index, screen) in NSScreen.screens.enumerated() { - let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)? - .uint32Value - if id == region.displayID { - return "Display \(index + 1)" - } - } - return "Display 1" - } + // MARK: - News - /// One line, only when there is something to say: the last action's result, or a - /// PDF that came back with marks. @ViewBuilder - private var statusRow: some View { - if let status = model.statusLine, !status.isEmpty { + private var newsRow: some View { + if let update = model.updateAvailable { + HStack(spacing: 6) { + Circle().fill(.green).frame(width: 6, height: 6) + Text(model.autoInstallUpdates + ? "Redline \(update.version) is ready — restarts when nothing is unsent" + : "Redline \(update.version) is ready") + .font(.caption) + .lineLimit(2) + Spacer(minLength: 4) + Button("Restart Now") { model.installUpdate() } + .buttonStyle(.link) + } + } else if let status = model.statusLine, !status.isEmpty { Text(status) .font(.caption) .foregroundStyle(.secondary) @@ -147,7 +177,9 @@ struct MenuBarView: View { } } - private var actionRows: some View { + // MARK: - Verbs + + private var verbs: some View { VStack(spacing: 6) { HStack(spacing: 6) { Button { @@ -165,10 +197,7 @@ struct MenuBarView: View { .disabled(model.isCapturing) Button { - guard let sender = model as? SendCapable else { - model.setStatus("Send is not available in this build.") - return - } + guard let sender = model as? SendCapable else { return } let anchor = NSApp.keyWindow?.contentView Task { await sender.send(anchor: anchor) } } label: { @@ -185,7 +214,7 @@ struct MenuBarView: View { HStack(spacing: 6) { Button { - Task { await model.startNewSession() } + Task { await model.newSession() } } label: { HStack(spacing: 4) { Image(systemName: "plus.square.on.square") @@ -194,8 +223,8 @@ struct MenuBarView: View { .frame(maxWidth: .infinity) } .controlSize(.regular) - .disabled(!model.canStartNewSession) - .help("Keeps this session and starts a fresh one. Nothing is deleted.") + .disabled(model.isSending) + .help("Keeps this session and starts a fresh one, then asks where to capture.") Button { presentWindow(focusLane: false) @@ -219,53 +248,7 @@ struct MenuBarView: View { return model.transport == .oneDrive ? "Save \(pages)…" : "Send \(pages)…" } - // MARK: - Footer - - private var footer: some View { - HStack(spacing: 6) { - Text("\(sendChannel) · \(model.retentionSummary)") - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - Spacer(minLength: 4) - Menu { - Button("Settings…") { - (model as? SettingsWindowPresenting)?.presentSettingsWindow() - } - .keyboardShortcut(",", modifiers: .command) - Button(model.isCheckingForUpdates ? "Checking for Updates…" : "Check for Updates…") { - model.checkForUpdates() - } - .disabled(model.isCheckingForUpdates) - if let update = model.updateAvailable { - Button("Update to \(update.version)") { model.installUpdate() } - } - if let previous = model.previousVersion { - Button("Revert to \(previous)") { model.revertToPreviousVersion() } - } - Divider() - Button("Quit Redline") { NSApp.terminate(nil) } - .keyboardShortcut("q", modifiers: .command) - } label: { - Image(systemName: "ellipsis.circle") - } - .menuStyle(.borderlessButton) - .menuIndicator(.hidden) - .fixedSize() - .help("More Redline actions") - .accessibilityLabel("More") - } - .overlay(alignment: .topTrailing) { - EmptyView() - } - } - - private var sendChannel: String { - model.transport == .oneDrive ? "Saves to OneDrive" : "Sends via AirDrop" - } - - // MARK: - Not granted + // MARK: - Permission private var permissionBlock: some View { HStack(alignment: .top, spacing: 6) { diff --git a/Sources/Shotdeck/PanelSelfTest.swift b/Sources/Shotdeck/PanelSelfTest.swift index 42c1ffa..58e330b 100644 --- a/Sources/Shotdeck/PanelSelfTest.swift +++ b/Sources/Shotdeck/PanelSelfTest.swift @@ -212,7 +212,21 @@ enum PanelSelfTest { "the window follows the new session") print("PANEL-SELFTEST PASS new-session kept=\(model.pastSessions.count)") - // Sidebar grouping: today's sessions land in "Today". + // Settings reflects the stored defaults: automatic updates and "ask what to + // capture" are both on unless the user turned them off. + let settingsWindow = makeWindow( + width: 460, height: 820, + content: AnyView(SettingsView().environment(model))) + settingsWindow.orderBack(nil) + pump(0.5) + let switches = switches(in: settingsWindow.contentView) + try check(switches.count >= 2, "settings shows both toggles (found \(switches.count))") + try check(switches.allSatisfy { $0.state == .on }, + "automatic updates and 'ask what to capture' start on") + print("PANEL-SELFTEST PASS settings toggles=\(switches.count)") + settingsWindow.orderOut(nil) + + // Sidebar grouping: today's sessions land under Today. let groups = model.groupedSections(for: model.sessions(matching: "")) try check(groups.first?.title == "Today", "sessions are grouped under Today") try check(groups.first?.sessions.count == 2, "both sessions are under Today") @@ -346,9 +360,23 @@ enum PanelSelfTest { // MARK: - Window and input helpers @MainActor - private static func makeWindow(model: AppModel, width: CGFloat, height: CGFloat) -> NSWindow { - let hosting = NSHostingController( - rootView: SessionsWindowView().environment(model)) + private static func switches(in view: NSView?) -> [NSSwitch] { + guard let view else { return [] } + var found: [NSSwitch] = [] + if let toggle = view as? NSSwitch { found.append(toggle) } + for subview in view.subviews { + found.append(contentsOf: switches(in: subview)) + } + return found + } + + @MainActor + private static func makeWindow( + width: CGFloat, + height: CGFloat, + content: AnyView + ) -> NSWindow { + let hosting = NSHostingController(rootView: content) let window = NSWindow(contentViewController: hosting) window.title = "Redline" window.styleMask = [.titled, .closable, .miniaturizable, .resizable] @@ -357,6 +385,14 @@ enum PanelSelfTest { return window } + @MainActor + private static func makeWindow(model: AppModel, width: CGFloat, height: CGFloat) -> NSWindow { + makeWindow( + width: width, height: height, + content: AnyView(SessionsWindowView().environment(model))) + } + + /// In-process capture of the live window (no Screen Recording permission needed): /// evidence of what the running window actually shows. @MainActor diff --git a/Sources/Shotdeck/PanelSnapshot.swift b/Sources/Shotdeck/PanelSnapshot.swift index f10d28a..be46590 100644 --- a/Sources/Shotdeck/PanelSnapshot.swift +++ b/Sources/Shotdeck/PanelSnapshot.swift @@ -78,7 +78,7 @@ enum PanelSnapshot { SettingsView().environment(model), to: directory.appendingPathComponent("panel-06-settings.png"), width: 460, - height: 560 + height: 820 ) // 06b — the sessions window: real sidebar, pages grid and inspector. @@ -162,7 +162,7 @@ enum PanelSnapshot { SettingsView().environment(model), to: directory.appendingPathComponent("panel-07-settings-onedrive.png"), width: 460, - height: 560 + height: 820 ) // 08 — no OneDrive folder found: a fake home with NO Library/CloudStorage at @@ -183,7 +183,7 @@ enum PanelSnapshot { SettingsView().environment(model), to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png"), width: 460, - height: 560 + height: 820 ) // 09 — menu bar panel, 3 captures present, OneDrive mode ("Send to OneDrive"). diff --git a/Sources/Shotdeck/RegionPickerController.swift b/Sources/Shotdeck/RegionPickerController.swift index 114fdcf..d3cfea5 100644 --- a/Sources/Shotdeck/RegionPickerController.swift +++ b/Sources/Shotdeck/RegionPickerController.swift @@ -15,12 +15,40 @@ public final class RegionPickerController { /// Presents one overlay per attached screen. A pick already in progress is cancelled /// (its completion called with nil) before the new one starts — never leaves a caller /// waiting forever on a dropped re-entrant call. - public func pick(completion: @escaping @MainActor (CaptureRegion?) -> Void) { + /// Passing `confirming` shows that area as already chosen and lets Return confirm + /// it — the fast path after "New Session": drag for a new area, or press Return to + /// keep the saved one. + public func pick( + confirming: CaptureRegion? = nil, + completion: @escaping @MainActor (CaptureRegion?) -> Void + ) { if self.completion != nil { finish(region: nil) } + self.confirmingRegion = confirming self.completion = completion presentOverlays() + if let confirming { + showConfirmingSelection(confirming) + } + } + + private var confirmingRegion: CaptureRegion? + + /// Shows the saved area as a pre-selection on the overlay for its display. + private func showConfirmingSelection(_ region: CaptureRegion) { + for window in windows where window.coveringScreen.frame.contains( + CGPoint(x: region.rect.midX, y: window.coveringScreen.frame.midY)) + { + let local = CGRect( + x: region.rect.minX - window.coveringScreen.frame.minX, + y: region.rect.minY, + width: region.rect.width, + height: region.rect.height + ) + window.updateSelection( + localRect: local, sizeText: "\(region.summary) · Return keeps it") + } } private func presentOverlays() { @@ -72,7 +100,11 @@ public final class RegionPickerController { switch type { case .keyDown: if keyCode == 53 { // kVK_Escape - finish(region: nil) + finish(region: confirmingRegion) + return true + } + if keyCode == 36, let confirmingRegion { // Return confirms the saved area + finish(region: confirmingRegion) return true } return false diff --git a/Sources/Shotdeck/SessionsWindowView.swift b/Sources/Shotdeck/SessionsWindowView.swift index 5dfde77..811a636 100644 --- a/Sources/Shotdeck/SessionsWindowView.swift +++ b/Sources/Shotdeck/SessionsWindowView.swift @@ -146,15 +146,51 @@ struct SessionsWindowView: View { .help(showInspector ? "Hide the inspector" : "Show the inspector") .accessibilityLabel(showInspector ? "Hide the inspector" : "Show the inspector") + // What the next capture takes, in the same place as the verbs. + Menu { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Button { + Task { + await model.chooseCaptureScope(scope) + await model.captureNow() + } + } label: { + Text("\(scope.menuTitle) — capture now") + } + } + Divider() + Button("Choose New Area…") { + Task { await model.rePickRegion() } + } + } label: { + HStack(spacing: 4) { + Image(systemName: scopeSymbol) + Text("\(model.captureScope.displayName) · \(scopeDetail)") + .lineLimit(1) + } + } + .menuStyle(.borderlessButton) + .fixedSize() + .help("What Capture takes") + .accessibilityLabel("Capture: \(model.captureTargetDescription)") + + if model.captureScope == .area { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + .fixedSize() + .help("Pick a new area to capture") + } + Button { - Task { await model.startNewSession() } + Task { await model.newSession() } } label: { Label("New Session", systemImage: "plus.square.on.square") } .keyboardShortcut("n", modifiers: .command) - .disabled(!model.canStartNewSession) + .disabled(model.isSending) .fixedSize() - .help("Keep this session and start a fresh one (⌘N)") + .help("Keep this session and start a fresh one, then ask where to capture (⌘N)") Button { Task { await model.captureNow() } @@ -199,6 +235,29 @@ struct SessionsWindowView: View { model.transport == .oneDrive ? "Save…" : "Send…" } + private var scopeSymbol: String { + switch model.captureScope { + case .area: return "rectangle.dashed" + case .window: return "macwindow" + case .browser: return "safari" + case .screen: return "display" + } + } + + /// Short form for the header: the area size, or what a window scope grabs. + private var scopeDetail: String { + switch model.captureScope { + case .area: + guard let region = model.region else { return "not set" } + return "\(Int(region.rect.width)) × \(Int(region.rect.height))" + case .window: return "front window" + case .browser: return "browser" + case .screen: + guard let region = model.region else { return "all" } + return "Display \(region.displayNumber)" + } + } + // MARK: - Pages @ViewBuilder diff --git a/Sources/Shotdeck/SettingsView.swift b/Sources/Shotdeck/SettingsView.swift index 3d77b95..a7391ba 100644 --- a/Sources/Shotdeck/SettingsView.swift +++ b/Sources/Shotdeck/SettingsView.swift @@ -13,6 +13,28 @@ struct SettingsView: View { var body: some View { Form { Section("Capture") { + LabeledContent("What to capture") { + Picker("What to capture", selection: scopeBinding) { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Text(scope.displayName).tag(scope) + } + } + .labelsHidden() + .pickerStyle(.segmented) + .frame(maxWidth: 240) + } + + LabeledContent("Saved area") { + HStack(spacing: 8) { + Text(areaSummary) + .foregroundStyle(.secondary) + .lineLimit(1) + Button("Choose…") { + Task { await model.rePickRegion() } + } + } + } + LabeledContent("Capture shortcut") { Button { armHotkeyRecorder() @@ -23,15 +45,12 @@ struct SettingsView: View { } } - LabeledContent("Area") { - HStack(spacing: 8) { - Text(areaSummary) - .foregroundStyle(.secondary) - Button("Choose…") { - Task { await model.rePickRegion() } - } - } - } + Toggle("Ask what to capture on New Session", isOn: askOnNewSessionBinding) + + Text("Window and Browser pick the window under the pointer, with the app named. New Session keeps this session and re-asks for the area.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } Section("Sending") { @@ -96,9 +115,40 @@ struct SettingsView: View { .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } + + Section("Updates") { + Toggle("Install updates automatically", isOn: autoInstallBinding) + + LabeledContent(updateSummary) { + Button(model.isCheckingForUpdates ? "Checking…" : "Check Now") { + model.checkForUpdates() + } + .disabled(model.isCheckingForUpdates) + } + + Text("Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + if let update = model.updateAvailable { + LabeledContent("Ready to install") { + Button("Restart Now") { model.installUpdate() } + } + Text("Redline \(update.version) is downloaded and waiting.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + Section { + LabeledContent("Redline \(model.appVersion)") { + Button("Quit Redline") { NSApp.terminate(nil) } + } + } } .formStyle(.grouped) - .frame(width: 460, height: 520) + .frame(width: 460, height: 820) .controlSize(.regular) .onDisappear { disarmHotkeyRecorder() } } @@ -106,8 +156,7 @@ struct SettingsView: View { // MARK: - Rows private var areaSummary: String { - guard let region = model.region else { return "Not chosen" } - return "\(Int(region.rect.width)) × \(Int(region.rect.height))" + model.region?.summary ?? "Not chosen" } private var oneDrivePath: String { @@ -152,6 +201,32 @@ struct SettingsView: View { // MARK: - Bindings + private var scopeBinding: Binding { + Binding( + get: { model.captureScope }, + set: { scope in Task { await model.chooseCaptureScope(scope) } } + ) + } + + private var askOnNewSessionBinding: Binding { + Binding( + get: { model.askWhatToCaptureOnNewSession }, + set: { model.setAskWhatToCaptureOnNewSession($0) } + ) + } + + private var autoInstallBinding: Binding { + Binding( + get: { model.autoInstallUpdates }, + set: { model.setAutoInstallUpdates($0) } + ) + } + + private var updateSummary: String { + let basis = model.updateStatusMessage ?? "Version \(model.appVersion)" + return basis + } + private var transportBinding: Binding { Binding(get: { model.transport }, set: { model.chooseTransport($0) }) } @@ -236,7 +311,7 @@ extension AppModel: SettingsWindowPresenting { window.title = "Redline Settings" window.styleMask = [.titled, .closable] window.isReleasedWhenClosed = false - window.setContentSize(NSSize(width: 460, height: 520)) + window.setContentSize(NSSize(width: 460, height: 820)) window.center() let controller = NSWindowController(window: window) Self.settingsWindowController = controller diff --git a/Sources/Shotdeck/WindowPickerController.swift b/Sources/Shotdeck/WindowPickerController.swift new file mode 100644 index 0000000..321ea23 --- /dev/null +++ b/Sources/Shotdeck/WindowPickerController.swift @@ -0,0 +1,252 @@ +import AppKit +import ShotdeckCore + +/// Hides Redline's own windows while the user is choosing what to capture, then puts +/// them back. The popover would otherwise sit on top of the thing being picked and, +/// worse, end up inside the screenshot. +@MainActor +enum RedlineWindows { + private static var hidden: [NSWindow] = [] + + static func hideForPicking() { + hidden = NSApp.windows.filter { window in + window.isVisible && !(window is RegionPickerWindow) + } + for window in hidden { + window.orderOut(nil) + } + } + + static func restoreAfterPicking() { + for window in hidden where !window.isVisible { + window.orderFront(nil) + } + hidden = [] + } +} + +/// Highlights the window under the pointer and captures the one the user clicks — +/// an app window, a browser window with its active tab, or the whole screen when the +/// pointer is over the desktop. +@MainActor +public final class WindowPickerController { + private var windows: [RegionPickerWindow] = [] + private var monitor: Any? + private var hoverTimer: Timer? + private var completion: (@MainActor (CaptureTarget?) -> Void)? + private var candidates: [WindowCandidate] = [] + private var primaryHeight: CGFloat = 0 + private var hovered: WindowCandidate? + private var hoveredScreen: NSScreen? + + public init() {} + + /// Presents the picker. The completion receives the chosen target, or nil when the + /// user pressed Escape. + public func pick( + onlyBrowsers: Bool = false, + completion: @escaping @MainActor (CaptureTarget?) -> Void + ) { + if self.completion != nil { + finish(target: nil) + } + self.completion = completion + self.primaryHeight = NSScreen.screens.first?.frame.height ?? 0 + + let all = ScreenCapturer.onScreenWindows().filter { candidate in + candidate.layer == 0 + && candidate.ownerBundleID != CaptureTargetResolver.ownBundleID + && candidate.frame.width >= 40 + && candidate.frame.height >= 40 + } + self.candidates = onlyBrowsers + ? all.filter { candidate in + guard let bundle = candidate.ownerBundleID else { return false } + return CaptureTargetResolver.browserBundleIDs.contains(bundle) + } + : all + + presentOverlays() + } + + // MARK: - Overlays + + private func presentOverlays() { + let screens = NSScreen.screens + guard !screens.isEmpty else { + finish(target: nil) + return + } + windows = screens.map { RegionPickerWindow(screen: $0) } + for window in windows { + window.orderFrontRegardless() + } + let mouse = NSEvent.mouseLocation + let keyWindow = windows.first { $0.coveringScreen.frame.contains(mouse) } ?? windows[0] + keyWindow.makeKey() + + // A timer drives the highlight from the real pointer position: mouse-moved + // events are only delivered to the key window, and the overlay must track the + // pointer even over another app's window. + hoverTimer?.invalidate() + hoverTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 60.0, repeats: true) { + [weak self] _ in + MainActor.assumeIsolated { + self?.updateHover(at: NSEvent.mouseLocation) + } + } + + monitor = NSEvent.addLocalMonitorForEvents( + matching: [.mouseMoved, .leftMouseDown, .keyDown] + ) { [weak self] event in + guard let self else { return event } + let type = event.type + let keyCode: UInt16 = (type == .keyDown) ? event.keyCode : 0 + let locationInWindow = event.locationInWindow + let windowNumber = event.windowNumber + let consume = MainActor.assumeIsolated { + let location = self.globalAppKitLocation( + locationInWindow: locationInWindow, windowNumber: windowNumber) + return self.handle(type: type, keyCode: keyCode, location: location) + } + return consume ? nil : event + } + + updateHover(at: mouse) + } + + private func handle(type: NSEvent.EventType, keyCode: UInt16, location: NSPoint?) -> Bool { + switch type { + case .keyDown: + if keyCode == 53 { // Escape + finish(target: nil) + return true + } + return false + case .mouseMoved: + updateHover(at: location ?? NSEvent.mouseLocation) + return false + case .leftMouseDown: + if let target = targetUnderPointer(at: location ?? NSEvent.mouseLocation) { + finish(target: target) + } + return true + default: + return false + } + } + + // MARK: - Hover + + private func updateHover(at point: NSPoint) { + let screen = NSScreen.screens.first { $0.frame.contains(point) } + let candidate = candidate(at: point) + hovered = candidate + hoveredScreen = screen + + let highlightRect = candidate.map { appKitRect($0.frame) } ?? screen?.frame + let chip: String + if let candidate { + let app = appName(for: candidate) + let title = windowTitle(for: candidate) + chip = title.isEmpty ? app : "\(app) — \(title)" + } else { + chip = "Entire Screen" + } + + for window in windows { + guard let windowScreen = windows.first(where: { $0 === window })?.coveringScreen + else { continue } + guard let highlightRect, windowScreen.frame.intersects(highlightRect) else { + window.updateSelection(localRect: nil, sizeText: nil) + continue + } + let local = CGRect( + x: highlightRect.minX - windowScreen.frame.minX, + y: highlightRect.minY - windowScreen.frame.minY, + width: highlightRect.width, + height: highlightRect.height + ) + window.updateSelection(localRect: local, sizeText: chip) + } + } + + private func targetUnderPointer(at point: NSPoint) -> CaptureTarget? { + if let candidate = candidate(at: point) { + return .window( + windowID: candidate.windowID, + frame: candidate.frame, + displayID: CaptureTargetResolver.displayID(containing: candidate.frame) + ) + } + guard let screen = NSScreen.screens.first(where: { $0.frame.contains(point) }) else { + return nil + } + return .display(displayID: displayID(for: screen)) + } + + private func candidate(at point: NSPoint) -> WindowCandidate? { + candidates.first { candidate in + appKitRect(candidate.frame).contains(point) + } + } + + // MARK: - Geometry and labels + + private func appKitRect(_ cgRect: CGRect) -> CGRect { + CGRect( + x: cgRect.minX, + y: primaryHeight - cgRect.minY - cgRect.height, + width: cgRect.width, + height: cgRect.height + ) + } + + private func displayID(for screen: NSScreen) -> UInt32 { + (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)? + .uint32Value ?? CGMainDisplayID() + } + + private func appName(for candidate: WindowCandidate) -> String { + guard let bundle = candidate.ownerBundleID, + let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundle) + else { return "Window" } + return FileManager.default.displayName(atPath: url.path) + .replacingOccurrences(of: ".app", with: "") + } + + private func windowTitle(for candidate: WindowCandidate) -> String { + guard let raw = CGWindowListCopyWindowInfo([.optionIncludingWindow], candidate.windowID) + as? [[String: Any]], let first = raw.first + else { return "" } + return first[kCGWindowName as String] as? String ?? "" + } + + private func globalAppKitLocation(locationInWindow: NSPoint, windowNumber: Int) -> NSPoint? { + if let window = windows.first(where: { $0.windowNumber == windowNumber }) { + return window.convertPoint(toScreen: locationInWindow) + } + if windowNumber != 0, let window = NSApp.window(withWindowNumber: windowNumber) { + return window.convertPoint(toScreen: locationInWindow) + } + return NSEvent.mouseLocation + } + + // MARK: - Finish + + private func finish(target: CaptureTarget?) { + hoverTimer?.invalidate() + hoverTimer = nil + if let monitor { + NSEvent.removeMonitor(monitor) + } + monitor = nil + for window in windows { + window.orderOut(nil) + } + windows = [] + let completion = self.completion + self.completion = nil + completion?(target) + } +} diff --git a/Sources/ShotdeckCore/Capture/CaptureRegion.swift b/Sources/ShotdeckCore/Capture/CaptureRegion.swift index d5a7ab2..adf544f 100644 --- a/Sources/ShotdeckCore/Capture/CaptureRegion.swift +++ b/Sources/ShotdeckCore/Capture/CaptureRegion.swift @@ -55,4 +55,20 @@ public struct CaptureRegion: Codable, Sendable, Equatable { /// Persisted in UserDefaults under this key BY THE APP (WP-4a), never by this type. public static let defaultsKey = "ai.flowmaster.shotdeck.region" + + /// 1-based position of this region's display in the current screen list; 1 when the + /// display is no longer attached. + public var displayNumber: Int { + let match = NSScreen.screens.firstIndex { screen in + let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] + as? NSNumber)?.uint32Value + return id == displayID + } + return (match ?? 0) + 1 + } + + /// "800 × 600 on Display 1" — the line the popover shows under the capture control. + public var summary: String { + String(format: "%.0f × %.0f on Display %d", rect.width, rect.height, displayNumber) + } } diff --git a/Sources/ShotdeckCore/Capture/CaptureScope.swift b/Sources/ShotdeckCore/Capture/CaptureScope.swift new file mode 100644 index 0000000..0efd925 --- /dev/null +++ b/Sources/ShotdeckCore/Capture/CaptureScope.swift @@ -0,0 +1,79 @@ +import Foundation + +/// What a capture takes a picture of. +/// +/// The choice belongs to the session being captured into: it is stored once and copied +/// to the next session, so a review run keeps capturing the same kind of thing until +/// the user says otherwise. Choosing anything other than `.area` never clears the saved +/// area — it comes back when Area is chosen again. +public enum CaptureScope: String, Codable, Sendable, CaseIterable { + case area + case window + case browser + case screen + + /// Label for the segmented control and the window's menu. + public var displayName: String { + switch self { + case .area: return "Area" + case .window: return "Window" + case .browser: return "Browser" + case .screen: return "Screen" + } + } + + /// The longer menu item wording (window picker). + public var menuTitle: String { + switch self { + case .area: return "Saved Area" + case .window: return "Front Window" + case .browser: return "Browser Page" + case .screen: return "Whole Screen" + } + } + + /// Sentence shown under the control: what pressing Capture will take. + public func targetDescription(savedArea: CaptureRegion?) -> String { + switch self { + case .area: + guard let savedArea else { return "No area saved yet — choose one first" } + return savedArea.summary + case .window: + return "The frontmost window when you capture" + case .browser: + return "The frontmost browser window when you capture" + case .screen: + guard let savedArea else { return "The display with the frontmost window" } + return "All of Display \(savedArea.displayNumber)" + } + } +} + +/// Persistence for the capture choice. Stored separately from the chosen area so +/// switching scope never destroys the area. +public enum CaptureSettings { + public static let scopeKey = "ai.flowmaster.shotdeck.captureScope" + public static let askOnNewSessionKey = "ai.flowmaster.shotdeck.askScopeOnNewSession" + + public static func scope(defaults: UserDefaults = .standard) -> CaptureScope { + guard let raw = defaults.string(forKey: scopeKey), + let scope = CaptureScope(rawValue: raw) + else { return .area } + return scope + } + + public static func setScope(_ scope: CaptureScope, defaults: UserDefaults = .standard) { + defaults.set(scope.rawValue, forKey: scopeKey) + } + + /// Whether "New Session…" asks what to capture before starting. Off means it + /// starts immediately with the current choice. + public static func askOnNewSession(defaults: UserDefaults = .standard) -> Bool { + guard defaults.object(forKey: askOnNewSessionKey) != nil else { return true } + return defaults.bool(forKey: askOnNewSessionKey) + } + + public static func setAskOnNewSession(_ value: Bool, defaults: UserDefaults = .standard) { + defaults.set(value, forKey: askOnNewSessionKey) + } +} diff --git a/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift b/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift new file mode 100644 index 0000000..faf1c96 --- /dev/null +++ b/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift @@ -0,0 +1,125 @@ +import CoreGraphics +import Foundation + +/// One on-screen window as the capture resolver sees it. Kept as plain data so the +/// choice logic is testable without a window server. +public struct WindowCandidate: Sendable, Equatable { + public let windowID: UInt32 + public let ownerBundleID: String? + public let ownerPID: Int32 + public let frame: CGRect + public let layer: Int + + public init( + windowID: UInt32, + ownerBundleID: String?, + ownerPID: Int32, + frame: CGRect, + layer: Int + ) { + self.windowID = windowID + self.ownerBundleID = ownerBundleID + self.ownerPID = ownerPID + self.frame = frame + self.layer = layer + } +} + +/// What a capture will take: one region of a display, one whole display, or one window. +public enum CaptureTarget: Sendable, Equatable { + case region(CaptureRegion) + case display(displayID: UInt32) + case window(windowID: UInt32, frame: CGRect, displayID: UInt32) +} + +/// Chooses the capture target for a scope from the windows that are on screen. +/// +/// Candidates arrive front-to-back (the order the window server reports), which is what +/// makes "the front window" well defined. Redline's own windows are never candidates, +/// so choosing Window never captures the app's own panel. +public enum CaptureTargetResolver { + /// Bundles whose front window counts as a browser page. + public static let browserBundleIDs: Set = [ + "com.apple.Safari", + "com.google.Chrome", + "com.google.Chrome.canary", + "com.microsoft.edgemac", + "com.brave.Browser", + "company.thebrowser.Browser", + "org.mozilla.firefox", + "com.vivaldi.Vivaldi", + "com.operasoftware.Opera", + ] + + /// Redline's own bundle identifier — never a capture target. + public static let ownBundleID = "ai.flowmaster.shotdeck" + + public static func resolve( + scope: CaptureScope, + savedArea: CaptureRegion?, + frontmostPID: Int32, + candidates: [WindowCandidate] + ) throws -> CaptureTarget { + let usable = candidates.filter { candidate in + candidate.layer == 0 + && candidate.ownerBundleID != ownBundleID + && candidate.frame.width >= 40 + && candidate.frame.height >= 40 + } + + switch scope { + case .area: + guard let savedArea else { throw ShotdeckError.noRegionRemembered } + return .region(savedArea) + + case .screen: + if let savedArea { + return .display(displayID: savedArea.displayID) + } + guard let window = usable.first else { throw ShotdeckError.noFrontWindow } + return .display(displayID: displayID(containing: window.frame)) + + case .window: + let ownAppFirst = usable.first { $0.ownerPID == frontmostPID } + guard let window = ownAppFirst ?? usable.first else { + throw ShotdeckError.noFrontWindow + } + return .window( + windowID: window.windowID, + frame: window.frame, + displayID: displayID(containing: window.frame) + ) + + case .browser: + guard let window = usable.first(where: { + guard let bundle = $0.ownerBundleID else { return false } + return browserBundleIDs.contains(bundle) + }) else { + throw ShotdeckError.noBrowserWindow + } + return .window( + windowID: window.windowID, + frame: window.frame, + displayID: displayID(containing: window.frame) + ) + } + } + + /// The display whose bounds contain the window's centre; the main display when a + /// window straddles two screens and belongs to neither cleanly. + public static func displayID(containing frame: CGRect) -> UInt32 { + let centre = CGPoint(x: frame.midX, y: frame.midY) + var count: UInt32 = 0 + guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else { + return CGMainDisplayID() + } + var displays = [CGDirectDisplayID](repeating: 0, count: Int(count)) + guard CGGetActiveDisplayList(count, &displays, &count) == .success else { + return CGMainDisplayID() + } + for display in displays.prefix(Int(count)) where CGDisplayBounds(display).contains(centre) { + return display + } + return CGMainDisplayID() + } +} diff --git a/Sources/ShotdeckCore/Capture/ScreenCapturer.swift b/Sources/ShotdeckCore/Capture/ScreenCapturer.swift index b6158fc..c5c06de 100644 --- a/Sources/ShotdeckCore/Capture/ScreenCapturer.swift +++ b/Sources/ShotdeckCore/Capture/ScreenCapturer.swift @@ -18,6 +18,135 @@ public struct ScreenCapturer: Sendable { /// Does NOT prompt. Reports the current Screen Recording grant. public static var isScreenRecordingGranted: Bool { CGPreflightScreenCaptureAccess() } + /// Captures whatever the given scope points at, resolving it right now. + public func capture( + _ scope: CaptureScope, + savedArea: CaptureRegion? + ) async throws -> CapturedImage { + guard Self.isScreenRecordingGranted else { + throw ShotdeckError.screenRecordingNotGranted + } + let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 + let target = try CaptureTargetResolver.resolve( + scope: scope, + savedArea: savedArea, + frontmostPID: frontmostPID, + candidates: Self.onScreenWindows() + ) + return try await capture(target) + } + + /// Captures one resolved target. A window is captured window-only (so an overlapping + /// window never ends up in a review shot); a region or a display goes through the + /// display path. + public func capture(_ target: CaptureTarget) async throws -> CapturedImage { + guard Self.isScreenRecordingGranted else { + throw ShotdeckError.screenRecordingNotGranted + } + switch target { + case .region(let region): + return try await capture(region) + case .display(let displayID): + let bounds = CGDisplayBounds(displayID) + return try await capture( + CaptureRegion( + displayID: displayID, rect: bounds, + capturedScale: Self.backingScale(for: displayID))) + case .window(let windowID, let frame, let displayID): + return try await captureWindow( + windowID: windowID, frame: frame, displayID: displayID) + } + } + + /// On-screen windows, front-most first, as plain data for the resolver. + public static func onScreenWindows() -> [WindowCandidate] { + guard let raw = CGWindowListCopyWindowInfo( + [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID + ) as? [[String: Any]] else { return [] } + + return raw.compactMap { entry in + guard let windowID = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value, + let ownerPID = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value, + let boundsDict = entry[kCGWindowBounds as String] as? [String: Any], + let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue + else { return nil } + let frame = CGRect( + x: boundsDict["X"] as? Double ?? 0, + y: boundsDict["Y"] as? Double ?? 0, + width: boundsDict["Width"] as? Double ?? 0, + height: boundsDict["Height"] as? Double ?? 0 + ) + return WindowCandidate( + windowID: windowID, + ownerBundleID: bundleIdentifier(forPID: ownerPID), + ownerPID: ownerPID, + frame: frame, + layer: layer + ) + } + } + + private static func bundleIdentifier(forPID pid: Int32) -> String? { + NSRunningApplication(processIdentifier: pid)?.bundleIdentifier + } + + private static func backingScale(for displayID: UInt32) -> CGFloat { + guard let mode = CGDisplayCopyDisplayMode(displayID), mode.width > 0 else { return 2 } + return CGFloat(mode.pixelWidth) / CGFloat(mode.width) + } + + /// Captures a single window through ScreenCaptureKit's window filter, at the display's + /// backing scale, without the window server compositing anything on top of it. + private func captureWindow( + windowID: UInt32, + frame: CGRect, + displayID: UInt32 + ) async throws -> CapturedImage { + let content: SCShareableContent + do { + content = try await SCShareableContent.excludingDesktopWindows( + false, onScreenWindowsOnly: true) + } catch { + throw ShotdeckError.captureFailed(underlying: error.localizedDescription) + } + guard let window = content.windows.first(where: { $0.windowID == windowID }) else { + throw ShotdeckError.noFrontWindow + } + + let scale = Self.backingScale(for: displayID) + let filter = SCContentFilter(desktopIndependentWindow: window) + let configuration = SCStreamConfiguration() + configuration.width = Int((frame.width * scale).rounded()) + configuration.height = Int((frame.height * scale).rounded()) + configuration.showsCursor = false + configuration.scalesToFit = false + + let cgImage: CGImage + do { + cgImage = try await SCScreenshotManager.captureImage( + contentFilter: filter, configuration: configuration) + } catch { + throw ShotdeckError.captureFailed(underlying: error.localizedDescription) + } + + let data = NSMutableData() + guard let dest = CGImageDestinationCreateWithData( + data, UTType.png.identifier as CFString, 1, nil + ) else { + throw ShotdeckError.captureFailed(underlying: "could not create PNG image destination") + } + CGImageDestinationAddImage(dest, cgImage, nil) + guard CGImageDestinationFinalize(dest) else { + throw ShotdeckError.captureFailed(underlying: "PNG encoding failed to finalize") + } + return CapturedImage( + pngData: data as Data, + pixelWidth: cgImage.width, + pixelHeight: cgImage.height, + scale: scale + ) + } + /// Captures `region` at the display's true backing scale. Throws /// `.screenRecordingNotGranted` when the grant is absent — never requests it. public func capture(_ region: CaptureRegion) async throws -> CapturedImage { diff --git a/Sources/ShotdeckCore/Model/ShotdeckError.swift b/Sources/ShotdeckCore/Model/ShotdeckError.swift index ab5b063..92e5687 100644 --- a/Sources/ShotdeckCore/Model/ShotdeckError.swift +++ b/Sources/ShotdeckCore/Model/ShotdeckError.swift @@ -11,6 +11,8 @@ public enum ShotdeckError: Error, LocalizedError, Sendable { case airDropUnavailable case noCommentedReturns case oneDriveFolderUnavailable(path: String) + case noFrontWindow + case noBrowserWindow public var errorDescription: String? { switch self { @@ -34,6 +36,10 @@ public enum ShotdeckError: Error, LocalizedError, Sendable { return "None of the returned PDFs have comments on them." case .oneDriveFolderUnavailable(let path): return "Your OneDrive folder is not available: \(path). Check that OneDrive is signed in, or choose another folder in Settings." + case .noFrontWindow: + return "There is no front window to capture. Click the window you want first, or choose Area." + case .noBrowserWindow: + return "No browser window is open. Open the page you want, or choose Window or Area." } } } diff --git a/Sources/ShotdeckCore/Support/UpdateSettings.swift b/Sources/ShotdeckCore/Support/UpdateSettings.swift new file mode 100644 index 0000000..44bac3d --- /dev/null +++ b/Sources/ShotdeckCore/Support/UpdateSettings.swift @@ -0,0 +1,19 @@ +import Foundation + +/// Whether Redline installs a staged update by itself. +/// +/// On by default: updates download in the background and install the next time the app +/// has nothing unsent, so the tool stays current without anyone chasing a menu row. +/// Off means the staged update waits for the "Update to X" action. +public enum UpdateSettings { + public static let autoInstallKey = "ai.flowmaster.shotdeck.autoInstallUpdates" + + public static func autoInstall(defaults: UserDefaults = .standard) -> Bool { + guard defaults.object(forKey: autoInstallKey) != nil else { return true } + return defaults.bool(forKey: autoInstallKey) + } + + public static func setAutoInstall(_ value: Bool, defaults: UserDefaults = .standard) { + defaults.set(value, forKey: autoInstallKey) + } +} diff --git a/Tests/ShotdeckCoreTests/CaptureScopeTests.swift b/Tests/ShotdeckCoreTests/CaptureScopeTests.swift new file mode 100644 index 0000000..035ed4f --- /dev/null +++ b/Tests/ShotdeckCoreTests/CaptureScopeTests.swift @@ -0,0 +1,165 @@ +import CoreGraphics +import Foundation +import ShotdeckCore +import Testing + +// Which window a capture takes, for each scope — pure logic over the window list the +// window server reports, so it is testable without a display session. + +private func window( + id: UInt32, + bundle: String?, + pid: Int32 = 100, + frame: CGRect = CGRect(x: 100, y: 100, width: 800, height: 600), + layer: Int = 0 +) -> WindowCandidate { + WindowCandidate( + windowID: id, ownerBundleID: bundle, ownerPID: pid, frame: frame, layer: layer) +} + +@Test +func windowScopeTakesTheFrontWindowOfTheFrontApp() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", pid: 10), + window(id: 2, bundle: "com.apple.Terminal", pid: 20), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 20, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func windowScopeFallsBackToTheFrontmostWindowOfAnyApp() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", pid: 10), + window(id: 2, bundle: "com.apple.Terminal", pid: 20), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 99, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 1) +} + +@Test +func redlineNeverCapturesItself() throws { + let candidates = [ + window(id: 1, bundle: CaptureTargetResolver.ownBundleID, pid: 5), + window(id: 2, bundle: "com.apple.Safari", pid: 10), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 5, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func chromeAndDesktopWindowsAreNotCandidates() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.dock", layer: 20), + window(id: 2, bundle: "com.apple.WindowManager", layer: 8), + window(id: 3, bundle: "com.apple.Safari"), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 3) +} + +@Test +func tinyWindowsAreIgnored() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", frame: CGRect(x: 0, y: 0, width: 20, height: 20)), + window(id: 2, bundle: "com.apple.Terminal"), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func browserScopeTakesTheFrontBrowserWindow() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Terminal", pid: 10), + window(id: 2, bundle: "com.google.Chrome", pid: 11), + window(id: 3, bundle: "com.apple.Safari", pid: 12), + ] + let target = try CaptureTargetResolver.resolve( + scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func browserScopeSaysSoWhenNoBrowserIsOpen() { + let candidates = [window(id: 1, bundle: "com.apple.Terminal")] + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates) + } +} + +@Test +func windowScopeSaysSoWhenThereIsNoWindow() { + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 10, + candidates: [window(id: 1, bundle: "com.apple.dock", layer: 20)]) + } +} + +@Test +func areaScopeUsesTheSavedAreaAndSaysWhenThereIsNone() throws { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200), + capturedScale: 2) + let target = try CaptureTargetResolver.resolve( + scope: .area, savedArea: area, frontmostPID: 0, candidates: []) + #expect(target == .region(area)) + + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .area, savedArea: nil, frontmostPID: 0, candidates: []) + } +} + +@Test +func screenScopeUsesTheAreaDisplay() throws { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200), + capturedScale: 2) + let target = try CaptureTargetResolver.resolve( + scope: .screen, savedArea: area, frontmostPID: 0, candidates: []) + #expect(target == .display(displayID: area.displayID)) +} + +@Test +func captureScopeDescriptionsNameWhatWillBeTaken() { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 0, y: 0, width: 800, height: 600), + capturedScale: 2) + #expect(CaptureScope.area.targetDescription(savedArea: area).contains("800 × 600")) + #expect(CaptureScope.area.targetDescription(savedArea: nil).contains("No area")) + #expect(CaptureScope.window.targetDescription(savedArea: area).contains("frontmost window")) + #expect(CaptureScope.browser.targetDescription(savedArea: area).contains("browser")) + #expect(CaptureScope.screen.targetDescription(savedArea: area).contains("Display")) +} diff --git a/design/ux-rework/redline-ux-v2.html b/design/ux-rework/redline-ux-v2.html new file mode 100644 index 0000000..0c3db8f --- /dev/null +++ b/design/ux-rework/redline-ux-v2.html @@ -0,0 +1,343 @@ + + + + + +Redline UX v2 + + + + +
+

Redline v2 — decide what you capture first

+

The popover now starts with the capture decision (what, and where), then the pages, then the two verbs. Settings has one visible door: the gear in the popover header. Filler lines are gone; a status line appears only when something happened. Updates install themselves.

+
+ + + + + + + + + + + + + + +
+
1Menu-bar popover340 pt · controlSize small · capture decision → pages → verbs
+
+ +
1a · Idle, empty session · light
+
◫Sat 31 Oct 13:05
+
+
  • Header has exactly two icons: details (opens the window on Lane) and Settings. No “…” menu.
  • The capture box is the first decision on screen; Choose Area… is always one click away.
  • No footer. Nothing is printed unless it is news.
+
+ +
1b · Pages present + one return · dark
+
◫ 3Sat 31 Oct 13:05
+
+
  • The Capture button wears the scope icon, so what ⌥⇧2 will grab is never ambiguous.
  • Choosing a non-area scope keeps the saved area (“area kept”) — switching back to Area restores it.
+
+ +
1c · New Session… — the capture decision at the moment of starting · light
+
◫ 3Sat 31 Oct 13:06
+
+
  • New Session… never starts silently: it shows scope, area and inherited details in place of the pages, with Start Session as the default button (Return).
  • Choose Area… here dismisses the popover, runs the picker, and comes back to this step with the new size.
+
+ +
1d · Capture-scope menu from the keyboard (⌥⇧1) · dark
+
◫Sat 31 Oct 13:06
+
+
  • ⌥⇧1 opens this menu where the pointer is; one keystroke captures with that scope and makes it the session’s scope.
  • Browser Page grabs the front browser window’s page area (Safari, Chrome, Arc, Edge); the tab strip and toolbar are cropped.
+
+ +
1e · Update installed in the background · light
+
◫Sat 31 Oct 13:07
+
+
DEV03 · v1.4.2 (41)
a1b2c3d4 · Ben Hippler
+
Redline 0.6.0 is ready — restarts after you sendRestart Now
+
Capture ⌥⇧2Send 2 pages
+
+
  • One line, only while it matters. It never interrupts a session with unsent pages.
  • Cropped to the relevant part for this mock.
+
+ +
+
+ + +
+
2Redline window · headerscope and area are part of the session, shown where the verbs are
+
+
2a · Current session · light
+
+
+
DEV03 Current
3 pages · not sent
+ Area · 800 × 600 + Choose Area… + Capture + New Session… + Send 3 pages +
+
Today
DEV03 13:05
3 pages · not sent
OMS test lane 11:48
2 pages marked
+
1
2
3
+
+
  • No gear here: Settings is ⌘, (and the popover gear) — one surface, one door.
  • Cropped to the header and a slice of the content for this mock.
+
+
2b · Same, dark, Browser scope
+
+
+
DEV03 Current
3 pages · not sent
+ Browser Page + Capture + New Session… + Send 3 pages +
+
+
  • With a non-area scope, Choose Area… disappears from the header; it lives in the scope menu as “Choose New Area…”.
+
+
+
+ + +
+
3Settings460 pt · one window, reached only from the popover gear or ⌘,
+
+
3a · light
+
+
Redline Settings
+
+
Capture
+
+
CaptureSaved Area
+
Saved area800 × 600 on Display 1Choose…
+
Capture shortcut⌥⇧2
+
Capture menu shortcut⌥⇧1
+
Ask what to capture on New Session
+
+
Sending
+
+
Send withAirDropOneDrive
+
Save PDFs to~/DesktopChoose…
+
Watch for returns in~/DownloadsChoose…
+
+
Sessions
+
+
Delete sessions older thanNever
+
20 sessions on this MacClean Up Now…
+
+
Deleting removes Redline’s own screenshots only. PDFs you sent stay where they are.
+
Updates
+
+
Install updates automatically
+
Version 0.5.0 · checked 13:02Check Now
+
+
Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.
+
Redline 0.5.0Quit Redline
+
+
+
3b · dark · update ready
+
+
Redline Settings
+
+
Updates
+
+
Install updates automatically
+
0.6.0 downloaded · installs after your next sendRestart Now
+
+
Turned off: Redline still checks every 6 hours and shows “Update to 0.6.0” here and in the popover, but waits for you.
+
Capture
+
+
CaptureFront Window
+
Saved area800 × 600 on Display 1Choose…
+
+
+
+
  • Quit lives here (and ⌘Q in the popover): the popover has no menu left to hide it in.
  • 3b is cropped to the changed groups.
+
+
+
+ + +
+
4Labels, keys, states
+
+

Strings

+ + + + + + + + + + + +
PlaceExact label
Popover header iconsEdit review details (tooltip + VoiceOver), Settings (tooltip “Settings (⌘,)”)
Scope segmented control (VoiceOver “Capture”)Area · Window · Browser · Screen
Target lineArea: 800 × 600 on Display 1 + Choose Area… · Window: Front window when you press ⌥⇧2 · Browser: Front browser page when you press ⌥⇧2 · Screen: Display 1 · 2560 × 1440; non-area scopes add area kept: 800 × 600
Empty pagesNo pages yet / ⌥⇧2 captures the area|window|page|screen
VerbsCapture ⌥⇧2, Send (empty, disabled) / Send 3 pages, OneDrive: Save 3 pages; New Session…, Open Redline
New-session stepTitle New session; subtitle The current 3 pages are kept as a past session.; groups Capture, Review details + Edit…; buttons Cancel, Start Session
Scope menu (⌥⇧1)Header Capture; Saved Area (1), Front Window (2), Browser Page (3), Whole Screen (4), Choose New Area… (A)
Status line (only when news)Captured page 4 · Sent · 3 pages · Saved to OneDrive · 3 pages · OMS test lane came back · 2 pages marked + Open · No front window to capture · No browser window in front · Redline 0.6.0 is ready — restarts after you send + Restart Now
SettingsGroups Capture, Sending, Sessions, Updates; rows as in 3a; captions as in 3a/3b; footer Quit Redline
+

Keyboard

+

Global: ⌥⇧2 capture with the session’s scope · ⌥⇧1 open the capture menu (1–4 or A picks and captures). Popover Tab order: Edit review details → Settings → scope segments (←/→ move) → Choose Area… → Capture → Send → New Session… → Open Redline. Return = Send when enabled, otherwise Capture; Escape closes. ⌘, opens Settings; ⌘N = New Session…; ⌘Q quits. New-session step: Tab scope → Choose Area… → Edit… → Cancel → Start Session; Return = Start Session, Escape = Cancel. Window: ⌘N New Session…, ⌘S Send, ⌘, Settings, ⌘F search.

+

Scope states

+

The scope belongs to the session and is copied to the next one. Area uses the saved rectangle; if none is saved, Capture first runs the picker. Window grabs the frontmost window of the app that was front before Redline (never Redline itself); none → status “No front window to capture”, nothing added. Browser grabs the frontmost Safari / Chrome / Arc / Edge / Firefox window, page area only; no browser in front → “No browser window in front”. Screen grabs the display the pointer is on. Choosing Window, Browser or Screen never clears the saved area: it is shown as “area kept” and comes back when Area is chosen. Choose Area… / Choose New Area… always replaces the saved area and switches the scope to Area.

+

Information architecture

+

The capture decision lives in the popover, above the pages, as a four-way segmented control with the target line under it — and again, unmissably, in the New Session… step, which replaces the page strip until Start Session. The window header mirrors the scope as a pop-up next to the verbs. Settings has one door: the gear in the popover header (⌘, from anywhere in Redline); the window has no gear and the popover has no “…” menu. Popover hierarchy, top to bottom: what is being reviewed (lane, build, commit, reviewer) → what will be captured (scope, target) → what has been captured (pages) → news (one status line, only when there is any) → verbs (Capture, Send) → session control (New Session…, Open Redline). Updates move into Settings › Updates and surface in the popover only when an installed update is waiting.

+

Still the biggest thing wrong

+

The popover still carries two jobs at once — deciding what to capture and reviewing what was captured — and the real fix is to make the session, not the popover, the unit of decision: every capture rule (scope, area, lane, build, commit) should be set once, when the session starts, and then stay out of the way. Today the new-session step is the only place that treats it that way; until scope and details are locked per session (with change visibly recorded on the PDF when they change mid-session), a reviewer can still produce a PDF whose pages were captured under different rules without anyone noticing.

+
+
+ +