diff --git a/README.md b/README.md index ce7590a..06ad46f 100644 --- a/README.md +++ b/README.md @@ -7,19 +7,33 @@ A macOS menu-bar app that captures a remembered screen region, builds a one-scre - **⌥⇧1** — pick a new region, then capture it. - **⌥⇧2** — capture the remembered region instantly (no picker). +## Where things live + +Two surfaces, two jobs: + +- **Menu-bar popover** — only the current session: its review details on one line, its + pages, then Capture, Send, New Session, Open Redline, and one status line when + something happened. Nothing else, so it never scrolls. +- **Redline window** (Open Redline) — the workspace: every session in a sidebar grouped + by day, the selected session's pages in the middle, and its review details, PDF facts + and session facts in the inspector. History, text entry and file facts live here + because they need room and a window that stays open. +- **Settings** (⌘, in the popover's … menu) — capture, sending, and the session age limit. + ## Sessions -Every review is a session. Captures go into the open session; "New session" closes it -and keeps it in the Past sessions list, named and dated, whether or not it was sent. +Every review is a session. Captures go into the open session; "New Session" closes it +and keeps it in the sidebar, named and dated, whether or not it was sent. - **Nothing is deleted by default.** A session is kept until you delete it. - **Settings > Sessions > Delete after** sets an age limit (7 days … 1 year). Sessions older than the limit are removed on the next launch and by **Clean up now**. Only Redline's own saved screenshots are removed; a PDF that was already sent stays in the folder it was sent to. -- **Details** on the current session records what is being reviewed: lane/environment, - the deployed build, the commit, the reviewer (pre-filled with this Mac's user) and a - free note. A new session inherits the previous session's details. +- **Review details** (inspector) record what is being reviewed: lane/environment, the + deployed build, the commit, the reviewer (pre-filled with this Mac's user) and a free + note. A new session inherits the previous session's details, and past sessions show + them read-only. ## Files and PDF metadata diff --git a/Sources/Shotdeck/AppModel.swift b/Sources/Shotdeck/AppModel.swift index 1517247..ca6cee2 100644 --- a/Sources/Shotdeck/AppModel.swift +++ b/Sources/Shotdeck/AppModel.swift @@ -15,8 +15,8 @@ public protocol SettingsWindowPresenting: AnyObject { } @MainActor -public protocol SubmissionsWindowPresenting: AnyObject { - func presentSubmissionsWindow() +public protocol SessionsWindowPresenting: AnyObject { + func presentSessionsWindow(focusLane: Bool) } @MainActor @@ -32,8 +32,13 @@ public final class AppModel { public private(set) var screenRecordingGranted: Bool public private(set) var allReturns: [ReturnedDocument] = [] public private(set) var commentedReturns: [ReturnedDocument] = [] - /// Retained past sessions (newest first) — what the Past submissions window lists. + /// Retained past sessions (newest first) — what the sessions window lists. public private(set) var pastSessions: [CaptureSession] = [] + /// The session the window is showing: the open one or a kept one. + public private(set) var selectedSessionID: UUID? + /// Set when the window was opened from the popover's pencil: the Lane field takes + /// focus on appear, then the flag is cleared. + public private(set) var laneFocusRequest = 0 public private(set) var statusLine: String? public private(set) var updateStatus: String? /// The user's age limit for kept sessions (Settings > Sessions). `.never` until @@ -159,7 +164,14 @@ public final class AppModel { allReturns = all commentedReturns = commented } - func setPastSessions(_ value: [CaptureSession]) { pastSessions = value } + func setPastSessions(_ value: [CaptureSession]) { + pastSessions = value + if selectedSessionID == nil { + selectedSessionID = session.id + } + } + func setSelectedSessionID(_ value: UUID?) { selectedSessionID = value } + func requestLaneFocus() { laneFocusRequest += 1 } func setFolderDisplayNames(outbox: String, watch: String) { outboxDisplayName = outbox watchFolderDisplayName = watch @@ -178,6 +190,9 @@ public final class AppModel { /// lets the LAST choice win instead of applying stale, superseded work. Not /// `@Observable`-relevant state — pure internal bookkeeping, never read by a View. var reconcileGeneration = 0 + /// Pending debounced review-detail write (see updateContext). + private var pendingContextWrite: Task? + /// The MOST RECENT watcher-reconcile Task spawned by chooseTransport/ /// chooseOneDriveFolder, if one is still (or was just) in flight. send() awaits /// this BEFORE snapshotting transport/folder, so a toggle immediately followed by @@ -218,6 +233,184 @@ public final class AppModel { } } + // MARK: - Session browsing (the sessions window) + + /// What a session row says about itself in the list. + public enum SessionDisplayState: Equatable { + case current + case notSent + case sent + case returned(markedPages: Int) + + public var label: String { + switch self { + case .current: return "not sent" + case .notSent: return "not sent" + case .sent: return "sent" + case .returned(let pages): + return pages == 1 ? "came back marked" : "came back marked · \(pages) pages" + } + } + + public var isReturned: Bool { + if case .returned = self { return true } + return false + } + } + + /// The session the window shows: the open one, or the selected kept one. + public var selectedSession: CaptureSession? { + guard let selectedSessionID else { return session } + if selectedSessionID == session.id { return session } + return pastSessions.first { $0.id == selectedSessionID } ?? session + } + + public var selectedIsCurrent: Bool { + selectedSession?.id == session.id + } + + public func selectSession(_ id: UUID?) { + selectedSessionID = id + } + + /// Where a capture's PNG lives, in whichever directory its session sits. + public func imageURL(for capture: Capture, in session: CaptureSession) -> URL { + let directory = session.state == .open + ? paths.sessionDirectory(session.id) + : paths.archiveDirectory(session.id) + return directory.appendingPathComponent(capture.fileName) + } + + /// The marked-up copy that came back for this session, when there is one. + public func returnedDocument(for session: CaptureSession) -> ReturnedDocument? { + guard let fileName = session.pdfFileName else { return nil } + return allReturns.first { $0.fileURL.lastPathComponent == fileName } + } + + public func state(of session: CaptureSession) -> SessionDisplayState { + if session.id == self.session.id, session.state == .open { + return .current + } + if let document = returnedDocument(for: session), document.isCommented { + return .returned(markedPages: document.annotatedPages.count) + } + return session.pdfFileName == nil ? .notSent : .sent + } + + /// Every session the window lists, newest first, with the open one first. + public var allSessionsNewestFirst: [CaptureSession] { + [session] + pastSessions.filter { $0.id != session.id } + } + + /// Text match over the fields a person would search by. + public func sessions(matching needle: String) -> [CaptureSession] { + let trimmed = needle.trimmingCharacters(in: .whitespaces).lowercased() + guard !trimmed.isEmpty else { return allSessionsNewestFirst } + return allSessionsNewestFirst.filter { candidate in + let haystack = [ + candidate.context.lane, + candidate.context.deployedVersion, + candidate.context.commit, + candidate.context.reviewer, + candidate.context.note, + candidate.pdfFileName ?? "", + candidate.shortID, + DubaiTime.stamp(candidate.createdAt), + ].joined(separator: " ").lowercased() + return haystack.contains(trimmed) + } + } + + /// One sidebar section: a day bucket or a month bucket. + public struct SessionGroup: Identifiable { + public var id: String { title } + public let title: String + public let sessions: [CaptureSession] + } + + /// Sidebar sections: Today, Yesterday, This week, then one bucket per month. + /// Empty sections are dropped so the list never shows a heading with nothing under it. + public func groupedSections(for sessions: [CaptureSession]) -> [SessionGroup] { + guard let dubai = TimeZone(identifier: "Asia/Dubai") else { + return [SessionGroup(title: "Sessions", sessions: sessions)] + } + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = dubai + let now = Date() + let startOfToday = calendar.startOfDay(for: now) + let startOfYesterday = calendar.date(byAdding: .day, value: -1, to: startOfToday) ?? startOfToday + let startOfWeek = calendar.date(byAdding: .day, value: -7, to: startOfToday) ?? startOfToday + let monthFormatter = DateFormatter() + monthFormatter.calendar = calendar + monthFormatter.timeZone = dubai + monthFormatter.dateFormat = "MMMM yyyy" + + var order: [String] = [] + var buckets: [String: [CaptureSession]] = [:] + for candidate in sessions { + let key: String + let created = candidate.createdAt + if created >= startOfToday { + key = "Today" + } else if created >= startOfYesterday { + key = "Yesterday" + } else if created >= startOfWeek { + key = "This week" + } else { + key = monthFormatter.string(from: created) + } + if buckets[key] == nil { + buckets[key] = [] + order.append(key) + } + buckets[key]?.append(candidate) + } + let preferred = ["Today", "Yesterday", "This week"] + let titles = preferred.filter { buckets[$0] != nil } + order.filter { !preferred.contains($0) } + return titles.map { SessionGroup(title: $0, sessions: buckets[$0] ?? []) } + } + + /// Updates a single review-detail field of the open session (used by the inspector's + /// rows, which each own one field). + public func updateContext(_ field: WritableKeyPath, _ value: String) { + var context = session.context + context[keyPath: field] = value + guard context != session.context else { return } + pendingContextWrite?.cancel() + pendingContextWrite = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(180)) + guard !Task.isCancelled, let self else { return } + await self.setContextField(context) + } + } + + /// Updates one or more review-detail fields of the open session. Writes are + /// debounced so typing produces one manifest write per pause, and a newer value can + /// never be overwritten by an older one. + public func updateContext( + lane: String? = nil, + deployedVersion: String? = nil, + commit: String? = nil, + reviewer: String? = nil, + note: String? = nil + ) { + let current = session.context + let next = ReviewContext( + lane: lane ?? current.lane, + deployedVersion: deployedVersion ?? current.deployedVersion, + commit: commit ?? current.commit, + reviewer: reviewer ?? current.reviewer, + note: note ?? current.note + ) + guard next != current else { return } + pendingContextWrite?.cancel() + pendingContextWrite = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(180)) + guard !Task.isCancelled, let self else { return } + await self.setContextField(next) + } + } + // MARK: - Session retention /// The sentence the panel footer and Settings show for the current policy. @@ -547,6 +740,7 @@ public final class AppModel { if let refreshProblem = await reloadFromSpool() { message += " \(refreshProblem)" } + selectSession(session.id) setStatus(message) } diff --git a/Sources/Shotdeck/MenuBarView.swift b/Sources/Shotdeck/MenuBarView.swift index 10adf82..d6b92b5 100644 --- a/Sources/Shotdeck/MenuBarView.swift +++ b/Sources/Shotdeck/MenuBarView.swift @@ -2,79 +2,125 @@ import AppKit import SwiftUI import ShotdeckCore -/// The menu-bar panel. Hierarchy: what is being worked on first, the three core -/// verbs second, recent sessions third, housekeeping last. +/// 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. struct MenuBarView: View { @Environment(AppModel.self) private var model - /// Snapshot-only: opens the details editor on first render. - private let startsWithDetailsOpen: Bool - @State private var showsDetails = false - - init(showsContextEditor: Bool = false) { - self.startsWithDetailsOpen = showsContextEditor - } var body: some View { - VStack(alignment: .leading, spacing: 10) { - statusRow - sessionBlock - Divider() - recentSessionsBlock - Divider() - secondaryActions - if !model.allReturns.isEmpty { + VStack(alignment: .leading, spacing: 8) { + if model.screenRecordingGranted { + sessionHeader + thumbnailRow + statusRow + actionRows Divider() - returnsBlock + footer + } else { + permissionBlock + Divider() + footer } - Divider() - footer } .padding(10) - .frame(width: 320, alignment: .leading) + .frame(width: 340, alignment: .leading) .controlSize(.small) - .onAppear { showsDetails = startsWithDetailsOpen } } - // MARK: - Status + // MARK: - Header - @ViewBuilder - private var statusRow: some View { - if !model.screenRecordingGranted { - HStack(alignment: .top, spacing: 6) { - Image(systemName: "exclamationmark.triangle") - .foregroundStyle(.yellow) - VStack(alignment: .leading, spacing: 4) { - Text( - ShotdeckError.screenRecordingNotGranted.errorDescription - ?? "Screen Recording is turned off." - ) - .font(.caption) - .fixedSize(horizontal: false, vertical: true) - Button("Open Screen Recording settings") { - model.openScreenRecordingSettings() + private var sessionHeader: some View { + HStack(alignment: .top, spacing: 8) { + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(laneTitle) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + if let version = versionTitle { + Text(version) + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .lineLimit(1) } } + Text(detailLine) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + .help(detailLine) } - } else if let status = model.statusLine { - Text(status) - .font(.caption) - .foregroundStyle(.primary) - .fixedSize(horizontal: false, vertical: true) - } else { - Text(defaultStatusText) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + 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: { + Image(systemName: "square.and.pencil") + .font(.system(size: 12, weight: .semibold)) + } + .buttonStyle(.borderless) + .help("Edit review details") + .accessibilityLabel("Edit review details") } } - private var defaultStatusText: String { - guard let region = model.region else { - return "No area selected yet — press \(model.hotkeyDisplayString) to pick one." + private var laneTitle: String { + let lane = model.session.context.lane + return lane.isEmpty ? "No lane" : lane + } + + private var versionTitle: String? { + let version = model.session.context.deployedVersion + return version.isEmpty ? nil : version + } + + private var detailLine: String { + let context = model.session.context + 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)" } - let w = Int(region.rect.width) - let h = Int(region.rect.height) - return "Capturing \(w) × \(h) on \(displayName(for: region))" + return parts.joined(separator: " · ") + " · started \(started)" + } + + // MARK: - Body + + @ViewBuilder + private var thumbnailRow: some View { + if model.session.isEmpty { + VStack(spacing: 2) { + Text("Nothing captured yet") + .font(.callout) + .foregroundStyle(.secondary) + Text(emptyHint) + .font(.caption) + .foregroundStyle(.tertiary) + } + .frame(maxWidth: .infinity, minHeight: 62) + .background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } else { + SessionStrip(limit: 3) + } + } + + 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))" } private func displayName(for region: CaptureRegion) -> String { @@ -88,322 +134,162 @@ struct MenuBarView: View { return "Display 1" } - // MARK: - Current session - - private var sessionBlock: some View { - VStack(alignment: .leading, spacing: 6) { - HStack(alignment: .firstTextBaseline, spacing: 6) { - Text("Current session") - .font(.caption.weight(.semibold)) - Spacer(minLength: 6) - Text(captureCountText) - .font(.caption) - .foregroundStyle(.secondary) - .monospacedDigit() - } - - HStack(alignment: .firstTextBaseline, spacing: 6) { - Text(contextSummary) - .font(.caption) - .foregroundStyle(model.sessionContext.summaryLine.isEmpty ? .secondary : .primary) - .lineLimit(1) - .truncationMode(.tail) - .help(contextSummary) - Spacer(minLength: 4) - // A bordered control, not a link: in a menu panel the row of text is - // the value, and the thing you press has to look pressable. - Button { - showsDetails.toggle() - } label: { - HStack(spacing: 2) { - Text(showsDetails ? "Hide" : "Details") - Image(systemName: showsDetails ? "chevron.up" : "chevron.down") - .font(.system(size: 9, weight: .semibold)) - } - } - .buttonStyle(.bordered) - .accessibilityLabel(showsDetails ? "Hide details" : "Show details") - } - - if showsDetails { - SessionContextEditor() - } - - SessionStrip() + /// 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 { + Text(status) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) + } + } + private var actionRows: some View { + VStack(spacing: 6) { HStack(spacing: 6) { - Button("Capture") { + Button { Task { await model.captureNow() } + } label: { + HStack(spacing: 4) { + Image(systemName: "viewfinder") + Text(model.isCapturing ? "Capturing…" : "Capture") + Text(model.hotkeyDisplayString) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) } + .controlSize(.regular) .disabled(model.isCapturing) - Button(model.transport == .oneDrive ? "Send to OneDrive" : "Send…") { + Button { guard let sender = model as? SendCapable else { model.setStatus("Send is not available in this build.") return } let anchor = NSApp.keyWindow?.contentView Task { await sender.send(anchor: anchor) } + } label: { + HStack(spacing: 4) { + Image(systemName: "paperplane.fill") + Text(sendTitle) + } + .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) + .controlSize(.regular) .disabled(model.session.isEmpty || model.isSending) + } - Button("New session") { + HStack(spacing: 6) { + Button { Task { await model.startNewSession() } + } label: { + HStack(spacing: 4) { + Image(systemName: "plus.square.on.square") + Text("New Session") + } + .frame(maxWidth: .infinity) } + .controlSize(.regular) .disabled(!model.canStartNewSession) - .help("Keeps these captures as a past session and starts a fresh one. Nothing is deleted.") + .help("Keeps this session and starts a fresh one. Nothing is deleted.") + + Button { + presentWindow(focusLane: false) + } label: { + HStack(spacing: 4) { + Image(systemName: "macwindow") + Text("Open Redline") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .controlSize(.regular) } - .frame(maxWidth: .infinity, alignment: .leading) } } - private var captureCountText: String { + private var sendTitle: String { let count = model.session.captures.count - if count == 0 { return "empty" } - return "\(count) capture\(count == 1 ? "" : "s")" - } - - private var contextSummary: String { - let summary = model.sessionContext.summaryLine - return summary.isEmpty ? "No lane or build recorded — add details" : summary - } - - // MARK: - Recent sessions - - private var recentSessionsBlock: some View { - VStack(alignment: .leading, spacing: 3) { - HStack(alignment: .firstTextBaseline, spacing: 6) { - Text("Recent sessions") - .font(.caption.weight(.semibold)) - if !model.pastSessions.isEmpty { - Text("\(model.pastSessions.count)") - .font(.caption) - .foregroundStyle(.secondary) - .monospacedDigit() - } - Spacer(minLength: 6) - Button("Show all…") { - if let presenter = model as? SubmissionsWindowPresenting { - presenter.presentSubmissionsWindow() - } else { - model.setStatus("Past sessions are not available in this build.") - } - } - .buttonStyle(.link) - } - - if model.pastSessions.isEmpty { - Text("Nothing yet. “New session” keeps this one and starts a fresh one.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } else { - ForEach(model.pastSessions.prefix(4)) { session in - RecentSessionRow(session: session) - } - } - } - } - - // MARK: - Secondary actions - - private var secondaryActions: some View { - VStack(alignment: .leading, spacing: 2) { - if let update = model.updateAvailable { - Button { - model.installUpdate() - } label: { - actionLabel("Update to \(update.version)") - .foregroundStyle(Color.accentColor) - } - } - - if let previous = model.previousVersion { - Button { - model.revertToPreviousVersion() - } label: { - actionLabel("Revert to \(previous)") - } - } - - Button { - model.revealLastPDF() - } label: { - actionLabel("Reveal last PDF") - } - .disabled(!model.canRevealLastPDF) - - Button { - Task { await model.copyCommentedLinks() } - } label: { - actionLabel( - "Copy commented links", - trailing: model.commentedReturns.isEmpty ? nil : "\(model.commentedReturns.count)" - ) - } - .disabled(model.commentedReturns.isEmpty) - - Button { - Task { await model.rePickRegion() } - } label: { - actionLabel("Re-select area") - } - - Button { - Task { await model.captureNow() } - } label: { - actionLabel("Capture now", trailing: model.hotkeyDisplayString) - } - .disabled(model.isCapturing) - } - .buttonStyle(.plain) - } - - private func actionLabel(_ title: String, trailing: String? = nil) -> some View { - HStack(spacing: 8) { - Text(title) - Spacer(minLength: 8) - if let trailing { - Text(trailing) - .foregroundStyle(.secondary) - .monospacedDigit() - } - } - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) - .padding(.vertical, 3) - } - - @ViewBuilder - private var returnsBlock: some View { - if let provider = model as? ReturnsSectionProviding { - provider.returnsSection() - } else { - VStack(alignment: .leading, spacing: 4) { - Text("Came back from your device") - .font(.caption.weight(.semibold)) - ForEach(newestReturns.prefix(6)) { doc in - HStack(spacing: 8) { - Text(doc.fileURL.lastPathComponent) - .lineLimit(1) - Spacer(minLength: 8) - Text(doc.isCommented - ? "\(doc.annotatedPages.count) page\(doc.annotatedPages.count == 1 ? "" : "s") marked" - : "not marked") - .font(.caption) - .foregroundStyle(doc.isCommented ? .primary : .secondary) - } - } - } - } - } - - private var newestReturns: [ReturnedDocument] { - model.allReturns.sorted { $0.detectedAt > $1.detectedAt } + guard count > 0 else { return "Send…" } + let pages = "\(count) page\(count == 1 ? "" : "s")" + return model.transport == .oneDrive ? "Save \(pages)…" : "Send \(pages)…" } // MARK: - Footer private var footer: some View { - VStack(alignment: .leading, spacing: 3) { - HStack(spacing: 6) { - Button("Settings…") { - if let presenter = model as? SettingsWindowPresenting { - presenter.presentSettingsWindow() - } else { - model.setStatus("Settings is not available in this build.") - } - } - .buttonStyle(.link) - Button("Check for updates") { - model.checkForUpdates() - } - .buttonStyle(.link) - .disabled(model.isCheckingForUpdates) - Spacer(minLength: 6) - Button("Quit") { - NSApp.terminate(nil) - } - .buttonStyle(.link) - } - Text("Redline \(model.appVersion) · \(model.retentionSummary)") + 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 + + private var permissionBlock: some View { + HStack(alignment: .top, spacing: 6) { + Image(systemName: "exclamationmark.triangle") + .foregroundStyle(.yellow) + VStack(alignment: .leading, spacing: 6) { + Text( + ShotdeckError.screenRecordingNotGranted.errorDescription + ?? "Screen Recording is turned off." + ) + .font(.caption) .fixedSize(horizontal: false, vertical: true) - if let message = model.updateStatusMessage { - Text(message) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + Button("Open Screen Recording settings") { + model.openScreenRecordingSettings() + } } } } -} -/// One row of the panel's recent-sessions list: timestamp, readable session label, -/// page count and sent state. Clicking reveals the sent PDF when there is one, -/// otherwise that session's captures. -private struct RecentSessionRow: View { - @Environment(AppModel.self) private var model - let session: CaptureSession - @State private var hovering = false - - var body: some View { - Button { - if model.sentPDFURL(for: session) != nil { - model.revealSentPDF(session) - } else { - model.revealSessionCaptures(session) - } - } label: { - HStack(spacing: 6) { - Text(DubaiTime.shortStamp(session.createdAt)) - .font(.caption) - .monospacedDigit() - .foregroundStyle(.secondary) - Text(SessionDisplay.label(for: session)) - .font(.caption) - .lineLimit(1) - .truncationMode(.tail) - Spacer(minLength: 6) - Text(session.pdfFileName == nil ? "Not sent" : "Sent") - .font(.caption) - .foregroundStyle(session.pdfFileName == nil ? .secondary : .primary) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.vertical, 2) - .contentShape(Rectangle()) - .background(hovering ? AnyShapeStyle(.quaternary) : AnyShapeStyle(.clear)) + private func presentWindow(focusLane: Bool) { + guard let presenter = model as? SessionsWindowPresenting else { + model.setStatus("The Redline window is not available in this build.") + return } - .buttonStyle(.plain) - .onHover { hovering = $0 } - .help(helpText) - } - - private var helpText: String { - let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" - let context = session.context.summaryLine - let detail = context.isEmpty ? pages : "\(pages) · \(context)" - if let name = session.pdfFileName { - return "\(detail)\nSent as \(name)" - } - return "\(detail)\nNever sent — opens the captures" - } -} - -/// Readable labels for sessions, shared by the panel and the Past sessions window. -/// -/// The label is what the user typed plus the session's short id — never the -/// upper-cased file-name slug, which is for filesystems, not people. -enum SessionDisplay { - static func label(for session: CaptureSession) -> String { - let lane = session.context.lane - return lane.isEmpty ? session.shortID : lane - } - - static func fullLabel(for session: CaptureSession) -> String { - let lane = session.context.lane - return lane.isEmpty ? session.shortID : "\(lane) · \(session.shortID)" + presenter.presentSessionsWindow(focusLane: focusLane) } } diff --git a/Sources/Shotdeck/PanelSelfTest.swift b/Sources/Shotdeck/PanelSelfTest.swift index 841e1de..42c1ffa 100644 --- a/Sources/Shotdeck/PanelSelfTest.swift +++ b/Sources/Shotdeck/PanelSelfTest.swift @@ -6,14 +6,6 @@ import PDFKit import SwiftUI import ShotdeckCore -/// In-process UI self-test for the session panel, driven by -/// `REDLINE_SELFTEST_PHASE=panel`. -/// -/// It opens the REAL `MenuBarView` in a real window against an isolated model, types -/// into the review-detail fields with real key events, presses "New session" through -/// the accessibility action a screen reader would use, then checks what landed on -/// disk: the manifest, the PDF's document info and its page text, and the age-based -/// cleanup. Nothing outside its own temporary root is touched. /// Command-line self-test selection: --selftest [--root ] [--result ]. /// Needed for the interactive end-to-end run, which must be launched through /// LaunchServices (open -n) to become the active app — that launch path cannot pass @@ -32,22 +24,28 @@ enum SelfTestLaunch { } } +/// Two ways to exercise Redline against isolated storage: +/// +/// * `panel` — headless: builds the real window and model, checks the manifest write, +/// the PDF (name, document info, page text) and the age-based cleanup. +/// * `e2e` — the real window in the ACTIVE app, typed into with the keyboard and +/// clicked with the mouse, driven through LaunchServices by `scripts/run-e2e-ui.sh`. +/// +/// Nothing outside the run's own temporary storage or preference suite is touched. enum PanelSelfTest { + // MARK: - Launch hooks + @MainActor static func runIfRequested() { let requested = SelfTestLaunch.phase == "panel" || ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" - guard requested else { - return - } - // Unbuffered stdout so a PASS line appears the moment it happens, even when - // the output is piped to a log file. + guard requested else { return } setvbuf(stdout, nil, _IONBF, 0) let app = NSApplication.shared app.setActivationPolicy(.accessory) Task { @MainActor in do { - try await execute() + try await executeHeadless() print("PANEL-SELFTEST PASS") exit(0) } catch { @@ -59,176 +57,13 @@ enum PanelSelfTest { exit(0) } - // MARK: - The run - - @MainActor - private static func execute() async throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("redline-panel-selftest-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - - let suiteName = "redline-panel-selftest-\(UUID().uuidString)" - guard let defaults = UserDefaults(suiteName: suiteName) else { - throw SelfTestFailure("could not create an isolated UserDefaults suite") - } - defaults.removePersistentDomain(forName: suiteName) - defer { defaults.removePersistentDomain(forName: suiteName) } - - let paths = try AppSupportPaths( - root: root, - outbox: root.appendingPathComponent("outbox", isDirectory: true), - watchFolder: root.appendingPathComponent("watch", isDirectory: true) - ) - let ledger = try ReturnLedger(paths: paths) - let model = AppModel( - paths: paths, - spool: try SpoolStore(paths: paths), - composer: PDFComposer(), - capturer: ScreenCapturer(), - hotkeys: HotkeyCenter(), - picker: RegionPickerController(), - ledger: ledger, - watcher: ReturnWatcher(paths: paths, ledger: ledger), - retentionDefaults: defaults - ) - model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) - model.replaceRegion( - CaptureRegion( - displayID: CGMainDisplayID(), - rect: CGRect(x: 100, y: 100, width: 640, height: 400), - capturedScale: 2.0)) - await model.bootstrap() - try check(!model.session.isEmpty == false, "the fresh session starts empty") - print("PANEL-SELFTEST PASS launch") - - // Two real captures through the production spool path. - for (index, colour) in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)].enumerated() { - let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) - _ = try await model.spool.append( - pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0, - capturedAt: Date().addingTimeInterval(Double(index))) - } - model.replaceSession(try await model.spool.currentSession()) - try check(model.session.captures.count == 2, "two captures are in the open session") - - // The real populated panel, in a real window. - let window = makePanelWindow(model: model) - NSApp.activate(ignoringOtherApps: true) - window.makeKeyAndOrderFront(nil) - pump(0.5) - try check(window.isVisible, "the panel window is on screen") - print("PANEL-SELFTEST PASS panel-visible") - - // The five review-detail fields are present and blank for a new session. - let fields = textFields(in: window.contentView) - try check(fields.count >= 5, "the five review-detail fields exist (found \(fields.count))") - try check(fields[0].stringValue.isEmpty && fields[1].stringValue.isEmpty && fields[2].stringValue.isEmpty, - "lane, deployed version and commit start empty rather than guessed") - try check(fields[3].stringValue == ReviewContext.currentUser(), - "the reviewer starts as this Mac's user (got '\(fields[3].stringValue)')") - print("PANEL-SELFTEST PASS details-fields \(fields.count) editable reviewer='\(fields[3].stringValue)'") - - // Typing through the field editors is the real user path, but macOS will not let - // a process launched from a background shell take key-window focus, so the - // field editors never commit. Record that instead of pretending it passed, and - // drive the same call the field's onChange makes. - print("PANEL-SELFTEST SKIP keyboard-typing keyWindow=\(window.isKeyWindow) active=\(NSApp.isActive)") - - await model.setContextField( - ReviewContext( - lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", - reviewer: "Ben Hippler")) - pump(0.4) - - let typed = try await model.spool.currentSession().context - try check(typed.lane == "dev03", "the lane reached the manifest (got '\(typed.lane)')") - try check(typed.deployedVersion == "v1.4.2", - "the deployed version reached the manifest (got '\(typed.deployedVersion)')") - try check(typed.commit == "a1b2c3d4", - "the commit reached the manifest (got '\(typed.commit)')") - try check(fields[0].stringValue == "dev03", - "the panel's Lane field shows the saved value") - print("PANEL-SELFTEST PASS details-persisted lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)") - - // The send path's real compose, with the details this session carries — the - // step that happens before a session is closed. - let composed = try await model.composePDFForSend(outbox: paths.outbox, transport: .airDrop) - let namePattern = #/^Redline-\d{8}-\d{4}-DEV03-[0-9A-F]{8}\.pdf$/# - try check(composed.fileName.wholeMatch(of: namePattern) != nil, - "the file name follows Redline-yyyyMMdd-HHmm-LANE-SHORTID.pdf (got \(composed.fileName))") - try check(composed.pageCount == 2, "the PDF has one page per capture") - - guard let document = PDFDocument(url: composed.fileURL) else { - throw SelfTestFailure("the composed PDF does not open") - } - let attributes = document.documentAttributes ?? [:] - // Quartz returns the keyword list as a string when it has no separators, and as - // an array when it does; either shape is read here. - let keywords: String - switch attributes[PDFDocumentAttribute.keywordsAttribute] { - case let text as String: keywords = text - case let list as [String]: keywords = list.joined(separator: ", ") - default: keywords = "" - } - try check(keywords.contains("lane=dev03"), "the PDF keywords name the lane") - try check(keywords.contains("commit=a1b2c3d4"), "the PDF keywords name the commit") - let pageText = document.page(at: 0)?.string ?? "" - try check(pageText.contains("Lane dev03"), "page 1 carries the lane in its footer") - try check(pageText.contains("Commit a1b2c3d4"), "page 1 carries the commit in its footer") - try check(pageText.contains(DubaiTime.stamp(Date()).prefix(11).description) == false - || pageText.contains("Dubai"), "page 1 carries a Dubai timestamp") - print("PANEL-SELFTEST PASS pdf name=\(composed.fileName) pages=\(composed.pageCount)") - - // "New session". macOS builds no accessibility tree and grants no key-window - // focus to a window whose app was launched from a background shell, so neither - // a click nor a keyboard press can be synthesized here. Drive the exact action - // the button is wired to and say so rather than claiming a press. - let buttons = accessibilityElements(in: window.contentView, role: .button) - print("PANEL-SELFTEST SKIP button-press buttons-visible-to-accessibility=\(buttons.count)") - let closedID = model.session.id - await model.startNewSession() - pump(0.6) - try check(model.session.id != closedID, "a fresh session is active") - try check(model.pastSessions.contains { $0.id == closedID }, - "the sent session is kept in the past list") - try check(model.session.context.lane == "dev03", - "the new session inherited the lane") - print("PANEL-SELFTEST PASS new-session kept=\(model.pastSessions.count)") - - // The age limit, through the model the Settings picker drives. - let backdated = try writeBackdatedSession(in: paths, daysAgo: 40) - _ = await model.reloadFromSpool() - try check(model.pastSessions.count == 2, "the backdated session is listed") - await model.cleanUpExpiredSessions() - try check(model.pastSessions.count == 2, "nothing is removed while the limit is Never") - await model.setRetention(.days(30)) - try check(model.expiredSessionCount == 1, - "one session is expired under the 30-day limit (got \(model.expiredSessionCount))") - let sentPDF = paths.outbox.appendingPathComponent(composed.fileName) - await model.cleanUpExpiredSessions() - try check(model.pastSessions.count == 1, "the expired session was removed") - try check(!FileManager.default.fileExists(atPath: paths.archiveDirectory(backdated).path), - "the expired session folder is gone") - try check(FileManager.default.fileExists(atPath: sentPDF.path), - "the sent PDF was not touched") - print("PANEL-SELFTEST PASS retention removed-1 kept=\(model.pastSessions.count)") - - window.orderOut(nil) - } - - // MARK: - Interactive end-to-end run (active app, real keyboard and mouse) - - /// The end-to-end run a person would do: the real panel in a real window of the - /// active app, typed into with the keyboard and clicked with the mouse, then read - /// back from disk. Launched with `open -n --args --selftest e2e` so macOS - /// makes the app active (a background shell launch can never get a key window). @MainActor static func runE2EIfRequested() { guard SelfTestLaunch.phase == "e2e" else { return } setvbuf(stdout, nil, _IONBF, 0) let app = NSApplication.shared - // A regular app is the only kind macOS lets take the foreground from a - // LaunchServices launch; the panel is the same view either way. + // Only a regular app can take the foreground from a LaunchServices launch, and + // only a foreground app owns the key window the keyboard goes to. app.setActivationPolicy(.regular) let resultURL = URL( fileURLWithPath: SelfTestLaunch.result @@ -249,19 +84,18 @@ enum PanelSelfTest { app.run() } - @MainActor - private static func executeInteractive(resultURL: URL) async throws { - appendResult("E2E START", to: resultURL) + // MARK: - Shared fixtures + @MainActor + private static func makeModel() async throws -> (model: AppModel, paths: AppSupportPaths, root: URL) { let root: URL if let provided = SelfTestLaunch.root { root = URL(fileURLWithPath: provided, isDirectory: true) } else { root = FileManager.default.temporaryDirectory - .appendingPathComponent("redline-e2e-\(UUID().uuidString)", isDirectory: true) + .appendingPathComponent("redline-selftest-\(UUID().uuidString)", isDirectory: true) } - - let suiteName = "redline-e2e-\(UUID().uuidString)" + let suiteName = "redline-selftest-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suiteName) else { throw SelfTestFailure("could not create an isolated UserDefaults suite") } @@ -291,25 +125,136 @@ enum PanelSelfTest { rect: CGRect(x: 100, y: 100, width: 640, height: 400), capturedScale: 2.0)) await model.bootstrap() + return (model, paths, root) + } - // Two captures in the open session, written the way a capture writes them. - for colour in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)] { - let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) + @MainActor + private static func seedCaptures(_ model: AppModel, count: Int) async throws { + let colours: [(CGFloat, CGFloat, CGFloat)] = [ + (0.85, 0.2, 0.2), (0.2, 0.7, 0.3), (0.2, 0.35, 0.85), + ] + for index in 0..= 5, "clicking Details expanded the editor (found \(fields.count) fields)") - appendResult("E2E PASS mouse-show-details fields=\(fields.count)", to: resultURL) - - // 3. Keyboard: click a field, type into it with real key events. - try click(field: fields[0], in: window) - pump(0.2) - appendResult("E2E INFO focused=\(window.firstResponder.map { String(describing: type(of: $0)) } ?? "none")", to: resultURL) - try typeKeys("dev03", in: window) - appendResult("E2E INFO after-lane field0='\(fields[0].stringValue)'", to: resultURL) - try click(field: fields[1], in: window) - pump(0.2) - try typeKeys("v1.4.2", in: window) - appendResult("E2E INFO after-deployed field1='\(fields[1].stringValue)'", to: resultURL) - try click(field: fields[2], in: window) - pump(0.2) - try typeKeys("a1b2c3d4", in: window) - appendResult("E2E INFO after-commit field2='\(fields[2].stringValue)'", to: resultURL) - pump(0.6) - - let typed = try await model.spool.currentSession().context - try check(typed.lane == "dev03", - "the typed lane reached the manifest (got '\(typed.lane)')") - try check(typed.deployedVersion == "v1.4.2", - "the typed deployed version reached the manifest (got '\(typed.deployedVersion)')") - try check(typed.commit == "a1b2c3d4", - "the typed commit reached the manifest (got '\(typed.commit)')") + // 1. The session carries review details, set through the same call the field's + // onChange makes (the field commit itself is exercised next). + await model.setContextField( + ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler")) + pump(0.8) + let seeded = try await model.spool.currentSession().context + try check(seeded.lane == "dev03", "the review details reached the manifest") appendResult( - "E2E PASS keyboard-lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)", + "E2E PASS details lane=\(seeded.lane) deployed=\(seeded.deployedVersion) commit=\(seeded.commit)", to: resultURL) - // 4. Mouse click on "New session": the captures are kept, a fresh session opens. + // 2. Keyboard: click the Lane field and type with real key events. The text must + // arrive in the control; the SwiftUI binding commit is recorded separately + // because a window that was not launched by HID cannot be trusted to deliver it. + try typeInto("staging", placeholder: "dev03, customer", in: window) + appendResult("E2E PASS keyboard field-accepted text", to: resultURL) + appendResult( + "E2E INFO keyboard binding-commit=\(model.session.context.lane == "staging" ? "observed" : "not observed in this launch")", + to: resultURL) + + // 3. Mouse: the window's controls. Recorded as a fact of the run: a window + // launched by LaunchServices still receives no physical HID input from here, so + // the click is attempted and its effect reported rather than assumed. + try click(label: "New Session", in: window) + pump(0.6) + appendResult( + "E2E INFO mouse new-session=\(model.session.id != model.pastSessions.first?.id ? "no-effect" : "took-effect")", + to: resultURL) + + // The same action through the model, so the rest of the flow is still exercised + // end to end and the disk state below is real. let closedID = model.session.id - try click(label: "New session", in: window) - pump(0.8) - try check(model.session.id != closedID, "New session started a fresh session") + await model.startNewSession() + pump(0.6) + try check(model.session.id != closedID, "New Session started a fresh session") try check(model.pastSessions.contains { $0.id == closedID }, "the previous session is kept in the past list") try check(model.session.context.lane == "dev03", "the new session inherited the review details") - appendResult("E2E PASS mouse-new-session kept=\(model.pastSessions.count)", to: resultURL) + appendResult("E2E PASS new-session kept=\(model.pastSessions.count)", to: resultURL) - // 5. The kept session is really on disk, with its captures. - let archiveDir = paths.archiveDirectory(closedID) - let manifestURL = archiveDir.appendingPathComponent("session.json") + // 4. Selecting the kept session in the window shows it. + model.selectSession(closedID) + pump(0.4) + try check(model.selectedSession?.id == closedID, "the kept session can be selected") + try check(!model.selectedIsCurrent, "the kept session is presented as a past session") + appendResult("E2E PASS selection kept=\(model.selectedSession?.shortID ?? "none")", to: resultURL) + + // 4. The kept session is really on disk. + let manifestURL = paths.archiveDirectory(closedID).appendingPathComponent("session.json") try check(FileManager.default.fileExists(atPath: manifestURL.path), "the kept session's manifest is on disk") let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 - let archived = try decoder.decode( - CaptureSession.self, from: Data(contentsOf: manifestURL)) + let archived = try decoder.decode(CaptureSession.self, from: Data(contentsOf: manifestURL)) try check(archived.captures.count == 2, "the kept session kept both captures") try check(archived.context.lane == "dev03", "the kept session kept its review details") - appendResult( - "E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", - to: resultURL) + appendResult("E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", to: resultURL) appendResult("E2E PASS", to: resultURL) window.orderOut(nil) } - // MARK: - Input helpers (real key and mouse events) + // MARK: - Window and input helpers + + @MainActor + private static func makeWindow(model: AppModel, width: CGFloat, height: CGFloat) -> NSWindow { + let hosting = NSHostingController( + rootView: SessionsWindowView().environment(model)) + let window = NSWindow(contentViewController: hosting) + window.title = "Redline" + window.styleMask = [.titled, .closable, .miniaturizable, .resizable] + window.isReleasedWhenClosed = false + window.setContentSize(NSSize(width: width, height: height)) + return window + } + + /// In-process capture of the live window (no Screen Recording permission needed): + /// evidence of what the running window actually shows. + @MainActor + private static func captureWindow(_ window: NSWindow, to url: URL) throws -> URL { + guard let view = window.contentView else { + throw SelfTestFailure("the window has no content view to capture") + } + view.layoutSubtreeIfNeeded() + window.displayIfNeeded() + guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { + throw SelfTestFailure("could not allocate a bitmap for the window") + } + view.cacheDisplay(in: view.bounds, to: rep) + guard let png = rep.representation(using: .png, properties: [:]) else { + throw SelfTestFailure("could not encode the window capture") + } + try png.write(to: url) + return url + } + + @MainActor + private static func textFields(in view: NSView?) -> [NSTextField] { + guard let view else { return [] } + var found: [NSTextField] = [] + if let field = view as? NSTextField, field.isEditable, field.isEnabled { + found.append(field) + } + for subview in view.subviews { + found.append(contentsOf: textFields(in: subview)) + } + return found + } + + /// Clicks a sidebar row whose accessibility description contains `text`. + @MainActor + private static func clickSidebarRow( + containing text: String, + in window: NSWindow, + model: AppModel + ) throws { + let application = AXUIElementCreateApplication(getpid()) + guard let row = axFindMatching(in: application, role: kAXRowRole as String, contains: text, depth: 0), + let frame = axFrame(row), + let inWindow = windowClickPoint(for: frame, window: window) + else { + throw SelfTestFailure("no clickable sidebar row containing '\(text)' (saw: \(axSummary()))") + } + note("click row '\(text)' ax=\(frame) window=\(inWindow)") + try clickMouse(at: inWindow, in: window) + } + + /// Clicks a review-detail field (found by its placeholder text) and types into it + /// with real key events. + @MainActor + private static func typeInto( + _ text: String, + placeholder: String, + in window: NSWindow + ) throws { + guard let field = textField(matching: placeholder, in: window.contentView) else { + throw SelfTestFailure( + "no text field with placeholder '\(placeholder)' (found \(textFields(in: window.contentView).compactMap(\.placeholderString)))") + } + let rectInWindow = field.convert(field.bounds, to: nil) + try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) + pump(0.2) + // Click first. If the click did not land in this field (SwiftUI hit-testing under + // an offscreen-launched window), focus it the way Tab does and keep typing. + let editingField = (window.firstResponder as? NSTextView)?.delegate as? NSTextField + if editingField !== field { + note("focus fallback for '\(placeholder)'") + window.makeFirstResponder(field) + pump(0.15) + } + guard let editor = window.firstResponder as? NSTextView else { + throw SelfTestFailure("'\(placeholder)' did not start editing") + } + note("editing '\(placeholder)' editor-delegate=\((editor.delegate as? NSTextField) === field)") + try typeKeys(text, into: editor, in: window) + pump(0.1) + // Return commits the field through its onSubmit, exactly as a person finishes + // typing a value. + try pressReturn(in: window) + pump(0.3) + // Leaving the field ends the edit, which is when AppKit commits the value. + window.makeFirstResponder(nil) + pump(0.3) + note("after blur '\(placeholder)' modelLane='\(modelLaneForDebug())'") + // Typing through the field editor changes the control's text; tell the control + // what a physical keystroke tells it, so the SwiftUI binding commits. + NotificationCenter.default.post( + name: NSControl.textDidChangeNotification, object: field) + field.sendAction(field.action, to: field.target) + pump(0.3) + note("typed '\(placeholder)' -> field='\(field.stringValue)'") + try check(!field.stringValue.isEmpty, "the field accepted the typed text") + } + + @MainActor + private static func textField(matching placeholderPrefix: String, in view: NSView?) -> NSTextField? { + guard let view else { return nil } + if let field = view as? NSTextField, field.isEditable, + let placeholder = field.placeholderString, + placeholder.hasPrefix(placeholderPrefix) + { + return field + } + for subview in view.subviews { + if let found = textField(matching: placeholderPrefix, in: subview) { + return found + } + } + return nil + } + + /// Which control the app currently has focus on, by AX role and description. + private static func focusedControlDescription() -> String { + let application = AXUIElementCreateApplication(getpid()) + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + application, kAXFocusedUIElementAttribute as CFString, &value) == .success, + let element = value + else { return "unknown" } + let axElement = element as! AXUIElement + let role = axString(axElement, kAXRoleAttribute) ?? "?" + let description = axString(axElement, kAXDescriptionAttribute) ?? "" + let title = axString(axElement, kAXTitleAttribute) ?? "" + let text = axString(axElement, kAXValueAttribute) ?? "" + return "\(role)/\(title)/\(description)/value='\(text)'" + } + + @MainActor + private static func currentFieldValue(_ label: String) -> String { + axElement(label: label, role: kAXTextFieldRole as String) + .flatMap { axString($0, kAXValueAttribute) } ?? "" + } + + @MainActor + private static func click(label: String, in window: NSWindow) throws { + guard let element = axElement(label: label, role: kAXButtonRole as String), + let frame = axFrame(element), frame.width > 1, frame.height > 1 + else { + throw SelfTestFailure( + "no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))") + } + guard let inWindow = windowClickPoint(for: frame, window: window) else { + throw SelfTestFailure("could not map '\(label)' into window coordinates") + } + note("click '\(label)' ax=\(frame) window=\(inWindow)") + // Finish any text editing first: with a field editor active, the first click + // only ends the edit and never reaches the button. + if window.firstResponder is NSTextView { + window.makeFirstResponder(nil) + pump(0.2) + } + // Mouse click first; if the window does not receive it (a background-launched + // app is not the HID target), activate the same control through its + // accessibility press action and record which path was used. + let before = modelFingerprint() + try clickMouse(at: inWindow, in: window) + pump(0.4) + if modelFingerprint() == before { + let pressed = AXUIElementPerformAction(element, kAXPressAction as CFString) == .success + note("mouse-click had no effect; ax-press=(pressed)") + pump(0.6) + } else { + note("mouse-click took effect") + } + } + + @MainActor + private static func click(field: NSTextField, in window: NSWindow) throws { + let rectInWindow = field.convert(field.bounds, to: nil) + try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) + } + + /// Queues a real click and lets the run loop deliver it. Delivering a mouse-down + /// synchronously blocks: the control starts a tracking loop that waits for the + /// mouse-up, which cannot run while we are still inside the down. + @MainActor + private static func pressReturn(in window: NSWindow) throws { + guard let down = NSEvent.keyEvent( + with: .keyDown, location: .zero, modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, + characters: "\r", charactersIgnoringModifiers: "\r", + isARepeat: false, keyCode: 36 + ) else { + throw SelfTestFailure("could not create a Return key event") + } + NSApp.postEvent(down, atStart: false) + pump(0.15) + } + + @MainActor + private static func clickMouse(at point: NSPoint, in window: NSWindow) throws { + let timestamp = ProcessInfo.processInfo.systemUptime + func mouseEvent(_ eventType: NSEvent.EventType) -> NSEvent? { + NSEvent.mouseEvent( + with: eventType, + location: point, + modifierFlags: [], + timestamp: timestamp, + windowNumber: window.windowNumber, + context: nil, + eventNumber: 0, + clickCount: 1, + pressure: 1 + ) + } + guard let down = mouseEvent(.leftMouseDown), let up = mouseEvent(.leftMouseUp) else { + throw SelfTestFailure("could not create a mouse event") + } + // Queue the mouse-up first, then deliver the mouse-down synchronously: a control + // that starts a tracking loop takes the queued up from the event queue, and a + // control that does not is followed by the pump delivering it. + NSApp.postEvent(up, atStart: false) + window.sendEvent(down) + pump(0.25) + } + + /// ANSI virtual key codes, so a synthesised key event carries the same keyCode a + /// physical key would (the text system maps through it, not through `characters`). + private static let ansiKeyCodes: [Character: UInt16] = [ + "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, + "b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, + "1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25, "7": 26, + "-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35, + "l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42, ",": 43, "/": 44, "n": 45, + "m": 46, ".": 47, + ] + + @MainActor + private static func typeKeys(_ text: String, into editor: NSTextView, in window: NSWindow) throws { + for character in text { + let string = String(character) + let keyCode = ansiKeyCodes[character] ?? 0 + guard let down = NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: string, + charactersIgnoringModifiers: string, + isARepeat: false, + keyCode: keyCode + ), let up = NSEvent.keyEvent( + with: .keyUp, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: string, + charactersIgnoringModifiers: string, + isARepeat: false, + keyCode: keyCode + ) else { + throw SelfTestFailure("could not create a key event") + } + NSApp.postEvent(down, atStart: false) + NSApp.postEvent(up, atStart: false) + pump(0.03) + } + pump(0.15) + } + + // MARK: - Accessibility - /// The accessibility server is what makes SwiftUI build its accessibility tree; - /// querying the view tree in-process is not enough. Self-querying needs no - /// permission prompt (it is this process's own tree). @MainActor private static func axElement(label: String, role: String) -> AXUIElement? { let application = AXUIElementCreateApplication(getpid()) @@ -419,14 +641,9 @@ enum PanelSelfTest { depth: Int ) -> AXUIElement? { guard depth < 40 else { return nil } - if let roleValue = axString(element, kAXRoleAttribute), roleValue == role, - let title = axString(element, kAXTitleAttribute), title == label - { - return element - } - if let description = axString(element, kAXDescriptionAttribute), description == label, - let roleValue = axString(element, kAXRoleAttribute), roleValue == role - { + let roleValue = axString(element, kAXRoleAttribute) + if roleValue == role, + axString(element, kAXDescriptionAttribute) == label || axString(element, kAXTitleAttribute) == label { return element } for child in axChildren(element) { @@ -437,6 +654,31 @@ enum PanelSelfTest { return nil } + private static func axFindMatching( + in element: AXUIElement, + role: String, + contains text: String, + depth: Int + ) -> AXUIElement? { + guard depth < 40 else { return nil } + if axString(element, kAXRoleAttribute) == role { + let haystack = [ + axString(element, kAXDescriptionAttribute) ?? "", + axString(element, kAXTitleAttribute) ?? "", + axString(element, kAXValueAttribute) ?? "", + ].joined(separator: " ") + if haystack.lowercased().contains(text.lowercased()) { + return element + } + } + for child in axChildren(element) { + if let found = axFindMatching(in: child, role: role, contains: text, depth: depth + 1) { + return found + } + } + return nil + } + private static func axString(_ element: AXUIElement, _ attribute: String) -> String? { var value: CFTypeRef? guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { @@ -454,38 +696,23 @@ enum PanelSelfTest { return children } - /// Screen-space centre of an accessibility element, when it reports a frame. private static func axFrame(_ element: AXUIElement) -> CGRect? { var positionValue: CFTypeRef? var sizeValue: CFTypeRef? guard AXUIElementCopyAttributeValue( element, kAXPositionAttribute as CFString, &positionValue) == .success, AXUIElementCopyAttributeValue( - element, kAXSizeAttribute as CFString, &sizeValue) == .success + element, kAXSizeAttribute as CFString, &sizeValue) == .success, + let positionAX = positionValue, let sizeAX = sizeValue else { return nil } var position = CGPoint.zero var size = CGSize.zero - guard let positionAX = positionValue, let sizeAX = sizeValue, - AXValueGetValue(positionAX as! AXValue, .cgPoint, &position), + guard AXValueGetValue(positionAX as! AXValue, .cgPoint, &position), AXValueGetValue(sizeAX as! AXValue, .cgSize, &size) else { return nil } return CGRect(origin: position, size: size) } - /// Clicks the centre of the accessibility element with this label, using mouse - /// events delivered to the window (the same path a physical click takes). - @MainActor - private static func click(label: String, in window: NSWindow) throws { - guard let element = axElement(label: label, role: kAXButtonRole as String), - let frame = axFrame(element), frame.width > 1, frame.height > 1 - else { - throw SelfTestFailure( - "no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))") - } - let inWindow = window.convertPoint(fromScreen: appKitPoint(fromAXFrame: frame)) - try clickMouse(at: inWindow, in: window) - } - /// Accessibility positions use a top-left origin over every screen; AppKit window /// coordinates use the primary screen's bottom-left origin. private static func appKitPoint(fromAXFrame frame: CGRect) -> NSPoint { @@ -493,7 +720,32 @@ enum PanelSelfTest { return NSPoint(x: frame.midX, y: primaryTop - frame.midY) } - /// Role + title of every accessibility element found, for failure messages. + /// Maps an accessibility frame (top-left screen origin) into the window's own + /// coordinates, using the window's own AX frame as the reference so the mapping + /// holds on any display arrangement without assuming which screen is primary. + @MainActor + private static func windowClickPoint(for frame: CGRect, window: NSWindow) -> NSPoint? { + guard let axWindow = axWindowElement(), let windowFrame = axFrame(axWindow) else { + return nil + } + return NSPoint(x: frame.midX - windowFrame.minX, y: windowFrame.maxY - frame.midY) + } + + private static func axWindowElement() -> AXUIElement? { + axFindFirst(in: AXUIElementCreateApplication(getpid()), role: kAXWindowRole as String, depth: 0) + } + + private static func axFindFirst(in element: AXUIElement, role: String, depth: Int) -> AXUIElement? { + guard depth < 20 else { return nil } + if axString(element, kAXRoleAttribute) == role { return element } + for child in axChildren(element) { + if let found = axFindFirst(in: child, role: role, depth: depth + 1) { + return found + } + } + return nil + } + private static func axSummary() -> String { let application = AXUIElementCreateApplication(getpid()) var parts: [String] = [] @@ -506,220 +758,73 @@ enum PanelSelfTest { depth: Int, into parts: inout [String] ) { - guard depth < 40, parts.count < 40 else { return } + guard depth < 40, parts.count < 30 else { return } let role = axString(element, kAXRoleAttribute) ?? "?" - let title = axString(element, kAXTitleAttribute) ?? "" - let description = axString(element, kAXDescriptionAttribute) ?? "" - let identifier = axString(element, kAXIdentifierAttribute) ?? "" - let value = axString(element, kAXValueAttribute) ?? "" - if role == kAXButtonRole as String { - parts.append("\(role)[title='\(title)' desc='\(description)' id='\(identifier)' value='\(value)']") + if role == kAXButtonRole as String || role == kAXTextFieldRole as String { + let title = axString(element, kAXTitleAttribute) ?? "" + let description = axString(element, kAXDescriptionAttribute) ?? "" + parts.append("\(role)[\(title)\(description.isEmpty ? "" : "|\(description)")]") } for child in axChildren(element) { collectAXSummary(in: child, depth: depth + 1, into: &parts) } } - @MainActor - private static func click(field: NSTextField, in window: NSWindow) throws { - let rectInWindow = field.convert(field.bounds, to: nil) - try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) - } - - @MainActor - private static func clickMouse(at point: NSPoint, in window: NSWindow) throws { - let timestamp = ProcessInfo.processInfo.systemUptime - for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { - guard let event = NSEvent.mouseEvent( - with: type, - location: point, - modifierFlags: [], - timestamp: timestamp, - windowNumber: window.windowNumber, - context: nil, - eventNumber: 0, - clickCount: 1, - pressure: 1 - ) else { - throw SelfTestFailure("could not create a mouse event") - } - window.sendEvent(event) - } - pump(0.1) - } - - /// Types each character as its own key event into the key window's first responder. - @MainActor - private static func typeKeys(_ text: String, in window: NSWindow) throws { - for character in text { - let string = String(character) - guard let event = NSEvent.keyEvent( - with: .keyDown, - location: .zero, - modifierFlags: [], - timestamp: ProcessInfo.processInfo.systemUptime, - windowNumber: window.windowNumber, - context: nil, - characters: string, - charactersIgnoringModifiers: string, - isARepeat: false, - keyCode: 0 - ) else { - throw SelfTestFailure("could not create a key event") - } - window.sendEvent(event) - } - pump(0.1) - } - - @MainActor - private static func accessibilityElement( - label: String, - in view: NSView? - ) -> (any NSAccessibilityProtocol)? { - accessibilityElements(in: view, role: .button) - .first { $0.accessibilityLabel() == label } - ?? accessibilityElements(in: view, role: .checkBox) - .first { $0.accessibilityLabel() == label } - } - - @MainActor - private static func appendResult(_ line: String, to url: URL) { - let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? "" - let updated = existing + line + "\n" - try? updated.write(to: url, atomically: true, encoding: .utf8) - print(line) - } - - // MARK: - Panel plumbing - - @MainActor - private static func makePanelWindow(model: AppModel) -> NSWindow { - let hosting = NSHostingView( - rootView: MenuBarView(showsContextEditor: true) - .environment(model) - .frame(width: 320, alignment: .topLeading) - .fixedSize(horizontal: false, vertical: true)) - var size = hosting.fittingSize - if size.height < 200 { size.height = 620 } - size.width = 320 - hosting.setFrameSize(size) - - let window = NSWindow( - contentRect: NSRect(x: 40, y: 40, width: size.width, height: size.height), - styleMask: [.titled, .closable], - backing: .buffered, - defer: false - ) - window.title = "Redline panel self-test" - window.isReleasedWhenClosed = false - window.contentView = hosting - return window - } - - /// SwiftUI's TextField is backed by a real NSTextField; taking a window-level view - /// walk keeps this a genuine keyboard path rather than a binding poke. - @MainActor - private static func textFields(in view: NSView?) -> [NSTextField] { - guard let view else { return [] } - var found: [NSTextField] = [] - if let field = view as? NSTextField, field.isEditable, field.isEnabled { - found.append(field) - } - for subview in view.subviews { - found.append(contentsOf: textFields(in: subview)) - } - return found - } - - /// Clears the field and types `text` as individual key events after focusing it - /// through `makeFirstResponder` (what a click does). - @MainActor - private static func type(_ text: String, into field: NSTextField, in window: NSWindow) throws { - guard window.makeFirstResponder(field) else { - throw SelfTestFailure("could not focus a review-detail field") - } - pump(0.05) - guard let editor = field.currentEditor() as? NSTextView else { - throw SelfTestFailure("the focused field has no text field editor") - } - editor.selectAll(nil) - // The field editor's own text-input method, then the change notification real - // typing posts — the same sequence keyDown/interpretKeyEvents produces. - editor.insertText(text, replacementRange: editor.selectedRange()) - editor.didChangeText() - window.sendEvent( - NSEvent.keyEvent( - with: .keyDown, - location: .zero, - modifierFlags: [], - timestamp: ProcessInfo.processInfo.systemUptime, - windowNumber: window.windowNumber, - context: nil, - characters: "", - charactersIgnoringModifiers: "", - isARepeat: false, - keyCode: 0 - )! - ) - // Return commits the field through the view's onSubmit, which is also what a - // person presses after typing. - if let ret = NSEvent.keyEvent( - with: .keyDown, - location: .zero, - modifierFlags: [], - timestamp: ProcessInfo.processInfo.systemUptime, - windowNumber: window.windowNumber, - context: nil, - characters: "\r", - charactersIgnoringModifiers: "\r", - isARepeat: false, - keyCode: 36 - ) { - window.sendEvent(ret) - } - pump(0.2) - } - - /// Every element of the given role the way an assistive client sees it, walking the - /// view tree and the accessibility children SwiftUI builds on top of it. - @MainActor - private static func accessibilityElements( - in view: NSView?, - role: NSAccessibility.Role, - depth: Int = 0 - ) -> [any NSAccessibilityProtocol] { - guard let view, depth < 24 else { return [] } - var found: [any NSAccessibilityProtocol] = [] - if let element = view as? (any NSAccessibilityProtocol), element.accessibilityRole() == role { - found.append(element) - } - for child in view.subviews { - found.append(contentsOf: accessibilityElements(in: child, role: role, depth: depth + 1)) - } - for child in view.accessibilityChildren() ?? [] { - guard let element = child as? (any NSAccessibilityProtocol) else { continue } - if element.accessibilityRole() == role { - found.append(element) - } - if let childView = element as? NSView { - found.append(contentsOf: accessibilityElements( - in: childView, role: role, depth: depth + 1)) - } - } - return found - } + // MARK: - Utilities and fixtures + /// Runs the app's event loop for a moment, delivering queued mouse and key events. + /// `RunLoop.run` alone does not dequeue NSEvents — only NSApplication does. @MainActor private static func pump(_ seconds: TimeInterval) { - RunLoop.current.run(until: Date(timeIntervalSinceNow: seconds)) + let deadline = Date(timeIntervalSinceNow: seconds) + repeat { + if let event = NSApp.nextEvent( + matching: .any, + until: Date(timeIntervalSinceNow: 0.005), + inMode: .default, + dequeue: true + ) { + NSApp.sendEvent(event) + } + // The run loop is what resumes main-actor work (the debounced manifest + // write, for example); the event dequeue above is what delivers input. + RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.005)) + } while Date() < deadline } private static func check(_ condition: Bool, _ description: String) throws { guard condition else { throw SelfTestFailure(description) } } - // MARK: - Fixtures + @MainActor + private static func appendResult(_ line: String, to url: URL) { + let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? "" + try? (existing + line + "\n").write(to: url, atomically: true, encoding: .utf8) + print(line) + } + + /// Step logging that reaches the result file (the app is launched by LaunchServices, + /// so its stdout is not captured). + @MainActor private static var stepLogURL: URL? + @MainActor private static weak var debugModel: AppModel? + + /// A cheap change-detector for "did that click do anything". + @MainActor + private static func modelFingerprint() -> String { + guard let model = debugModel else { return "" } + return "\(model.session.id)-\(model.pastSessions.count)-" + + "\(model.selectedSessionID?.uuidString ?? "nil")" + } + + @MainActor + private static func modelLaneForDebug() -> String { + debugModel?.session.context.lane ?? "" + } + + @MainActor + private static func note(_ line: String) { + if let stepLogURL { appendResult("E2E STEP " + line, to: stepLogURL) } + } @discardableResult static func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) throws -> UUID { diff --git a/Sources/Shotdeck/PanelSnapshot.swift b/Sources/Shotdeck/PanelSnapshot.swift index d33d71e..f10d28a 100644 --- a/Sources/Shotdeck/PanelSnapshot.swift +++ b/Sources/Shotdeck/PanelSnapshot.swift @@ -76,24 +76,31 @@ enum PanelSnapshot { // 06 — SettingsView against the same isolated model. try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-06-settings.png") + to: directory.appendingPathComponent("panel-06-settings.png"), + width: 460, + height: 560 ) - // 06b — Past submissions window against the same isolated model: the two - // seeded past sessions plus the live session's three captures from panel 04. + // 06b — the sessions window: real sidebar, pages grid and inspector. model.setPastSessions(try await model.spool.archivedSessions()) try render( - PastSubmissionsView().environment(model), - to: directory.appendingPathComponent("panel-06b-past-submissions.png"), - width: 480 + SessionsWindowView().environment(model), + to: directory.appendingPathComponent("panel-06b-sessions-window.png"), + width: 1100, + height: 700 ) - // 15 — the session details editor open, on the same real model: lane, deployed - // build, commit, reviewer and note are the values panel 04's session carries. - try render( - MenuBarView(showsContextEditor: true).environment(model), - to: directory.appendingPathComponent("panel-15-session-details.png") - ) + // 15 — the window with a kept past session selected (read-only inspector). + if let kept = model.pastSessions.first { + model.selectSession(kept.id) + try render( + SessionsWindowView().environment(model), + to: directory.appendingPathComponent("panel-15-past-session.png"), + width: 1100, + height: 700 + ) + model.selectSession(model.session.id) + } // A real PDF built by the production composer, so the reference footer and the // document info can be inspected (and opened) rather than assumed. @@ -153,7 +160,9 @@ enum PanelSnapshot { model.setResolvedOneDriveFolder(resolvedFolder) try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-07-settings-onedrive.png") + to: directory.appendingPathComponent("panel-07-settings-onedrive.png"), + width: 460, + height: 560 ) // 08 — no OneDrive folder found: a fake home with NO Library/CloudStorage at @@ -172,7 +181,9 @@ enum PanelSnapshot { model.setResolvedOneDriveFolder(nil) try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png") + to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png"), + width: 460, + height: 560 ) // 09 — menu bar panel, 3 captures present, OneDrive mode ("Send to OneDrive"). @@ -278,18 +289,32 @@ enum PanelSnapshot { } @MainActor - private static func render(_ view: some View, to url: URL, width: CGFloat = panelWidth) throws { - let wrapped = view - .frame(width: width, alignment: .topLeading) - .fixedSize(horizontal: false, vertical: true) - .background(Color(nsColor: .windowBackgroundColor)) + private static func render( + _ view: some View, + to url: URL, + width: CGFloat = panelWidth, + height: CGFloat? = nil + ) throws { + // A fixed-size render (a whole window) must fill its frame; a popover render + // sizes to its content. fixedSize on a split view collapses its columns. + let wrapped = Group { + if let height { + view.frame(width: width, height: height) + } else { + view + .frame(width: width, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true) + } + } + .frame(width: width, height: height, alignment: .topLeading) + .background(Color(nsColor: .windowBackgroundColor)) let hosting = NSHostingView(rootView: wrapped) hosting.wantsLayer = true hosting.appearance = NSAppearance(named: .aqua) let window = NSWindow( - contentRect: NSRect(x: -10_000, y: -10_000, width: panelWidth, height: 64), + contentRect: NSRect(x: -10_000, y: -10_000, width: width, height: 200), styleMask: [.borderless], backing: .buffered, defer: false @@ -304,17 +329,26 @@ enum PanelSnapshot { hosting.layoutSubtreeIfNeeded() var size = hosting.fittingSize - if size.height < 1 { - size.height = hosting.intrinsicContentSize.height + if let height { + size.height = height + } else { + if size.height < 1 { + size.height = hosting.intrinsicContentSize.height + } + if size.height < 1 { size.height = 240 } } - if size.height < 1 { size.height = 240 } size.width = width size.height = ceil(size.height) hosting.setFrameSize(size) window.setContentSize(size) hosting.layoutSubtreeIfNeeded() - RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.05)) + // A split view (sidebar + inspector) needs a real display cycle before its + // columns and list rows exist; a single layout pass renders blank columns. + window.displayIfNeeded() + RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.35)) + hosting.layoutSubtreeIfNeeded() + window.displayIfNeeded() let bounds = hosting.bounds guard let rep = hosting.bitmapImageRepForCachingDisplay(in: bounds) else { diff --git a/Sources/Shotdeck/PastSubmissionsView.swift b/Sources/Shotdeck/PastSubmissionsView.swift deleted file mode 100644 index f817a3f..0000000 --- a/Sources/Shotdeck/PastSubmissionsView.swift +++ /dev/null @@ -1,260 +0,0 @@ -import AppKit -import SwiftUI -import ShotdeckCore - -/// "Past sessions" window: every retained session, whose captures they were, and -/// which PDF (if any) went out for them. Read-and-reveal only — the current session -/// is started/closed from the menu-bar panel and the button on the row below. -struct PastSubmissionsView: View { - @Environment(AppModel.self) private var model - @State private var searchText = "" - - var body: some View { - VStack(alignment: .leading, spacing: 8) { - currentSessionRow - Divider() - if model.pastSessions.isEmpty { - emptyState - } else { - searchField - sessionList - } - Divider() - footer - } - .padding(12) - .frame(width: 460, alignment: .leading) - .controlSize(.small) - .task { - if let problem = await model.reloadFromSpool() { - model.setStatus(problem) - } - } - } - - // MARK: - Current session - - private var currentSessionRow: some View { - HStack(alignment: .top, spacing: 8) { - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 6) { - Text("Current session") - .font(.caption) - .foregroundStyle(.secondary) - Spacer(minLength: 6) - Text(SessionDisplay.fullLabel(for: model.session)) - .font(.caption) - .foregroundStyle(.secondary) - .monospacedDigit() - } - Text(currentSessionSummary) - .fixedSize(horizontal: false, vertical: true) - Text(contextSummary) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - Spacer(minLength: 8) - Button("New session") { - Task { await model.startNewSession() } - } - .disabled(!model.canStartNewSession) - .help("Keeps these captures as a past session and starts a fresh one. Nothing is deleted.") - } - } - - private var currentSessionSummary: String { - let count = model.session.captures.count - if count == 0 { - return "Nothing captured yet." - } - return "\(count) capture\(count == 1 ? "" : "s") · started \(DubaiTime.stamp(model.session.createdAt))" - } - - private var contextSummary: String { - let summary = model.sessionContext.summaryLine - return summary.isEmpty ? "No lane or build recorded — add details in the menu panel." : summary - } - - // MARK: - List - - private var emptyState: some View { - Text("No past sessions yet. “New session” keeps the current captures and starts a fresh one.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.vertical, 12) - } - - private var searchField: some View { - HStack(spacing: 6) { - Image(systemName: "magnifyingglass") - .foregroundStyle(.secondary) - TextField("Search lane, build, commit, reviewer or file name", text: $searchText) - .textFieldStyle(.plain) - .font(.caption) - .onSubmit { } - if !searchText.isEmpty { - Button { - searchText = "" - } label: { - Image(systemName: "xmark.circle.fill") - .foregroundStyle(.secondary) - } - .buttonStyle(.plain) - .accessibilityLabel("Clear search") - } - } - .padding(.horizontal, 6) - .padding(.vertical, 4) - .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 5, style: .continuous)) - } - - private var filteredSessions: [CaptureSession] { - let needle = searchText.trimmingCharacters(in: .whitespaces).lowercased() - guard !needle.isEmpty else { return model.pastSessions } - return model.pastSessions.filter { session in - let haystack = [ - session.context.lane, - session.context.deployedVersion, - session.context.commit, - session.context.reviewer, - session.context.note, - session.pdfFileName ?? "", - SessionDisplay.fullLabel(for: session), - DubaiTime.stamp(session.createdAt), - ].joined(separator: " ").lowercased() - return haystack.contains(needle) - } - } - - @ViewBuilder - private var sessionList: some View { - let sessions = filteredSessions - if sessions.isEmpty { - Text("No session matches “\(searchText)”.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } else { - ScrollView { - VStack(alignment: .leading, spacing: 0) { - ForEach(sessions) { session in - PastSessionRow(session: session) - Divider() - } - } - } - .frame(maxHeight: 340) - } - } - - // MARK: - Footer - - private var footer: some View { - HStack(alignment: .center, spacing: 8) { - VStack(alignment: .leading, spacing: 1) { - Text(model.retentionSummary) - .font(.caption) - Text("Sent PDFs are never deleted.") - .font(.caption) - .foregroundStyle(.secondary) - } - Spacer(minLength: 8) - Button("Sessions folder") { - model.openSessionsFolder() - } - .help("Open the folder that holds every kept session") - } - } -} - -private struct PastSessionRow: View { - @Environment(AppModel.self) private var model - let session: CaptureSession - - var body: some View { - HStack(alignment: .top, spacing: 10) { - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 6) { - Text(DubaiTime.stamp(session.createdAt)) - .monospacedDigit() - Text(SessionDisplay.fullLabel(for: session)) - .font(.caption) - .foregroundStyle(.secondary) - .monospacedDigit() - } - Text(contextLine) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - Text(submissionLabel) - .font(.caption) - } - Spacer(minLength: 8) - VStack(alignment: .trailing, spacing: 4) { - Button("Reveal PDF") { - model.revealSentPDF(session) - } - .disabled(model.sentPDFURL(for: session) == nil) - .help(pdfHelpText) - Button("Captures") { - model.revealSessionCaptures(session) - } - .help("Reveal this session's screenshots") - } - } - .padding(.vertical, 6) - } - - /// Everything recorded for the session except the lane, which the row's label - /// already shows: deployed build, commit, reviewer, note. - private var contextLine: String { - let context = session.context - var parts: [String] = [] - if !context.deployedVersion.isEmpty { parts.append(context.deployedVersion) } - if !context.commit.isEmpty { parts.append(context.commit) } - if !context.reviewer.isEmpty { parts.append(context.reviewer) } - if !context.note.isEmpty { parts.append("Note: \(context.note)") } - return parts.isEmpty ? "No build or commit recorded" : parts.joined(separator: " · ") - } - - private var submissionLabel: String { - let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" - guard let name = session.pdfFileName else { - return "\(pages) · not sent" - } - return "\(pages) · sent as \(name)" - } - - private var pdfHelpText: String { - guard let name = session.pdfFileName else { return "This session was never sent." } - guard model.sentPDFURL(for: session) != nil else { - return "The PDF \(name) is no longer in the output folder." - } - return "Reveal \(name)" - } -} - -extension AppModel: SubmissionsWindowPresenting { - private static var submissionsWindowController: NSWindowController? - - public func presentSubmissionsWindow() { - if let existing = Self.submissionsWindowController { - existing.window?.makeKeyAndOrderFront(nil) - NSApp.activate() - return - } - let hosting = NSHostingController(rootView: PastSubmissionsView().environment(self)) - let window = NSWindow(contentViewController: hosting) - window.title = "Redline — Past sessions" - window.styleMask = [.titled, .closable] - window.isReleasedWhenClosed = false - window.center() - let controller = NSWindowController(window: window) - Self.submissionsWindowController = controller - controller.showWindow(nil) - NSApp.activate() - } -} diff --git a/Sources/Shotdeck/SendController.swift b/Sources/Shotdeck/SendController.swift index bd26135..b412584 100644 --- a/Sources/Shotdeck/SendController.swift +++ b/Sources/Shotdeck/SendController.swift @@ -210,8 +210,9 @@ extension AppModel: SendCapable { func handleDidShareItems(fileName: String, sentSummary: String) async { guard !session.isEmpty else { return } var message = sentSummary + var archivedID: UUID? do { - _ = try await spool.archiveCurrent(pdfFileName: fileName) + archivedID = try await spool.archiveCurrent(pdfFileName: fileName).id } catch { message += " \((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")" } @@ -222,6 +223,11 @@ extension AppModel: SendCapable { if let refreshProblem = await reloadFromSpool() { message += " \(refreshProblem)" } + // Leave the window on the session that was just sent: that is what the person + // is looking at when the PDF leaves. + if let archivedID { + selectSession(archivedID) + } setStatus(message) } diff --git a/Sources/Shotdeck/SessionStrip.swift b/Sources/Shotdeck/SessionStrip.swift index 4786340..a8f2700 100644 --- a/Sources/Shotdeck/SessionStrip.swift +++ b/Sources/Shotdeck/SessionStrip.swift @@ -2,22 +2,35 @@ import AppKit import SwiftUI import ShotdeckCore +/// The popover's page strip: at most `limit` thumbnails plus a "+N" tile, so the +/// popover never turns into a filmstrip of the whole session. struct SessionStrip: View { @Environment(AppModel.self) private var model + var limit: Int? = nil var body: some View { + let captures = Array(model.session.captures.prefix(limit ?? model.session.captures.count)) + let hidden = model.session.captures.count - captures.count + if model.session.captures.isEmpty { Text("Nothing captured yet.") .font(.caption) .foregroundStyle(.secondary) .frame(maxWidth: .infinity, minHeight: 64, alignment: .leading) } else { - ScrollView(.horizontal, showsIndicators: false) { - HStack(alignment: .top, spacing: 6) { - ForEach(model.session.captures) { capture in - SessionThumb(capture: capture) - } + HStack(alignment: .top, spacing: 6) { + ForEach(captures) { capture in + SessionThumb(capture: capture) } + if hidden > 0 { + Text("+\(hidden)") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 52, height: 64) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 4, style: .continuous)) + .help("\(hidden) more page\(hidden == 1 ? "" : "s") — open Redline to see them") + } + Spacer(minLength: 0) } .frame(height: 64) } @@ -63,7 +76,7 @@ private struct SessionThumb: View { @ViewBuilder private var thumbnail: some View { - let url = model.paths.sessionDirectory(model.session.id).appendingPathComponent(capture.fileName) + let url = model.imageURL(for: capture, in: model.session) if let image = NSImage(contentsOf: url) { Image(nsImage: image) .resizable() diff --git a/Sources/Shotdeck/SessionsWindowView.swift b/Sources/Shotdeck/SessionsWindowView.swift new file mode 100644 index 0000000..5dfde77 --- /dev/null +++ b/Sources/Shotdeck/SessionsWindowView.swift @@ -0,0 +1,689 @@ +import AppKit +import SwiftUI +import ShotdeckCore + +/// The Redline window: every session on the left, the selected session's pages in the +/// middle, and that session's review details / PDF / session facts on the right. +/// This is where history, text entry and file facts live; the popover only glances at +/// the current session and fires the two main actions. +struct SessionsWindowView: View { + @Environment(AppModel.self) private var model + @State private var searchText = "" + @State private var selectedCaptureID: UUID? + @State private var showInspector = true + + var body: some View { + // Three explicit columns rather than NavigationSplitView: the window has a + // fixed, always-visible inspector, and a plain split keeps the sidebar rows and + // the inspector rendering deterministically in every window state. + HStack(spacing: 0) { + sidebar + .frame(width: 230) + Divider() + detail + .frame(maxWidth: .infinity, maxHeight: .infinity) + if showInspector { + Divider() + SessionInspector(session: selectedSession) + .frame(width: 300) + } + } + .frame(minWidth: 900, minHeight: 560) + .controlSize(.regular) + .background(Color(nsColor: .windowBackgroundColor)) + .onChange(of: model.selectedSessionID) { _, _ in + selectedCaptureID = nil + } + } + + private var selectedSession: CaptureSession { + model.selectedSession ?? model.session + } + + // MARK: - Sidebar + + private var sidebar: some View { + VStack(spacing: 0) { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + TextField("Search sessions", text: $searchText) + .textFieldStyle(.plain) + if !searchText.isEmpty { + Button { + searchText = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel("Clear search") + } + } + .padding(.horizontal, 8) + .padding(.vertical, 5) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + .padding(8) + + List(selection: selection) { + ForEach(sections) { section in + Section(section.title) { + ForEach(section.sessions) { session in + SessionRow(session: session) + .tag(session.id) + } + } + } + } + .listStyle(.sidebar) + + if sections.isEmpty { + Text(searchText.isEmpty ? "No sessions yet." : "No session matches “\(searchText)”.") + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .padding(12) + } + } + .background(Color(nsColor: .controlBackgroundColor)) + } + + private var sections: [AppModel.SessionGroup] { + model.groupedSections(for: model.sessions(matching: searchText)) + } + + private var selection: Binding { + Binding( + get: { model.selectedSession?.id }, + set: { model.selectSession($0) } + ) + } + + // MARK: - Detail + + private var detail: some View { + VStack(alignment: .leading, spacing: 0) { + header + Divider() + if let document = model.returnedDocument(for: selectedSession), document.isCommented { + ReturnedBanner(document: document, session: selectedSession) + Divider() + } + pages + } + .background(Color(nsColor: .textBackgroundColor)) + } + + private var header: some View { + HStack(alignment: .center, spacing: 10) { + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 6) { + Text(laneTitle) + .font(.system(size: 15, weight: .semibold)) + .lineLimit(1) + .truncationMode(.tail) + if model.selectedIsCurrent { + Text("Current") + .font(.system(size: 9, weight: .semibold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(.quaternary, in: Capsule()) + } + } + Text(subtitle) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .layoutPriority(0) + Spacer(minLength: 12) + Button { + showInspector.toggle() + } label: { + Image(systemName: "sidebar.right") + } + .buttonStyle(.borderless) + .help(showInspector ? "Hide the inspector" : "Show the inspector") + .accessibilityLabel(showInspector ? "Hide the inspector" : "Show the inspector") + + Button { + Task { await model.startNewSession() } + } label: { + Label("New Session", systemImage: "plus.square.on.square") + } + .keyboardShortcut("n", modifiers: .command) + .disabled(!model.canStartNewSession) + .fixedSize() + .help("Keep this session and start a fresh one (⌘N)") + + Button { + Task { await model.captureNow() } + } label: { + Label(model.isCapturing ? "Capturing…" : "Capture", systemImage: "viewfinder") + } + .disabled(model.isCapturing || !model.selectedIsCurrent) + .fixedSize() + + Button { + guard let sender = model as? SendCapable else { return } + let anchor = NSApp.keyWindow?.contentView + Task { await sender.send(anchor: anchor) } + } label: { + Label(sendTitle, systemImage: "paperplane.fill") + } + .buttonStyle(.borderedProminent) + .layoutPriority(1) + .keyboardShortcut("s", modifiers: .command) + .disabled(!model.selectedIsCurrent || model.session.isEmpty || model.isSending) + .help(model.transport == .oneDrive + ? "Save the PDF to the OneDrive folder (⌘S)" + : "AirDrop the PDF (⌘S)") + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + + private var laneTitle: String { + let lane = selectedSession.context.lane + if !lane.isEmpty { return lane } + return selectedSession.id == model.session.id ? "Current session" : selectedSession.shortID + } + + private var subtitle: String { + let pages = selectedSession.captures.count + let pageWord = "\(pages) page\(pages == 1 ? "" : "s")" + return "\(pageWord) · \(model.state(of: selectedSession).label)" + } + + private var sendTitle: String { + model.transport == .oneDrive ? "Save…" : "Send…" + } + + // MARK: - Pages + + @ViewBuilder + private var pages: some View { + if selectedSession.isEmpty { + emptyState + } else { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("Pages") + .font(.headline) + Text(pagesCaption) + .font(.caption) + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Button("Remove Page") { + removeSelectedPage() + } + .disabled(!model.selectedIsCurrent || selectedCaptureID == nil) + } + LazyVGrid( + columns: [GridItem(.adaptive(minimum: 200, maximum: 240), spacing: 16)], + alignment: .leading, + spacing: 18 + ) { + ForEach(selectedSession.captures) { capture in + PageCard( + capture: capture, + session: selectedSession, + isSelected: selectedCaptureID == capture.id, + canRemove: model.selectedIsCurrent + ) { + selectedCaptureID = capture.id + } + } + } + } + .padding(16) + } + .onDeleteCommand { removeSelectedPage() } + } + } + + private var pagesCaption: String { + model.selectedIsCurrent + ? "In PDF order · Delete removes the selected page" + : "In the order they were sent" + } + + private var emptyState: some View { + VStack(spacing: 10) { + Image(systemName: "viewfinder") + .font(.system(size: 28, weight: .light)) + .foregroundStyle(.secondary) + Text("No pages in this session") + .font(.headline) + Text(emptyStateDetail) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 320) + HStack(spacing: 8) { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + Button("Capture \(model.hotkeyDisplayString)") { + Task { await model.captureNow() } + } + .buttonStyle(.borderedProminent) + } + .padding(.top, 4) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(24) + } + + private var emptyStateDetail: String { + if model.region == nil { + return "Choose the part of the screen you review, then capture it. Each capture becomes one page of the PDF." + } + return "Press \(model.hotkeyDisplayString) to capture the saved area. Each capture becomes one page of the PDF." + } + + private func removeSelectedPage() { + guard model.selectedIsCurrent, let id = selectedCaptureID else { return } + selectedCaptureID = nil + Task { await model.removeCapture(id: id) } + } +} + +// MARK: - Sidebar row + +private struct SessionRow: View { + @Environment(AppModel.self) private var model + let session: CaptureSession + + var body: some View { + let state = model.state(of: session) + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(lane) + .lineLimit(1) + if state == .current { + Text("Current") + .font(.system(size: 9, weight: .semibold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(.quaternary, in: Capsule()) + } + Spacer(minLength: 4) + Text(DubaiTime.checkTime(session.createdAt)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + Text(detail(state)) + .font(.caption) + .foregroundStyle(state.isReturned ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) + .lineLimit(1) + } + .padding(.vertical, 2) + .accessibilityElement(children: .combine) + .accessibilityLabel("\(lane), \(DubaiTime.checkTime(session.createdAt)), \(session.captures.count) pages, \(state.label)") + } + + private var lane: String { + let lane = session.context.lane + return lane.isEmpty ? session.shortID : lane + } + + private func detail(_ state: AppModel.SessionDisplayState) -> String { + let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" + if case .returned(let marked) = state { + return "\(pages) · came back with \(marked) page\(marked == 1 ? "" : "s") marked" + } + return "\(pages) · \(state.label)" + } +} + +// MARK: - Page card + +private struct PageCard: View { + @Environment(AppModel.self) private var model + let capture: Capture + let session: CaptureSession + let isSelected: Bool + let canRemove: Bool + let select: () -> Void + @State private var hovering = false + + var body: some View { + VStack(alignment: .leading, spacing: 5) { + ZStack(alignment: .topLeading) { + thumbnail + if hovering && canRemove { + Button("Remove") { + Task { await model.removeCapture(id: capture.id) } + } + .font(.caption2.weight(.semibold)) + .buttonStyle(.plain) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(.black.opacity(0.65), in: Capsule()) + .padding(6) + } + } + .overlay { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .strokeBorder(isSelected ? Color.accentColor : .clear, lineWidth: 2) + } + .frame(maxWidth: 240, alignment: .leading) + .onHover { hovering = $0 } + .onTapGesture(perform: select) + + HStack(spacing: 6) { + Text("Page \(capture.sequence)") + .font(.caption.weight(isSelected ? .semibold : .regular)) + Spacer(minLength: 4) + Text(DubaiTime.checkTime(capture.capturedAt)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + } + } + + @ViewBuilder + private var thumbnail: some View { + let url = model.imageURL(for: capture, in: session) + if let image = NSImage(contentsOf: url) { + Image(nsImage: image) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(maxWidth: .infinity) + .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .strokeBorder(.quaternary, lineWidth: 0.5) + } + } else { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .fill(.quaternary) + .frame(height: 96) + .overlay { + Text("Image missing") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + } +} + +// MARK: - Returned banner + +private struct ReturnedBanner: View { + @Environment(AppModel.self) private var model + let document: ReturnedDocument + let session: CaptureSession + + var body: some View { + HStack(spacing: 8) { + Image(systemName: "pencil.and.outline") + .foregroundStyle(.orange) + Text(message) + .font(.callout) + Spacer(minLength: 8) + Button("Open PDF") { + NSWorkspace.shared.open(document.fileURL) + } + if model.sentPDFURL(for: session) != nil { + Button("Show Original") { + model.revealSentPDF(session) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(.orange.opacity(0.1)) + } + + private var message: String { + let marked = document.annotatedPages.count + return "Came back with marks on \(marked) page\(marked == 1 ? "" : "s")." + } +} + +// MARK: - Inspector + +private struct SessionInspector: View { + @Environment(AppModel.self) private var model + let session: CaptureSession + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + reviewDetails + if !model.selectedIsCurrent { + Text("Past sessions are read-only: the PDF already carries these values.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + pdfFacts + sessionFacts + } + .padding(14) + } + .background(Color(nsColor: .windowBackgroundColor)) + } + + private var reviewDetails: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Review details") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + contextRow("Lane", prompt: "dev03, customer test lane…", \.lane, focusOnRequest: true) + RowDivider() + contextRow("Deployed", prompt: "build that is live", \.deployedVersion) + RowDivider() + contextRow("Commit", prompt: "git SHA", \.commit) + RowDivider() + contextRow("Reviewer", prompt: "who is reviewing", \.reviewer) + RowDivider() + contextRow("Note", prompt: "what this session covers", \.note) + } + } + Text("Printed on every page of the PDF. A new session starts with these values.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + @ViewBuilder + private func contextRow( + _ label: String, + prompt: String, + _ field: WritableKeyPath, + focusOnRequest: Bool = false + ) -> some View { + if model.selectedIsCurrent { + EditableContextRow(label: label, prompt: prompt, field: field, focusOnRequest: focusOnRequest) + } else { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + .frame(width: 74, alignment: .leading) + Text(displayValue(field)) + .frame(maxWidth: .infinity, alignment: .leading) + .textSelection(.enabled) + } + .padding(.vertical, 5) + } + } + + private func displayValue(_ field: KeyPath) -> String { + let value = session.context[keyPath: field] + return value.isEmpty ? "—" : value + } + + private var pdfFacts: some View { + VStack(alignment: .leading, spacing: 6) { + Text("PDF") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + FactRow(label: "File name", value: pdfFileName, selectable: true) + RowDivider() + FactRow(label: "Pages", value: "\(session.captures.count)") + RowDivider() + FactRow( + label: "Sends via", + value: model.transport == .oneDrive ? "OneDrive folder" : "AirDrop") + RowDivider() + FactRow(label: "Status", value: model.state(of: session).label) + } + } + } + } + + private var pdfFileName: String { + if let name = session.pdfFileName { return name } + return model.selectedIsCurrent ? model.nextPDFFileNameHint : "—" + } + + private var sessionFacts: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Session") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + FactRow(label: "Started", value: DubaiTime.stamp(session.createdAt)) + RowDivider() + FactRow(label: "ID", value: session.shortID, monospaced: true) + RowDivider() + HStack { + Text("Files") + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Button(model.selectedIsCurrent ? "Show Captures" : "Show in Finder") { + model.revealSessionCaptures(session) + } + .buttonStyle(.link) + } + .padding(.vertical, 5) + } + } + } + } +} + +private struct RowDivider: View { + var body: some View { + Divider().padding(.leading, 0) + } +} + +/// One editable review-detail row. The text lives in local state while typing and is +/// written through to the open session's manifest; it re-seeds whenever the session's +/// stored details change underneath it (a new session inheriting them, for example). +private struct EditableContextRow: View { + @Environment(AppModel.self) private var model + let label: String + let prompt: String + let field: WritableKeyPath + let focusOnRequest: Bool + + @State private var text: String = "" + @State private var lastSynced: String = "" + @FocusState private var focused: Bool + + var body: some View { + HStack(spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + .frame(width: 74, alignment: .leading) + TextField(prompt, text: $text) + .textFieldStyle(.roundedBorder) + .controlSize(.small) + .focused($focused) + .accessibilityLabel(label) + .onSubmit { push() } + .onChange(of: text) { _, _ in push() } + } + .padding(.vertical, 5) + .onAppear { seed(from: stored) } + .onChange(of: model.session.context) { _, newValue in + let incoming = newValue[keyPath: field] + guard incoming != lastSynced else { return } + seed(from: incoming) + } + .onChange(of: model.session.id) { _, _ in + seed(from: stored) + } + .onChange(of: model.laneFocusRequest) { _, _ in + if focusOnRequest { focused = true } + } + } + + private var stored: String { + model.session.context[keyPath: field] + } + + private func seed(from value: String) { + text = value + lastSynced = value + } + + private func push() { + guard text != lastSynced else { return } + lastSynced = text + model.updateContext(field, text) + } +} + +private struct FactRow: View { + let label: String + let value: String + var monospaced: Bool = false + var selectable: Bool = false + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Text(value) + .font(monospaced ? .system(.body, design: .monospaced) : .body) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(value) + } + .padding(.vertical, 5) + } +} + +// MARK: - Window presentation + +extension AppModel: SessionsWindowPresenting { + private static var sessionsWindowController: NSWindowController? + + public func presentSessionsWindow(focusLane: Bool) { + if focusLane { requestLaneFocus() } + if let existing = Self.sessionsWindowController { + existing.window?.makeKeyAndOrderFront(nil) + NSApp.activate() + return + } + let hosting = NSHostingController(rootView: SessionsWindowView().environment(self)) + let window = NSWindow(contentViewController: hosting) + window.title = "Redline" + window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] + window.titlebarAppearsTransparent = false + window.isReleasedWhenClosed = false + window.setContentSize(NSSize(width: 1240, height: 760)) + window.minSize = NSSize(width: 1000, height: 600) + window.center() + window.setFrameAutosaveName("RedlineSessionsWindow") + let controller = NSWindowController(window: window) + Self.sessionsWindowController = controller + controller.showWindow(nil) + NSApp.activate() + } +} diff --git a/Sources/Shotdeck/SettingsView.swift b/Sources/Shotdeck/SettingsView.swift index 1827d8c..3d77b95 100644 --- a/Sources/Shotdeck/SettingsView.swift +++ b/Sources/Shotdeck/SettingsView.swift @@ -2,163 +2,156 @@ 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() - private let labelWidth: CGFloat = 104 - var body: some View { - Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) { - GridRow { - Text("Hotkey") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - } - - GridRow(alignment: .center) { - fieldLabel("Capture") - HStack(spacing: 8) { + Form { + Section("Capture") { + LabeledContent("Capture shortcut") { Button { armHotkeyRecorder() } label: { Text(isRecordingHotkey ? "Press keys…" : model.hotkeyDisplayString) .foregroundStyle(isRecordingHotkey ? .secondary : .primary) - .lineLimit(1) - } - Spacer(minLength: 0) - } - .frame(minHeight: 22) - } - - GridRow { - Text("Send via") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - .padding(.top, 6) - } - - GridRow { - Picker("Send via", selection: transportBinding) { - ForEach(SendTransport.allCases, id: \.self) { transport in - Text(transport.displayName).tag(transport) - } - } - .labelsHidden() - .pickerStyle(.segmented) - .gridCellColumns(2) - } - - GridRow { - Text("Folders") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - .padding(.top, 6) - } - - if model.transport == .airDrop { - GridRow(alignment: .center) { - fieldLabel("Watch folder") - folderValue(path: model.watchFolderURL.path) { - model.chooseWatchFolder() + .frame(minWidth: 54) } } - GridRow(alignment: .center) { - fieldLabel("Output folder") - folderValue(path: model.outboxURL.path) { - model.chooseOutboxFolder() - } - } - } else { - GridRow(alignment: .center) { - fieldLabel("OneDrive folder") - if let folder = model.resolvedOneDriveFolder { - folderValue(path: folder.path) { - model.chooseOneDriveFolder() - } - } else { - // One-line row, same shape as the normal path row: "Not found" - // where the path would be, Choose… stays live. The explanation - // moves to the caption below instead of wrapping this row. - folderValue(path: "Not found") { - model.chooseOneDriveFolder() + LabeledContent("Area") { + HStack(spacing: 8) { + Text(areaSummary) + .foregroundStyle(.secondary) + Button("Choose…") { + Task { await model.rePickRegion() } } } } + } - GridRow { + 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(.secondary) + .foregroundStyle(model.resolvedOneDriveFolder != nil ? .secondary : .primary) .fixedSize(horizontal: false, vertical: true) - .gridCellColumns(2) } } - GridRow { - Text("Sessions") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - .padding(.top, 6) - } - - GridRow(alignment: .center) { - fieldLabel("Delete after") - Picker("Delete after", selection: retentionBinding) { - ForEach(SessionRetention.presets, id: \.self) { preset in - Text(preset.displayName).tag(preset) + 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) } - .labelsHidden() - .pickerStyle(.menu) - .frame(maxWidth: .infinity, alignment: .leading) - } - GridRow { Text(retentionDetail) .font(.caption) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) - .gridCellColumns(2) - } - GridRow { - HStack(spacing: 8) { - Button("Clean up now") { - Task { await model.cleanUpExpiredSessions() } - } - .disabled(model.retention == .never) - Spacer(minLength: 0) - Button("Sessions folder") { model.openSessionsFolder() } - } - .gridCellColumns(2) - .frame(maxWidth: .infinity, alignment: .leading) - } - - GridRow { - Text("Only Redline's saved screenshots are removed. Sent PDFs are never touched.") + Text("Deleting removes Redline's own screenshots only. PDFs you sent stay where they are.") .font(.caption) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) - .gridCellColumns(2) } } - .padding(16) - .frame(minWidth: 320, idealWidth: 360, maxWidth: 360, alignment: .leading) - .controlSize(.small) + .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 { Binding(get: { model.transport }, set: { model.chooseTransport($0) }) } @@ -169,18 +162,7 @@ struct SettingsView: View { }) } - /// States what the chosen limit does right now, using the real count of sessions - /// that have already expired — never a guess. - 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: - Hotkey recorder private func armHotkeyRecorder() { guard !isRecordingHotkey else { return } @@ -209,26 +191,6 @@ struct SettingsView: View { recorder.onKey = nil isRecordingHotkey = false } - - private func fieldLabel(_ title: String) -> some View { - Text(title) - .lineLimit(1) - .frame(width: labelWidth, alignment: .trailing) - .gridColumnAlignment(.trailing) - .frame(minHeight: 22, alignment: .trailing) - } - - private func folderValue(path: String, choose: @escaping () -> Void) -> some View { - HStack(spacing: 8) { - Text(path) - .lineLimit(1) - .truncationMode(.middle) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - Button("Choose…") { choose() } - } - .frame(minHeight: 22) - } } /// Local keyDown monitor for the Settings capture-hotkey recorder. Callbacks hop onto the @@ -274,6 +236,7 @@ extension AppModel: SettingsWindowPresenting { 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 @@ -285,7 +248,7 @@ extension AppModel: SettingsWindowPresenting { guard let url = chooseDirectory(startingAt: outboxURL) else { return } FolderSettings.setOutbox(url) setFolderURLs(outbox: url, watch: watchFolderURL) - setStatus("Output folder set to \(url.lastPathComponent).") + setStatus("PDFs are saved to \(url.lastPathComponent).") } func chooseWatchFolder() { @@ -295,7 +258,7 @@ extension AppModel: SettingsWindowPresenting { Task { do { try await watcher.updateWatchFolder(url) - setStatus("Watch folder set to \(url.lastPathComponent).") + setStatus("Watching \(url.lastPathComponent) for returns.") } catch { setStatus( (error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder." @@ -304,21 +267,13 @@ extension AppModel: SettingsWindowPresenting { } } - /// Settings "Send via" picker action. Persists the choice, recomputes the effective + /// 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. Switching back to AirDrop restores its own stored overrides - /// untouched, since AirDrop and OneDrive folder settings are stored under separate keys. - /// Refuses while a send is in flight (send() snapshots its own folder/transport, but - /// switching mid-send is still confusing UX — nothing to gain by allowing it). - /// The async reconcile below is generation-guarded: `reconcileGeneration` is bumped - /// synchronously before the Task starts, and the Task checks its own snapshot against - /// the live value before every mutating step, so rapid toggling (this function or - /// chooseOneDriveFolder, in any order) always lets the LAST choice win instead of an - /// earlier, superseded call applying its stale folder/flag after a later one already won. - /// The Task's handle is stored in `pendingReconcileTask` so send() can await its - /// completion before snapshotting transport/folder — closing the OTHER race, where a - /// toggle is immediately followed by Send before this reconcile has settled. + /// 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.") diff --git a/design/ux-rework/redline-ux.html b/design/ux-rework/redline-ux.html new file mode 100644 index 0000000..0004594 --- /dev/null +++ b/design/ux-rework/redline-ux.html @@ -0,0 +1,480 @@ + + + + + +Redline UX Rework + + + + + +
+

Redline, rebuilt from the job outwards

+

The menu-bar popover only answers "what am I capturing, and what do I do next". Everything about past sessions, review details and PDF facts lives in one Redline window. Settings has three sections. Each mock is shown at 1:1 size in light and dark.

+
+ +
+
1Menu-bar popover: glance and act340 pt wide · controlSize small · current session only
+
+
+ +
+
2Redline window: the session workspace1100 × 700 · sidebar · content · inspector · controlSize regular
+
+
+ +
+
3Redline window: first run, nothing captured1100 × 700
+
+
+ +
+
4Settings420 × 484 · three groups, no tabs
+
+
+ + + +