pi-web-ui 0.114.0 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +187 -187
  3. package/README.zh-CN.md +227 -227
  4. package/README.zh-TW.md +227 -227
  5. package/bin/device-hub-cli.mjs +577 -577
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -9
  8. package/bin/pi-web-ui.mjs +4081 -4073
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service.js +131 -55
  12. package/dist/server/attachments.js +51 -5
  13. package/dist/server/canvas/canvas-agent-tool.js +3 -3
  14. package/dist/server/canvas/canvas-cards.js +1 -1
  15. package/dist/server/canvas/canvas-orchestrator.js +3 -3
  16. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  17. package/dist/server/canvas/canvas-validation.js +1 -1
  18. package/dist/server/client-state.js +6 -2
  19. package/dist/server/compaction-instructions.js +8 -8
  20. package/dist/server/device-center/connector.js +33 -14
  21. package/dist/server/device-center/desktop-page.js +228 -228
  22. package/dist/server/device-center/hub-page.js +64 -64
  23. package/dist/server/device-center/hub.js +2 -1
  24. package/dist/server/device-center/local-hub.js +92 -0
  25. package/dist/server/device-center/local.js +60 -7
  26. package/dist/server/device-center/native-desktop/macos.js +190 -190
  27. package/dist/server/device-center/native-desktop/windows.js +116 -116
  28. package/dist/server/device-center/path-portal.js +1 -1
  29. package/dist/server/device-center/relay.js +45 -8
  30. package/dist/server/dispatch-domain-handlers.js +1 -0
  31. package/dist/server/dsh/dsh-agent-service.js +5 -1
  32. package/dist/server/dsh/runtime/cordis.yml +1 -1
  33. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  34. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  35. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  36. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  37. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  38. package/dist/server/engine-probe.js +36 -6
  39. package/dist/server/eval-tool.js +135 -135
  40. package/dist/server/global-loader.js +40 -2
  41. package/dist/server/index.js +56 -32
  42. package/dist/server/patch-bash-process.js +125 -0
  43. package/dist/server/patch-tool.js +9 -9
  44. package/dist/server/patch-turn-end-boundary.js +3 -3
  45. package/dist/server/persona-chain.js +8 -8
  46. package/dist/server/plugins.js +26 -2
  47. package/dist/server/preset-fields.js +7 -0
  48. package/dist/server/preset-share.js +1 -0
  49. package/dist/server/prompt-templates.js +106 -0
  50. package/dist/server/protocol-version.js +1 -1
  51. package/dist/server/remote-ssh-service.js +39 -39
  52. package/dist/server/resolve-global-sdk.js +2 -0
  53. package/dist/server/schedule-agent-tool.js +39 -21
  54. package/dist/server/scheduler-tasks.js +45 -9
  55. package/dist/server/scm-commitmsg.js +10 -10
  56. package/dist/server/settings-service.js +6 -0
  57. package/dist/server/setup-page.js +620 -620
  58. package/dist/server/text-quote.js +9 -0
  59. package/dist/server/tool-manager.js +2 -1
  60. package/dist/server/universal/drivers/claude-code.js +5 -0
  61. package/dist/server/universal/drivers/codex.js +336 -0
  62. package/dist/server/universal/index.js +1 -0
  63. package/dist/server/universal/universal-attachments.js +24 -1
  64. package/dist/server/universal/universal-session.js +23 -0
  65. package/dist/server/vision-bridge.js +18 -18
  66. package/docs/device-center.md +148 -142
  67. package/docs/device-desktop.md +48 -48
  68. package/docs/dsh-engine.md +493 -493
  69. package/extensions/webui.ts +335 -335
  70. package/package.json +2 -2
  71. package/plugin-sdk/README.md +174 -174
  72. package/plugin-sdk/client-utils.mjs +279 -279
  73. package/plugin-sdk/import-check.mjs +210 -210
  74. package/plugin-sdk/index.d.ts +698 -698
  75. package/plugin-sdk/index.mjs +696 -696
  76. package/plugin-sdk/package.json +13 -13
  77. package/plugin-sdk/ssh-host-trust.mjs +225 -225
  78. package/plugins/catalog.json +10 -0
  79. package/themes/aetheris.css +501 -501
  80. package/themes/ayu-light.css +116 -116
  81. package/themes/bases/flow-base.css +1357 -1357
  82. package/themes/bases/obsidian-base.css +895 -895
  83. package/themes/bases/statusbar-flat-base.css +112 -112
  84. package/themes/bases/zhujian-base.css +688 -688
  85. package/themes/bases/zhupi-base.css +660 -660
  86. package/themes/catppuccin-latte.css +119 -119
  87. package/themes/catppuccin.css +116 -116
  88. package/themes/claude-code-dark.css +147 -147
  89. package/themes/codex.css +114 -114
  90. package/themes/cyberpunk.css +50 -50
  91. package/themes/dark-teal.css +264 -264
  92. package/themes/dazzle.css +38 -38
  93. package/themes/everforest-light.css +115 -115
  94. package/themes/flow-light.css +164 -164
  95. package/themes/flow.css +161 -161
  96. package/themes/geist.css +114 -114
  97. package/themes/gruvbox-light.css +115 -115
  98. package/themes/kanagawa-lotus.css +115 -115
  99. package/themes/md-preview.css +24 -24
  100. package/themes/mist.css +166 -166
  101. package/themes/nord.css +107 -107
  102. package/themes/one-dark.css +106 -106
  103. package/themes/paper.css +174 -174
  104. package/themes/rose-pine-dawn.css +114 -114
  105. package/themes/sakura.css +166 -166
  106. package/themes/solarized-light.css +114 -114
  107. package/themes/tokyo-night.css +115 -115
  108. package/themes/translucent.css +85 -85
  109. package/themes/transparent.css +116 -116
  110. package/themes/vs-code-dark.css +147 -147
  111. package/themes/wallpaper-flow.css +382 -382
  112. package/themes/wallpaper-obsidian.css +74 -74
  113. package/themes/white.css +164 -164
  114. package/themes/zhujian-dark.css +115 -115
  115. package/themes/zhujian.css +114 -114
  116. package/themes/zhupi-dark.css +115 -115
  117. package/themes/zhupi.css +114 -114
  118. package/web/dist/.build-assets.json +1 -1
  119. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  120. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  121. package/web/dist/assets/{CanvasStudio-BEJZE5BI.js → CanvasStudio-PI9pid0Y.js} +3 -3
  122. package/web/dist/assets/{CanvasStudio-CgUNHqos.js → CanvasStudio-nf5-HxLM.js} +3 -3
  123. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  124. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  125. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  126. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  127. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  128. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  129. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  130. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  131. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  132. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  133. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  134. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  135. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  136. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  137. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  138. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  139. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  140. package/web/dist/assets/{TerminalPanel-DL20uKgU.js → TerminalPanel-BBuM_Sez.js} +2 -2
  141. package/web/dist/assets/{TerminalPanel-D6cPRFei.js → TerminalPanel-D6x6xz8Q.js} +2 -2
  142. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  143. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  144. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  145. package/web/dist/assets/{desktop-DPyTy4M3.js → desktop-YguLbrX1.js} +1 -1
  146. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  147. package/web/dist/assets/index-BPvpea8t.js +85 -0
  148. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  149. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  150. package/web/dist/assets/{plugin-host-CqA4yW6w.js → plugin-host-BRBg6zmQ.js} +1 -1
  151. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  152. package/web/dist/index.html +37 -36
  153. package/web/dist/sw.js +179 -179
  154. package/web/public/sw.js +179 -179
  155. package/dist/gh-comment-781.md +0 -5
  156. package/dist/server/device-center/local-page.js +0 -17
  157. package/dist/server/device-center/smoke-preview.js +0 -3
  158. package/dist/server/durable/durable-capabilities.js +0 -11
  159. package/dist/server/markers/builtins/services.js +0 -123
  160. package/dist/server/markers/builtins/todo.js +0 -189
  161. package/dist/server/markers-list-tool.js +0 -34
  162. package/dist/server/orchestrator.js +0 -109
  163. package/dist/server/system-prompt-soul.js +0 -41
  164. package/dist/server/univer-service.js +0 -448
  165. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  166. package/dist/test-artifact.md +0 -9
  167. package/dist/test-preview-modal.md +0 -11
  168. package/dist/test-report.html +0 -20
  169. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +0 -1
  170. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +0 -1
  171. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +0 -3
  172. package/web/dist/assets/DeviceCenter-CVblvhNX.js +0 -3
  173. package/web/dist/assets/Dropdown-Oug0DDte.js +0 -1
  174. package/web/dist/assets/FilePreview-CvdX6nr6.js +0 -2
  175. package/web/dist/assets/FilePreview-kCZhfBAF.js +0 -2
  176. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +0 -1
  177. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +0 -1
  178. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +0 -1
  179. package/web/dist/assets/GroupConversation-DZ71jEi8.js +0 -1
  180. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +0 -2
  181. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +0 -1
  182. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +0 -1
  183. package/web/dist/assets/SCMPanel-BP1TUT-V.js +0 -2
  184. package/web/dist/assets/SCMPanel-BscPm9kf.js +0 -2
  185. package/web/dist/assets/SettingsModal-C8UgMjVM.js +0 -20
  186. package/web/dist/assets/SettingsModal-VynB7jNb.js +0 -20
  187. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +0 -1
  188. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +0 -1
  189. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +0 -1
  190. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +0 -1
  191. package/web/dist/assets/app-globals-CnO6KlEM.js +0 -325
  192. package/web/dist/assets/index-CPgAH5q7.js +0 -83
  193. package/web/dist/assets/index-Cje8iugL.js +0 -83
  194. package/web/dist/assets/index-DnKeiDbj.css +0 -1
  195. package/web/dist/assets/theme-BqdAjEjF.js +0 -1
@@ -1,192 +1,192 @@
1
1
  // CoreGraphics follows the same capture/input split as krd, without a network service.
2
- export const macDesktopScript = String.raw `
3
- import Foundation
4
- import CoreGraphics
5
- import ImageIO
6
- import ApplicationServices
7
- import ScreenCaptureKit
8
- import Darwin
9
-
10
- func fail(_ message: String) -> Never {
11
- FileHandle.standardError.write(Data((message + "\n").utf8))
12
- exit(1)
13
- }
14
- guard #available(macOS 14.0, *) else { fail("Native capture requires macOS 14 or newer.") }
15
- let mode = CommandLine.arguments.last ?? "view"
16
- let readOnly = mode != "control"
17
- // Only an explicit local permission action may trigger TCC or open Settings.
18
- // Use the same Swift process identity as capture and input injection.
19
- func openPrivacy(_ pane: String) {
20
- let settings = Process()
21
- settings.executableURL = URL(fileURLWithPath: "/usr/bin/open")
22
- settings.arguments = ["x-apple.systempreferences:com.apple.preference.security?" + pane]
23
- settings.standardOutput = FileHandle.nullDevice
24
- settings.standardError = FileHandle.nullDevice
25
- try? settings.run()
26
- }
27
- if mode == "permissions-screen" || mode == "permissions-control" {
28
- if !CGPreflightScreenCaptureAccess() {
29
- _ = CGRequestScreenCaptureAccess()
30
- if !CGPreflightScreenCaptureAccess() { openPrivacy("Privacy_ScreenCapture") }
31
- }
32
- // Request both permissions for control even if Screen Recording was denied.
33
- if mode == "permissions-control" && !AXIsProcessTrusted() {
34
- let prompt = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
35
- _ = AXIsProcessTrustedWithOptions(prompt)
36
- if !AXIsProcessTrusted() { openPrivacy("Privacy_Accessibility") }
37
- }
38
- let result: [String: Bool] = ["screen": CGPreflightScreenCaptureAccess(), "accessibility": AXIsProcessTrusted()]
39
- guard let data = try? JSONSerialization.data(withJSONObject: result) else { fail("Cannot serialize permission status.") }
40
- FileHandle.standardOutput.write(data)
41
- exit(0)
42
- }
43
- if !CGPreflightScreenCaptureAccess() {
44
- fail("MAC_SCREEN_PERMISSION_REQUIRED: On this Mac, open the local Device Center and request Screen Recording permission for the app macOS identifies. Restart the actual server after granting access, then reconnect.")
45
- }
46
- if !readOnly && !AXIsProcessTrusted() {
47
- fail("MAC_ACCESSIBILITY_PERMISSION_REQUIRED: On this Mac, open the local Device Center and request Accessibility permission for the app macOS identifies. Restart the actual server after granting access, then reconnect.")
48
- }
49
- let lock = NSLock()
50
- let acknowledged = DispatchSemaphore(value: 0)
51
- var stopped = false
52
- var keys = Set<CGKeyCode>()
53
- var buttons = Set<Int>()
54
- var lastPoint = CGPoint.zero
55
- let keyMap: [String: CGKeyCode] = [
56
- "KeyA":0,"KeyS":1,"KeyD":2,"KeyF":3,"KeyH":4,"KeyG":5,"KeyZ":6,"KeyX":7,"KeyC":8,"KeyV":9,"KeyB":11,
57
- "KeyQ":12,"KeyW":13,"KeyE":14,"KeyR":15,"KeyY":16,"KeyT":17,"Digit1":18,"Digit2":19,"Digit3":20,"Digit4":21,
58
- "Digit6":22,"Digit5":23,"Equal":24,"Digit9":25,"Digit7":26,"Minus":27,"Digit8":28,"Digit0":29,"BracketRight":30,
59
- "KeyO":31,"KeyU":32,"BracketLeft":33,"KeyI":34,"KeyP":35,"Enter":36,"KeyL":37,"KeyJ":38,"Quote":39,"KeyK":40,
60
- "Semicolon":41,"Backslash":42,"Comma":43,"Slash":44,"KeyN":45,"KeyM":46,"Period":47,"Tab":48,"Space":49,
61
- "Backquote":50,"Backspace":51,"Escape":53,"MetaRight":54,"MetaLeft":55,"ShiftLeft":56,"CapsLock":57,
62
- "AltLeft":58,"ControlLeft":59,"ShiftRight":60,"AltRight":61,"ControlRight":62,"F1":122,"F2":120,"F3":99,
63
- "F4":118,"F5":96,"F6":97,"F7":98,"F8":100,"F9":101,"F10":109,"F11":103,"F12":111,"Insert":114,
64
- "Home":115,"PageUp":116,"Delete":117,"End":119,"PageDown":121,"ArrowLeft":123,"ArrowRight":124,"ArrowDown":125,"ArrowUp":126
65
- ]
66
- let modifiers: [CGKeyCode: CGEventFlags] = [54:.maskCommand,55:.maskCommand,56:.maskShift,60:.maskShift,58:.maskAlternate,61:.maskAlternate,59:.maskControl,62:.maskControl]
67
- func flags() -> CGEventFlags {
68
- var f = CGEventFlags()
69
- for k in keys { if let bit = modifiers[k] { f.formUnion(bit) } }
70
- return f
71
- }
72
- func key(_ code: CGKeyCode, _ down: Bool) {
73
- let event = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: down)
74
- event?.flags = flags()
75
- event?.post(tap: .cghidEventTap)
76
- }
77
- func mouse(_ button: Int, _ down: Bool) {
78
- let kind: CGEventType = button == 0 ? (down ? .leftMouseDown : .leftMouseUp) : button == 2 ? (down ? .rightMouseDown : .rightMouseUp) : (down ? .otherMouseDown : .otherMouseUp)
79
- let event = CGEvent(mouseEventSource: nil, mouseType: kind, mouseCursorPosition: lastPoint, mouseButton: button == 0 ? .left : button == 2 ? .right : .center)
80
- event?.flags = flags()
81
- event?.post(tap: .cghidEventTap)
82
- }
83
- func release() {
84
- lock.lock(); defer { lock.unlock() }
85
- stopped = true
86
- let held = keys; keys.removeAll()
87
- for k in held { key(k, false) }
88
- for b in buttons { mouse(b, false) }
89
- buttons.removeAll()
90
- acknowledged.signal()
91
- }
92
- // stdin EOF is also a disconnect: release even if no explicit close was delivered.
93
- DispatchQueue.global().async {
94
- defer { release(); exit(0) }
95
- while let line = readLine() {
96
- if line.utf8.count > 32768 { fail("Input exceeds limit.") }
97
- guard let data = line.data(using: .utf8), let e = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let type = e["type"] as? String else { continue }
98
- if type == "close" { return }
99
- if type == "ack" { acknowledged.signal(); continue }
100
- if readOnly { continue }
101
- lock.lock()
102
- if stopped { lock.unlock(); return }
103
- switch type {
104
- case "release":
105
- let held = keys; keys.removeAll()
106
- for k in held { key(k, false) }
107
- for b in buttons { mouse(b, false) }
108
- buttons.removeAll()
109
- case "pointer":
110
- if let x = e["x"] as? Double, let y = e["y"] as? Double, let action = e["action"] as? String {
111
- let bounds = CGDisplayBounds(CGMainDisplayID())
112
- lastPoint = CGPoint(x: bounds.minX + x * max(0, bounds.width - 1), y: bounds.minY + y * max(0, bounds.height - 1))
113
- let b = e["button"] as? Int ?? 0
114
- if action == "move" {
115
- let drag = buttons.contains(0) ? CGEventType.leftMouseDragged : buttons.contains(2) ? .rightMouseDragged : buttons.contains(1) ? .otherMouseDragged : .mouseMoved
116
- let event = CGEvent(mouseEventSource: nil, mouseType: drag, mouseCursorPosition: lastPoint, mouseButton: buttons.contains(2) ? .right : buttons.contains(1) ? .center : .left)
117
- event?.flags = flags(); event?.post(tap: .cghidEventTap)
118
- } else {
119
- if action == "down" { buttons.insert(b) } else { buttons.remove(b) }
120
- mouse(b, action == "down")
121
- }
122
- }
123
- case "key":
124
- if let code = e["code"] as? String, let k = keyMap[code], let action = e["action"] as? String {
125
- if action == "down" { keys.insert(k) } else { keys.remove(k) }
126
- key(k, action == "down")
127
- }
128
- case "wheel":
129
- if let dy = e["deltaY"] as? Double { CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 1, wheel1: Int32(-dy), wheel2: 0, wheel3: 0)?.post(tap: .cghidEventTap) }
130
- case "text":
131
- if let text = e["text"] as? String {
132
- let units = Array(text.utf16)
133
- units.withUnsafeBufferPointer { buffer in
134
- for down in [true, false] {
135
- let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: down)
136
- event?.keyboardSetUnicodeString(stringLength: units.count, unicodeString: buffer.baseAddress)
137
- event?.post(tap: .cghidEventTap)
138
- }
139
- }
140
- }
141
- default: break
142
- }
143
- lock.unlock()
144
- }
145
- }
146
- // ScreenCaptureKit is also used by krd. SCScreenshotManager avoids deprecated
147
- // CGDisplayCreateImage on current macOS SDKs and never opens a network port.
148
- @available(macOS 14.0, *)
149
- func captureImage() -> CGImage {
150
- let ready = DispatchSemaphore(value: 0)
151
- var result: CGImage?
152
- var failure: String?
153
- Task {
154
- do {
155
- let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
156
- guard let display = content.displays.first(where: { $0.displayID == CGMainDisplayID() }) else {
157
- failure = "No active main display."; ready.signal(); return
158
- }
159
- let filter = SCContentFilter(display: display, excludingWindows: [])
160
- let config = SCStreamConfiguration()
161
- let scale = min(1.0, 1920.0 / Double(max(display.width, display.height)))
162
- config.width = max(1, Int(Double(display.width) * scale))
163
- config.height = max(1, Int(Double(display.height) * scale))
164
- config.showsCursor = true
165
- result = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
166
- } catch { failure = String(describing: error) }
167
- ready.signal()
168
- }
169
- guard ready.wait(timeout: .now() + 15) == .success, let image = result else {
170
- release(); fail("ScreenCaptureKit capture failed: " + (failure ?? "timeout; check Screen Recording permission and active desktop."))
171
- }
172
- return image
173
- }
174
- while true {
175
- autoreleasepool {
176
- let image = captureImage()
177
- let scale = min(1.0, 1920.0 / Double(max(image.width, image.height)))
178
- let width = max(1, Int(Double(image.width) * scale)), height = max(1, Int(Double(image.height) * scale))
179
- guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { release(); fail("Cannot allocate capture buffer.") }
180
- context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
181
- let data = NSMutableData()
182
- guard let scaled = context.makeImage(), let destination = CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil) else { release(); fail("Cannot create JPEG encoder.") }
183
- CGImageDestinationAddImage(destination, scaled, [kCGImageDestinationLossyCompressionQuality: 0.65] as CFDictionary)
184
- guard CGImageDestinationFinalize(destination), data.length > 0, data.length <= 4194304 else { release(); fail("JPEG exceeds 4 MB or encoding failed.") }
185
- var size = UInt32(data.length).bigEndian
186
- FileHandle.standardOutput.write(Data(bytes: &size, count: 4))
187
- FileHandle.standardOutput.write(data as Data)
188
- }
189
- if acknowledged.wait(timeout: .now() + 15) == .timedOut { release(); fail("Frame consumer stopped responding.") }
190
- Thread.sleep(forTimeInterval: 0.1)
191
- }
2
+ export const macDesktopScript = String.raw `
3
+ import Foundation
4
+ import CoreGraphics
5
+ import ImageIO
6
+ import ApplicationServices
7
+ import ScreenCaptureKit
8
+ import Darwin
9
+
10
+ func fail(_ message: String) -> Never {
11
+ FileHandle.standardError.write(Data((message + "\n").utf8))
12
+ exit(1)
13
+ }
14
+ guard #available(macOS 14.0, *) else { fail("Native capture requires macOS 14 or newer.") }
15
+ let mode = CommandLine.arguments.last ?? "view"
16
+ let readOnly = mode != "control"
17
+ // Only an explicit local permission action may trigger TCC or open Settings.
18
+ // Use the same Swift process identity as capture and input injection.
19
+ func openPrivacy(_ pane: String) {
20
+ let settings = Process()
21
+ settings.executableURL = URL(fileURLWithPath: "/usr/bin/open")
22
+ settings.arguments = ["x-apple.systempreferences:com.apple.preference.security?" + pane]
23
+ settings.standardOutput = FileHandle.nullDevice
24
+ settings.standardError = FileHandle.nullDevice
25
+ try? settings.run()
26
+ }
27
+ if mode == "permissions-screen" || mode == "permissions-control" {
28
+ if !CGPreflightScreenCaptureAccess() {
29
+ _ = CGRequestScreenCaptureAccess()
30
+ if !CGPreflightScreenCaptureAccess() { openPrivacy("Privacy_ScreenCapture") }
31
+ }
32
+ // Request both permissions for control even if Screen Recording was denied.
33
+ if mode == "permissions-control" && !AXIsProcessTrusted() {
34
+ let prompt = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
35
+ _ = AXIsProcessTrustedWithOptions(prompt)
36
+ if !AXIsProcessTrusted() { openPrivacy("Privacy_Accessibility") }
37
+ }
38
+ let result: [String: Bool] = ["screen": CGPreflightScreenCaptureAccess(), "accessibility": AXIsProcessTrusted()]
39
+ guard let data = try? JSONSerialization.data(withJSONObject: result) else { fail("Cannot serialize permission status.") }
40
+ FileHandle.standardOutput.write(data)
41
+ exit(0)
42
+ }
43
+ if !CGPreflightScreenCaptureAccess() {
44
+ fail("MAC_SCREEN_PERMISSION_REQUIRED: On this Mac, open the local Device Center and request Screen Recording permission for the app macOS identifies. Restart the actual server after granting access, then reconnect.")
45
+ }
46
+ if !readOnly && !AXIsProcessTrusted() {
47
+ fail("MAC_ACCESSIBILITY_PERMISSION_REQUIRED: On this Mac, open the local Device Center and request Accessibility permission for the app macOS identifies. Restart the actual server after granting access, then reconnect.")
48
+ }
49
+ let lock = NSLock()
50
+ let acknowledged = DispatchSemaphore(value: 0)
51
+ var stopped = false
52
+ var keys = Set<CGKeyCode>()
53
+ var buttons = Set<Int>()
54
+ var lastPoint = CGPoint.zero
55
+ let keyMap: [String: CGKeyCode] = [
56
+ "KeyA":0,"KeyS":1,"KeyD":2,"KeyF":3,"KeyH":4,"KeyG":5,"KeyZ":6,"KeyX":7,"KeyC":8,"KeyV":9,"KeyB":11,
57
+ "KeyQ":12,"KeyW":13,"KeyE":14,"KeyR":15,"KeyY":16,"KeyT":17,"Digit1":18,"Digit2":19,"Digit3":20,"Digit4":21,
58
+ "Digit6":22,"Digit5":23,"Equal":24,"Digit9":25,"Digit7":26,"Minus":27,"Digit8":28,"Digit0":29,"BracketRight":30,
59
+ "KeyO":31,"KeyU":32,"BracketLeft":33,"KeyI":34,"KeyP":35,"Enter":36,"KeyL":37,"KeyJ":38,"Quote":39,"KeyK":40,
60
+ "Semicolon":41,"Backslash":42,"Comma":43,"Slash":44,"KeyN":45,"KeyM":46,"Period":47,"Tab":48,"Space":49,
61
+ "Backquote":50,"Backspace":51,"Escape":53,"MetaRight":54,"MetaLeft":55,"ShiftLeft":56,"CapsLock":57,
62
+ "AltLeft":58,"ControlLeft":59,"ShiftRight":60,"AltRight":61,"ControlRight":62,"F1":122,"F2":120,"F3":99,
63
+ "F4":118,"F5":96,"F6":97,"F7":98,"F8":100,"F9":101,"F10":109,"F11":103,"F12":111,"Insert":114,
64
+ "Home":115,"PageUp":116,"Delete":117,"End":119,"PageDown":121,"ArrowLeft":123,"ArrowRight":124,"ArrowDown":125,"ArrowUp":126
65
+ ]
66
+ let modifiers: [CGKeyCode: CGEventFlags] = [54:.maskCommand,55:.maskCommand,56:.maskShift,60:.maskShift,58:.maskAlternate,61:.maskAlternate,59:.maskControl,62:.maskControl]
67
+ func flags() -> CGEventFlags {
68
+ var f = CGEventFlags()
69
+ for k in keys { if let bit = modifiers[k] { f.formUnion(bit) } }
70
+ return f
71
+ }
72
+ func key(_ code: CGKeyCode, _ down: Bool) {
73
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: down)
74
+ event?.flags = flags()
75
+ event?.post(tap: .cghidEventTap)
76
+ }
77
+ func mouse(_ button: Int, _ down: Bool) {
78
+ let kind: CGEventType = button == 0 ? (down ? .leftMouseDown : .leftMouseUp) : button == 2 ? (down ? .rightMouseDown : .rightMouseUp) : (down ? .otherMouseDown : .otherMouseUp)
79
+ let event = CGEvent(mouseEventSource: nil, mouseType: kind, mouseCursorPosition: lastPoint, mouseButton: button == 0 ? .left : button == 2 ? .right : .center)
80
+ event?.flags = flags()
81
+ event?.post(tap: .cghidEventTap)
82
+ }
83
+ func release() {
84
+ lock.lock(); defer { lock.unlock() }
85
+ stopped = true
86
+ let held = keys; keys.removeAll()
87
+ for k in held { key(k, false) }
88
+ for b in buttons { mouse(b, false) }
89
+ buttons.removeAll()
90
+ acknowledged.signal()
91
+ }
92
+ // stdin EOF is also a disconnect: release even if no explicit close was delivered.
93
+ DispatchQueue.global().async {
94
+ defer { release(); exit(0) }
95
+ while let line = readLine() {
96
+ if line.utf8.count > 32768 { fail("Input exceeds limit.") }
97
+ guard let data = line.data(using: .utf8), let e = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let type = e["type"] as? String else { continue }
98
+ if type == "close" { return }
99
+ if type == "ack" { acknowledged.signal(); continue }
100
+ if readOnly { continue }
101
+ lock.lock()
102
+ if stopped { lock.unlock(); return }
103
+ switch type {
104
+ case "release":
105
+ let held = keys; keys.removeAll()
106
+ for k in held { key(k, false) }
107
+ for b in buttons { mouse(b, false) }
108
+ buttons.removeAll()
109
+ case "pointer":
110
+ if let x = e["x"] as? Double, let y = e["y"] as? Double, let action = e["action"] as? String {
111
+ let bounds = CGDisplayBounds(CGMainDisplayID())
112
+ lastPoint = CGPoint(x: bounds.minX + x * max(0, bounds.width - 1), y: bounds.minY + y * max(0, bounds.height - 1))
113
+ let b = e["button"] as? Int ?? 0
114
+ if action == "move" {
115
+ let drag = buttons.contains(0) ? CGEventType.leftMouseDragged : buttons.contains(2) ? .rightMouseDragged : buttons.contains(1) ? .otherMouseDragged : .mouseMoved
116
+ let event = CGEvent(mouseEventSource: nil, mouseType: drag, mouseCursorPosition: lastPoint, mouseButton: buttons.contains(2) ? .right : buttons.contains(1) ? .center : .left)
117
+ event?.flags = flags(); event?.post(tap: .cghidEventTap)
118
+ } else {
119
+ if action == "down" { buttons.insert(b) } else { buttons.remove(b) }
120
+ mouse(b, action == "down")
121
+ }
122
+ }
123
+ case "key":
124
+ if let code = e["code"] as? String, let k = keyMap[code], let action = e["action"] as? String {
125
+ if action == "down" { keys.insert(k) } else { keys.remove(k) }
126
+ key(k, action == "down")
127
+ }
128
+ case "wheel":
129
+ if let dy = e["deltaY"] as? Double { CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 1, wheel1: Int32(-dy), wheel2: 0, wheel3: 0)?.post(tap: .cghidEventTap) }
130
+ case "text":
131
+ if let text = e["text"] as? String {
132
+ let units = Array(text.utf16)
133
+ units.withUnsafeBufferPointer { buffer in
134
+ for down in [true, false] {
135
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: down)
136
+ event?.keyboardSetUnicodeString(stringLength: units.count, unicodeString: buffer.baseAddress)
137
+ event?.post(tap: .cghidEventTap)
138
+ }
139
+ }
140
+ }
141
+ default: break
142
+ }
143
+ lock.unlock()
144
+ }
145
+ }
146
+ // ScreenCaptureKit is also used by krd. SCScreenshotManager avoids deprecated
147
+ // CGDisplayCreateImage on current macOS SDKs and never opens a network port.
148
+ @available(macOS 14.0, *)
149
+ func captureImage() -> CGImage {
150
+ let ready = DispatchSemaphore(value: 0)
151
+ var result: CGImage?
152
+ var failure: String?
153
+ Task {
154
+ do {
155
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
156
+ guard let display = content.displays.first(where: { $0.displayID == CGMainDisplayID() }) else {
157
+ failure = "No active main display."; ready.signal(); return
158
+ }
159
+ let filter = SCContentFilter(display: display, excludingWindows: [])
160
+ let config = SCStreamConfiguration()
161
+ let scale = min(1.0, 1920.0 / Double(max(display.width, display.height)))
162
+ config.width = max(1, Int(Double(display.width) * scale))
163
+ config.height = max(1, Int(Double(display.height) * scale))
164
+ config.showsCursor = true
165
+ result = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
166
+ } catch { failure = String(describing: error) }
167
+ ready.signal()
168
+ }
169
+ guard ready.wait(timeout: .now() + 15) == .success, let image = result else {
170
+ release(); fail("ScreenCaptureKit capture failed: " + (failure ?? "timeout; check Screen Recording permission and active desktop."))
171
+ }
172
+ return image
173
+ }
174
+ while true {
175
+ autoreleasepool {
176
+ let image = captureImage()
177
+ let scale = min(1.0, 1920.0 / Double(max(image.width, image.height)))
178
+ let width = max(1, Int(Double(image.width) * scale)), height = max(1, Int(Double(image.height) * scale))
179
+ guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { release(); fail("Cannot allocate capture buffer.") }
180
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
181
+ let data = NSMutableData()
182
+ guard let scaled = context.makeImage(), let destination = CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil) else { release(); fail("Cannot create JPEG encoder.") }
183
+ CGImageDestinationAddImage(destination, scaled, [kCGImageDestinationLossyCompressionQuality: 0.65] as CFDictionary)
184
+ guard CGImageDestinationFinalize(destination), data.length > 0, data.length <= 4194304 else { release(); fail("JPEG exceeds 4 MB or encoding failed.") }
185
+ var size = UInt32(data.length).bigEndian
186
+ FileHandle.standardOutput.write(Data(bytes: &size, count: 4))
187
+ FileHandle.standardOutput.write(data as Data)
188
+ }
189
+ if acknowledged.wait(timeout: .now() + 15) == .timedOut { release(); fail("Frame consumer stopped responding.") }
190
+ Thread.sleep(forTimeInterval: 0.1)
191
+ }
192
192
  `;
@@ -1,118 +1,118 @@
1
1
  // Embedded so tsc/npm packaging cannot omit the native helper.
2
- export const windowsDesktopScript = String.raw `
3
- $ErrorActionPreference = 'Stop'
4
- Add-Type -ReferencedAssemblies System.Drawing,System.Windows.Forms,System.Web.Extensions -TypeDefinition @'
5
- using System;
6
- using System.IO;
7
- using System.Text;
8
- using System.Drawing;
9
- using System.Drawing.Imaging;
10
- using System.Runtime.InteropServices;
11
- using System.Collections.Generic;
12
- using System.Threading;
13
- using System.Web.Script.Serialization;
14
- public static class NativeDesktop {
15
- [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx,dy; public uint mouseData,dwFlags,time; public UIntPtr extra; }
16
- [StructLayout(LayoutKind.Sequential)] struct KEYBDINPUT { public ushort vk,scan; public uint flags,time; public UIntPtr extra; }
17
- [StructLayout(LayoutKind.Explicit)] struct UNION { [FieldOffset(0)] public MOUSEINPUT m; [FieldOffset(0)] public KEYBDINPUT k; }
18
- [StructLayout(LayoutKind.Sequential)] struct INPUT { public uint type; public UNION u; }
19
- [DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint n, INPUT[] input, int size);
20
- [DllImport("user32.dll")] static extern bool SetCursorPos(int x,int y);
21
- [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
22
- static readonly object gate = new object();
23
- static readonly HashSet<int> keys = new HashSet<int>();
24
- static readonly HashSet<int> buttons = new HashSet<int>();
25
- static readonly AutoResetEvent ack = new AutoResetEvent(false);
26
- static volatile bool stopped;
27
- static void Send(INPUT i) { if(SendInput(1,new INPUT[]{i},Marshal.SizeOf(typeof(INPUT)))!=1) throw new Exception("SendInput failed; Windows blocks control of elevated apps and secure desktops."); }
28
- static void Key(int vk,bool down) { INPUT i=new INPUT(); i.type=1; i.u.k.vk=(ushort)vk; i.u.k.flags=down?0u:2u; if(vk==0xA3||vk==0xA5||vk==0x5B||vk==0x5C||(vk>=0x21&&vk<=0x2E)) i.u.k.flags|=1; Send(i); }
29
- static void Mouse(int b,bool down) { INPUT i=new INPUT(); i.u.m.dwFlags=b==0?(down?2u:4u):b==1?(down?32u:64u):(down?8u:16u); Send(i); }
30
- static int Code(string c) {
31
- if(c.Length==4&&c.StartsWith("Key")&&c[3]>='A'&&c[3]<='Z') return c[3];
32
- if(c.Length==6&&c.StartsWith("Digit")&&c[5]>='0'&&c[5]<='9') return c[5];
33
- int f; if(c.StartsWith("F")&&int.TryParse(c.Substring(1),out f)&&f>=1&&f<=12) return 111+f;
34
- switch(c) {
35
- case "Enter":return 13; case "Escape":return 27; case "Backspace":return 8; case "Tab":return 9; case "Space":return 32;
36
- case "ShiftLeft":return 160; case "ShiftRight":return 161; case "ControlLeft":return 162; case "ControlRight":return 163;
37
- case "AltLeft":return 164; case "AltRight":return 165; case "MetaLeft":return 91; case "MetaRight":return 92;
38
- case "ArrowLeft":return 37; case "ArrowUp":return 38; case "ArrowRight":return 39; case "ArrowDown":return 40;
39
- case "Home":return 36; case "End":return 35; case "PageUp":return 33; case "PageDown":return 34; case "Insert":return 45; case "Delete":return 46;
40
- case "CapsLock":return 20; case "Backquote":return 192; case "Minus":return 189; case "Equal":return 187;
41
- case "BracketLeft":return 219; case "BracketRight":return 221; case "Backslash":return 220; case "Semicolon":return 186;
42
- case "Quote":return 222; case "Comma":return 188; case "Period":return 190; case "Slash":return 191;
43
- default:return 0;
44
- }
45
- }
46
- static void Release() {
47
- lock(gate) {
48
- foreach(int k in keys) { try { Key(k,false); } catch {} } keys.Clear();
49
- foreach(int b in buttons) { try { Mouse(b,false); } catch {} } buttons.Clear();
50
- }
51
- }
52
- static void Apply(Dictionary<string,object> e) {
53
- string type=(string)e["type"];
54
- lock(gate) {
55
- if(stopped) return;
56
- if(type=="pointer") {
57
- var r=System.Windows.Forms.Screen.PrimaryScreen.Bounds;
58
- if(!SetCursorPos(r.Left+(int)Math.Round(Convert.ToDouble(e["x"])*(r.Width-1)),r.Top+(int)Math.Round(Convert.ToDouble(e["y"])*(r.Height-1)))) throw new Exception("Cannot move pointer on the current desktop.");
59
- string action=(string)e["action"]; if(action=="move") return;
60
- int b=Convert.ToInt32(e["button"]); bool down=action=="down";
61
- if(down) buttons.Add(b); Mouse(b,down); if(!down) buttons.Remove(b);
62
- } else if(type=="key") {
63
- int k=Code((string)e["code"]); if(k==0) return; bool down=(string)e["action"]=="down";
64
- if(down) keys.Add(k); Key(k,down); if(!down) keys.Remove(k);
65
- } else if(type=="wheel") {
66
- INPUT i=new INPUT(); i.u.m.dwFlags=0x800; i.u.m.mouseData=unchecked((uint)(int)-Convert.ToDouble(e["deltaY"])); Send(i);
67
- } else if(type=="text") {
68
- foreach(char ch in (string)e["text"]) { INPUT i=new INPUT(); i.type=1; i.u.k.scan=ch; i.u.k.flags=4; Send(i); i.u.k.flags=6; Send(i); }
69
- }
70
- }
71
- }
72
- static void Capture() {
73
- try {
74
- Stream output=Console.OpenStandardOutput();
75
- ImageCodecInfo codec=Array.Find(ImageCodecInfo.GetImageEncoders(),c=>c.MimeType=="image/jpeg");
76
- while(!stopped) {
77
- var r=System.Windows.Forms.Screen.PrimaryScreen.Bounds;
78
- if(r.Width<1||r.Height<1||r.Width>32768||r.Height>32768||(long)r.Width*r.Height>64000000) throw new Exception("Unsupported display size.");
79
- using(var full=new Bitmap(r.Width,r.Height,PixelFormat.Format24bppRgb)) {
80
- using(var g=Graphics.FromImage(full)) g.CopyFromScreen(r.Left,r.Top,0,0,r.Size,CopyPixelOperation.SourceCopy);
81
- double scale=Math.Min(1.0,1920.0/Math.Max(r.Width,r.Height));
82
- using(var image=new Bitmap(full,new Size(Math.Max(1,(int)(r.Width*scale)),Math.Max(1,(int)(r.Height*scale)))))
83
- using(var data=new MemoryStream())
84
- using(var p=new EncoderParameters(1)) {
85
- p.Param[0]=new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,65L);
86
- image.Save(data,codec,p);
87
- if(data.Length>4194304) throw new Exception("JPEG exceeds 4 MB.");
88
- int n=(int)data.Length; byte[] h={(byte)(n>>24),(byte)(n>>16),(byte)(n>>8),(byte)n};
89
- output.Write(h,0,4); data.WriteTo(output); output.Flush();
90
- }
91
- }
92
- // One outstanding frame: pipe congestion never creates a growing frame queue.
93
- if(!ack.WaitOne(15000)) throw new Exception("Frame consumer stopped responding.");
94
- Thread.Sleep(100);
95
- }
96
- } catch(Exception e) { if(!stopped) Console.Error.WriteLine(e.Message); stopped=true; Release(); Environment.Exit(1); }
97
- }
98
- public static void Run(bool readOnly) {
99
- SetProcessDPIAware();
100
- Thread capture=new Thread(Capture); capture.IsBackground=true; capture.Start();
101
- try {
102
- using(var input=new StreamReader(Console.OpenStandardInput(),new UTF8Encoding(false))) {
103
- var json=new JavaScriptSerializer(); json.MaxJsonLength=32768;
104
- string line;
105
- while(!stopped&&(line=input.ReadLine())!=null) {
106
- if(line.Length>32768) throw new Exception("Input exceeds limit.");
107
- var e=json.Deserialize<Dictionary<string,object>>(line); string type=(string)e["type"];
108
- if(type=="close") break;
109
- if(type=="ack") { ack.Set(); continue; }
110
- if(!readOnly) { if(type=="release") Release(); else Apply(e); }
111
- }
112
- }
113
- } finally { stopped=true; ack.Set(); Release(); }
114
- }
115
- }
116
- '@
117
- [NativeDesktop]::Run($args[0] -ne 'control')
2
+ export const windowsDesktopScript = String.raw `
3
+ $ErrorActionPreference = 'Stop'
4
+ Add-Type -ReferencedAssemblies System.Drawing,System.Windows.Forms,System.Web.Extensions -TypeDefinition @'
5
+ using System;
6
+ using System.IO;
7
+ using System.Text;
8
+ using System.Drawing;
9
+ using System.Drawing.Imaging;
10
+ using System.Runtime.InteropServices;
11
+ using System.Collections.Generic;
12
+ using System.Threading;
13
+ using System.Web.Script.Serialization;
14
+ public static class NativeDesktop {
15
+ [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx,dy; public uint mouseData,dwFlags,time; public UIntPtr extra; }
16
+ [StructLayout(LayoutKind.Sequential)] struct KEYBDINPUT { public ushort vk,scan; public uint flags,time; public UIntPtr extra; }
17
+ [StructLayout(LayoutKind.Explicit)] struct UNION { [FieldOffset(0)] public MOUSEINPUT m; [FieldOffset(0)] public KEYBDINPUT k; }
18
+ [StructLayout(LayoutKind.Sequential)] struct INPUT { public uint type; public UNION u; }
19
+ [DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint n, INPUT[] input, int size);
20
+ [DllImport("user32.dll")] static extern bool SetCursorPos(int x,int y);
21
+ [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
22
+ static readonly object gate = new object();
23
+ static readonly HashSet<int> keys = new HashSet<int>();
24
+ static readonly HashSet<int> buttons = new HashSet<int>();
25
+ static readonly AutoResetEvent ack = new AutoResetEvent(false);
26
+ static volatile bool stopped;
27
+ static void Send(INPUT i) { if(SendInput(1,new INPUT[]{i},Marshal.SizeOf(typeof(INPUT)))!=1) throw new Exception("SendInput failed; Windows blocks control of elevated apps and secure desktops."); }
28
+ static void Key(int vk,bool down) { INPUT i=new INPUT(); i.type=1; i.u.k.vk=(ushort)vk; i.u.k.flags=down?0u:2u; if(vk==0xA3||vk==0xA5||vk==0x5B||vk==0x5C||(vk>=0x21&&vk<=0x2E)) i.u.k.flags|=1; Send(i); }
29
+ static void Mouse(int b,bool down) { INPUT i=new INPUT(); i.u.m.dwFlags=b==0?(down?2u:4u):b==1?(down?32u:64u):(down?8u:16u); Send(i); }
30
+ static int Code(string c) {
31
+ if(c.Length==4&&c.StartsWith("Key")&&c[3]>='A'&&c[3]<='Z') return c[3];
32
+ if(c.Length==6&&c.StartsWith("Digit")&&c[5]>='0'&&c[5]<='9') return c[5];
33
+ int f; if(c.StartsWith("F")&&int.TryParse(c.Substring(1),out f)&&f>=1&&f<=12) return 111+f;
34
+ switch(c) {
35
+ case "Enter":return 13; case "Escape":return 27; case "Backspace":return 8; case "Tab":return 9; case "Space":return 32;
36
+ case "ShiftLeft":return 160; case "ShiftRight":return 161; case "ControlLeft":return 162; case "ControlRight":return 163;
37
+ case "AltLeft":return 164; case "AltRight":return 165; case "MetaLeft":return 91; case "MetaRight":return 92;
38
+ case "ArrowLeft":return 37; case "ArrowUp":return 38; case "ArrowRight":return 39; case "ArrowDown":return 40;
39
+ case "Home":return 36; case "End":return 35; case "PageUp":return 33; case "PageDown":return 34; case "Insert":return 45; case "Delete":return 46;
40
+ case "CapsLock":return 20; case "Backquote":return 192; case "Minus":return 189; case "Equal":return 187;
41
+ case "BracketLeft":return 219; case "BracketRight":return 221; case "Backslash":return 220; case "Semicolon":return 186;
42
+ case "Quote":return 222; case "Comma":return 188; case "Period":return 190; case "Slash":return 191;
43
+ default:return 0;
44
+ }
45
+ }
46
+ static void Release() {
47
+ lock(gate) {
48
+ foreach(int k in keys) { try { Key(k,false); } catch {} } keys.Clear();
49
+ foreach(int b in buttons) { try { Mouse(b,false); } catch {} } buttons.Clear();
50
+ }
51
+ }
52
+ static void Apply(Dictionary<string,object> e) {
53
+ string type=(string)e["type"];
54
+ lock(gate) {
55
+ if(stopped) return;
56
+ if(type=="pointer") {
57
+ var r=System.Windows.Forms.Screen.PrimaryScreen.Bounds;
58
+ if(!SetCursorPos(r.Left+(int)Math.Round(Convert.ToDouble(e["x"])*(r.Width-1)),r.Top+(int)Math.Round(Convert.ToDouble(e["y"])*(r.Height-1)))) throw new Exception("Cannot move pointer on the current desktop.");
59
+ string action=(string)e["action"]; if(action=="move") return;
60
+ int b=Convert.ToInt32(e["button"]); bool down=action=="down";
61
+ if(down) buttons.Add(b); Mouse(b,down); if(!down) buttons.Remove(b);
62
+ } else if(type=="key") {
63
+ int k=Code((string)e["code"]); if(k==0) return; bool down=(string)e["action"]=="down";
64
+ if(down) keys.Add(k); Key(k,down); if(!down) keys.Remove(k);
65
+ } else if(type=="wheel") {
66
+ INPUT i=new INPUT(); i.u.m.dwFlags=0x800; i.u.m.mouseData=unchecked((uint)(int)-Convert.ToDouble(e["deltaY"])); Send(i);
67
+ } else if(type=="text") {
68
+ foreach(char ch in (string)e["text"]) { INPUT i=new INPUT(); i.type=1; i.u.k.scan=ch; i.u.k.flags=4; Send(i); i.u.k.flags=6; Send(i); }
69
+ }
70
+ }
71
+ }
72
+ static void Capture() {
73
+ try {
74
+ Stream output=Console.OpenStandardOutput();
75
+ ImageCodecInfo codec=Array.Find(ImageCodecInfo.GetImageEncoders(),c=>c.MimeType=="image/jpeg");
76
+ while(!stopped) {
77
+ var r=System.Windows.Forms.Screen.PrimaryScreen.Bounds;
78
+ if(r.Width<1||r.Height<1||r.Width>32768||r.Height>32768||(long)r.Width*r.Height>64000000) throw new Exception("Unsupported display size.");
79
+ using(var full=new Bitmap(r.Width,r.Height,PixelFormat.Format24bppRgb)) {
80
+ using(var g=Graphics.FromImage(full)) g.CopyFromScreen(r.Left,r.Top,0,0,r.Size,CopyPixelOperation.SourceCopy);
81
+ double scale=Math.Min(1.0,1920.0/Math.Max(r.Width,r.Height));
82
+ using(var image=new Bitmap(full,new Size(Math.Max(1,(int)(r.Width*scale)),Math.Max(1,(int)(r.Height*scale)))))
83
+ using(var data=new MemoryStream())
84
+ using(var p=new EncoderParameters(1)) {
85
+ p.Param[0]=new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,65L);
86
+ image.Save(data,codec,p);
87
+ if(data.Length>4194304) throw new Exception("JPEG exceeds 4 MB.");
88
+ int n=(int)data.Length; byte[] h={(byte)(n>>24),(byte)(n>>16),(byte)(n>>8),(byte)n};
89
+ output.Write(h,0,4); data.WriteTo(output); output.Flush();
90
+ }
91
+ }
92
+ // One outstanding frame: pipe congestion never creates a growing frame queue.
93
+ if(!ack.WaitOne(15000)) throw new Exception("Frame consumer stopped responding.");
94
+ Thread.Sleep(100);
95
+ }
96
+ } catch(Exception e) { if(!stopped) Console.Error.WriteLine(e.Message); stopped=true; Release(); Environment.Exit(1); }
97
+ }
98
+ public static void Run(bool readOnly) {
99
+ SetProcessDPIAware();
100
+ Thread capture=new Thread(Capture); capture.IsBackground=true; capture.Start();
101
+ try {
102
+ using(var input=new StreamReader(Console.OpenStandardInput(),new UTF8Encoding(false))) {
103
+ var json=new JavaScriptSerializer(); json.MaxJsonLength=32768;
104
+ string line;
105
+ while(!stopped&&(line=input.ReadLine())!=null) {
106
+ if(line.Length>32768) throw new Exception("Input exceeds limit.");
107
+ var e=json.Deserialize<Dictionary<string,object>>(line); string type=(string)e["type"];
108
+ if(type=="close") break;
109
+ if(type=="ack") { ack.Set(); continue; }
110
+ if(!readOnly) { if(type=="release") Release(); else Apply(e); }
111
+ }
112
+ }
113
+ } finally { stopped=true; ack.Set(); Release(); }
114
+ }
115
+ }
116
+ '@
117
+ [NativeDesktop]::Run($args[0] -ne 'control')
118
118
  `;