feat(capture): choose what to capture — area, window, browser page or screen
Capture is now a decision, not a hidden setting. The popover shows a four-way scope control with the target named under it (800 x 600 on Display 1, the frontmost window, the front browser window, the whole display), and the window header carries the same choice beside the verbs. Picking Window or Browser hides Redline, dims the screen, names the app under the pointer and highlights its window; a click captures exactly that window, Escape cancels, and the desktop highlights the whole screen. New Session is one click: the current captures stay in their own folder, a fresh session opens, and the area picker comes straight up with the saved area pre-selected — Return keeps it, a drag replaces it. Settings is consolidated into one door (the popover gear, plus Cmd-,): what to capture, saved area, shortcut, ask-on-new-session, sending, session age limit, and a new Updates group with automatic install (on by default; installs only when nothing is unsent). The footer filler and the extra-actions menu are gone.
This commit is contained in:
+130
-19
@@ -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<CaptureRegion?, Never>) 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<CaptureRegion?, Never>) 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<CaptureRegion?, Never>) 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<CaptureTarget?, Never>) 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 {
|
||||
|
||||
@@ -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<CaptureScope> {
|
||||
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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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").
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<CaptureScope> {
|
||||
Binding(
|
||||
get: { model.captureScope },
|
||||
set: { scope in Task { await model.chooseCaptureScope(scope) } }
|
||||
)
|
||||
}
|
||||
|
||||
private var askOnNewSessionBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: { model.askWhatToCaptureOnNewSession },
|
||||
set: { model.setAskWhatToCaptureOnNewSession($0) }
|
||||
)
|
||||
}
|
||||
|
||||
private var autoInstallBinding: Binding<Bool> {
|
||||
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<SendTransport> {
|
||||
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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<String> = [
|
||||
"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()
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user