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:
Claude Fable 5
2026-11-01 11:47:58 +04:00
parent 1ae8351b04
commit 3fb9b504f4
18 changed files with 1601 additions and 152 deletions
+130 -19
View File
@@ -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 {
+87 -104
View File
@@ -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) {
+40 -4
View File
@@ -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
+3 -3
View File
@@ -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").
+34 -2
View File
@@ -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
+62 -3
View File
@@ -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
+88 -13
View File
@@ -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)
}
}