dsh-ide-window 0.3.1 → 0.3.3

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.
package/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * connection service answers whether the request may be served at all.
17
17
  */
18
18
  import { spawn } from 'node:child_process'
19
- import { appendFileSync, existsSync, mkdirSync, openSync, fstatSync, readSync, closeSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs'
19
+ import { appendFileSync, existsSync, mkdirSync, openSync, fstatSync, readSync, closeSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
20
20
  import { fileURLToPath } from 'node:url'
21
21
  import { homedir, tmpdir } from 'node:os'
22
22
  import { platform } from './platform/index.js'
@@ -45,6 +45,8 @@ const ROUTE_TEXT = '/dsh-ide/text'
45
45
  const ROUTE_LICENSE = '/dsh-ide/license'
46
46
  const ROUTE_DIAG = '/dsh-ide/diagnostics'
47
47
  const ROUTE_THEME = '/dsh-ide/theme'
48
+ const ROUTE_SCREENSHOT = '/dsh-ide/screenshot'
49
+ const ROUTE_SCREEN_PERMISSION = '/dsh-ide/screen-permission'
48
50
 
49
51
  /** Where this file lives: the themes sit next to it, not in the profile. */
50
52
  const PLUGIN_ROOT = fileURLToPath(new URL('.', import.meta.url))
@@ -763,6 +765,11 @@ function grepWorkspace(payload) {
763
765
 
764
766
  /** Largest JSON request body accepted; `/dsh-ide/kinds` sends a directory of paths. */
765
767
  const MAX_BODY_BYTES = 64 * 1024
768
+ /**
769
+ * Screenshot bodies carry the annotated image itself (a data URL), which is
770
+ * hundreds of kilobytes by design; the default cap is for JSON commands.
771
+ */
772
+ const MAX_SCREENSHOT_BODY_BYTES = 8 * 1024 * 1024
766
773
 
767
774
  /** The four queries the seam exposes; anything else is a caller bug. */
768
775
  const OPERATIONS = new Set(['goToDefinition', 'findReferences', 'goToImplementation', 'hover'])
@@ -796,6 +803,190 @@ export function themeCss(id) {
796
803
  }
797
804
  }
798
805
 
806
+ /**
807
+ * Run a one-shot command and collect its output.
808
+ *
809
+ * Screenshot and clipboard helpers are short-lived OS tools; the same shell
810
+ * rule as the licence verbs applies on Windows (a `.bat`/`.cmd` needs a shell).
811
+ */
812
+ function runProcess(command, args, timeoutMs) {
813
+ return new Promise((resolve) => {
814
+ let child
815
+ try {
816
+ child = spawn(command, args, {
817
+ stdio: ['ignore', 'pipe', 'pipe'],
818
+ shell: platform.needsShell(command),
819
+ })
820
+ } catch (error) {
821
+ resolve({ code: -1, output: String(error?.message ?? error) })
822
+ return
823
+ }
824
+ let output = ''
825
+ const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs)
826
+ const collect = (chunk) => {
827
+ output += String(chunk)
828
+ if (output.length > 20000) output = output.slice(-20000)
829
+ }
830
+ child.stdout.on('data', collect)
831
+ child.stderr.on('data', collect)
832
+ child.on('error', (error) => {
833
+ clearTimeout(timer)
834
+ resolve({ code: -1, output: String(error?.message ?? error) })
835
+ })
836
+ child.on('close', (code) => {
837
+ clearTimeout(timer)
838
+ resolve({ code: code ?? -1, output })
839
+ })
840
+ })
841
+ }
842
+
843
+ /**
844
+ * Whether a failed capture looks like a missing screen-recording grant.
845
+ *
846
+ * `screencapture` says "could not create image from display" when macOS denied
847
+ * the permission; the wording is the only signal available, so it is pinned by
848
+ * a test rather than being an inline regex.
849
+ */
850
+ export function screenshotLooksPermissionDenied(output) {
851
+ return /could not create image|not permitt|permission|denied|屏幕录制|隐私/i.test(String(output ?? ''))
852
+ }
853
+
854
+ /**
855
+ * Capture the screen into a temp PNG.
856
+ *
857
+ * `copy` also puts it on the system clipboard, which is what "只截图" hands the
858
+ * user. The data URL is what the panel previews and what gets pasted into the
859
+ * conversation, so the client never needs a file:// URL.
860
+ */
861
+ /** The capture is shrunk to a JPEG (the platform sets the long edge). */
862
+ const IDE_SCREENSHOT_MAX_BYTES = 1024 * 1024
863
+ /**
864
+ * Capture resolution used by the editor.
865
+ *
866
+ * Bigger than the final 1080p export: the user crops a region, and cropping a
867
+ * 1080p capture would leave a blurry result.
868
+ */
869
+ const IDE_SCREENSHOT_EDIT_EDGE = 2560
870
+ /** JPEG quality ladder: the first result under the budget wins. */
871
+ const IDE_SCREENSHOT_QUALITIES = [80, 70, 60, 50]
872
+
873
+ /**
874
+ * Shrink a capture to a 1080p-class JPEG under 1 MB.
875
+ *
876
+ * A Retina full-screen capture is several megabytes and no chat needs that. The
877
+ * ladder stops at the first size that fits, so a mostly-flat screen keeps its
878
+ * quality while a text-heavy one steps down. Returns the file that was written,
879
+ * or the PNG when no quality produced a file (the caller still has an image).
880
+ */
881
+ async function optimizeScreenshot(pngPath, longEdge) {
882
+ const jpegPath = pngPath.replace(/\.png$/i, '') + '.jpg'
883
+ let best = null
884
+ for (const quality of IDE_SCREENSHOT_QUALITIES) {
885
+ const { command, args } = platform.imageOptimizeCommand(pngPath, jpegPath, quality, longEdge)
886
+ const { code, output } = await runProcess(command, args, 20000)
887
+ let bytes = 0
888
+ try {
889
+ bytes = statSync(jpegPath).size
890
+ } catch {
891
+ bytes = 0
892
+ }
893
+ if (code !== 0 || bytes === 0) {
894
+ logEvent('warn', 'screenshot', `optimise failed at quality ${quality}`, output.trim())
895
+ continue
896
+ }
897
+ best = { path: jpegPath, bytes, quality }
898
+ if (bytes <= IDE_SCREENSHOT_MAX_BYTES) break
899
+ }
900
+ return best
901
+ }
902
+
903
+ export async function captureScreen(payload) {
904
+ // The editor produces the final image in the page; write it out, then copy it.
905
+ if (typeof payload?.copyDataUrl === 'string' && payload.copyDataUrl.startsWith('data:image/')) {
906
+ const comma = payload.copyDataUrl.indexOf(',')
907
+ const binary = Buffer.from(payload.copyDataUrl.slice(comma + 1), 'base64')
908
+ const file = join(tmpdir(), `dsh-ide-shot-${Date.now()}.jpg`)
909
+ writeFileSync(file, binary)
910
+ const clipboard = platform.clipboardImageCommand(file)
911
+ const copied = await runProcess(clipboard.command, clipboard.args, 20000)
912
+ if (copied.code !== 0) {
913
+ logEvent('warn', 'screenshot', 'clipboard copy failed', copied.output)
914
+ throw new RouteError(500, 'clipboard-failed', copied.output.trim() || 'clipboard copy failed')
915
+ }
916
+ return { path: file, copied: true, bytes: binary.length, dataUrl: '' }
917
+ }
918
+ // "只截图" after a capture only needs the existing file on the clipboard.
919
+ if (typeof payload?.copyOf === 'string' && payload.copyOf !== '') {
920
+ const existing = payload.copyOf
921
+ const clipboard = platform.clipboardImageCommand(existing)
922
+ const copied = await runProcess(clipboard.command, clipboard.args, 20000)
923
+ if (copied.code !== 0) {
924
+ logEvent('warn', 'screenshot', 'clipboard copy failed', copied.output)
925
+ throw new RouteError(500, 'clipboard-failed', copied.output.trim() || 'clipboard copy failed')
926
+ }
927
+ return { path: existing, copied: true, bytes: 0, dataUrl: '' }
928
+ }
929
+ const target = join(tmpdir(), `dsh-ide-shot-${Date.now()}.png`)
930
+ const { command, args } = platform.screenshotCommand(target)
931
+ const { code, output } = await runProcess(command, args, 20000)
932
+ logEvent('info', 'screenshot', 'capture: spawned', { code, bytes: output.length })
933
+ let bytes = 0
934
+ try {
935
+ bytes = statSync(target).size
936
+ } catch {
937
+ bytes = 0
938
+ }
939
+ if (code !== 0 || bytes === 0) {
940
+ if (screenshotLooksPermissionDenied(output)) {
941
+ throw new RouteError(403, 'no-screen-permission', output.trim() || 'screen recording is not permitted')
942
+ }
943
+ throw new RouteError(500, 'capture-failed', output.trim() || `screenshot exited ${code}`)
944
+ }
945
+ if (payload?.copy === true) {
946
+ const clipboard = platform.clipboardImageCommand(target)
947
+ const copied = await runProcess(clipboard.command, clipboard.args, 20000)
948
+ if (copied.code !== 0) {
949
+ logEvent('warn', 'screenshot', 'clipboard copy failed', copied.output)
950
+ }
951
+ }
952
+ // A raw screen is far too big for a chat attachment: shrink it before it is
953
+ // ever shown or pasted, and keep only the small file on disk.
954
+ const optimized = await optimizeScreenshot(target, IDE_SCREENSHOT_EDIT_EDGE)
955
+ try {
956
+ rmSync(target, { force: true })
957
+ } catch {
958
+ /* the OS will clean the temp dir anyway */
959
+ }
960
+ if (optimized === null) {
961
+ throw new RouteError(500, 'capture-failed', 'the capture could not be optimised')
962
+ }
963
+ const mime = /\.jpe?g$/i.test(optimized.path) ? 'image/jpeg' : 'image/png'
964
+ const dataUrl = `data:${mime};base64,${readFileSync(optimized.path).toString('base64')}`
965
+ logEvent('info', 'screenshot', 'captured', {
966
+ bytes: optimized.bytes,
967
+ quality: optimized.quality,
968
+ path: optimized.path,
969
+ })
970
+ // The temp file stays for "只截图" (the notice shows the path).
971
+ return { path: optimized.path, bytes: optimized.bytes, quality: optimized.quality, dataUrl }
972
+ }
973
+
974
+ /**
975
+ * Open the OS place where screen recording is granted.
976
+ *
977
+ * Only macOS gates capture behind a permission; on Windows the answer says so
978
+ * instead of opening a settings window that does not exist.
979
+ */
980
+ export async function openScreenPermission() {
981
+ if (platform.name !== 'mac') {
982
+ return { opened: false, hint: platform.name === 'windows' ? 'windows-no-permission' : 'unsupported' }
983
+ }
984
+ const url = 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'
985
+ const opened = platform.openUrlCommand(url)
986
+ const { code } = await runProcess(opened.command, opened.args, 10000)
987
+ return { opened: code === 0, hint: 'macos-screen-recording' }
988
+ }
989
+
799
990
  /** Serve one palette as CSS; the ETag keeps a reopened panel from refetching. */
800
991
  function createThemeHandler() {
801
992
  return async (request, response) => {
@@ -835,12 +1026,12 @@ function writeJson(response, status, payload) {
835
1026
  }
836
1027
 
837
1028
  /** Read and parse the request body under a byte cap. */
838
- async function readJsonBody(request) {
1029
+ async function readJsonBody(request, limit = MAX_BODY_BYTES) {
839
1030
  const chunks = []
840
1031
  let size = 0
841
1032
  for await (const chunk of request) {
842
1033
  size += chunk.length
843
- if (size > MAX_BODY_BYTES) throw new RouteError(413, 'body-too-large', 'request body is too large')
1034
+ if (size > limit) throw new RouteError(413, 'body-too-large', 'request body is too large')
844
1035
  chunks.push(chunk)
845
1036
  }
846
1037
  if (size === 0) return {}
@@ -1287,11 +1478,16 @@ function createHandler(ctx) {
1287
1478
  return
1288
1479
  }
1289
1480
  pathname = new URL(request.url ?? '/', 'http://dsh-ide.internal').pathname
1290
- if (pathname !== ROUTE_LSP && pathname !== ROUTE_GREP && pathname !== ROUTE_DIFF && pathname !== ROUTE_JAR && pathname !== ROUTE_STATUS && pathname !== ROUTE_BLAME && pathname !== ROUTE_DOCTOR && pathname !== ROUTE_KINDS && pathname !== ROUTE_LOG && pathname !== ROUTE_REFS && pathname !== ROUTE_PATCH && pathname !== ROUTE_TEXT && pathname !== ROUTE_LICENSE && pathname !== ROUTE_DIAG) {
1481
+ if (pathname !== ROUTE_LSP && pathname !== ROUTE_GREP && pathname !== ROUTE_DIFF && pathname !== ROUTE_JAR && pathname !== ROUTE_STATUS && pathname !== ROUTE_BLAME && pathname !== ROUTE_DOCTOR && pathname !== ROUTE_KINDS && pathname !== ROUTE_LOG && pathname !== ROUTE_REFS && pathname !== ROUTE_PATCH && pathname !== ROUTE_TEXT && pathname !== ROUTE_LICENSE && pathname !== ROUTE_DIAG && pathname !== ROUTE_SCREENSHOT && pathname !== ROUTE_SCREEN_PERMISSION) {
1291
1482
  writeJson(response, 404, { ok: false, error: { code: 'not-found', message: 'unknown route' } })
1292
1483
  return
1293
1484
  }
1294
- const payload = await readJsonBody(request)
1485
+ // The editor sends the finished image back when copying it: that body is
1486
+ // the picture, not a command, so it gets its own ceiling.
1487
+ const payload = await readJsonBody(
1488
+ request,
1489
+ pathname === ROUTE_SCREENSHOT ? MAX_SCREENSHOT_BODY_BYTES : MAX_BODY_BYTES,
1490
+ )
1295
1491
  const value = pathname === ROUTE_GREP
1296
1492
  ? await grepWorkspace(payload)
1297
1493
  : pathname === ROUTE_DIFF
@@ -1318,6 +1514,10 @@ function createHandler(ctx) {
1318
1514
  ? await licenseCommand(payload)
1319
1515
  : pathname === ROUTE_DIAG
1320
1516
  ? diagnosticsReport(payload)
1517
+ : pathname === ROUTE_SCREENSHOT
1518
+ ? await captureScreen(payload)
1519
+ : pathname === ROUTE_SCREEN_PERMISSION
1520
+ ? await openScreenPermission()
1321
1521
  : await query(ctx, payload)
1322
1522
  writeJson(response, 200, { ok: true, value })
1323
1523
  } catch (error) {
@@ -1409,4 +1609,14 @@ export function apply(ctx) {
1409
1609
  path: ROUTE_THEME,
1410
1610
  handler: createThemeHandler(),
1411
1611
  }), 'dsh-ide-window: theme route')
1612
+ ctx.effect(() => ctx.webServer.register({
1613
+ kind: 'prefix',
1614
+ path: ROUTE_SCREENSHOT,
1615
+ handler,
1616
+ }), 'dsh-ide-window: screenshot route')
1617
+ ctx.effect(() => ctx.webServer.register({
1618
+ kind: 'prefix',
1619
+ path: ROUTE_SCREEN_PERMISSION,
1620
+ handler,
1621
+ }), 'dsh-ide-window: screen permission route')
1412
1622
  }
package/locale/en.json CHANGED
@@ -228,5 +228,26 @@
228
228
  "theme_github_light": "GitHub Light",
229
229
  "theme_atom_one_light": "Atom One Light",
230
230
  "theme_solarized_light": "Solarized Light",
231
- "theme_intellij_light": "IntelliJ Light"
231
+ "theme_intellij_light": "IntelliJ Light",
232
+ "shortcutScreenshot": "Screenshot (can jump to chat)",
233
+ "shotBusy": "Capturing…",
234
+ "shotRetry": "Retry",
235
+ "shotFailed": "Screenshot failed",
236
+ "shotNoPermissionTitle": "Cannot capture: Screen Recording permission is missing",
237
+ "shotNoPermissionMac": "Enable DeepSeek Harness under System Settings → Privacy & Security → Screen Recording, then quit and reopen the app (the grant only applies after a relaunch).",
238
+ "shotNoPermissionWindows": "Windows needs no permission for this. Check that the screen is unlocked and no remote-desktop session or policy blocks capture, then retry.",
239
+ "shotOpenSettings": "Open System Settings",
240
+ "shotAttached": "Screenshot inserted into the conversation",
241
+ "shotCopied": "Screenshot copied to the clipboard",
242
+ "shotNoEditor": "Composer not found: the screenshot is on the clipboard, press ⌘V",
243
+ "shotOpenFailed": "Could not open System Settings. Open it manually: Privacy & Security → Screen Recording",
244
+ "paletteActionScreenshot": "Take a screenshot",
245
+ "shotSelectHint": "Press the left button and drag to frame the area; release to finish, Esc cancels.",
246
+ "shotMarkHint": "Drag inside the frame to draw a box, or pick Text and click to type. ⌘Z undoes, Esc closes.",
247
+ "shotTool_rect": "Box",
248
+ "shotTool_text": "Text",
249
+ "shotUndo": "Undo",
250
+ "shotTextPlaceholder": "Type, then press Enter",
251
+ "shotCopy": "Capture",
252
+ "shotJump": "Capture and open chat"
232
253
  }
package/locale/zh.json CHANGED
@@ -228,5 +228,26 @@
228
228
  "theme_github_light": "GitHub 浅色",
229
229
  "theme_atom_one_light": "Atom One 浅色",
230
230
  "theme_solarized_light": "Solarized 浅色",
231
- "theme_intellij_light": "IntelliJ 浅色"
231
+ "theme_intellij_light": "IntelliJ 浅色",
232
+ "shortcutScreenshot": "截图(可跳转会话)",
233
+ "shotBusy": "正在截图…",
234
+ "shotRetry": "重试",
235
+ "shotFailed": "截图失败",
236
+ "shotNoPermissionTitle": "无法截图:缺少屏幕录制权限",
237
+ "shotNoPermissionMac": "请在「系统设置 → 隐私与安全性 → 屏幕录制」里勾选 DeepSeek Harness,然后完全退出并重新打开应用(授权后必须重启才生效)。",
238
+ "shotNoPermissionWindows": "Windows 截图不需要授权。请确认没有锁屏、远程桌面占用或企业策略拦截,然后重试。",
239
+ "shotOpenSettings": "打开系统设置",
240
+ "shotAttached": "已把截图插入对话",
241
+ "shotCopied": "截图已复制到剪贴板",
242
+ "shotNoEditor": "没找到对话框:截图已复制到剪贴板,按 ⌘V 粘贴",
243
+ "shotOpenFailed": "打不开系统设置,请手动打开:系统设置 → 隐私与安全性 → 屏幕录制",
244
+ "paletteActionScreenshot": "截图",
245
+ "shotSelectHint": "按住鼠标左键拖动,框出要截的范围;松开后完成选框,Esc 取消",
246
+ "shotMarkHint": "在选框内拖动可画矩形,选「文字」后点一下输入;⌘Z 撤销,Esc 关闭",
247
+ "shotTool_rect": "矩形",
248
+ "shotTool_text": "文字",
249
+ "shotUndo": "撤销",
250
+ "shotTextPlaceholder": "输入文字后回车",
251
+ "shotCopy": "截图",
252
+ "shotJump": "截图并跳转会话"
232
253
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ide-window",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "IDEA-style code workspace for DeepSeek Harness: a centre panel with a workspace file tree, editor tabs and live-updating source, while the left navigation column hides.",
5
5
  "type": "module",
6
6
  "icon": "icon.svg",
@@ -30,7 +30,7 @@
30
30
  "scripts": {
31
31
  "build": "node build.mjs",
32
32
  "check": "node --check index.js && node --check client.js",
33
- "test": "node test/platform.mjs && node test/diagnostics.mjs && node test/status.mjs && node test/harness.mjs && node test/inference.mjs && node test/maven.mjs && node test/theme.mjs"
33
+ "test": "node test/platform.mjs && node test/diagnostics.mjs && node test/status.mjs && node test/harness.mjs && node test/inference.mjs && node test/maven.mjs && node test/theme.mjs && node test/screenshot.mjs"
34
34
  },
35
35
  "dsh": {
36
36
  "bundle": {
@@ -28,6 +28,13 @@
28
28
  * @property {string[]} ripgrepSuffixes Binary paths inside the bundled packages.
29
29
  * @property {string[]} serverLauncherNames Launcher file names, in try order.
30
30
  * @property {(path: string) => boolean} needsShell `spawn` needs `shell: true`
31
+ * @property {(path: string) => {command: string, args: string[]}} screenshotCommand
32
+ * Capture the whole screen into that PNG with an OS built-in tool.
33
+ * @property {(input: string, output: string, quality: number, longEdge: number) => {command: string, args: string[]}} imageOptimizeCommand
34
+ * Shrink that PNG to a JPEG whose long edge is `longEdge` (1920 = 1080p on a
35
+ * 16:9 screen; the editor keeps a larger capture to crop from), at `quality`.
36
+ * @property {(path: string) => {command: string, args: string[]}} clipboardImageCommand
37
+ * Put that image file on the system clipboard.
31
38
  * for this path (Windows blocks `.bat`/`.cmd` without it since CVE-2024-27980).
32
39
  * @property {(url: string) => { command: string, args: string[] }} openUrlCommand
33
40
  */
@@ -43,4 +50,7 @@ export const PLATFORM_METHODS = [
43
50
  'serverLauncherNames',
44
51
  'needsShell',
45
52
  'openUrlCommand',
53
+ 'screenshotCommand',
54
+ 'imageOptimizeCommand',
55
+ 'clipboardImageCommand',
46
56
  ]
package/platform/macos.js CHANGED
@@ -27,4 +27,23 @@ export const macPlatform = {
27
27
  serverLauncherNames: ['intellij-server'],
28
28
  needsShell: () => false,
29
29
  openUrlCommand: (url) => ({ command: 'open', args: [url] }),
30
+ // Both tools ship with macOS: `screencapture` writes the PNG and AppleScript
31
+ // puts it on the pasteboard, so nothing has to be installed.
32
+ screenshotCommand: (path) => ({ command: 'screencapture', args: ['-x', '-t', 'png', String(path ?? '')] }),
33
+ // `sips` ships with macOS: `-Z` fits the long edge and `-s formatOptions` is
34
+ // the JPEG quality. A Retina capture is 5120×2880; 1080p is plenty for chat.
35
+ imageOptimizeCommand: (input, output, quality, longEdge) => ({
36
+ command: 'sips',
37
+ args: [
38
+ '-Z', String(longEdge ?? 1920),
39
+ '-s', 'format', 'jpeg',
40
+ '-s', 'formatOptions', String(quality),
41
+ String(input ?? ''),
42
+ '--out', String(output ?? ''),
43
+ ],
44
+ }),
45
+ clipboardImageCommand: (path) => ({
46
+ command: 'osascript',
47
+ args: ['-e', `set the clipboard to (read (POSIX file "${String(path ?? '')}") as «class PNGf»)`],
48
+ }),
30
49
  }
@@ -38,4 +38,71 @@ export const windowsPlatform = {
38
38
  // goes through a shell layer; `cmd /c start ""` is the documented form and
39
39
  // keeps the empty title argument that `start` needs for a quoted URL.
40
40
  openUrlCommand: (url) => ({ command: 'cmd', args: ['/c', 'start', '', url] }),
41
+ // .NET (part of Windows) captures the virtual screen and fills the clipboard,
42
+ // so no third-party tool is needed. The script writes a real PNG file.
43
+ screenshotCommand: (path) => ({
44
+ command: 'powershell.exe',
45
+ args: ['-NoProfile', '-NonInteractive', '-Command', windowsScreenshotScript(path)],
46
+ }),
47
+ imageOptimizeCommand: (input, output, quality, longEdge) => ({
48
+ command: 'powershell.exe',
49
+ args: ['-NoProfile', '-NonInteractive', '-Command', windowsOptimizeScript(input, output, quality, longEdge)],
50
+ }),
51
+ clipboardImageCommand: (path) => ({
52
+ command: 'powershell.exe',
53
+ args: ['-NoProfile', '-NonInteractive', '-STA', '-Command', windowsClipboardScript(path)],
54
+ }),
55
+ }
56
+
57
+ /** The PowerShell that grabs every monitor into one PNG. */
58
+ function windowsScreenshotScript(path) {
59
+ const target = String(path ?? '').replace(/'/g, "''")
60
+ return [
61
+ 'Add-Type -AssemblyName System.Windows.Forms,System.Drawing',
62
+ '$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen',
63
+ '$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height',
64
+ '$graphics = [System.Drawing.Graphics]::FromImage($bitmap)',
65
+ '$graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bitmap.Size)',
66
+ `$bitmap.Save('${target}', [System.Drawing.Imaging.ImageFormat]::Png)`,
67
+ '$graphics.Dispose()',
68
+ '$bitmap.Dispose()',
69
+ ].join('; ')
70
+ }
71
+
72
+ /** The PowerShell that shrinks a capture to a 1080p-class JPEG. */
73
+ function windowsOptimizeScript(input, output, quality, longEdge) {
74
+ const source = String(input ?? '').replace(/'/g, "''")
75
+ const target = String(output ?? '').replace(/'/g, "''")
76
+ const level = Math.min(100, Math.max(10, Number.isFinite(quality) ? quality : 80))
77
+ const edge = Number.isFinite(longEdge) && longEdge > 0 ? Math.round(longEdge) : 1920
78
+ return [
79
+ 'Add-Type -AssemblyName System.Drawing',
80
+ `$source = [System.Drawing.Image]::FromFile('${source}')`,
81
+ '$long = [Math]::Max($source.Width, $source.Height)',
82
+ `$scale = [Math]::Min(1.0, ${edge} / $long)`,
83
+ '$width = [int][Math]::Round($source.Width * $scale)',
84
+ '$height = [int][Math]::Round($source.Height * $scale)',
85
+ '$bitmap = New-Object System.Drawing.Bitmap $width, $height',
86
+ '$graphics = [System.Drawing.Graphics]::FromImage($bitmap)',
87
+ '$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic',
88
+ '$graphics.DrawImage($source, 0, 0, $width, $height)',
89
+ '$codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq "image/jpeg" }',
90
+ '$parameters = New-Object System.Drawing.Imaging.EncoderParameters(1)',
91
+ `$parameters.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, [long]${level})`,
92
+ `$bitmap.Save('${target}', $codec, $parameters)`,
93
+ '$graphics.Dispose()',
94
+ '$bitmap.Dispose()',
95
+ '$source.Dispose()',
96
+ ].join('; ')
97
+ }
98
+
99
+ /** The PowerShell that puts an existing PNG on the clipboard. */
100
+ function windowsClipboardScript(path) {
101
+ const target = String(path ?? '').replace(/'/g, "''")
102
+ return [
103
+ 'Add-Type -AssemblyName System.Windows.Forms,System.Drawing',
104
+ `$image = [System.Drawing.Image]::FromFile('${target}')`,
105
+ '[System.Windows.Forms.Clipboard]::SetImage($image)',
106
+ '$image.Dispose()',
107
+ ].join('; ')
41
108
  }