Files
shotdeck/Sources/Shotdeck/SettingsView.swift
T
Claude Fable 5 3061e45bcb feat(ui): rebuild the UX around two surfaces — a glance popover and a session window
The menu-bar popover was being used as a session manager: status, five text fields,
thumbnails, three buttons, a history list and eight more flat rows in 320 pt. The
redesign splits the product by job, from a UX pass whose mockups are kept under
design/ux-rework/.

- Popover: only the current session. Review details as one line plus a pencil that
  opens the window with the Lane field focused, at most three thumbnails, a Capture
  and a Send row, a New Session and Open Redline row, one status line when something
  happened, and a footer with the send channel, the retention policy and a ... menu
  for Settings / updates / quit.
- Window: sidebar of sessions grouped Today / Yesterday / This week / by month with
  a Current tag and each session's state, the selected session's pages as cards
  (select, Delete or Remove Page, sent sessions read-only), and an inspector with
  editable review details, the PDF facts (file name, pages, channel, status) and the
  session facts (started, id, files). Past sessions show their details read-only.
- Settings: three labelled groups (Capture, Sending, Sessions) replacing the
  headings-plus-grid layout.
- Sessions list/search/grouping/state live on the model, so the window and the popover
  read the same truth (came-back-marked state comes from the return ledger).
- Verification: 159 tests, the headless panel self-test, and an end-to-end run against
  the active app (scripts/run-e2e-ui.sh) which opens the real window, types into the
  Lane field with key events and clicks New Session, reporting what the launch mode
  could and could not deliver.
2026-10-31 13:03:08 +04:00

355 lines
14 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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("Capture shortcut") {
Button {
armHotkeyRecorder()
} label: {
Text(isRecordingHotkey ? "Press keys…" : model.hotkeyDisplayString)
.foregroundStyle(isRecordingHotkey ? .secondary : .primary)
.frame(minWidth: 54)
}
}
LabeledContent("Area") {
HStack(spacing: 8) {
Text(areaSummary)
.foregroundStyle(.secondary)
Button("Choose…") {
Task { await model.rePickRegion() }
}
}
}
}
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)
}
}
.formStyle(.grouped)
.frame(width: 460, height: 520)
.controlSize(.regular)
.onDisappear { disarmHotkeyRecorder() }
}
// MARK: - Rows
private var areaSummary: String {
guard let region = model.region else { return "Not chosen" }
return "\(Int(region.rect.width)) × \(Int(region.rect.height))"
}
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 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: 520))
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
}
}