clipboard.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { execFile, spawn } from "node:child_process"
  2. import { readFile, rm } from "node:fs/promises"
  3. import { platform, release, tmpdir } from "node:os"
  4. import path from "node:path"
  5. import { promisify } from "node:util"
  6. const exec = promisify(execFile)
  7. function command(command: string, args: string[] = [], input?: string) {
  8. return new Promise<Buffer>((resolve, reject) => {
  9. const child = spawn(command, args, { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"] })
  10. const output: Buffer[] = []
  11. child.on("error", reject)
  12. child.stdout?.on("data", (chunk: Buffer) => output.push(chunk))
  13. child.on("close", (code) => {
  14. if (code === 0) return resolve(Buffer.concat(output))
  15. reject(new Error(`${command} exited with code ${code}`))
  16. })
  17. if (input !== undefined) child.stdin?.end(input)
  18. })
  19. }
  20. function writeOsc52(text: string) {
  21. if (!process.stdout.isTTY) return
  22. const sequence = `\x1b]52;c;${Buffer.from(text).toString("base64")}\x07`
  23. process.stdout.write(process.env.TMUX || process.env.STY ? `\x1bPtmux;\x1b${sequence}\x1b\\` : sequence)
  24. }
  25. export async function read() {
  26. if (platform() === "darwin") {
  27. const file = path.join(tmpdir(), "opencode-clipboard.png")
  28. try {
  29. await exec("osascript", [
  30. "-e",
  31. 'set imageData to the clipboard as "PNGf"',
  32. "-e",
  33. `set fileRef to open for access POSIX file "${file}" with write permission`,
  34. "-e",
  35. "set eof fileRef to 0",
  36. "-e",
  37. "write imageData to fileRef",
  38. "-e",
  39. "close access fileRef",
  40. ])
  41. return { data: (await readFile(file)).toString("base64"), mime: "image/png" }
  42. } catch {
  43. // Fall through to text clipboard.
  44. } finally {
  45. await rm(file, { force: true }).catch(() => {})
  46. }
  47. }
  48. if (platform() === "win32" || release().includes("WSL")) {
  49. const script =
  50. "Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"
  51. const image = await command("powershell.exe", ["-NonInteractive", "-NoProfile", "-command", script]).catch(() =>
  52. Buffer.alloc(0),
  53. )
  54. if (image.length) return { data: image.toString().trim(), mime: "image/png" }
  55. }
  56. if (platform() === "linux") {
  57. const wayland = await command("wl-paste", ["-t", "image/png"]).catch(() => Buffer.alloc(0))
  58. if (wayland.length) return { data: wayland.toString("base64"), mime: "image/png" }
  59. const x11 = await command("xclip", ["-selection", "clipboard", "-t", "image/png", "-o"]).catch(() =>
  60. Buffer.alloc(0),
  61. )
  62. if (x11.length) return { data: x11.toString("base64"), mime: "image/png" }
  63. }
  64. const { default: clipboardy } = await import("clipboardy")
  65. const text = await clipboardy.read().catch(() => undefined)
  66. if (text) return { data: text, mime: "text/plain" }
  67. }
  68. export function copyCommand(
  69. os: NodeJS.Platform,
  70. wayland: boolean,
  71. has: (name: string) => boolean,
  72. ): string[] | undefined {
  73. if (os === "darwin" && has("osascript")) return ["osascript"]
  74. if (os === "linux" && wayland && has("wl-copy")) return ["wl-copy"]
  75. if (os === "linux" && has("xclip")) return ["xclip", "-selection", "clipboard"]
  76. if (os === "linux" && has("xsel")) return ["xsel", "--clipboard", "--input"]
  77. if (os === "win32" && has("powershell.exe")) {
  78. return [
  79. "powershell.exe",
  80. "-NonInteractive",
  81. "-NoProfile",
  82. "-Command",
  83. "[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())",
  84. ]
  85. }
  86. }
  87. let copyMethod: Promise<(text: string) => Promise<void>> | undefined
  88. function getCopyMethod() {
  89. return (copyMethod ??= (async () => {
  90. const { which } = await import("@opencode-ai/core/util/which")
  91. const native = copyCommand(platform(), Boolean(process.env.WAYLAND_DISPLAY), (name) => Boolean(which(name)))
  92. if (native?.[0] === "osascript") {
  93. return async (text: string) => {
  94. const escaped = text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
  95. await command("osascript", ["-e", `set the clipboard to "${escaped}"`]).catch(() => undefined)
  96. }
  97. }
  98. if (native) {
  99. return async (text: string) => {
  100. await command(native[0], native.slice(1), text).catch(() => undefined)
  101. }
  102. }
  103. return async (text: string) => {
  104. const { default: clipboardy } = await import("clipboardy")
  105. await clipboardy.write(text).catch(() => undefined)
  106. }
  107. })())
  108. }
  109. export async function write(text: string) {
  110. writeOsc52(text)
  111. const method = await getCopyMethod()
  112. await method(text)
  113. }