Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions Sources/ContextLensApp/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ import ContextLensCapture
@Published var exportPreviewError: String?
@Published var preview: NSImage?
@Published var editorImage: NSImage?
@Published var screenPermission = false
@Published private(set) var screenAccess: ScreenAccessState = .unverified
var screenPermission: Bool { screenAccess.isVerified }
@Published var checkingScreenAccess = false
@Published var screenAccessError: String?
private var screenAccessVerified = false
@Published var axPermission = Permissions.accessibility
@Published var storageBase = UserDefaults.standard.string(forKey: "storagePath").map { URL(fileURLWithPath: $0) } ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("ContextLens/Sessions") {
didSet { UserDefaults.standard.set(storageBase.path, forKey: "storagePath") }
Expand Down Expand Up @@ -105,29 +104,38 @@ import ContextLensCapture
axPermission = Permissions.accessibility
do {
guard let available = try await ScreenAccessProbe.windows(preflightGranted: Permissions.screenRecording,
userInitiated: userInitiated, previouslyVerified: screenAccessVerified) else {
screenPermission = false; windows = []; windowID = nil; preview = nil
status = "Screen capture access has not been verified. Choose Check Access."
userInitiated: userInitiated, previouslyVerified: screenPermission) else {
windows = []; windowID = nil; preview = nil
// A skipped passive check has no new evidence. Preserve an earlier
// denial/error instead of relabeling it as an unverified first launch.
status = screenAccess.message
return
}
screenAccessVerified = true; screenPermission = true; screenAccessError = nil; windows = available
screenAccess = .verified; windows = available
if !available.contains(where: { $0.id == windowID }) { windowID = nil; preview = nil }
if available.isEmpty { status = "Access verified. Open an application window, then refresh." }
else if !userInitiated { if session.frames.isEmpty { status = "Choose a window to begin." } }
else { status = "Screen capture access verified. Select a window to capture." }
} catch {
screenAccessVerified = false; screenPermission = false; windows = []; windowID = nil; preview = nil
screenAccessError = error.localizedDescription
status = "macOS could not verify screen capture access. If Settings is enabled, reopen this build and check again."
screenAccess = ScreenAccessState(error: error, permissionDenied: WindowCapture.endReason(for: error) == .permissionDenied)
windows = []; windowID = nil; preview = nil
status = screenAccess.message
}
}
func showPreview() async {
guard !recording, let w = windows.first(where: { $0.id == windowID }) else { return }
do { let (img, _) = try await WindowCapture.image(window: w.window); preview = NSImage(cgImage: img, size: .zero) }
catch { self.error = error.localizedDescription }
catch {
if WindowCapture.endReason(for: error) == .permissionDenied {
screenAccess = ScreenAccessState(error: error, permissionDenied: true)
windows = []; windowID = nil; preview = nil
}
self.error = ScreenAccessState(error: error, permissionDenied: false).errorDetails
}
}
func start() async {
guard !recording, !stopping, let chosen = windows.first(where: { $0.id == windowID }), let target = chosen.captureIdentity else { return }
guard !recording, !stopping, !checkingScreenAccess, screenPermission,
let chosen = windows.first(where: { $0.id == windowID }), let target = chosen.captureIdentity else { return }
if captureCompletion?.needsRecovery == true {
guard await saveSession(), !recording, !stopping else { return }
}
Expand Down Expand Up @@ -169,7 +177,11 @@ import ContextLensCapture
startedAt = Date(); captureStartedAt = startedAt; installEventMonitors()
}, missingReason: {
NSRunningApplication(processIdentifier: target.processID)?.isTerminated != false ? .applicationExited : .targetUnavailable
}, classify: { WindowCapture.endReason(for: $0) })
}, classify: { [self] failure in
let reason = WindowCapture.endReason(for: failure)
if reason == .permissionDenied { screenAccess = ScreenAccessState(error: failure, permissionDenied: true) }
return reason
})
captureRun = run
captureTask = Task { [self] in
let result = await run.run()
Expand All @@ -179,7 +191,7 @@ import ContextLensCapture
mainTab = .review; status = result.status(frameCount: session.frames.count)
if let detail = result.errorDetails { error = detail }
if result.reason == .permissionDenied {
screenPermission = false; screenAccessVerified = false; windows = []; windowID = nil; preview = nil
windows = []; windowID = nil; preview = nil
}
if selectedFrameID == nil { select(session.frames.first?.id) }
}
Expand Down
28 changes: 10 additions & 18 deletions Sources/ContextLensApp/CapturePanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ private struct PickWindowCard: View {
HStack(spacing: 8) { Circle().fill(Color(hex: 0xFF8A8E)).frame(width: 9, height: 9); Text("Start Capture") }
}
.buttonStyle(.lens(.primary, height: 42, fullWidth: true))
.disabled(model.windowID == nil || !model.screenPermission)
.disabled(model.windowID == nil || !model.screenPermission || model.checkingScreenAccess)
.keyboardShortcut(.defaultAction)
Button("Open ContextLens", action: openMain).buttonStyle(.plain).font(Lens.font(12, .bold)).foregroundStyle(Lens.accent)
.frame(maxWidth: .infinity)
Expand Down Expand Up @@ -383,31 +383,23 @@ private struct AppIcon: View {

private struct PermissionBlock: View {
@EnvironmentObject var model: AppModel
@State private var showHelp = false
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Label("Screen Recording is needed", systemImage: "macwindow").font(Lens.font(13.5, .heavy)).foregroundStyle(Lens.ink)
Text("If it's already on in System Settings, check again. A rebuilt copy of the app may need a fresh approval.")
ScrollView {
VStack(alignment: .leading, spacing: 10) {
Label(model.screenAccess.title, systemImage: "macwindow").font(Lens.font(13.5, .heavy)).foregroundStyle(Lens.ink)
Text(model.screenAccess.message)
.font(Lens.font(12)).foregroundStyle(Lens.muted).fixedSize(horizontal: false, vertical: true)
VStack(spacing: 8) {
Button("Check Access") { Task { await model.refresh(userInitiated: true) } }
Button(model.checkingScreenAccess ? "Checking…" : "Check Access") { Task { await model.refresh(userInitiated: true) } }
.buttonStyle(.lens(.primary, height: 34, fullWidth: true)).disabled(model.checkingScreenAccess)
Button("Open System Settings", action: Permissions.openScreenSettings)
.buttonStyle(.lens(.ghost, height: 34, fullWidth: true))
}
if let message = model.screenAccessError {
Text(message).font(Lens.font(11.5)).foregroundStyle(Lens.muted).textSelection(.enabled)
}
DisclosureGroup("Already on in Settings?", isExpanded: $showHelp) {
VStack(alignment: .leading, spacing: 6) {
Text("Quit ContextLens fully and reopen it. If access still fails, remove only the ContextLens entry with − in Screen & System Audio Recording, add this copy with +, turn it on and reopen.")
Text(Bundle.main.bundleURL.path).font(Lens.mono(10.5)).textSelection(.enabled)
}
.font(Lens.font(11.5)).foregroundStyle(Lens.muted).padding(.top, 4)
}
.font(Lens.font(12, .bold))
ScreenAccessDetails()
}
.padding(12)
}
.padding(12)
.frame(height: 260)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Lens.warningFill))
}
}
Expand Down
41 changes: 41 additions & 0 deletions Sources/ContextLensApp/ScreenAccessDetails.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import SwiftUI
import AppKit
import ContextLensCapture

/// Shared by onboarding and the capture panel. All diagnostics stay in this UI.
struct ScreenAccessDetails: View {
@EnvironmentObject var model: AppModel
@State private var showRecovery = false
@State private var showIdentity = false
private let identity = Permissions.runningCopyDescription

var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Running copy: \(Bundle.main.bundleURL.path)")
.font(Lens.mono(10.5)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
if let message = model.screenAccess.errorDetails {
Text(message).font(Lens.mono(10.5)).textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
}
DisclosureGroup("Copy and signing details", isExpanded: $showIdentity) {
Text(identity).font(Lens.mono(10.5)).textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true).padding(.top, 4)
}
DisclosureGroup("Reconnect an enabled entry", isExpanded: $showRecovery) {
VStack(alignment: .leading, spacing: 6) {
Text("1. Save your work and quit all ContextLens copies.")
Text("2. Open System Settings → Privacy & Security → Screen & System Audio Recording. Remove only ContextLens with the − button.")
Text("3. Use + to add the running copy shown above. In the file chooser, ⌘⇧G lets you enter its full path. Enable its switch.")
Text("4. Reopen that same copy, following any macOS Quit & Reopen request, then choose Check Access. Access is verified only when ScreenCaptureKit enumeration succeeds.")
Text("Ad-hoc updates and switching between development and release copies can change the approved identity even when the name is unchanged. These steps require your approval in macOS.")
}
.fixedSize(horizontal: false, vertical: true).padding(.top, 4)
}
Button("Show This Copy in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([Bundle.main.bundleURL])
}
.buttonStyle(.link)
}
.font(Lens.font(11.5)).foregroundStyle(Lens.muted)
}
}
15 changes: 10 additions & 5 deletions Sources/ContextLensApp/Sheets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ struct OnboardingView: View {
@EnvironmentObject var model: AppModel
var done: () -> Void
@State private var mascotUp = false
@State private var showScreenAccessDetails = false
@Environment(\.accessibilityReduceMotion) private var reduce

var body: some View {
Expand All @@ -28,15 +29,19 @@ struct OnboardingView: View {
.staggerIn(0)
VStack(spacing: 10) {
StepRow(icon: "display", title: "Screen Recording", tag: "Required",
detail: "Lets ContextLens capture the one window you pick. macOS asks once.", granted: model.screenPermission) {
detail: "\(model.screenAccess.title). \(model.screenAccess.message)", granted: model.screenPermission) {
Button("Open Settings", action: Permissions.openScreenSettings).buttonStyle(.lens(.quiet, height: 32))
Button("Allow") {
Permissions.requestScreen()
Task { await model.refresh(userInitiated: true) }
}
Button(model.checkingScreenAccess ? "Checking…" : "Check Access") { Task { await model.refresh(userInitiated: true) } }
.buttonStyle(.lens(.primary, height: 32))
.disabled(model.checkingScreenAccess)
Button("Details…") { showScreenAccessDetails = true }
.buttonStyle(.lens(.quiet, height: 32))
}
.staggerIn(1)
.popover(isPresented: $showScreenAccessDetails) {
ScrollView { ScreenAccessDetails().padding(20) }
.frame(width: 420, height: 360)
}
StepRow(icon: "cursorarrow.rays", title: "Accessibility", tag: "Optional",
detail: "Notes which kind of control you clicked, like “button”. Never reads text, values or passwords.", granted: model.axPermission) {
Button("Allow", action: Permissions.requestAccessibility).buttonStyle(.lens(.ghost, height: 32))
Expand Down
26 changes: 26 additions & 0 deletions Sources/ContextLensCapture/WindowCapture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ScreenCaptureKit
import ApplicationServices
import ContextLensCore
import ContextLensImaging
import Security

public struct WindowChoice: Identifiable {
public var id: CGWindowID { window.windowID }
Expand All @@ -24,6 +25,31 @@ public struct WindowChoice: Identifiable {
_ = AXIsProcessTrustedWithOptions(options)
}
public static func openScreenSettings() { NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")!) }
/// Read the identity of this process, never a different copy registered for the bundle ID.
public static var runningCopyDescription: String {
let bundle = Bundle.main
let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown"
let build = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"
var lines = [bundle.bundleURL.path, "\(bundle.bundleIdentifier ?? "unknown identifier") · \(version) (\(build))",
"Executable: \(bundle.executableURL?.path ?? "unknown")", "Process: \(ProcessInfo.processInfo.processIdentifier)"]
var code: SecCode?, staticCode: SecStaticCode?, info: CFDictionary?
if SecCodeCopySelf([], &code) == errSecSuccess, let code,
SecCodeCopyStaticCode(code, [], &staticCode) == errSecSuccess, let staticCode,
SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
let values = info as? [String: Any], let flags = values[kSecCodeInfoFlags as String] as? NSNumber {
if flags.uint32Value & SecCodeSignatureFlags.adhoc.rawValue != 0 {
lines.append("Ad-hoc signature: updates can require a new Screen Recording approval.")
} else {
lines.append("Certificate signature. Team: \(values[kSecCodeInfoTeamIdentifier as String] as? String ?? "unavailable")")
}
if let hash = values[kSecCodeInfoUnique as String] as? Data {
lines.append("Code hash: " + hash.map { String(format: "%02x", $0) }.joined())
}
} else {
lines.append("Signing identity could not be read. Screen Recording access must be checked separately.")
}
return lines.joined(separator: "\n")
}
}
public enum WindowCapture {
public static func selected(id: CGWindowID, pid: pid_t, in available: [WindowChoice]) throws -> WindowChoice {
Expand Down
47 changes: 47 additions & 0 deletions Sources/ContextLensCore/ScreenAccessState.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Foundation

/// Access is verified only by a successful ScreenCaptureKit enumeration, never by preflight alone.
public enum ScreenAccessState: Equatable, Sendable {
case unverified
case verified
case denied(String)
case failed(String)

public init(error: Error, permissionDenied: Bool) {
var messages: [String] = []
var current: NSError? = error as NSError
// Bound nested diagnostics: malformed/cyclic error chains must not stall the UI.
for _ in 0..<4 {
guard let value = current else { break }
messages.append("\(value.domain) (\(value.code)): \(value.localizedDescription)")
if let reason = value.localizedFailureReason { messages.append(reason) }
if let recovery = value.localizedRecoverySuggestion { messages.append(recovery) }
current = value.userInfo[NSUnderlyingErrorKey] as? NSError
}
let details = messages.joined(separator: "\n")
self = permissionDenied ? .denied(details) : .failed(details)
}
public var isVerified: Bool { self == .verified }
public var errorDetails: String? {
switch self {
case .denied(let details), .failed(let details): return details
default: return nil
}
}
public var title: String {
switch self {
case .unverified: return "Screen Recording access unverified"
case .verified: return "Screen Recording access verified"
case .denied: return "Screen Recording access denied"
case .failed: return "ScreenCaptureKit verification failed"
}
}
public var message: String {
switch self {
case .unverified: return "Choose Check Access to try ScreenCaptureKit. macOS may ask you to allow this copy."
case .verified: return "ScreenCaptureKit enumeration succeeded. Select a window to capture."
case .denied: return "macOS denied ScreenCaptureKit access. Enable this copy in Screen & System Audio Recording, then reopen it if requested."
case .failed: return "ScreenCaptureKit enumeration failed. Review the error details and choose Check Access to retry."
}
}
}
Loading
Loading