| 1 | |
| 2 | |
| 3 | import AppKit |
| 4 | import ScreenCaptureKit |
| 5 | import ImageIO |
| 6 | import UniformTypeIdentifiers |
| 7 | |
| 8 | struct ClaudeCanvas { |
| 9 | let id: CGWindowID |
| 10 | let pid: pid_t |
| 11 | let frame: CGRect |
| 12 | let cropTop: CGFloat |
| 13 | let scale: CGFloat |
| 14 | let resizable: Bool |
| 15 | var content: CGSize { CGSize(width: frame.width, height: frame.height - cropTop) } |
| 16 | |
| 17 | func matches(_ other: ClaudeCanvas) -> Bool { |
| 18 | id == other.id && pid == other.pid && frame == other.frame && cropTop == other.cropTop && scale == other.scale |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | private func axAttribute(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { |
| 23 | var value: CFTypeRef? |
| 24 | guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return nil } |
| 25 | return value |
| 26 | } |
| 27 | |
| 28 | private func axRect(_ element: AXUIElement) -> CGRect? { |
| 29 | guard let p = axAttribute(element, kAXPositionAttribute), CFGetTypeID(p) == AXValueGetTypeID(), |
| 30 | let s = axAttribute(element, kAXSizeAttribute), CFGetTypeID(s) == AXValueGetTypeID() else { return nil } |
| 31 | var pos = CGPoint.zero, size = CGSize.zero |
| 32 | guard AXValueGetValue(p as! AXValue, .cgPoint, &pos), AXValueGetValue(s as! AXValue, .cgSize, &size) else { return nil } |
| 33 | return CGRect(origin: pos, size: size) |
| 34 | } |
| 35 | |
| 36 | private func liveBounds(_ id: CGWindowID, _ pid: pid_t) throws -> CGRect { |
| 37 | let windows = CGWindowListCopyWindowInfo(.optionIncludingWindow, id) as? [[String:Any]] |
| 38 | guard let info = windows?.first, info[kCGWindowOwnerPID as String] as? Int32 == pid, |
| 39 | info[kCGWindowIsOnscreen as String] as? Bool == true, |
| 40 | let box = info[kCGWindowBounds as String] as? NSDictionary, |
| 41 | let rect = CGRect(dictionaryRepresentation: box), !rect.isEmpty else { throw Failure(7, "window_changed") } |
| 42 | return rect |
| 43 | } |
| 44 | |
| 45 | private func owningAXWindow(_ pid: pid_t, _ frame: CGRect) -> AXUIElement? { |
| 46 | guard AXIsProcessTrusted(), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, |
| 47 | let raw = axAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute), |
| 48 | CFGetTypeID(raw) == AXUIElementGetTypeID() else { return nil } |
| 49 | let window = raw as! AXUIElement |
| 50 | guard let actual = axRect(window), abs(actual.minX-frame.minX)<1, abs(actual.minY-frame.minY)<1, |
| 51 | abs(actual.width-frame.width)<1, abs(actual.height-frame.height)<1 else { return nil } |
| 52 | return window |
| 53 | } |
| 54 | |
| 55 | private func canSet(_ window: AXUIElement, _ name: String) -> Bool { |
| 56 | var result = DarwinBoolean(false) |
| 57 | return AXUIElementIsAttributeSettable(window, name as CFString, &result) == .success && result.boolValue |
| 58 | } |
| 59 | |
| 60 | private func titleBarHeight(_ window: AXUIElement, _ frame: CGRect) -> CGFloat { |
| 61 | var bottom: CGFloat = 0 |
| 62 | for name in [kAXCloseButtonAttribute, kAXMinimizeButtonAttribute, kAXZoomButtonAttribute] { |
| 63 | guard let raw = axAttribute(window, name), CFGetTypeID(raw) == AXUIElementGetTypeID(), |
| 64 | let button = axRect(raw as! AXUIElement), button.width > 2, button.height > 2, |
| 65 | frame.contains(button), button.minX-frame.minX < 100, button.maxY-frame.minY < 70 else { continue } |
| 66 | let margin = min(8, max(2, button.minY - frame.minY)) |
| 67 | bottom = max(bottom, ceil(button.maxY - frame.minY + margin)) |
| 68 | } |
| 69 | return bottom < frame.height / 3 ? bottom : 0 |
| 70 | } |
| 71 | |
| 72 | @MainActor |
| 73 | final class ClaudeCanvasSession { |
| 74 | static let shared = ClaudeCanvasSession() |
| 75 | private var last: ClaudeCanvas? |
| 76 | private var token = "" |
| 77 | private var requested: (id: CGWindowID, pid: pid_t, size: CGSize, observed: CGSize, time: Date)? |
| 78 | |
| 79 | func layout(_ window: SCWindow, filter: SCContentFilter, width: Int, height: Int, scale: Double) async throws -> ClaudeCanvas { |
| 80 | guard let pid = window.owningApplication?.processID, |
| 81 | (320...2560).contains(width), (240...1600).contains(height), |
| 82 | scale.isFinite, (1...2).contains(scale) else { throw Failure(8, "invalid_input") } |
| 83 | var bounds = try liveBounds(window.windowID, pid) |
| 84 | var crop: CGFloat = 0, resized = false |
| 85 | if let ax = owningAXWindow(pid, bounds) { |
| 86 | crop = titleBarHeight(ax, bounds) |
| 87 | if canSet(ax, kAXSizeAttribute) { |
| 88 | let display = CGDisplayBounds(CGMainDisplayID()) |
| 89 | let wanted = CGSize(width: min(CGFloat(width), display.width), |
| 90 | height: min(CGFloat(height) + crop, display.height)) |
| 91 | let close = abs(bounds.width - wanted.width) < 2 && abs(bounds.height - wanted.height) < 2 |
| 92 | let recent = requested.map { $0.id == window.windowID && $0.pid == pid && $0.size == wanted && |
| 93 | $0.observed == bounds.size && Date().timeIntervalSince($0.time) < 3 } ?? false |
| 94 | if !close && !recent { |
| 95 | var size = wanted |
| 96 | if let value = AXValueCreate(.cgSize, &size), |
| 97 | AXUIElementSetAttributeValue(ax, kAXSizeAttribute as CFString, value) == .success { |
| 98 | try await Task.sleep(nanoseconds: 70_000_000) |
| 99 | bounds = try liveBounds(window.windowID, pid) |
| 100 | |
| 101 | var origin = CGPoint(x: max(display.minX, min(bounds.minX, display.maxX-bounds.width)), |
| 102 | y: max(display.minY, min(bounds.minY, display.maxY-bounds.height))) |
| 103 | if origin != bounds.origin, canSet(ax, kAXPositionAttribute), |
| 104 | let point = AXValueCreate(.cgPoint, &origin) { |
| 105 | _ = AXUIElementSetAttributeValue(ax, kAXPositionAttribute as CFString, point) |
| 106 | bounds = try liveBounds(window.windowID, pid) |
| 107 | } |
| 108 | } |
| 109 | requested = (window.windowID, pid, wanted, bounds.size, Date()) |
| 110 | } |
| 111 | resized = abs(bounds.width-wanted.width) < 2 && abs(bounds.height-wanted.height) < 2 |
| 112 | crop = titleBarHeight(ax, bounds) |
| 113 | } |
| 114 | } |
| 115 | return ClaudeCanvas(id: window.windowID, pid: pid, frame: bounds, cropTop: crop, |
| 116 | scale: min(max(1,CGFloat(filter.pointPixelScale)), CGFloat(scale)), resizable: resized) |
| 117 | } |
| 118 | |
| 119 | func record(_ value: ClaudeCanvas) -> String { |
| 120 | if last?.matches(value) != true { token = UUID().uuidString; last = value } |
| 121 | return token |
| 122 | } |
| 123 | |
| 124 | func inputGeometry(_ requested: String, window: SCWindow) throws -> ClaudeCanvas { |
| 125 | guard let last, token == requested, last.id == window.windowID, last.pid == window.owningApplication?.processID, |
| 126 | try liveBounds(last.id, last.pid) == last.frame, |
| 127 | let ax = owningAXWindow(last.pid, last.frame), titleBarHeight(ax,last.frame) == last.cropTop else { |
| 128 | throw Failure(7, "window_changed") |
| 129 | } |
| 130 | return last |
| 131 | } |
| 132 | |
| 133 | func capture(_ window: SCWindow, filter: SCContentFilter, layout: ClaudeCanvas, after: String? = nil, wait: Bool = false, binary: Bool = false, phoneJPEG: Bool = false) async throws -> [String:Any] { |
| 134 | let config = SCStreamConfiguration() |
| 135 | config.width = max(1, Int((layout.frame.width*layout.scale).rounded())) |
| 136 | config.height = max(1, Int((layout.frame.height*layout.scale).rounded())) |
| 137 | config.captureResolution = .best |
| 138 | config.ignoreShadowsSingleWindow = true; config.showsCursor = false |
| 139 | if #available(macOS 14.2, *) { config.includeChildWindows = false } |
| 140 | let geometry = record(layout) |
| 141 | let (updated, sequence) = try await MacWindowStream.shared.frame(filter: filter, configuration: config, identity: geometry, after: after, wait: wait) |
| 142 | guard try liveBounds(layout.id, layout.pid) == layout.frame, |
| 143 | try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") } |
| 144 | guard let image = updated else { return ["unchanged": true, "sequence": sequence, "geometry": geometry] } |
| 145 | let top = Int((layout.cropTop * CGFloat(image.height) / layout.frame.height).rounded()) |
| 146 | guard top >= 0, top < image.height, |
| 147 | let content = image.cropping(to: CGRect(x:0,y:top,width:image.width,height:image.height-top)), |
| 148 | try liveBounds(layout.id, layout.pid) == layout.frame, |
| 149 | try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") } |
| 150 | var data = phoneJPEG ? try phoneDesktopJPEG(content) : try pngData(content) |
| 151 | var mime = phoneJPEG ? "image/jpeg" : "image/png" |
| 152 | if data.count >= 8<<20 { |
| 153 | |
| 154 | mime = "image/jpeg" |
| 155 | for quality in [0.93, 0.84] { |
| 156 | data = try encodedImage(content, type:.jpeg, properties:[kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) |
| 157 | if data.count < 8<<20 { break } |
| 158 | } |
| 159 | } |
| 160 | guard data.count < 8<<20 else { throw Failure(8, "frame_limit") } |
| 161 | var reply: [String:Any] = ["window":layout.id,"pid":layout.pid,"mime":mime,"sequence":sequence, |
| 162 | "contentWidth":layout.content.width,"contentHeight":layout.content.height, |
| 163 | "pixelWidth":content.width,"pixelHeight":content.height,"cropTop":layout.cropTop, |
| 164 | "resizable":layout.resizable, "geometry":geometry] |
| 165 | if binary { reply["imageBytes"] = data } |
| 166 | else { reply["image"] = data.base64EncodedString() } |
| 167 | return reply |
| 168 | } |
| 169 | } |