Files
shotdeck/Sources/Shotdeck/SettingsView.swift
T
Claude Fable 5 3fb9b504f4 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.
2026-11-01 11:47:58 +04:00

430 lines
16 KiB
Swift

import AppKit
import SwiftUI
import ShotdeckCore
/// Settings: three labelled groups, every row "what it is" on the left and the control
/// on the right. Nothing here is needed while reviewing, which is why it is its own
/// window and not part of the session surfaces.
struct SettingsView: View {
@Environment(AppModel.self) private var model
@State private var isRecordingHotkey = false
@State private var recorder = HotkeyRecorderBox()
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()
} label: {
Text(isRecordingHotkey ? "Press keys…" : model.hotkeyDisplayString)
.foregroundStyle(isRecordingHotkey ? .secondary : .primary)
.frame(minWidth: 54)
}
}
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") {
LabeledContent("Send with") {
Picker("Send with", selection: transportBinding) {
ForEach(SendTransport.allCases, id: \.self) { transport in
Text(transport.displayName).tag(transport)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(maxWidth: 220)
}
if model.transport == .airDrop {
LabeledContent("Save PDFs to") {
folderRow(path: model.outboxURL.path) { model.chooseOutboxFolder() }
}
LabeledContent("Watch for returns in") {
folderRow(path: model.watchFolderURL.path) { model.chooseWatchFolder() }
}
} else {
LabeledContent("OneDrive folder") {
folderRow(path: oneDrivePath) { model.chooseOneDriveFolder() }
}
Text(
model.resolvedOneDriveFolder != nil
? "The PDF is saved here and this same folder is watched for the marked-up copy. On the iPad open it from Files > OneDrive."
: "No OneDrive folder found. Sign in to OneDrive, or choose a folder."
)
.font(.caption)
.foregroundStyle(model.resolvedOneDriveFolder != nil ? .secondary : .primary)
.fixedSize(horizontal: false, vertical: true)
}
}
Section("Sessions") {
LabeledContent("Delete sessions older than") {
Picker("Delete sessions older than", selection: retentionBinding) {
ForEach(SessionRetention.presets, id: \.self) { preset in
Text(preset.displayName).tag(preset)
}
}
.labelsHidden()
.frame(maxWidth: 150)
}
LabeledContent(keptSummary) {
Button("Clean Up Now…") {
Task { await model.cleanUpExpiredSessions() }
}
.disabled(model.retention == .never || model.expiredSessionCount == 0)
}
Text(retentionDetail)
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
Text("Deleting removes Redline's own screenshots only. PDFs you sent stay where they are.")
.font(.caption)
.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: 820)
.controlSize(.regular)
.onDisappear { disarmHotkeyRecorder() }
}
// MARK: - Rows
private var areaSummary: String {
model.region?.summary ?? "Not chosen"
}
private var oneDrivePath: String {
model.resolvedOneDriveFolder?.path ?? "Not found"
}
private var keptSummary: String {
let count = model.pastSessions.count + 1
return "\(count) session\(count == 1 ? "" : "s") kept"
}
private func folderRow(path: String, choose: @escaping () -> Void) -> some View {
HStack(spacing: 8) {
Text(abbreviateHome(path))
.lineLimit(1)
.truncationMode(.middle)
.foregroundStyle(.secondary)
.frame(maxWidth: 150, alignment: .trailing)
.help(path)
Button("Choose…") { choose() }
}
}
private func abbreviateHome(_ path: String) -> String {
let home = FileManager.default.homeDirectoryForCurrentUser.path
guard path.hasPrefix(home) else { return path }
return "~" + path.dropFirst(home.count)
}
// MARK: - Detail text
private var retentionDetail: String {
guard model.retention != .never else {
return "All sessions are kept. Nothing is deleted automatically."
}
let count = model.expiredSessionCount
if count == 0 {
return "No kept session is older than \(model.retention.displayName) yet."
}
return "\(count) session\(count == 1 ? " is" : "s are") already older than \(model.retention.displayName) and will be removed on the next launch or cleanup."
}
// 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) })
}
private var retentionBinding: Binding<SessionRetention> {
Binding(get: { model.retention }, set: { value in
Task { await model.setRetention(value) }
})
}
// MARK: - Hotkey recorder
private func armHotkeyRecorder() {
guard !isRecordingHotkey else { return }
isRecordingHotkey = true
recorder.onKey = { keyCode, flags in
handleRecorderKey(keyCode: keyCode, flags: flags)
}
recorder.arm()
}
private func handleRecorderKey(keyCode: UInt16, flags: NSEvent.ModifierFlags) {
if keyCode == 53 { // kVK_Escape
disarmHotkeyRecorder()
return
}
guard let pref = HotkeyPreference.fromKeyEvent(keyCode: keyCode, modifierFlags: flags) else {
return
}
pref.save()
model.reRegisterHotkey()
disarmHotkeyRecorder()
}
private func disarmHotkeyRecorder() {
recorder.disarm()
recorder.onKey = nil
isRecordingHotkey = false
}
}
/// Local keyDown monitor for the Settings capture-hotkey recorder. Callbacks hop onto the
/// main actor the same way `RegionPickerController` does — local monitors fire on the
/// main run loop during `NSApp.sendEvent`.
@MainActor
private final class HotkeyRecorderBox {
var onKey: ((UInt16, NSEvent.ModifierFlags) -> Void)?
private var monitor: Any?
func arm() {
disarm()
monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
guard let self else { return event }
let keyCode = event.keyCode
let rawFlags = event.modifierFlags.rawValue
MainActor.assumeIsolated {
self.onKey?(keyCode, NSEvent.ModifierFlags(rawValue: rawFlags))
}
return nil
}
}
func disarm() {
if let monitor {
NSEvent.removeMonitor(monitor)
}
monitor = nil
}
}
extension AppModel: SettingsWindowPresenting {
private static var settingsWindowController: NSWindowController?
public func presentSettingsWindow() {
if let existing = Self.settingsWindowController {
existing.window?.makeKeyAndOrderFront(nil)
NSApp.activate()
return
}
let hosting = NSHostingController(rootView: SettingsView().environment(self))
let window = NSWindow(contentViewController: hosting)
window.title = "Redline Settings"
window.styleMask = [.titled, .closable]
window.isReleasedWhenClosed = false
window.setContentSize(NSSize(width: 460, height: 820))
window.center()
let controller = NSWindowController(window: window)
Self.settingsWindowController = controller
controller.showWindow(nil)
NSApp.activate()
}
func chooseOutboxFolder() {
guard let url = chooseDirectory(startingAt: outboxURL) else { return }
FolderSettings.setOutbox(url)
setFolderURLs(outbox: url, watch: watchFolderURL)
setStatus("PDFs are saved to \(url.lastPathComponent).")
}
func chooseWatchFolder() {
guard let url = chooseDirectory(startingAt: watchFolderURL) else { return }
FolderSettings.setWatchFolder(url)
setFolderURLs(outbox: outboxURL, watch: url)
Task {
do {
try await watcher.updateWatchFolder(url)
setStatus("Watching \(url.lastPathComponent) for returns.")
} catch {
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
/// Settings "Send with" picker action. Persists the choice, recomputes the effective
/// outbox/watch folder for the new transport, creates the OneDrive folder if it
/// doesn't exist yet, and re-points the running watcher (folder + recordUncommented)
/// at the new state. Refuses while a send is in flight.
/// The async reconcile below is generation-guarded so rapid toggling always lets the
/// LAST choice win; its handle is stored in `pendingReconcileTask` so send() can
/// await it before snapshotting transport/folder.
func chooseTransport(_ value: SendTransport) {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
guard value != transport else { return }
TransportSettings.setTransport(value)
setTransport(value)
let folders = TransportSettings.effectiveFolders()
if value == .oneDrive {
try? FileManager.default.createDirectory(
at: folders.outbox, withIntermediateDirectories: true
)
}
setFolderURLs(outbox: folders.outbox, watch: folders.watch)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
await watcher.setRecordUncommented(value == .airDrop)
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(folders.watch)
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
/// Refuses while a send is in flight, same reasoning as chooseTransport. See
/// chooseTransport's doc comment for the generation-guard mechanism shared here.
func chooseOneDriveFolder() {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
let start = resolvedOneDriveFolder ?? FileManager.default.homeDirectoryForCurrentUser
guard let url = chooseDirectory(startingAt: start) else { return }
TransportSettings.setOneDriveFolder(url)
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
guard transport == .oneDrive else { return }
setFolderURLs(outbox: url, watch: url)
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(url)
guard generation == self.reconcileGeneration else { return }
setStatus("OneDrive folder set to \(url.lastPathComponent).")
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
private func chooseDirectory(startingAt directory: URL) -> URL? {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.canCreateDirectories = true
panel.prompt = "Choose"
panel.directoryURL = directory
guard panel.runModal() == .OK else { return nil }
return panel.url
}
}