From 0f40bf9dc1550a4a29f7cb14123dd8fe38e8a59e Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Wed, 12 Aug 2026 16:22:32 +0800 Subject: [PATCH 1/3] feat(mac): add presentation visual tools --- mac/Sources/MirrorCast/AppDelegate.swift | 35 ++- mac/Sources/MirrorCast/AppState.swift | 171 ++++++++++++ .../MirrorCast/Mirror/MirrorLayerView.swift | 175 +++++++++++++ .../Mirror/MirrorWindowController.swift | 16 ++ .../Presentation/AnnotationDocument.swift | 100 +++++++ .../AnnotationOverlayController.swift | 244 ++++++++++++++++++ .../MirrorCast/Services/GlobalHotKey.swift | 149 +++++++---- .../Services/PreferencesStore.swift | 28 ++ .../MirrorCast/UI/ControlPanelView.swift | 118 +++++++-- 9 files changed, 952 insertions(+), 84 deletions(-) create mode 100644 mac/Sources/MirrorCast/Presentation/AnnotationDocument.swift create mode 100644 mac/Sources/MirrorCast/Presentation/AnnotationOverlayController.swift diff --git a/mac/Sources/MirrorCast/AppDelegate.swift b/mac/Sources/MirrorCast/AppDelegate.swift index 14f7be9..531709e 100644 --- a/mac/Sources/MirrorCast/AppDelegate.swift +++ b/mac/Sources/MirrorCast/AppDelegate.swift @@ -17,7 +17,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let hosting = NSHostingView(rootView: ControlPanelView(state: state)) let window = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: 440, height: 680), + contentRect: NSRect(x: 0, y: 0, width: 460, height: 780), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) @@ -89,11 +89,44 @@ final class AppDelegate: NSObject, NSApplicationDelegate { state.onHotKeyChangeRequested = { [weak self] combination in self?.globalHotKey.replace(with: combination) == true } + state.onMirroringStateChange = { [weak self] _ in + self?.updatePresentationHotKeys() + } + state.onPresentationKeyModeChange = { [weak self] in + self?.updatePresentationHotKeys() + } if !registered { state.status = "全局快捷键 \(state.hotKey.displayName) 注册失败,可能与其他应用冲突" } } + private func updatePresentationHotKeys() { + globalHotKey.unregisterPresentationKeys() + guard state.isMirroring, state.presentationKeyMode else { return } + + let keys: [(String, UInt32, String, () -> Void)] = [ + ("f1", UInt32(kVK_F1), "F1", { [weak self] in self?.state.toggleScreenZoom() }), + ("f2", UInt32(kVK_F2), "F2", { [weak self] in self?.state.toggleMagnifier() }), + ("f3", UInt32(kVK_F3), "F3", { [weak self] in self?.state.toggleSpotlight() }), + ("f4", UInt32(kVK_F4), "F4", { [weak self] in self?.state.toggleAnnotations() }), + ("escape", UInt32(kVK_Escape), "Esc", { [weak self] in + guard let self else { return } + Task { await self.state.exitPresentationModeOrStop() } + }) + ] + + var unavailable: [String] = [] + for (key, keyCode, label, action) in keys { + let combination = HotKeyCombination(keyCode: keyCode, modifiers: 0, keyLabel: label) + if !globalHotKey.register(key: key, combination: combination, action: action) { + unavailable.append(label) + } + } + if !unavailable.isEmpty { + state.status = "演示快捷键 \(unavailable.joined(separator: "、")) 已被系统占用" + } + } + private func observeState() { state.objectWillChange .receive(on: RunLoop.main) diff --git a/mac/Sources/MirrorCast/AppState.swift b/mac/Sources/MirrorCast/AppState.swift index be4a373..16a19cd 100644 --- a/mac/Sources/MirrorCast/AppState.swift +++ b/mac/Sources/MirrorCast/AppState.swift @@ -20,6 +20,10 @@ struct ScreenItem: Identifiable, Hashable { @MainActor final class AppState: ObservableObject { + private enum PresentationFeature { + case screenZoom, magnifier, spotlight, annotation + } + @Published private(set) var windows: [WindowItem] = [] @Published private(set) var screens: [ScreenItem] = [] @Published var selectedWindowID: CGWindowID? @@ -45,8 +49,26 @@ final class AppState: ObservableObject { @Published var showsPermissionOnboarding = false @Published var walkthroughStep: WalkthroughStep? @Published private(set) var hotKey = HotKeyCombination.defaultValue + @Published var presentationKeyMode = true { + didSet { + preferences.presentationKeyMode = presentationKeyMode + onPresentationKeyModeChange?() + } + } + @Published var presentationZoomFactor = 2.0 { + didSet { preferences.presentationZoomFactor = presentationZoomFactor } + } + @Published var pointerEffectSize = 240.0 { + didSet { preferences.pointerEffectSize = pointerEffectSize } + } + @Published private(set) var isScreenZoomActive = false + @Published private(set) var isMagnifierActive = false + @Published private(set) var isSpotlightActive = false + @Published private(set) var isAnnotationActive = false var onHotKeyChangeRequested: ((HotKeyCombination) -> Bool)? + var onMirroringStateChange: ((Bool) -> Void)? + var onPresentationKeyModeChange: (() -> Void)? /// SwiftUI only ever sees `WindowItem`; the live SCWindow objects stay here because /// the capture filter needs the real thing. @@ -55,9 +77,15 @@ final class AppState: ObservableObject { private let capture = CaptureEngine() private let mirrorWindow = MirrorWindowController() private let preferences = PreferencesStore() + private let annotationDocument = AnnotationDocument() private var mirrorMonitorTask: Task? + private var pointerMonitorTask: Task? private var activeWindowID: CGWindowID? private var isSwitchingSource = false + private var featureOrder: [PresentationFeature] = [] + private lazy var annotationOverlay = AnnotationOverlayController( + document: annotationDocument, + onExit: { [weak self] in self?.toggleAnnotations() }) var canStart: Bool { hasPermission && selectedWindowID != nil && selectedScreenID != nil && screens.count > 1 @@ -67,6 +95,9 @@ final class AppState: ObservableObject { showsCursor = preferences.showsCursor scaleMode = preferences.scaleMode hotKey = preferences.hotKey + presentationKeyMode = preferences.presentationKeyMode + presentationZoomFactor = preferences.presentationZoomFactor + pointerEffectSize = preferences.pointerEffectSize hasPermission = PermissionService.hasScreenRecordingAccess() showsPermissionOnboarding = !hasPermission walkthroughStep = hasPermission && !preferences.completedWalkthrough ? .sourceWindow : nil @@ -84,6 +115,10 @@ final class AppState: ObservableObject { self.status = "镜像已停止" } } + annotationDocument.onChange = { [weak self] in + guard let self else { return } + self.mirrorWindow.updateAnnotations(self.annotationDocument.items) + } } // MARK: - Permission @@ -216,9 +251,12 @@ final class AppState: ObservableObject { showsCursor: showsCursor, scale: sourceScale) isMirroring = true + resetPresentationFeatures() activeWindowID = windowID rememberSource(windowID) startMirrorMonitor(windowID: windowID, targetScreenID: screenID) + startPointerMonitor() + onMirroringStateChange?(true) let title = windows.first(where: { $0.id == windowID })?.title ?? "所选窗口" status = "正在镜像:\(title)" } catch { @@ -258,6 +296,12 @@ final class AppState: ObservableObject { status = "正在切换到:\(title)" do { + if isAnnotationActive { + annotationOverlay.close() + isAnnotationActive = false + track(.annotation, active: false) + annotationDocument.reset() + } try await capture.start( window: window, showsCursor: showsCursor, @@ -278,9 +322,15 @@ final class AppState: ObservableObject { private func finishMirroring() { mirrorMonitorTask?.cancel() mirrorMonitorTask = nil + pointerMonitorTask?.cancel() + pointerMonitorTask = nil + annotationOverlay.close() + resetPresentationFeatures() activeWindowID = nil mirrorWindow.close() + let wasMirroring = isMirroring isMirroring = false + if wasMirroring { onMirroringStateChange?(false) } } func toggleMirroring() async { @@ -331,6 +381,127 @@ final class AppState: ObservableObject { updateHotKey(.defaultValue) } + func toggleScreenZoom() { + guard isMirroring else { return } + isScreenZoomActive.toggle() + if isScreenZoomActive { + isMagnifierActive = false + track(.magnifier, active: false) + } + track(.screenZoom, active: isScreenZoomActive) + updatePresentation() + } + + func toggleMagnifier() { + guard isMirroring else { return } + isMagnifierActive.toggle() + if isMagnifierActive { + isScreenZoomActive = false + track(.screenZoom, active: false) + } + track(.magnifier, active: isMagnifierActive) + updatePresentation() + } + + func toggleSpotlight() { + guard isMirroring else { return } + isSpotlightActive.toggle() + track(.spotlight, active: isSpotlightActive) + updatePresentation() + } + + func toggleAnnotations() { + guard isMirroring else { return } + isAnnotationActive.toggle() + if isAnnotationActive, let frame = activeSourceFrame() { + annotationOverlay.show(sourceFrame: frame) + } else { + annotationOverlay.close() + } + track(.annotation, active: isAnnotationActive) + } + + func exitPresentationModeOrStop() async { + guard isMirroring else { return } + reconcileFeatureOrder() + guard let feature = featureOrder.last else { + await stopMirroring() + return + } + switch feature { + case .screenZoom: toggleScreenZoom() + case .magnifier: toggleMagnifier() + case .spotlight: toggleSpotlight() + case .annotation: toggleAnnotations() + } + } + + private func track(_ feature: PresentationFeature, active: Bool) { + featureOrder.removeAll { $0 == feature } + if active { featureOrder.append(feature) } + } + + private func reconcileFeatureOrder() { + featureOrder.removeAll { feature in + switch feature { + case .screenZoom: !isScreenZoomActive + case .magnifier: !isMagnifierActive + case .spotlight: !isSpotlightActive + case .annotation: !isAnnotationActive + } + } + } + + private func resetPresentationFeatures() { + isScreenZoomActive = false + isMagnifierActive = false + isSpotlightActive = false + isAnnotationActive = false + featureOrder.removeAll() + annotationDocument.reset() + updatePresentation(pointer: CGPoint(x: 0.5, y: 0.5)) + } + + private func startPointerMonitor() { + pointerMonitorTask?.cancel() + pointerMonitorTask = Task { [weak self] in + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 33_000_000) + guard let self, self.isMirroring, !Task.isCancelled else { return } + self.updatePresentation() + if self.isAnnotationActive, let frame = self.activeSourceFrame() { + self.annotationOverlay.update(sourceFrame: frame) + } + } + } + } + + private func updatePresentation(pointer: CGPoint? = nil) { + let normalized = pointer ?? normalizedPointerInSource() + mirrorWindow.updatePresentation( + pointer: normalized, + zoomFactor: isScreenZoomActive ? presentationZoomFactor : 1, + magnifierVisible: isMagnifierActive, + spotlightVisible: isSpotlightActive, + effectSize: pointerEffectSize) + } + + private func activeSourceFrame() -> CGRect? { + guard let activeWindowID else { return nil } + return scWindows[activeWindowID]?.frame + } + + private func normalizedPointerInSource() -> CGPoint { + guard let frame = activeSourceFrame(), frame.width > 0, frame.height > 0 else { + return CGPoint(x: 0.5, y: 0.5) + } + let appKitPoint = NSEvent.mouseLocation + let mainTop = NSScreen.screens.first?.frame.maxY ?? 0 + let capturePoint = CGPoint(x: appKitPoint.x, y: mainTop - appKitPoint.y) + return CGPoint(x: min(max((capturePoint.x - frame.minX) / frame.width, 0), 1), + y: min(max((capturePoint.y - frame.minY) / frame.height, 0), 1)) + } + func acceptDefaultHotKeyFallback() { hotKey = .defaultValue preferences.hotKey = .defaultValue diff --git a/mac/Sources/MirrorCast/Mirror/MirrorLayerView.swift b/mac/Sources/MirrorCast/Mirror/MirrorLayerView.swift index 2aff392..97d9da5 100644 --- a/mac/Sources/MirrorCast/Mirror/MirrorLayerView.swift +++ b/mac/Sources/MirrorCast/Mirror/MirrorLayerView.swift @@ -9,6 +9,18 @@ import AppKit final class MirrorLayerView: NSView { private let contentLayer = CALayer() + private let spotlightLayer = CAShapeLayer() + private let magnifierLayer = CALayer() + private let magnifierFrameLayer = CAShapeLayer() + private let annotationLayer = CAShapeLayer() + private var sourcePixelSize = CGSize.zero + private var zoomFactor: CGFloat = 1 + private var pointer = CGPoint(x: 0.5, y: 0.5) + private var magnifierVisible = false + private var spotlightVisible = false + private var pointerEffectSize: CGFloat = 240 + private var annotations: [AnnotationItem] = [] + private var contentGravity: CALayerContentsGravity = .resizeAspect override init(frame frameRect: NSRect) { super.init(frame: frameRect) @@ -30,6 +42,26 @@ final class MirrorLayerView: NSView { contentLayer.backgroundColor = NSColor.black.cgColor contentLayer.frame = bounds root.addSublayer(contentLayer) + + spotlightLayer.fillRule = .evenOdd + spotlightLayer.fillColor = NSColor.black.withAlphaComponent(0.72).cgColor + spotlightLayer.isHidden = true + root.addSublayer(spotlightLayer) + + magnifierLayer.contentsGravity = .resizeAspectFill + magnifierLayer.masksToBounds = true + magnifierLayer.cornerRadius = 12 + magnifierLayer.isHidden = true + root.addSublayer(magnifierLayer) + + magnifierFrameLayer.fillColor = NSColor.clear.cgColor + magnifierFrameLayer.strokeColor = NSColor.white.cgColor + magnifierFrameLayer.lineWidth = 3 + magnifierFrameLayer.isHidden = true + root.addSublayer(magnifierFrameLayer) + + annotationLayer.fillColor = NSColor.clear.cgColor + root.addSublayer(annotationLayer) } override func layout() { @@ -38,6 +70,9 @@ final class MirrorLayerView: NSView { CATransaction.begin() CATransaction.setDisableActions(true) contentLayer.frame = bounds + spotlightLayer.frame = bounds + annotationLayer.frame = bounds + updatePresentationLayers() CATransaction.commit() } @@ -45,6 +80,10 @@ final class MirrorLayerView: NSView { CATransaction.begin() CATransaction.setDisableActions(true) contentLayer.contents = surface + magnifierLayer.contents = surface + sourcePixelSize = CGSize(width: IOSurfaceGetWidth(surface), + height: IOSurfaceGetHeight(surface)) + updatePresentationLayers() CATransaction.commit() } @@ -52,6 +91,142 @@ final class MirrorLayerView: NSView { CATransaction.begin() CATransaction.setDisableActions(true) contentLayer.contentsGravity = gravity + contentGravity = gravity + magnifierLayer.contentsGravity = .resizeAspectFill + updatePresentationLayers() CATransaction.commit() } + + func updatePresentation(pointer: CGPoint, + zoomFactor: CGFloat, + magnifierVisible: Bool, + spotlightVisible: Bool, + effectSize: CGFloat) { + self.pointer = CGPoint(x: min(max(pointer.x, 0), 1), + y: min(max(pointer.y, 0), 1)) + self.zoomFactor = max(1, zoomFactor) + self.magnifierVisible = magnifierVisible + self.spotlightVisible = spotlightVisible + pointerEffectSize = effectSize + updatePresentationLayers() + } + + func updateAnnotations(_ items: [AnnotationItem]) { + annotations = items + updateAnnotationLayers() + } + + private func updatePresentationLayers() { + guard bounds.width > 0, bounds.height > 0 else { return } + CATransaction.begin() + CATransaction.setDisableActions(true) + + let crop = sourceCrop() + contentLayer.contentsRect = crop + let projected = project(pointer, through: crop) + + let size = min(pointerEffectSize, min(bounds.width, bounds.height) * 0.65) + let frame = CGRect(x: min(max(projected.x - size / 2, 8), bounds.width - size - 8), + y: min(max(projected.y - size / 2, 8), bounds.height - size - 8), + width: size, height: size) + magnifierLayer.frame = frame + let lensScale: CGFloat = 2 + let lensRect = CGRect(x: min(max(pointer.x - 0.5 / lensScale, 0), 1 - 1 / lensScale), + y: min(max(pointer.y - 0.5 / lensScale, 0), 1 - 1 / lensScale), + width: 1 / lensScale, height: 1 / lensScale) + magnifierLayer.contentsRect = lensRect + magnifierLayer.isHidden = !magnifierVisible + magnifierFrameLayer.path = CGPath(roundedRect: frame, cornerWidth: 12, + cornerHeight: 12, transform: nil) + magnifierFrameLayer.isHidden = !magnifierVisible + + let spotlightPath = CGMutablePath() + spotlightPath.addRect(bounds) + let radius = max(40, pointerEffectSize / 2) + spotlightPath.addEllipse(in: CGRect(x: projected.x - radius, + y: projected.y - radius, + width: radius * 2, height: radius * 2)) + spotlightLayer.path = spotlightPath + spotlightLayer.isHidden = !spotlightVisible + + updateAnnotationLayers(crop: crop) + CATransaction.commit() + } + + private func sourceCrop() -> CGRect { + guard zoomFactor > 1 else { return CGRect(x: 0, y: 0, width: 1, height: 1) } + let width = 1 / zoomFactor + let height = 1 / zoomFactor + return CGRect(x: min(max(pointer.x - width / 2, 0), 1 - width), + y: min(max(pointer.y - height / 2, 0), 1 - height), + width: width, height: height) + } + + private func project(_ normalized: CGPoint, through crop: CGRect) -> CGPoint { + let imageRect = projectedImageRect() + return CGPoint(x: imageRect.minX + (normalized.x - crop.minX) / crop.width * imageRect.width, + y: imageRect.minY + (normalized.y - crop.minY) / crop.height * imageRect.height) + } + + private func projectedImageRect() -> CGRect { + guard sourcePixelSize.width > 0, sourcePixelSize.height > 0, + contentGravity != .resize else { return bounds } + let scale = contentGravity == .resizeAspect + ? min(bounds.width / sourcePixelSize.width, bounds.height / sourcePixelSize.height) + : max(bounds.width / sourcePixelSize.width, bounds.height / sourcePixelSize.height) + let size = CGSize(width: sourcePixelSize.width * scale, + height: sourcePixelSize.height * scale) + return CGRect(x: (bounds.width - size.width) / 2, + y: (bounds.height - size.height) / 2, + width: size.width, height: size.height) + } + + private func updateAnnotationLayers(crop: CGRect? = nil) { + annotationLayer.sublayers?.forEach { $0.removeFromSuperlayer() } + let crop = crop ?? sourceCrop() + for item in annotations { + let layer = CAShapeLayer() + layer.fillColor = NSColor.clear.cgColor + layer.strokeColor = item.color.withAlphaComponent(item.opacity).cgColor + layer.lineWidth = item.thickness + layer.lineCap = .round + layer.lineJoin = .round + layer.path = annotationPath(item, crop: crop) + annotationLayer.addSublayer(layer) + } + } + + private func annotationPath(_ item: AnnotationItem, crop: CGRect) -> CGPath? { + guard let first = item.points.first else { return nil } + let points = item.points.map { project(CGPoint(x: $0.x, y: $0.y), through: crop) } + let path = CGMutablePath() + switch item.tool { + case .pen, .highlighter: + path.move(to: points[0]) + points.dropFirst().forEach { path.addLine(to: $0) } + case .line: + path.move(to: points[0]); path.addLine(to: points.last ?? points[0]) + case .arrow: + let end = points.last ?? points[0] + path.move(to: points[0]); path.addLine(to: end) + let angle = atan2(end.y - points[0].y, end.x - points[0].x) + let length = max(12, item.thickness * 4) + path.move(to: end) + path.addLine(to: CGPoint(x: end.x - length * cos(angle - .pi / 6), + y: end.y - length * sin(angle - .pi / 6))) + path.move(to: end) + path.addLine(to: CGPoint(x: end.x - length * cos(angle + .pi / 6), + y: end.y - length * sin(angle + .pi / 6))) + case .rectangle, .ellipse: + let end = points.last ?? points[0] + let rect = CGRect(x: min(points[0].x, end.x), y: min(points[0].y, end.y), + width: abs(points[0].x - end.x), height: abs(points[0].y - end.y)) + if item.tool == .rectangle { path.addRect(rect) } + else { path.addEllipse(in: rect) } + case .eraser: + return nil + } + _ = first + return path + } } diff --git a/mac/Sources/MirrorCast/Mirror/MirrorWindowController.swift b/mac/Sources/MirrorCast/Mirror/MirrorWindowController.swift index 9c9a94e..15e8fe4 100644 --- a/mac/Sources/MirrorCast/Mirror/MirrorWindowController.swift +++ b/mac/Sources/MirrorCast/Mirror/MirrorWindowController.swift @@ -52,6 +52,22 @@ final class MirrorWindowController { mirrorView?.setScaleMode(gravity) } + func updatePresentation(pointer: CGPoint, + zoomFactor: CGFloat, + magnifierVisible: Bool, + spotlightVisible: Bool, + effectSize: CGFloat) { + mirrorView?.updatePresentation(pointer: pointer, + zoomFactor: zoomFactor, + magnifierVisible: magnifierVisible, + spotlightVisible: spotlightVisible, + effectSize: effectSize) + } + + func updateAnnotations(_ items: [AnnotationItem]) { + mirrorView?.updateAnnotations(items) + } + func close() { window?.orderOut(nil) window?.contentView = nil diff --git a/mac/Sources/MirrorCast/Presentation/AnnotationDocument.swift b/mac/Sources/MirrorCast/Presentation/AnnotationDocument.swift new file mode 100644 index 0000000..c2bcd33 --- /dev/null +++ b/mac/Sources/MirrorCast/Presentation/AnnotationDocument.swift @@ -0,0 +1,100 @@ +import AppKit +import Combine + +enum AnnotationTool: String, CaseIterable, Identifiable { + case pen, highlighter, line, arrow, rectangle, ellipse, eraser + + var id: String { rawValue } + + var title: String { + switch self { + case .pen: "画笔" + case .highlighter: "荧光笔" + case .line: "直线" + case .arrow: "箭头" + case .rectangle: "矩形" + case .ellipse: "椭圆" + case .eraser: "橡皮擦" + } + } +} + +struct AnnotationPoint: Equatable { + let x: CGFloat + let y: CGFloat +} + +struct AnnotationItem: Identifiable, Equatable { + let id = UUID() + let tool: AnnotationTool + let points: [AnnotationPoint] + let color: NSColor + let thickness: CGFloat + let opacity: CGFloat + + static func == (lhs: AnnotationItem, rhs: AnnotationItem) -> Bool { + lhs.id == rhs.id + } +} + +@MainActor +final class AnnotationDocument: ObservableObject { + @Published private(set) var items: [AnnotationItem] = [] + @Published private(set) var canUndo = false + @Published private(set) var canRedo = false + + var onChange: (() -> Void)? + + private var history: [[AnnotationItem]] = [[]] + private var historyIndex = 0 + + func add(_ item: AnnotationItem) { + commit(items + [item]) + } + + func remove(ids: Set) { + guard !ids.isEmpty else { return } + let next = items.filter { !ids.contains($0.id) } + guard next.count != items.count else { return } + commit(next) + } + + func undo() { + guard historyIndex > 0 else { return } + historyIndex -= 1 + publish() + } + + func redo() { + guard historyIndex + 1 < history.count else { return } + historyIndex += 1 + publish() + } + + func clear() { + guard !items.isEmpty else { return } + commit([]) + } + + func reset() { + history = [[]] + historyIndex = 0 + publish() + } + + private func commit(_ next: [AnnotationItem]) { + if historyIndex + 1 < history.count { + history.removeSubrange((historyIndex + 1).. 0 + canRedo = historyIndex + 1 < history.count + onChange?() + } +} diff --git a/mac/Sources/MirrorCast/Presentation/AnnotationOverlayController.swift b/mac/Sources/MirrorCast/Presentation/AnnotationOverlayController.swift new file mode 100644 index 0000000..135da37 --- /dev/null +++ b/mac/Sources/MirrorCast/Presentation/AnnotationOverlayController.swift @@ -0,0 +1,244 @@ +import AppKit +import SwiftUI + +@MainActor +final class AnnotationOverlayController { + private var panel: NSPanel? + private let document: AnnotationDocument + private let onExit: () -> Void + + init(document: AnnotationDocument, onExit: @escaping () -> Void) { + self.document = document + self.onExit = onExit + } + + var isShowing: Bool { panel != nil } + + func show(sourceFrame: CGRect) { + if panel == nil { + let panel = NSPanel( + contentRect: appKitRect(fromCaptureRect: sourceFrame), + styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, + defer: false) + panel.isOpaque = false + panel.backgroundColor = .clear + panel.hasShadow = false + panel.level = .screenSaver + panel.collectionBehavior = [.canJoinAllSpaces, .stationary, + .fullScreenAuxiliary, .ignoresCycle] + panel.hidesOnDeactivate = false + panel.isMovable = false + panel.contentView = NSHostingView(rootView: AnnotationOverlayView( + document: document, + onExit: onExit)) + panel.orderFrontRegardless() + self.panel = panel + } + update(sourceFrame: sourceFrame) + } + + func update(sourceFrame: CGRect) { + panel?.setFrame(appKitRect(fromCaptureRect: sourceFrame), display: true) + } + + func close() { + panel?.orderOut(nil) + panel?.contentView = nil + panel = nil + } + + private func appKitRect(fromCaptureRect rect: CGRect) -> NSRect { + let mainTop = NSScreen.screens.first?.frame.maxY ?? 0 + return NSRect(x: rect.minX, + y: mainTop - rect.maxY, + width: rect.width, + height: rect.height) + } +} + +private struct AnnotationOverlayView: View { + @ObservedObject var document: AnnotationDocument + let onExit: () -> Void + + @State private var tool: AnnotationTool = .pen + @State private var color = NSColor.systemRed + @State private var thickness: CGFloat = 4 + @State private var draft: [AnnotationPoint] = [] + @State private var erasedIDs: Set = [] + + private let colors: [NSColor] = [.systemRed, .systemYellow, .systemBlue, + .systemGreen, .white] + + var body: some View { + GeometryReader { proxy in + ZStack(alignment: .top) { + Color.black.opacity(0.001) + AnnotationCanvas(items: document.items.filter { !erasedIDs.contains($0.id) }, + draft: draftItem) + .contentShape(Rectangle()) + .gesture(drawGesture(size: proxy.size)) + + toolbar + .padding(.top, 10) + } + } + } + + private var toolbar: some View { + HStack(spacing: 5) { + ForEach(AnnotationTool.allCases) { candidate in + Button(candidate.title) { tool = candidate } + .buttonStyle(.bordered) + .tint(tool == candidate ? .accentColor : .secondary) + .controlSize(.small) + } + + Divider().frame(height: 24) + + ForEach(colors, id: \.self) { candidate in + Button { color = candidate } label: { + Circle().fill(Color(nsColor: candidate)).frame(width: 18, height: 18) + .overlay(Circle().stroke(.white.opacity(color == candidate ? 1 : 0.25), lineWidth: 2)) + } + .buttonStyle(.plain) + } + + Slider(value: $thickness, in: 2...12, step: 1).frame(width: 70) + Button("撤销") { document.undo() }.disabled(!document.canUndo) + Button("重做") { document.redo() }.disabled(!document.canRedo) + Button("清空") { document.clear() } + Button("退出") { onExit() }.keyboardShortcut(.cancelAction) + } + .padding(7) + .background(.black.opacity(0.82), in: RoundedRectangle(cornerRadius: 8)) + .foregroundStyle(.white) + } + + private var draftItem: AnnotationItem? { + guard !draft.isEmpty, tool != .eraser else { return nil } + return AnnotationItem(tool: tool, + points: draft, + color: color, + thickness: tool == .highlighter ? thickness * 3 : thickness, + opacity: tool == .highlighter ? 0.38 : 1) + } + + private func drawGesture(size: CGSize) -> some Gesture { + DragGesture(minimumDistance: 0, coordinateSpace: .local) + .onChanged { value in + let point = normalized(value.location, size: size) + if tool == .eraser { + erase(at: point, size: size) + } else if draft.isEmpty { + draft = [point] + } else if tool == .pen || tool == .highlighter { + draft.append(point) + } else if draft.count == 1 { + draft.append(point) + } else { + draft[draft.count - 1] = point + } + } + .onEnded { value in + if tool == .eraser { + document.remove(ids: erasedIDs) + erasedIDs.removeAll() + return + } + let end = normalized(value.location, size: size) + if draft.count == 1 { draft.append(end) } + guard let item = draftItem else { return } + document.add(item) + draft.removeAll() + } + } + + private func normalized(_ point: CGPoint, size: CGSize) -> AnnotationPoint { + AnnotationPoint(x: min(max(point.x / max(1, size.width), 0), 1), + y: min(max(1 - point.y / max(1, size.height), 0), 1)) + } + + private func erase(at point: AnnotationPoint, size: CGSize) { + let tolerance = 14 / max(1, min(size.width, size.height)) + for item in document.items.reversed() where !erasedIDs.contains(item.id) { + if hit(item, point: point, tolerance: tolerance) { + erasedIDs.insert(item.id) + return + } + } + } + + private func hit(_ item: AnnotationItem, point: AnnotationPoint, tolerance: CGFloat) -> Bool { + guard !item.points.isEmpty else { return false } + if item.points.count == 1 { + return hypot(item.points[0].x - point.x, item.points[0].y - point.y) <= tolerance + } + for index in 1.. CGFloat { + let dx = end.x - start.x + let dy = end.y - start.y + let lengthSquared = dx * dx + dy * dy + if lengthSquared < 0.000001 { return hypot(point.x - start.x, point.y - start.y) } + let t = min(max(((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared, 0), 1) + return hypot(point.x - (start.x + t * dx), point.y - (start.y + t * dy)) + } +} + +private struct AnnotationCanvas: View { + let items: [AnnotationItem] + let draft: AnnotationItem? + + var body: some View { + Canvas { context, size in + for item in items { draw(item, in: &context, size: size) } + if let draft { draw(draft, in: &context, size: size) } + } + } + + private func draw(_ item: AnnotationItem, in context: inout GraphicsContext, size: CGSize) { + guard let first = item.points.first else { return } + let points = item.points.map { CGPoint(x: $0.x * size.width, y: (1 - $0.y) * size.height) } + var path = Path() + switch item.tool { + case .pen, .highlighter: + path.move(to: points[0]) + for point in points.dropFirst() { path.addLine(to: point) } + case .line: + guard let last = points.last else { return } + path.move(to: points[0]); path.addLine(to: last) + case .arrow: + guard let last = points.last else { return } + path.move(to: points[0]); path.addLine(to: last) + let angle = atan2(last.y - points[0].y, last.x - points[0].x) + let length = max(12, item.thickness * 4) + path.move(to: last) + path.addLine(to: CGPoint(x: last.x - length * cos(angle - .pi / 6), + y: last.y - length * sin(angle - .pi / 6))) + path.move(to: last) + path.addLine(to: CGPoint(x: last.x - length * cos(angle + .pi / 6), + y: last.y - length * sin(angle + .pi / 6))) + case .rectangle, .ellipse: + guard let last = points.last else { return } + let rect = CGRect(x: min(points[0].x, last.x), y: min(points[0].y, last.y), + width: abs(points[0].x - last.x), height: abs(points[0].y - last.y)) + path = item.tool == .rectangle ? Path(rect) : Path(ellipseIn: rect) + case .eraser: + return + } + context.opacity = item.opacity + context.stroke(path, with: .color(Color(nsColor: item.color)), + style: StrokeStyle(lineWidth: item.thickness, + lineCap: .round, lineJoin: .round)) + _ = first + } +} diff --git a/mac/Sources/MirrorCast/Services/GlobalHotKey.swift b/mac/Sources/MirrorCast/Services/GlobalHotKey.swift index afe9919..513c301 100644 --- a/mac/Sources/MirrorCast/Services/GlobalHotKey.swift +++ b/mac/Sources/MirrorCast/Services/GlobalHotKey.swift @@ -24,95 +24,132 @@ struct HotKeyCombination: Equatable { @MainActor final class GlobalHotKey { - nonisolated(unsafe) private static var action: (() -> Void)? - - private var hotKey: EventHotKeyRef? + private static let signature = OSType( + UInt32(ascii: "M") << 24 + | UInt32(ascii: "C") << 16 + | UInt32(ascii: "A") << 8 + | UInt32(ascii: "S")) + + nonisolated(unsafe) private static var actions: [UInt32: () -> Void] = [:] + nonisolated(unsafe) private static var nextID: UInt32 = 1 + + private var hotKeys: [String: EventHotKeyRef] = [:] + private var ids: [String: UInt32] = [:] + private var combinations: [String: HotKeyCombination] = [:] + private var handlers: [String: () -> Void] = [:] private var eventHandler: EventHandlerRef? - private var currentCombination: HotKeyCombination? + + init() { + installHandler() + } @discardableResult func register(_ combination: HotKeyCombination, action: @escaping () -> Void) -> Bool { - unregister() - Self.action = action - - var eventType = EventTypeSpec( - eventClass: OSType(kEventClassKeyboard), - eventKind: UInt32(kEventHotKeyPressed)) - - let handlerStatus = InstallEventHandler( - GetApplicationEventTarget(), - { _, _, _ in - DispatchQueue.main.async { - GlobalHotKey.action?() - } - return noErr - }, - 1, - &eventType, - nil, - &eventHandler) - guard handlerStatus == noErr else { - Self.action = nil - return false - } - - let signature = OSType( - UInt32(ascii: "M") << 24 - | UInt32(ascii: "C") << 16 - | UInt32(ascii: "A") << 8 - | UInt32(ascii: "S")) - let identifier = EventHotKeyID(signature: signature, id: 1) + register(key: "primary", combination: combination, action: action) + } - let hotKeyStatus = RegisterEventHotKey( + @discardableResult + func register(key: String, + combination: HotKeyCombination, + action: @escaping () -> Void) -> Bool { + unregister(key: key) + installHandler() + + let id = Self.nextID + Self.nextID += 1 + let identifier = EventHotKeyID(signature: Self.signature, id: id) + var hotKey: EventHotKeyRef? + let status = RegisterEventHotKey( combination.keyCode, combination.modifiers, identifier, GetApplicationEventTarget(), 0, &hotKey) - guard hotKeyStatus == noErr else { - unregister() - return false - } + guard status == noErr, let hotKey else { return false } - currentCombination = combination + hotKeys[key] = hotKey + ids[key] = id + combinations[key] = combination + handlers[key] = action + Self.actions[id] = action return true } func replace(with combination: HotKeyCombination) -> Bool { - guard let action = Self.action, - let previousCombination = currentCombination + guard let action = handlers["primary"], + let previous = combinations["primary"] else { return false } - if register(combination, action: action) { + if register(key: "primary", combination: combination, action: action) { return true } - - _ = register(previousCombination, action: action) + _ = register(key: "primary", combination: previous, action: action) return false } - func unregister() { - if let hotKey { + func unregister(key: String) { + if let hotKey = hotKeys.removeValue(forKey: key) { UnregisterEventHotKey(hotKey) - self.hotKey = nil } + if let id = ids.removeValue(forKey: key) { + Self.actions.removeValue(forKey: id) + } + combinations.removeValue(forKey: key) + handlers.removeValue(forKey: key) + } + + func unregisterPresentationKeys() { + ["f1", "f2", "f3", "f4", "escape"].forEach(unregister(key:)) + } + + func unregister() { + for hotKey in hotKeys.values { UnregisterEventHotKey(hotKey) } + for id in ids.values { Self.actions.removeValue(forKey: id) } + hotKeys.removeAll() + ids.removeAll() + combinations.removeAll() + handlers.removeAll() if let eventHandler { RemoveEventHandler(eventHandler) self.eventHandler = nil } - currentCombination = nil - Self.action = nil + } + + private func installHandler() { + guard eventHandler == nil else { return } + var eventType = EventTypeSpec( + eventClass: OSType(kEventClassKeyboard), + eventKind: UInt32(kEventHotKeyPressed)) + InstallEventHandler( + GetApplicationEventTarget(), + { _, event, _ in + guard let event else { return OSStatus(eventNotHandledErr) } + var identifier = EventHotKeyID() + let status = GetEventParameter( + event, + EventParamName(kEventParamDirectObject), + EventParamType(typeEventHotKeyID), + nil, + MemoryLayout.size, + nil, + &identifier) + guard status == noErr, identifier.signature == GlobalHotKey.signature, + let action = GlobalHotKey.actions[identifier.id] + else { return OSStatus(eventNotHandledErr) } + DispatchQueue.main.async { action() } + return noErr + }, + 1, + &eventType, + nil, + &eventHandler) } deinit { - if let hotKey { - UnregisterEventHotKey(hotKey) - } - if let eventHandler { - RemoveEventHandler(eventHandler) - } + for hotKey in hotKeys.values { UnregisterEventHotKey(hotKey) } + if let eventHandler { RemoveEventHandler(eventHandler) } } } diff --git a/mac/Sources/MirrorCast/Services/PreferencesStore.swift b/mac/Sources/MirrorCast/Services/PreferencesStore.swift index db6522a..9d5e21e 100644 --- a/mac/Sources/MirrorCast/Services/PreferencesStore.swift +++ b/mac/Sources/MirrorCast/Services/PreferencesStore.swift @@ -12,6 +12,9 @@ final class PreferencesStore { static let hotKeyCode = "hotKeyCode" static let hotKeyModifiers = "hotKeyModifiers" static let hotKeyLabel = "hotKeyLabel" + static let presentationKeyMode = "presentationKeyMode" + static let presentationZoomFactor = "presentationZoomFactor" + static let pointerEffectSize = "pointerEffectSize" } private let defaults = UserDefaults.standard @@ -85,4 +88,29 @@ final class PreferencesStore { defaults.set(newValue.keyLabel, forKey: Key.hotKeyLabel) } } + + var presentationKeyMode: Bool { + get { + defaults.object(forKey: Key.presentationKeyMode) == nil + ? true + : defaults.bool(forKey: Key.presentationKeyMode) + } + set { defaults.set(newValue, forKey: Key.presentationKeyMode) } + } + + var presentationZoomFactor: Double { + get { + let value = defaults.double(forKey: Key.presentationZoomFactor) + return value == 0 ? 2 : value + } + set { defaults.set(newValue, forKey: Key.presentationZoomFactor) } + } + + var pointerEffectSize: Double { + get { + let value = defaults.double(forKey: Key.pointerEffectSize) + return value == 0 ? 240 : value + } + set { defaults.set(newValue, forKey: Key.pointerEffectSize) } + } } diff --git a/mac/Sources/MirrorCast/UI/ControlPanelView.swift b/mac/Sources/MirrorCast/UI/ControlPanelView.swift index 7ae84c2..8dd090a 100644 --- a/mac/Sources/MirrorCast/UI/ControlPanelView.swift +++ b/mac/Sources/MirrorCast/UI/ControlPanelView.swift @@ -17,7 +17,7 @@ struct ControlPanelView: View { controlPanel } } - .frame(minWidth: 420, minHeight: 620) + .frame(minWidth: 440, minHeight: 720) .task { state.refreshPermission() await state.refreshSources() @@ -28,35 +28,38 @@ struct ControlPanelView: View { } private var controlPanel: some View { - VStack(alignment: .leading, spacing: 14) { - header + ScrollView { + VStack(alignment: .leading, spacing: 14) { + header - if !state.hasPermission { - permissionBanner - } else { - windowSection - screenSection - scaleModePicker - HotKeySettingView( - combination: state.hotKey, - onChange: state.updateHotKey, - onRestoreDefault: state.restoreDefaultHotKey) - Toggle("在副屏显示鼠标指针", isOn: $state.showsCursor) - .disabled(state.isMirroring) - } - - Spacer(minLength: 0) - - if !state.status.isEmpty { - Text(state.status) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } + if !state.hasPermission { + permissionBanner + } else { + windowSection + screenSection + scaleModePicker + HotKeySettingView( + combination: state.hotKey, + onChange: state.updateHotKey, + onRestoreDefault: state.restoreDefaultHotKey) + Toggle("在副屏显示鼠标指针", isOn: $state.showsCursor) + .disabled(state.isMirroring) + presentationSettings + } + + Spacer(minLength: 0) - actionSection + if !state.status.isEmpty { + Text(state.status) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + actionSection + } + .padding(18) } - .padding(18) .overlayPreferenceValue(WalkthroughFramePreferenceKey.self) { anchors in GeometryReader { proxy in if let step = state.walkthroughStep { @@ -176,10 +179,71 @@ struct ControlPanelView: View { .controlSize(.large) .buttonStyle(.borderedProminent) .disabled(!state.isMirroring && !state.canStart) + + if state.isMirroring { + presentationActions + .padding(.top, 8) + } } .walkthroughTarget(.startMirror) } + private var presentationSettings: some View { + VStack(alignment: .leading, spacing: 9) { + Divider() + Text("演示辅助") + .font(.subheadline) + .foregroundStyle(.secondary) + Toggle("镜像时启用 F1-F4 演示快捷模式", isOn: $state.presentationKeyMode) + HStack { + Text("放大倍数") + Slider(value: $state.presentationZoomFactor, in: 1.25...5, step: 0.25) + Text("\(state.presentationZoomFactor, specifier: "%.2f")x") + .monospacedDigit().frame(width: 48, alignment: .trailing) + } + HStack { + Text("指针范围") + Slider(value: $state.pointerEffectSize, in: 120...480, step: 20) + Text("\(Int(state.pointerEffectSize)) px") + .monospacedDigit().frame(width: 58, alignment: .trailing) + } + Text("F1 屏幕放大 · F2 指针放大镜 · F3 指针聚光灯 · F4 屏幕标注 · Esc 逐层退出") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + private var presentationActions: some View { + VStack(spacing: 6) { + HStack(spacing: 6) { + presentationButton(state.isScreenZoomActive ? "关闭屏幕放大" : "F1 屏幕放大", + active: state.isScreenZoomActive, + action: state.toggleScreenZoom) + presentationButton(state.isMagnifierActive ? "关闭放大镜" : "F2 指针放大镜", + active: state.isMagnifierActive, + action: state.toggleMagnifier) + } + HStack(spacing: 6) { + presentationButton(state.isSpotlightActive ? "关闭聚光灯" : "F3 指针聚光灯", + active: state.isSpotlightActive, + action: state.toggleSpotlight) + presentationButton(state.isAnnotationActive ? "退出标注" : "F4 屏幕标注", + active: state.isAnnotationActive, + action: state.toggleAnnotations) + } + } + } + + private func presentationButton(_ title: String, + active: Bool, + action: @escaping () -> Void) -> some View { + Button(title, action: action) + .frame(maxWidth: .infinity) + .buttonStyle(.bordered) + .tint(active ? .accentColor : .secondary) + } + private var scaleModePicker: some View { VStack(alignment: .leading, spacing: 6) { Text("第三步:选择缩放模式") From dc33810f24b084eeb4342315c627c988381190bc Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Wed, 12 Aug 2026 16:25:33 +0800 Subject: [PATCH 2/3] fix(mac): import function key constants --- mac/Sources/MirrorCast/AppDelegate.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/mac/Sources/MirrorCast/AppDelegate.swift b/mac/Sources/MirrorCast/AppDelegate.swift index 531709e..377111d 100644 --- a/mac/Sources/MirrorCast/AppDelegate.swift +++ b/mac/Sources/MirrorCast/AppDelegate.swift @@ -1,4 +1,5 @@ import AppKit +import Carbon import Combine import SwiftUI From b25d09538877053275720d020a02d47815f1f8c8 Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Wed, 12 Aug 2026 16:30:38 +0800 Subject: [PATCH 3/3] fix(mac): align presentation pointer coordinates --- README.md | 6 ++++-- mac/README.md | 6 ++++++ mac/Sources/MirrorCast/AppState.swift | 12 +++++++----- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 06349c2..b5e8b12 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ xattr -dr com.apple.quarantine "/Applications/MirrorCast.app" 按 `Esc` 取消录制。如果组合键被其他应用占用,MirrorCast 会保留原设置。 -### 演示辅助(Windows) +### 演示辅助 镜像开始后,可以从运行状态面板或全局快捷键切换以下效果: @@ -117,10 +117,12 @@ xattr -dr com.apple.quarantine "/Applications/MirrorCast.app" - 指针聚光灯:压暗副屏其他区域并突出鼠标附近,默认 `Ctrl + Alt + Shift + P`。 - 屏幕标注:在主屏源窗口上绘制画笔、荧光笔、直线、箭头、矩形和椭圆,副屏同步显示,默认 `Ctrl + Alt + Shift + A`。 -放大倍数、指针效果范围和四组快捷键均可在控制面板中调整。屏幕放大与指针放大镜互斥,聚光灯可以与任一模式组合。标注工具栏支持撤销、重做、清空和橡皮擦;按 `Esc` 可退出标注。标注内容仅在本次镜像期间保留。 +放大倍数和指针效果范围可在控制面板中调整。Windows 版还支持分别设置四组组合快捷键。屏幕放大与指针放大镜互斥,聚光灯可以与任一模式组合。标注工具栏支持撤销、重做、清空和橡皮擦;按 `Esc` 可退出标注。标注内容仅在本次镜像期间保留。 默认开启“演示快捷模式”:仅在镜像期间使用 `F1` 开关屏幕放大、`F2` 开关指针放大镜、`F3` 开关指针聚光灯、`F4` 开关屏幕标注。按 `Esc` 会先退出最近开启的辅助功能;全部辅助功能都关闭后,再按一次 `Esc` 才会停止镜像。停止镜像后,MirrorCast 会立即释放这些按键。 +Mac 键盘若将功能键用于亮度或音量控制,需要按住 `Fn` 再按对应功能键,或在系统设置中启用标准功能键。 + ## 缩放模式 | 平台 | 模式 | 效果 | diff --git a/mac/README.md b/mac/README.md index fe31aa3..524f651 100644 --- a/mac/README.md +++ b/mac/README.md @@ -26,6 +26,9 @@ xcode-select --install - 源窗口改变大小时动态更新捕获配置 - 镜像期间单击窗口列表即可切换源窗口 - 鼠标指针显示开关 +- GPU 路径的全屏放大、指针放大镜和指针聚光灯 +- 主屏矢量标注工具栏,副屏同步显示画笔、荧光笔、图形和箭头 +- 镜像期间使用 `F1`、`F2`、`F3`、`F4` 快速切换演示功能,按 `Esc` 逐层退出 - 源窗口关闭或目标显示器断开时自动停止 - 跨 Space 保持副屏镜像 - 副屏镜像窗口点击穿透 @@ -33,6 +36,8 @@ xcode-select --install - 显示器、缩放、指针、窗口和快捷键设置持久化 - 屏幕录制权限引导与五步使用教学 +部分 Mac 键盘默认将功能键用于亮度、音量等系统控制,此时需要按住 `Fn` 再按 `F1` 至 `F4`,或在系统设置中启用“将 F1、F2 等键用作标准功能键”。演示快捷模式可以在控制面板中关闭。 + ## 构建应用 ```bash @@ -103,6 +108,7 @@ Intel 架构名为 `x86_64`,Apple Silicon 为 `arm64`,双架构包为 `unive mac/Sources/MirrorCast/ ├── Capture/ # ScreenCaptureKit 捕获与帧输出 ├── Mirror/ # 副屏窗口、CALayer 显示和缩放模式 +├── Presentation/ # 放大、聚光灯和矢量标注 ├── Services/ # 权限、偏好设置、菜单栏和全局快捷键 ├── UI/ # 控制面板、权限引导和使用教学 ├── AppDelegate.swift diff --git a/mac/Sources/MirrorCast/AppState.swift b/mac/Sources/MirrorCast/AppState.swift index 16a19cd..f065de4 100644 --- a/mac/Sources/MirrorCast/AppState.swift +++ b/mac/Sources/MirrorCast/AppState.swift @@ -495,11 +495,13 @@ final class AppState: ObservableObject { guard let frame = activeSourceFrame(), frame.width > 0, frame.height > 0 else { return CGPoint(x: 0.5, y: 0.5) } - let appKitPoint = NSEvent.mouseLocation - let mainTop = NSScreen.screens.first?.frame.maxY ?? 0 - let capturePoint = CGPoint(x: appKitPoint.x, y: mainTop - appKitPoint.y) - return CGPoint(x: min(max((capturePoint.x - frame.minX) / frame.width, 0), 1), - y: min(max((capturePoint.y - frame.minY) / frame.height, 0), 1)) + guard let capturePoint = CGEvent(source: nil)?.location else { + return CGPoint(x: 0.5, y: 0.5) + } + let normalizedX = (capturePoint.x - frame.minX) / frame.width + let normalizedYFromTop = (capturePoint.y - frame.minY) / frame.height + return CGPoint(x: min(max(normalizedX, 0), 1), + y: min(max(1 - normalizedYFromTop, 0), 1)) } func acceptDefaultHotKeyFallback() {