Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 58b1c58bc5 | |||
| d80badc50f | |||
| 75279e5ccf | |||
| 7893b84614 | |||
| cfc715bd48 | |||
| 39bcba85a9 | |||
| da3df51316 | |||
| 12190e4efc | |||
| d2a9b2f64a | |||
| aacadd8a8a | |||
| 969154a473 | |||
| 4d6ca3fab1 | |||
| 00ea5082e7 | |||
| 4a878b88c0 | |||
| 6de955847c | |||
| 3ba5d528b4 | |||
| f99e2b3429 | |||
| 7e4e6f6e51 | |||
| 0514f3f43b | |||
| 1e07384364 | |||
| 4c4739c422 | |||
| 2d8b90a6ff | |||
| a2fa7ffa42 | |||
| f7d6175283 | |||
| 9ed187ee52 | |||
| 14d81e574b | |||
| 6efe8cc8df | |||
| daa5fc916a | |||
| c659496b96 | |||
| 21fbf21cb6 | |||
| f31cbf2744 | |||
| 8322f18e03 | |||
| 562bdb95e2 | |||
| a57ce8365d | |||
| 0da83ae67e | |||
| 662d022a48 | |||
| 9efef03919 | |||
| 7a9fb3fa92 | |||
| ea96ead346 | |||
| 6100a77b85 |
@@ -1,12 +1,13 @@
|
||||
# Download Stats
|
||||
|
||||
| Date | GitHub Downloads | npm Downloads | Total |
|
||||
| ---------- | ---------------- | --------------- | --------------- |
|
||||
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
|
||||
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
|
||||
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
|
||||
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
|
||||
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
|
||||
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
|
||||
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
|
||||
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
|
||||
| Date | GitHub Downloads | npm Downloads | Total |
|
||||
| ---------- | ---------------- | --------------- | ---------------- |
|
||||
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
|
||||
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
|
||||
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
|
||||
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
|
||||
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
|
||||
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
|
||||
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
|
||||
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
|
||||
| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) |
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"dev": "bun run packages/opencode/src/index.ts",
|
||||
"typecheck": "bun run --filter='*' typecheck",
|
||||
"stainless": "bun run ./packages/opencode/src/index.ts serve ",
|
||||
"stainless": "./scripts/stainless",
|
||||
"postinstall": "./scripts/hooks"
|
||||
},
|
||||
"workspaces": {
|
||||
|
||||
@@ -14,111 +14,267 @@
|
||||
"properties": {
|
||||
"leader": {
|
||||
"type": "string",
|
||||
"description": "Leader key for keybind combinations"
|
||||
"default": "ctrl+x",
|
||||
"description": "Leader key for keybind combinations\n\ndefault: `ctrl+x`",
|
||||
"examples": [
|
||||
"ctrl+x"
|
||||
]
|
||||
},
|
||||
"help": {
|
||||
"app_help": {
|
||||
"type": "string",
|
||||
"description": "Show help dialog"
|
||||
"default": "<leader>h",
|
||||
"description": "Show help dialog\n\ndefault: `<leader>h`",
|
||||
"examples": [
|
||||
"<leader>h"
|
||||
]
|
||||
},
|
||||
"editor_open": {
|
||||
"type": "string",
|
||||
"description": "Open external editor"
|
||||
"default": "<leader>e",
|
||||
"description": "Open external editor\n\ndefault: `<leader>e`",
|
||||
"examples": [
|
||||
"<leader>e"
|
||||
]
|
||||
},
|
||||
"session_new": {
|
||||
"type": "string",
|
||||
"description": "Create a new session"
|
||||
"default": "<leader>n",
|
||||
"description": "Create a new session\n\ndefault: `<leader>n`",
|
||||
"examples": [
|
||||
"<leader>n"
|
||||
]
|
||||
},
|
||||
"session_list": {
|
||||
"type": "string",
|
||||
"description": "List all sessions"
|
||||
"default": "<leader>l",
|
||||
"description": "List all sessions\n\ndefault: `<leader>l`",
|
||||
"examples": [
|
||||
"<leader>l"
|
||||
]
|
||||
},
|
||||
"session_share": {
|
||||
"type": "string",
|
||||
"description": "Share current session"
|
||||
"default": "<leader>s",
|
||||
"description": "Share current session\n\ndefault: `<leader>s`",
|
||||
"examples": [
|
||||
"<leader>s"
|
||||
]
|
||||
},
|
||||
"session_unshare": {
|
||||
"type": "string",
|
||||
"default": "<leader>u",
|
||||
"description": "Unshare current session\n\ndefault: `<leader>u`",
|
||||
"examples": [
|
||||
"<leader>u"
|
||||
]
|
||||
},
|
||||
"session_interrupt": {
|
||||
"type": "string",
|
||||
"description": "Interrupt current session"
|
||||
"default": "esc",
|
||||
"description": "Interrupt current session\n\ndefault: `esc`",
|
||||
"examples": [
|
||||
"esc"
|
||||
]
|
||||
},
|
||||
"session_compact": {
|
||||
"type": "string",
|
||||
"description": "Toggle compact mode for session"
|
||||
"default": "<leader>c",
|
||||
"description": "Compact the session\n\ndefault: `<leader>c`",
|
||||
"examples": [
|
||||
"<leader>c"
|
||||
]
|
||||
},
|
||||
"tool_details": {
|
||||
"type": "string",
|
||||
"description": "Show tool details"
|
||||
"default": "<leader>d",
|
||||
"description": "Toggle tool details\n\ndefault: `<leader>d`",
|
||||
"examples": [
|
||||
"<leader>d"
|
||||
]
|
||||
},
|
||||
"model_list": {
|
||||
"type": "string",
|
||||
"description": "List available models"
|
||||
"default": "<leader>m",
|
||||
"description": "List available models\n\ndefault: `<leader>m`",
|
||||
"examples": [
|
||||
"<leader>m"
|
||||
]
|
||||
},
|
||||
"theme_list": {
|
||||
"type": "string",
|
||||
"description": "List available themes"
|
||||
"default": "<leader>t",
|
||||
"description": "List available themes\n\ndefault: `<leader>t`",
|
||||
"examples": [
|
||||
"<leader>t"
|
||||
]
|
||||
},
|
||||
"file_list": {
|
||||
"type": "string",
|
||||
"default": "<leader>f",
|
||||
"description": "List files\n\ndefault: `<leader>f`",
|
||||
"examples": [
|
||||
"<leader>f"
|
||||
]
|
||||
},
|
||||
"file_close": {
|
||||
"type": "string",
|
||||
"default": "esc",
|
||||
"description": "Close file\n\ndefault: `esc`",
|
||||
"examples": [
|
||||
"esc"
|
||||
]
|
||||
},
|
||||
"file_search": {
|
||||
"type": "string",
|
||||
"default": "<leader>/",
|
||||
"description": "Search file\n\ndefault: `<leader>/`",
|
||||
"examples": [
|
||||
"<leader>/"
|
||||
]
|
||||
},
|
||||
"file_diff_toggle": {
|
||||
"type": "string",
|
||||
"default": "<leader>v",
|
||||
"description": "Split/unified diff\n\ndefault: `<leader>v`",
|
||||
"examples": [
|
||||
"<leader>v"
|
||||
]
|
||||
},
|
||||
"project_init": {
|
||||
"type": "string",
|
||||
"description": "Initialize project configuration"
|
||||
"default": "<leader>i",
|
||||
"description": "Create/update AGENTS.md\n\ndefault: `<leader>i`",
|
||||
"examples": [
|
||||
"<leader>i"
|
||||
]
|
||||
},
|
||||
"input_clear": {
|
||||
"type": "string",
|
||||
"description": "Clear input field"
|
||||
"default": "ctrl+c",
|
||||
"description": "Clear input field\n\ndefault: `ctrl+c`",
|
||||
"examples": [
|
||||
"ctrl+c"
|
||||
]
|
||||
},
|
||||
"input_paste": {
|
||||
"type": "string",
|
||||
"description": "Paste from clipboard"
|
||||
"default": "ctrl+v",
|
||||
"description": "Paste from clipboard\n\ndefault: `ctrl+v`",
|
||||
"examples": [
|
||||
"ctrl+v"
|
||||
]
|
||||
},
|
||||
"input_submit": {
|
||||
"type": "string",
|
||||
"description": "Submit input"
|
||||
"default": "enter",
|
||||
"description": "Submit input\n\ndefault: `enter`",
|
||||
"examples": [
|
||||
"enter"
|
||||
]
|
||||
},
|
||||
"input_newline": {
|
||||
"type": "string",
|
||||
"description": "Insert newline in input"
|
||||
},
|
||||
"history_previous": {
|
||||
"type": "string",
|
||||
"description": "Navigate to previous history item"
|
||||
},
|
||||
"history_next": {
|
||||
"type": "string",
|
||||
"description": "Navigate to next history item"
|
||||
"default": "shift+enter,ctrl+j",
|
||||
"description": "Insert newline in input\n\ndefault: `shift+enter,ctrl+j`",
|
||||
"examples": [
|
||||
"shift+enter,ctrl+j"
|
||||
]
|
||||
},
|
||||
"messages_page_up": {
|
||||
"type": "string",
|
||||
"description": "Scroll messages up by one page"
|
||||
"default": "pgup",
|
||||
"description": "Scroll messages up by one page\n\ndefault: `pgup`",
|
||||
"examples": [
|
||||
"pgup"
|
||||
]
|
||||
},
|
||||
"messages_page_down": {
|
||||
"type": "string",
|
||||
"description": "Scroll messages down by one page"
|
||||
"default": "pgdown",
|
||||
"description": "Scroll messages down by one page\n\ndefault: `pgdown`",
|
||||
"examples": [
|
||||
"pgdown"
|
||||
]
|
||||
},
|
||||
"messages_half_page_up": {
|
||||
"type": "string",
|
||||
"description": "Scroll messages up by half page"
|
||||
"default": "ctrl+alt+u",
|
||||
"description": "Scroll messages up by half page\n\ndefault: `ctrl+alt+u`",
|
||||
"examples": [
|
||||
"ctrl+alt+u"
|
||||
]
|
||||
},
|
||||
"messages_half_page_down": {
|
||||
"type": "string",
|
||||
"description": "Scroll messages down by half page"
|
||||
"default": "ctrl+alt+d",
|
||||
"description": "Scroll messages down by half page\n\ndefault: `ctrl+alt+d`",
|
||||
"examples": [
|
||||
"ctrl+alt+d"
|
||||
]
|
||||
},
|
||||
"messages_previous": {
|
||||
"type": "string",
|
||||
"description": "Navigate to previous message"
|
||||
"default": "ctrl+up",
|
||||
"description": "Navigate to previous message\n\ndefault: `ctrl+up`",
|
||||
"examples": [
|
||||
"ctrl+up"
|
||||
]
|
||||
},
|
||||
"messages_next": {
|
||||
"type": "string",
|
||||
"description": "Navigate to next message"
|
||||
"default": "ctrl+down",
|
||||
"description": "Navigate to next message\n\ndefault: `ctrl+down`",
|
||||
"examples": [
|
||||
"ctrl+down"
|
||||
]
|
||||
},
|
||||
"messages_first": {
|
||||
"type": "string",
|
||||
"description": "Navigate to first message"
|
||||
"default": "ctrl+g",
|
||||
"description": "Navigate to first message\n\ndefault: `ctrl+g`",
|
||||
"examples": [
|
||||
"ctrl+g"
|
||||
]
|
||||
},
|
||||
"messages_last": {
|
||||
"type": "string",
|
||||
"description": "Navigate to last message"
|
||||
"default": "ctrl+alt+g",
|
||||
"description": "Navigate to last message\n\ndefault: `ctrl+alt+g`",
|
||||
"examples": [
|
||||
"ctrl+alt+g"
|
||||
]
|
||||
},
|
||||
"messages_layout_toggle": {
|
||||
"type": "string",
|
||||
"default": "<leader>p",
|
||||
"description": "Toggle layout\n\ndefault: `<leader>p`",
|
||||
"examples": [
|
||||
"<leader>p"
|
||||
]
|
||||
},
|
||||
"messages_copy": {
|
||||
"type": "string",
|
||||
"default": "<leader>y",
|
||||
"description": "Copy message\n\ndefault: `<leader>y`",
|
||||
"examples": [
|
||||
"<leader>y"
|
||||
]
|
||||
},
|
||||
"messages_revert": {
|
||||
"type": "string",
|
||||
"default": "<leader>r",
|
||||
"description": "Revert message\n\ndefault: `<leader>r`",
|
||||
"examples": [
|
||||
"<leader>r"
|
||||
]
|
||||
},
|
||||
"app_exit": {
|
||||
"type": "string",
|
||||
"description": "Exit the application"
|
||||
"default": "ctrl+c,<leader>q",
|
||||
"description": "Exit the application\n\ndefault: `ctrl+c,<leader>q`",
|
||||
"examples": [
|
||||
"ctrl+c,<leader>q"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
@@ -171,9 +327,15 @@
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"release_date": {
|
||||
"type": "string"
|
||||
},
|
||||
"attachment": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -202,7 +364,10 @@
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": ["input", "output"],
|
||||
"required": [
|
||||
"input",
|
||||
"output"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"limit": {
|
||||
@@ -215,12 +380,12 @@
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": ["context", "output"],
|
||||
"required": [
|
||||
"context",
|
||||
"output"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"additionalProperties": {}
|
||||
@@ -234,7 +399,9 @@
|
||||
"additionalProperties": {}
|
||||
}
|
||||
},
|
||||
"required": ["models"],
|
||||
"required": [
|
||||
"models"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"description": "Custom provider configurations and model overrides"
|
||||
@@ -270,7 +437,10 @@
|
||||
"description": "Enable or disable the MCP server on startup"
|
||||
}
|
||||
},
|
||||
"required": ["type", "command"],
|
||||
"required": [
|
||||
"type",
|
||||
"command"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -290,7 +460,10 @@
|
||||
"description": "Enable or disable the MCP server on startup"
|
||||
}
|
||||
},
|
||||
"required": ["type", "url"],
|
||||
"required": [
|
||||
"type",
|
||||
"url"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
@@ -330,7 +503,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["command"],
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
@@ -353,7 +528,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["command"],
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
@@ -366,4 +543,4 @@
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"$schema": "http://json-schema.org/draft-07/schema#"
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,7 @@ if (!snapshot) {
|
||||
const lower = x.toLowerCase()
|
||||
return (
|
||||
!lower.includes("ignore:") &&
|
||||
!lower.includes("chore:") &&
|
||||
!lower.includes("ci:") &&
|
||||
!lower.includes("wip:") &&
|
||||
!lower.includes("docs:") &&
|
||||
|
||||
@@ -4,5 +4,30 @@ import "zod-openapi/extend"
|
||||
import { Config } from "../src/config/config"
|
||||
import { zodToJsonSchema } from "zod-to-json-schema"
|
||||
|
||||
const result = zodToJsonSchema(Config.Info)
|
||||
const result = zodToJsonSchema(Config.Info, {
|
||||
/**
|
||||
* We'll use the `default` values of the field as the only value in `examples`.
|
||||
* This will ensure no docs are needed to be read, as the configuration is
|
||||
* self-documenting.
|
||||
*
|
||||
* See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.9.5
|
||||
*/
|
||||
postProcess(jsonSchema) {
|
||||
const schema = jsonSchema as typeof jsonSchema & {
|
||||
examples?: unknown[]
|
||||
}
|
||||
if (schema && typeof schema === "object" && "type" in schema && schema.type === "string" && schema?.default) {
|
||||
if (!schema.examples) {
|
||||
schema.examples = [schema.default]
|
||||
}
|
||||
|
||||
schema.description = [schema.description || "", `default: \`${schema.default}\``]
|
||||
.filter(Boolean)
|
||||
.join("\n\n")
|
||||
.trim()
|
||||
}
|
||||
|
||||
return jsonSchema
|
||||
},
|
||||
})
|
||||
await Bun.write("config.schema.json", JSON.stringify(result, null, 2))
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { App } from "../app/app"
|
||||
import { ConfigHooks } from "../config/hooks"
|
||||
import { FileWatcher } from "../file/watch"
|
||||
import { Format } from "../format"
|
||||
import { LSP } from "../lsp"
|
||||
import { Share } from "../share/share"
|
||||
@@ -11,7 +10,6 @@ export async function bootstrap<T>(input: App.Input, cb: (app: App.Info) => Prom
|
||||
Format.init()
|
||||
ConfigHooks.init()
|
||||
LSP.init()
|
||||
FileWatcher.init()
|
||||
|
||||
return cb(app)
|
||||
})
|
||||
|
||||
@@ -25,7 +25,6 @@ export const SymbolsCommand = cmd({
|
||||
builder: (yargs) => yargs.positional("query", { type: "string", demandOption: true }),
|
||||
async handler(args) {
|
||||
await bootstrap({ cwd: process.cwd() }, async () => {
|
||||
await LSP.touchFile("./src/index.ts", true)
|
||||
using _ = Log.Default.time("symbols")
|
||||
const results = await LSP.workspaceSymbol(args.query)
|
||||
console.log(JSON.stringify(results, null, 2))
|
||||
|
||||
@@ -45,7 +45,7 @@ const FilesCommand = cmd({
|
||||
const files = await Ripgrep.files({
|
||||
cwd: app.path.cwd,
|
||||
query: args.query,
|
||||
glob: args.glob,
|
||||
glob: args.glob ? [args.glob] : undefined,
|
||||
limit: args.limit,
|
||||
})
|
||||
console.log(files.join("\n"))
|
||||
|
||||
@@ -125,6 +125,20 @@ export const RunCommand = cmd({
|
||||
}
|
||||
})
|
||||
|
||||
let errorMsg: string | undefined
|
||||
Bus.subscribe(Session.Event.Error, async (evt) => {
|
||||
const { sessionID, error } = evt.properties
|
||||
if (sessionID !== session.id || !error) return
|
||||
let err = String(error.name)
|
||||
|
||||
if ("data" in error && error.data && "message" in error.data) {
|
||||
err = error.data.message
|
||||
}
|
||||
errorMsg = errorMsg ? errorMsg + "\n" + err : err
|
||||
|
||||
UI.error(err)
|
||||
})
|
||||
|
||||
const result = await Session.chat({
|
||||
sessionID: session.id,
|
||||
providerID,
|
||||
@@ -140,6 +154,7 @@ export const RunCommand = cmd({
|
||||
if (isPiped) {
|
||||
const match = result.parts.findLast((x) => x.type === "text")
|
||||
if (match) process.stdout.write(match.text)
|
||||
if (errorMsg) process.stdout.write(errorMsg)
|
||||
}
|
||||
UI.empty()
|
||||
})
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Installation } from "../../installation"
|
||||
import { Config } from "../../config/config"
|
||||
import { Bus } from "../../bus"
|
||||
import { Log } from "../../util/log"
|
||||
import { FileWatcher } from "../../file/watch"
|
||||
|
||||
export const TuiCommand = cmd({
|
||||
command: "$0 [project]",
|
||||
@@ -40,6 +41,7 @@ export const TuiCommand = cmd({
|
||||
return
|
||||
}
|
||||
const result = await bootstrap({ cwd }, async (app) => {
|
||||
FileWatcher.init()
|
||||
const providers = await Provider.list()
|
||||
if (Object.keys(providers).length === 0) {
|
||||
return "needs_provider"
|
||||
@@ -82,6 +84,7 @@ export const TuiCommand = cmd({
|
||||
stdin: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
CGO_ENABLED: "0",
|
||||
OPENCODE_SERVER: server.url.toString(),
|
||||
OPENCODE_APP_INFO: JSON.stringify(app),
|
||||
},
|
||||
|
||||
@@ -57,33 +57,43 @@ export namespace Config {
|
||||
|
||||
export const Keybinds = z
|
||||
.object({
|
||||
leader: z.string().optional().describe("Leader key for keybind combinations"),
|
||||
help: z.string().optional().describe("Show help dialog"),
|
||||
editor_open: z.string().optional().describe("Open external editor"),
|
||||
session_new: z.string().optional().describe("Create a new session"),
|
||||
session_list: z.string().optional().describe("List all sessions"),
|
||||
session_share: z.string().optional().describe("Share current session"),
|
||||
session_interrupt: z.string().optional().describe("Interrupt current session"),
|
||||
session_compact: z.string().optional().describe("Toggle compact mode for session"),
|
||||
tool_details: z.string().optional().describe("Show tool details"),
|
||||
model_list: z.string().optional().describe("List available models"),
|
||||
theme_list: z.string().optional().describe("List available themes"),
|
||||
project_init: z.string().optional().describe("Initialize project configuration"),
|
||||
input_clear: z.string().optional().describe("Clear input field"),
|
||||
input_paste: z.string().optional().describe("Paste from clipboard"),
|
||||
input_submit: z.string().optional().describe("Submit input"),
|
||||
input_newline: z.string().optional().describe("Insert newline in input"),
|
||||
history_previous: z.string().optional().describe("Navigate to previous history item"),
|
||||
history_next: z.string().optional().describe("Navigate to next history item"),
|
||||
messages_page_up: z.string().optional().describe("Scroll messages up by one page"),
|
||||
messages_page_down: z.string().optional().describe("Scroll messages down by one page"),
|
||||
messages_half_page_up: z.string().optional().describe("Scroll messages up by half page"),
|
||||
messages_half_page_down: z.string().optional().describe("Scroll messages down by half page"),
|
||||
messages_previous: z.string().optional().describe("Navigate to previous message"),
|
||||
messages_next: z.string().optional().describe("Navigate to next message"),
|
||||
messages_first: z.string().optional().describe("Navigate to first message"),
|
||||
messages_last: z.string().optional().describe("Navigate to last message"),
|
||||
app_exit: z.string().optional().describe("Exit the application"),
|
||||
leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
|
||||
app_help: z.string().optional().default("<leader>h").describe("Show help dialog"),
|
||||
editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
|
||||
session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
|
||||
session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
|
||||
session_share: z.string().optional().default("<leader>s").describe("Share current session"),
|
||||
session_unshare: z.string().optional().default("<leader>u").describe("Unshare current session"),
|
||||
session_interrupt: z.string().optional().default("esc").describe("Interrupt current session"),
|
||||
session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
|
||||
tool_details: z.string().optional().default("<leader>d").describe("Toggle tool details"),
|
||||
model_list: z.string().optional().default("<leader>m").describe("List available models"),
|
||||
theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
|
||||
file_list: z.string().optional().default("<leader>f").describe("List files"),
|
||||
file_close: z.string().optional().default("esc").describe("Close file"),
|
||||
file_search: z.string().optional().default("<leader>/").describe("Search file"),
|
||||
file_diff_toggle: z.string().optional().default("<leader>v").describe("Split/unified diff"),
|
||||
project_init: z.string().optional().default("<leader>i").describe("Create/update AGENTS.md"),
|
||||
input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
|
||||
input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
|
||||
input_submit: z.string().optional().default("enter").describe("Submit input"),
|
||||
input_newline: z.string().optional().default("shift+enter,ctrl+j").describe("Insert newline in input"),
|
||||
messages_page_up: z.string().optional().default("pgup").describe("Scroll messages up by one page"),
|
||||
messages_page_down: z.string().optional().default("pgdown").describe("Scroll messages down by one page"),
|
||||
messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
|
||||
messages_half_page_down: z
|
||||
.string()
|
||||
.optional()
|
||||
.default("ctrl+alt+d")
|
||||
.describe("Scroll messages down by half page"),
|
||||
messages_previous: z.string().optional().default("ctrl+up").describe("Navigate to previous message"),
|
||||
messages_next: z.string().optional().default("ctrl+down").describe("Navigate to next message"),
|
||||
messages_first: z.string().optional().default("ctrl+g").describe("Navigate to first message"),
|
||||
messages_last: z.string().optional().default("ctrl+alt+g").describe("Navigate to last message"),
|
||||
messages_layout_toggle: z.string().optional().default("<leader>p").describe("Toggle layout"),
|
||||
messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
|
||||
messages_revert: z.string().optional().default("<leader>r").describe("Revert message"),
|
||||
app_exit: z.string().optional().default("ctrl+c,<leader>q").describe("Exit the application"),
|
||||
})
|
||||
.strict()
|
||||
.openapi({
|
||||
|
||||
@@ -185,10 +185,15 @@ export namespace Ripgrep {
|
||||
return filepath
|
||||
}
|
||||
|
||||
export async function files(input: { cwd: string; query?: string; glob?: string; limit?: number }) {
|
||||
const commands = [
|
||||
`${await filepath()} --files --hidden --glob='!.git/*' ${input.glob ? `--glob='${input.glob}'` : ``}`,
|
||||
]
|
||||
export async function files(input: { cwd: string; query?: string; glob?: string[]; limit?: number }) {
|
||||
const commands = [`${$.escape(await filepath())} --files --follow --hidden --glob='!.git/*'`]
|
||||
|
||||
if (input.glob) {
|
||||
for (const g of input.glob) {
|
||||
commands[0] += ` --glob='${g}'`
|
||||
}
|
||||
}
|
||||
|
||||
if (input.query) commands.push(`${await Fzf.filepath()} --filter=${input.query}`)
|
||||
if (input.limit) commands.push(`head -n ${input.limit}`)
|
||||
const joined = commands.join(" | ")
|
||||
|
||||
@@ -34,46 +34,54 @@ export namespace LSPClient {
|
||||
),
|
||||
}
|
||||
|
||||
export async function create(serverID: string, server: LSPServer.Handle) {
|
||||
export async function create(input: { serverID: string; server: LSPServer.Handle; root: string }) {
|
||||
const app = App.info()
|
||||
log.info("starting client", { id: serverID })
|
||||
const l = log.clone().tag("serverID", input.serverID)
|
||||
l.info("starting client")
|
||||
|
||||
const connection = createMessageConnection(
|
||||
new StreamMessageReader(server.process.stdout),
|
||||
new StreamMessageWriter(server.process.stdin),
|
||||
new StreamMessageReader(input.server.process.stdout),
|
||||
new StreamMessageWriter(input.server.process.stdin),
|
||||
)
|
||||
|
||||
const diagnostics = new Map<string, Diagnostic[]>()
|
||||
connection.onNotification("textDocument/publishDiagnostics", (params) => {
|
||||
const path = new URL(params.uri).pathname
|
||||
log.info("textDocument/publishDiagnostics", {
|
||||
l.info("textDocument/publishDiagnostics", {
|
||||
path,
|
||||
})
|
||||
const exists = diagnostics.has(path)
|
||||
diagnostics.set(path, params.diagnostics)
|
||||
if (!exists && serverID === "typescript") return
|
||||
Bus.publish(Event.Diagnostics, { path, serverID })
|
||||
if (!exists && input.serverID === "typescript") return
|
||||
Bus.publish(Event.Diagnostics, { path, serverID: input.serverID })
|
||||
})
|
||||
connection.onRequest("window/workDoneProgress/create", (params) => {
|
||||
l.info("window/workDoneProgress/create", params)
|
||||
return null
|
||||
})
|
||||
connection.onRequest("workspace/configuration", async () => {
|
||||
return [{}]
|
||||
})
|
||||
connection.listen()
|
||||
|
||||
log.info("sending initialize", { id: serverID })
|
||||
l.info("sending initialize")
|
||||
await withTimeout(
|
||||
connection.sendRequest("initialize", {
|
||||
rootUri: "file://" + app.path.cwd,
|
||||
processId: server.process.pid,
|
||||
rootUri: "file://" + input.root,
|
||||
processId: input.server.process.pid,
|
||||
workspaceFolders: [
|
||||
{
|
||||
name: "workspace",
|
||||
uri: "file://" + app.path.cwd,
|
||||
uri: "file://" + input.root,
|
||||
},
|
||||
],
|
||||
initializationOptions: {
|
||||
...server.initialization,
|
||||
...input.server.initialization,
|
||||
},
|
||||
capabilities: {
|
||||
window: {
|
||||
workDoneProgress: true,
|
||||
},
|
||||
workspace: {
|
||||
configuration: true,
|
||||
},
|
||||
@@ -90,9 +98,9 @@ export namespace LSPClient {
|
||||
}),
|
||||
5_000,
|
||||
).catch((err) => {
|
||||
log.error("initialize error", { error: err })
|
||||
l.error("initialize error", { error: err })
|
||||
throw new InitializeError(
|
||||
{ serverID },
|
||||
{ serverID: input.serverID },
|
||||
{
|
||||
cause: err,
|
||||
},
|
||||
@@ -100,17 +108,15 @@ export namespace LSPClient {
|
||||
})
|
||||
|
||||
await connection.sendNotification("initialized", {})
|
||||
log.info("initialized", {
|
||||
serverID,
|
||||
})
|
||||
|
||||
const files: {
|
||||
[path: string]: number
|
||||
} = {}
|
||||
|
||||
const result = {
|
||||
root: input.root,
|
||||
get serverID() {
|
||||
return serverID
|
||||
return input.serverID
|
||||
},
|
||||
get connection() {
|
||||
return connection
|
||||
@@ -170,13 +176,19 @@ export namespace LSPClient {
|
||||
})
|
||||
},
|
||||
async shutdown() {
|
||||
log.info("shutting down", { serverID })
|
||||
l.info("shutting down")
|
||||
connection.end()
|
||||
connection.dispose()
|
||||
log.info("shutdown", { serverID })
|
||||
input.server.process.kill()
|
||||
l.info("shutdown")
|
||||
},
|
||||
}
|
||||
|
||||
if (input.server.onInitialized) {
|
||||
await input.server.onInitialized(result)
|
||||
}
|
||||
l.info("initialized")
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ import { Log } from "../util/log"
|
||||
import { LSPClient } from "./client"
|
||||
import path from "path"
|
||||
import { LSPServer } from "./server"
|
||||
import { Ripgrep } from "../file/ripgrep"
|
||||
import { z } from "zod"
|
||||
import { Filesystem } from "../util/filesystem"
|
||||
|
||||
export namespace LSP {
|
||||
const log = Log.create({ service: "lsp" })
|
||||
@@ -36,29 +36,39 @@ export namespace LSP {
|
||||
"lsp",
|
||||
async (app) => {
|
||||
log.info("initializing")
|
||||
const clients = new Map<string, LSPClient.Info>()
|
||||
const clients: LSPClient.Info[] = []
|
||||
|
||||
for (const server of Object.values(LSPServer)) {
|
||||
for (const extension of server.extensions) {
|
||||
const [file] = await Ripgrep.files({
|
||||
cwd: app.path.cwd,
|
||||
glob: "*" + extension,
|
||||
const roots = await server.roots(app)
|
||||
|
||||
for (const root of roots) {
|
||||
if (!Filesystem.overlaps(app.path.cwd, root)) continue
|
||||
log.info("", {
|
||||
root,
|
||||
serverID: server.id,
|
||||
})
|
||||
if (!file) continue
|
||||
const handle = await server.spawn(App.info())
|
||||
const handle = await server.spawn(App.info(), root)
|
||||
if (!handle) break
|
||||
const client = await LSPClient.create(server.id, handle).catch((err) => log.error("", { error: err }))
|
||||
const client = await LSPClient.create({
|
||||
serverID: server.id,
|
||||
server: handle,
|
||||
root,
|
||||
}).catch((err) => {
|
||||
handle.process.kill()
|
||||
log.error("", { error: err })
|
||||
})
|
||||
if (!client) break
|
||||
clients.set(server.id, client)
|
||||
break
|
||||
clients.push(client)
|
||||
}
|
||||
}
|
||||
|
||||
log.info("initialized")
|
||||
return {
|
||||
clients,
|
||||
}
|
||||
},
|
||||
async (state) => {
|
||||
for (const client of state.clients.values()) {
|
||||
for (const client of state.clients) {
|
||||
await client.shutdown()
|
||||
}
|
||||
},
|
||||
@@ -109,14 +119,17 @@ export namespace LSP {
|
||||
|
||||
export async function workspaceSymbol(query: string) {
|
||||
return run((client) =>
|
||||
client.connection.sendRequest("workspace/symbol", {
|
||||
query,
|
||||
}),
|
||||
client.connection
|
||||
.sendRequest("workspace/symbol", {
|
||||
query,
|
||||
})
|
||||
.then((result: any) => result.slice(0, 10))
|
||||
.catch(() => []),
|
||||
).then((result) => result.flat() as LSP.Symbol[])
|
||||
}
|
||||
|
||||
async function run<T>(input: (client: LSPClient.Info) => Promise<T>): Promise<T[]> {
|
||||
const clients = await state().then((x) => [...x.clients.values()])
|
||||
const clients = await state().then((x) => x.clients)
|
||||
const tasks = clients.map((x) => input(x))
|
||||
return Promise.all(tasks)
|
||||
}
|
||||
|
||||
@@ -94,4 +94,6 @@ export const LANGUAGE_EXTENSIONS: Record<string, string> = {
|
||||
".yml": "yaml",
|
||||
".mjs": "javascript",
|
||||
".cjs": "javascript",
|
||||
".zig": "zig",
|
||||
".zon": "zig",
|
||||
} as const
|
||||
|
||||
@@ -6,6 +6,10 @@ import { Log } from "../util/log"
|
||||
import { BunProc } from "../bun"
|
||||
import { $ } from "bun"
|
||||
import fs from "fs/promises"
|
||||
import { unique } from "remeda"
|
||||
import { Ripgrep } from "../file/ripgrep"
|
||||
import type { LSPClient } from "./client"
|
||||
import { withTimeout } from "../util/timeout"
|
||||
|
||||
export namespace LSPServer {
|
||||
const log = Log.create({ service: "lsp.server" })
|
||||
@@ -13,21 +17,40 @@ export namespace LSPServer {
|
||||
export interface Handle {
|
||||
process: ChildProcessWithoutNullStreams
|
||||
initialization?: Record<string, any>
|
||||
onInitialized?: (lsp: LSPClient.Info) => Promise<void>
|
||||
}
|
||||
|
||||
type RootsFunction = (app: App.Info) => Promise<string[]>
|
||||
|
||||
const SimpleRoots = (patterns: string[]): RootsFunction => {
|
||||
return async (app) => {
|
||||
const glob = `**/*/{${patterns.join(",")}}`
|
||||
const files = await Ripgrep.files({
|
||||
glob: [glob],
|
||||
cwd: app.path.root,
|
||||
})
|
||||
const dirs = files.map((file) => path.dirname(file))
|
||||
return unique(dirs).map((dir) => path.join(app.path.root, dir))
|
||||
}
|
||||
}
|
||||
|
||||
export interface Info {
|
||||
id: string
|
||||
extensions: string[]
|
||||
spawn(app: App.Info): Promise<Handle | undefined>
|
||||
global?: boolean
|
||||
roots: (app: App.Info) => Promise<string[]>
|
||||
spawn(app: App.Info, root: string): Promise<Handle | undefined>
|
||||
}
|
||||
|
||||
export const Typescript: Info = {
|
||||
id: "typescript",
|
||||
roots: SimpleRoots(["tsconfig.json", "jsconfig.json", "package.json"]),
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
|
||||
async spawn(app) {
|
||||
async spawn(app, root) {
|
||||
const tsserver = await Bun.resolve("typescript/lib/tsserver.js", app.path.cwd).catch(() => {})
|
||||
if (!tsserver) return
|
||||
const proc = spawn(BunProc.which(), ["x", "typescript-language-server", "--stdio"], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
BUN_BE_BUN: "1",
|
||||
@@ -40,14 +63,32 @@ export namespace LSPServer {
|
||||
path: tsserver,
|
||||
},
|
||||
},
|
||||
// tsserver sucks and won't start processing codebase until you open a file
|
||||
onInitialized: async (lsp) => {
|
||||
const [hint] = await Ripgrep.files({
|
||||
cwd: lsp.root,
|
||||
glob: ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"],
|
||||
limit: 1,
|
||||
})
|
||||
const wait = new Promise<void>(async (resolve) => {
|
||||
const notif = lsp.connection.onNotification("$/progress", (params) => {
|
||||
if (params.value.kind !== "end") return
|
||||
notif.dispose()
|
||||
resolve()
|
||||
})
|
||||
await lsp.notify.open({ path: path.join(lsp.root, hint) })
|
||||
})
|
||||
await withTimeout(wait, 5_000)
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const Gopls: Info = {
|
||||
id: "golang",
|
||||
roots: SimpleRoots(["go.mod", "go.sum"]),
|
||||
extensions: [".go"],
|
||||
async spawn() {
|
||||
async spawn(_, root) {
|
||||
let bin = Bun.which("gopls", {
|
||||
PATH: process.env["PATH"] + ":" + Global.Path.bin,
|
||||
})
|
||||
@@ -72,15 +113,18 @@ export namespace LSPServer {
|
||||
})
|
||||
}
|
||||
return {
|
||||
process: spawn(bin!),
|
||||
process: spawn(bin!, {
|
||||
cwd: root,
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const RubyLsp: Info = {
|
||||
id: "ruby-lsp",
|
||||
roots: SimpleRoots(["Gemfile"]),
|
||||
extensions: [".rb", ".rake", ".gemspec", ".ru"],
|
||||
async spawn() {
|
||||
async spawn(_, root) {
|
||||
let bin = Bun.which("ruby-lsp", {
|
||||
PATH: process.env["PATH"] + ":" + Global.Path.bin,
|
||||
})
|
||||
@@ -109,7 +153,9 @@ export namespace LSPServer {
|
||||
})
|
||||
}
|
||||
return {
|
||||
process: spawn(bin!, ["--stdio"]),
|
||||
process: spawn(bin!, ["--stdio"], {
|
||||
cwd: root,
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -117,8 +163,17 @@ export namespace LSPServer {
|
||||
export const Pyright: Info = {
|
||||
id: "pyright",
|
||||
extensions: [".py", ".pyi"],
|
||||
async spawn() {
|
||||
roots: SimpleRoots([
|
||||
"pyproject.toml",
|
||||
"setup.py",
|
||||
"setup.cfg",
|
||||
"requirements.txt",
|
||||
"Pipfile",
|
||||
"pyrightconfig.json",
|
||||
]),
|
||||
async spawn(_, root) {
|
||||
const proc = spawn(BunProc.which(), ["x", "pyright-langserver", "--stdio"], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
BUN_BE_BUN: "1",
|
||||
@@ -133,7 +188,8 @@ export namespace LSPServer {
|
||||
export const ElixirLS: Info = {
|
||||
id: "elixir-ls",
|
||||
extensions: [".ex", ".exs"],
|
||||
async spawn() {
|
||||
roots: SimpleRoots(["mix.exs", "mix.lock"]),
|
||||
async spawn(_, root) {
|
||||
let binary = Bun.which("elixir-ls")
|
||||
if (!binary) {
|
||||
const elixirLsPath = path.join(Global.Path.bin, "elixir-ls")
|
||||
@@ -177,7 +233,9 @@ export namespace LSPServer {
|
||||
}
|
||||
|
||||
return {
|
||||
process: spawn(binary),
|
||||
process: spawn(binary, {
|
||||
cwd: root,
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -99,19 +99,27 @@ export namespace Provider {
|
||||
info.access = tokens.access
|
||||
}
|
||||
let isAgentCall = false
|
||||
let isVisionRequest = false
|
||||
try {
|
||||
const body = typeof init.body === "string" ? JSON.parse(init.body) : init.body
|
||||
if (body?.messages) {
|
||||
isAgentCall = body.messages.some((msg: any) => msg.role && ["tool", "assistant"].includes(msg.role))
|
||||
isVisionRequest = body.messages.some(
|
||||
(msg: any) =>
|
||||
Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"),
|
||||
)
|
||||
}
|
||||
} catch {}
|
||||
const headers = {
|
||||
const headers: Record<string, string> = {
|
||||
...init.headers,
|
||||
...copilot.HEADERS,
|
||||
Authorization: `Bearer ${info.access}`,
|
||||
"Openai-Intent": "conversation-edits",
|
||||
"X-Initiator": isAgentCall ? "agent" : "user",
|
||||
}
|
||||
if (isVisionRequest) {
|
||||
headers["Copilot-Vision-Request"] = "true"
|
||||
}
|
||||
delete headers["x-api-key"]
|
||||
return fetch(input, {
|
||||
...init,
|
||||
|
||||
@@ -558,7 +558,7 @@ export namespace Server {
|
||||
description: "Symbols",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(z.unknown().array()),
|
||||
schema: resolver(LSP.Symbol.array()),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -99,6 +99,7 @@ export namespace Session {
|
||||
Error: Bus.event(
|
||||
"session.error",
|
||||
z.object({
|
||||
sessionID: z.string().optional(),
|
||||
error: MessageV2.Assistant.shape.error,
|
||||
}),
|
||||
),
|
||||
@@ -371,11 +372,11 @@ export namespace Session {
|
||||
return [
|
||||
{
|
||||
type: "text",
|
||||
text: ["Called the Read tool on " + url.pathname].join("\n"),
|
||||
text: `Called the Read tool with the following input: {\"filePath\":\"${url.pathname}\"}`,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64url"),
|
||||
url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"),
|
||||
mime: part.mime,
|
||||
filename: part.filename!,
|
||||
},
|
||||
@@ -727,6 +728,7 @@ export namespace Session {
|
||||
next.error = new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e })
|
||||
}
|
||||
Bus.publish(Event.Error, {
|
||||
sessionID: next.sessionID,
|
||||
error: next.error,
|
||||
})
|
||||
}
|
||||
@@ -871,20 +873,58 @@ export namespace Session {
|
||||
},
|
||||
})
|
||||
|
||||
for await (const value of result.fullStream) {
|
||||
switch (value.type) {
|
||||
case "text":
|
||||
if (!text) {
|
||||
text = {
|
||||
type: "text",
|
||||
text: value.text,
|
||||
}
|
||||
next.parts.push(text)
|
||||
} else text.text += value.text
|
||||
await updateMessage(next)
|
||||
break
|
||||
try {
|
||||
for await (const value of result.fullStream) {
|
||||
switch (value.type) {
|
||||
case "text":
|
||||
if (!text) {
|
||||
text = {
|
||||
type: "text",
|
||||
text: value.text,
|
||||
}
|
||||
next.parts.push(text)
|
||||
} else text.text += value.text
|
||||
await updateMessage(next)
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
log.error("summarize stream error", {
|
||||
error: e,
|
||||
})
|
||||
switch (true) {
|
||||
case e instanceof DOMException && e.name === "AbortError":
|
||||
next.error = new MessageV2.AbortedError(
|
||||
{ message: e.message },
|
||||
{
|
||||
cause: e,
|
||||
},
|
||||
).toObject()
|
||||
break
|
||||
case MessageV2.OutputLengthError.isInstance(e):
|
||||
next.error = e
|
||||
break
|
||||
case LoadAPIKeyError.isInstance(e):
|
||||
next.error = new Provider.AuthError(
|
||||
{
|
||||
providerID: input.providerID,
|
||||
message: e.message,
|
||||
},
|
||||
{ cause: e },
|
||||
).toObject()
|
||||
break
|
||||
case e instanceof Error:
|
||||
next.error = new NamedError.Unknown({ message: e.toString() }, { cause: e }).toObject()
|
||||
break
|
||||
default:
|
||||
next.error = new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e }).toObject()
|
||||
}
|
||||
Bus.publish(Event.Error, {
|
||||
error: next.error,
|
||||
})
|
||||
}
|
||||
next.time.completed = Date.now()
|
||||
await updateMessage(next)
|
||||
}
|
||||
|
||||
function lock(sessionID: string) {
|
||||
|
||||
@@ -39,7 +39,8 @@ export namespace Storage {
|
||||
|
||||
const state = App.state("storage", async () => {
|
||||
const app = App.info()
|
||||
const dir = path.join(app.path.data, "storage")
|
||||
const dir = path.normalize(path.join(app.path.data, "storage"))
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
const migration = await Bun.file(path.join(dir, "migration"))
|
||||
.json()
|
||||
.then((x) => parseInt(x))
|
||||
|
||||
@@ -27,7 +27,7 @@ export const GlobTool = Tool.define({
|
||||
let truncated = false
|
||||
for (const file of await Ripgrep.files({
|
||||
cwd: search,
|
||||
glob: params.pattern,
|
||||
glob: [params.pattern],
|
||||
})) {
|
||||
if (files.length >= limit) {
|
||||
truncated = true
|
||||
|
||||
@@ -2,7 +2,7 @@ Reads a file from the local filesystem. You can access any file directly by usin
|
||||
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
||||
|
||||
Usage:
|
||||
- The file_path parameter must be an absolute path, not a relative path
|
||||
- The filePath parameter must be an absolute path, not a relative path
|
||||
- By default, it reads up to 2000 lines starting from the beginning of the file
|
||||
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
|
||||
- Any lines longer than 2000 characters will be truncated
|
||||
|
||||
@@ -5,7 +5,7 @@ import { App } from "../app/app"
|
||||
|
||||
const TodoInfo = z.object({
|
||||
content: z.string().min(1).describe("Brief description of the task"),
|
||||
status: z.enum(["pending", "in_progress", "completed"]).describe("Current status of the task"),
|
||||
status: z.enum(["pending", "in_progress", "completed", "cancelled"]).describe("Current status of the task"),
|
||||
priority: z.enum(["high", "medium", "low"]).describe("Priority level of the task"),
|
||||
id: z.string().describe("Unique identifier for the todo item"),
|
||||
})
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
import { exists } from "fs/promises"
|
||||
import { dirname, join } from "path"
|
||||
import { dirname, join, relative } from "path"
|
||||
|
||||
export namespace Filesystem {
|
||||
export function overlaps(a: string, b: string) {
|
||||
const relA = relative(a, b)
|
||||
const relB = relative(b, a)
|
||||
return !relA || !relA.startsWith("..") || !relB || !relB.startsWith("..")
|
||||
}
|
||||
|
||||
export function contains(parent: string, child: string) {
|
||||
return relative(parent, child).startsWith("..")
|
||||
}
|
||||
|
||||
export async function findUp(target: string, start: string, stop?: string) {
|
||||
let current = start
|
||||
const result = []
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [changkun] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -0,0 +1,71 @@
|
||||
# Copyright 2021 The golang.design Initiative Authors.
|
||||
# All rights reserved. Use of this source code is governed
|
||||
# by a MIT license that can be found in the LICENSE file.
|
||||
#
|
||||
# Written by Changkun Ou <changkun.de>
|
||||
|
||||
name: clipboard
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
platform_test:
|
||||
env:
|
||||
DISPLAY: ':0.0'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
go: ['1.24.x']
|
||||
steps:
|
||||
- name: Install and run dependencies (xvfb libx11-dev)
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y xvfb libx11-dev x11-utils libegl1-mesa-dev libgles2-mesa-dev
|
||||
Xvfb :0 -screen 0 1024x768x24 > /dev/null 2>&1 &
|
||||
# Wait for Xvfb
|
||||
MAX_ATTEMPTS=120 # About 60 seconds
|
||||
COUNT=0
|
||||
echo -n "Waiting for Xvfb to be ready..."
|
||||
while ! xdpyinfo -display "${DISPLAY}" >/dev/null 2>&1; do
|
||||
echo -n "."
|
||||
sleep 0.50s
|
||||
COUNT=$(( COUNT + 1 ))
|
||||
if [ "${COUNT}" -ge "${MAX_ATTEMPTS}" ]; then
|
||||
echo " Gave up waiting for X server on ${DISPLAY}"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "Done - Xvfb is ready!"
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
stable: 'false'
|
||||
go-version: ${{ matrix.go }}
|
||||
|
||||
- name: Build (${{ matrix.go }})
|
||||
run: |
|
||||
go build -o gclip cmd/gclip/main.go
|
||||
go build -o gclip-gui cmd/gclip-gui/main.go
|
||||
|
||||
- name: Run Tests with CGO_ENABLED=1 (${{ matrix.go }})
|
||||
if: ${{ runner.os == 'Linux' || runner.os == 'macOS'}}
|
||||
run: |
|
||||
CGO_ENABLED=1 go test -v -covermode=atomic .
|
||||
|
||||
- name: Run Tests with CGO_ENABLED=0 (${{ matrix.go }})
|
||||
if: ${{ runner.os == 'Linux' || runner.os == 'macOS'}}
|
||||
run: |
|
||||
CGO_ENABLED=0 go test -v -covermode=atomic .
|
||||
|
||||
- name: Run Tests on Windows (${{ matrix.go }})
|
||||
if: ${{ runner.os == 'Windows'}}
|
||||
run: |
|
||||
go test -v -covermode=atomic .
|
||||
@@ -0,0 +1,15 @@
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copyright 2021 The golang.design Initiative Authors.
|
||||
# All rights reserved. Use of this source code is governed
|
||||
# by a MIT license that can be found in the LICENSE file.
|
||||
#
|
||||
# Written by Changkun Ou <changkun.de>
|
||||
|
||||
FROM golang:1.24
|
||||
RUN apt-get update && apt-get install -y \
|
||||
xvfb libx11-dev libegl1-mesa-dev libgles2-mesa-dev \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
CMD [ "sh", "-c", "./tests/test-docker.sh" ]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Changkun Ou <contact@changkun.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,162 @@
|
||||
# clipboard [](https://pkg.go.dev/golang.design/x/clipboard)  
|
||||
|
||||
Cross platform (macOS/Linux/Windows/Android/iOS) clipboard package in Go
|
||||
|
||||
```go
|
||||
import "golang.design/x/clipboard"
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- Cross platform supports: **macOS, Linux (X11), Windows, iOS, and Android**
|
||||
- Copy/paste UTF-8 text
|
||||
- Copy/paste PNG encoded images (Desktop-only)
|
||||
- Command `gclip` as a demo application
|
||||
- Mobile app `gclip-gui` as a demo application
|
||||
|
||||
## API Usage
|
||||
|
||||
Package clipboard provides cross platform clipboard access and supports
|
||||
macOS/Linux/Windows/Android/iOS platform. Before interacting with the
|
||||
clipboard, one must call Init to assert if it is possible to use this
|
||||
package:
|
||||
|
||||
```go
|
||||
// Init returns an error if the package is not ready for use.
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
The most common operations are `Read` and `Write`. To use them:
|
||||
|
||||
```go
|
||||
// write/read text format data of the clipboard, and
|
||||
// the byte buffer regarding the text are UTF8 encoded.
|
||||
clipboard.Write(clipboard.FmtText, []byte("text data"))
|
||||
clipboard.Read(clipboard.FmtText)
|
||||
|
||||
// write/read image format data of the clipboard, and
|
||||
// the byte buffer regarding the image are PNG encoded.
|
||||
clipboard.Write(clipboard.FmtImage, []byte("image data"))
|
||||
clipboard.Read(clipboard.FmtImage)
|
||||
```
|
||||
|
||||
Note that read/write regarding image format assumes that the bytes are
|
||||
PNG encoded since it serves the alpha blending purpose that might be
|
||||
used in other graphical software.
|
||||
|
||||
In addition, `clipboard.Write` returns a channel that can receive an
|
||||
empty struct as a signal, which indicates the corresponding write call
|
||||
to the clipboard is outdated, meaning the clipboard has been overwritten
|
||||
by others and the previously written data is lost. For instance:
|
||||
|
||||
```go
|
||||
changed := clipboard.Write(clipboard.FmtText, []byte("text data"))
|
||||
|
||||
select {
|
||||
case <-changed:
|
||||
println(`"text data" is no longer available from clipboard.`)
|
||||
}
|
||||
```
|
||||
|
||||
You can ignore the returning channel if you don't need this type of
|
||||
notification. Furthermore, when you need more than just knowing whether
|
||||
clipboard data is changed, use the watcher API:
|
||||
|
||||
```go
|
||||
ch := clipboard.Watch(context.TODO(), clipboard.FmtText)
|
||||
for data := range ch {
|
||||
// print out clipboard data whenever it is changed
|
||||
println(string(data))
|
||||
}
|
||||
```
|
||||
|
||||
## Demos
|
||||
|
||||
- A command line tool `gclip` for command line clipboard accesses, see document [here](./cmd/gclip/README.md).
|
||||
- A GUI application `gclip-gui` for functionality verifications on mobile systems, see a document [here](./cmd/gclip-gui/README.md).
|
||||
|
||||
|
||||
## Command Usage
|
||||
|
||||
`gclip` command offers the ability to interact with the system clipboard
|
||||
from the shell. To install:
|
||||
|
||||
```bash
|
||||
$ go install golang.design/x/clipboard/cmd/gclip@latest
|
||||
```
|
||||
|
||||
```bash
|
||||
$ gclip
|
||||
gclip is a command that provides clipboard interaction.
|
||||
|
||||
usage: gclip [-copy|-paste] [-f <file>]
|
||||
|
||||
options:
|
||||
-copy
|
||||
copy data to clipboard
|
||||
-f string
|
||||
source or destination to a given file path
|
||||
-paste
|
||||
paste data from clipboard
|
||||
|
||||
examples:
|
||||
gclip -paste paste from clipboard and prints the content
|
||||
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
|
||||
gclip -paste -f x.png paste from clipboard and save as image to x.png
|
||||
|
||||
cat x.txt | gclip -copy copy content from x.txt to clipboard
|
||||
gclip -copy -f x.txt copy content from x.txt to clipboard
|
||||
gclip -copy -f x.png copy x.png as image data to clipboard
|
||||
```
|
||||
|
||||
If `-copy` is used, the command will exit when the data is no longer
|
||||
available from the clipboard. You can always send the command to the
|
||||
background using a shell `&` operator, for example:
|
||||
|
||||
```bash
|
||||
$ cat x.txt | gclip -copy &
|
||||
```
|
||||
|
||||
## Platform Specific Details
|
||||
|
||||
This package spent efforts to provide cross platform abstraction regarding
|
||||
accessing system clipboards, but here are a few details you might need to know.
|
||||
|
||||
### Dependency
|
||||
|
||||
- macOS: require Cgo, no dependency
|
||||
- Linux: require X11 dev package. For instance, install `libx11-dev` or `xorg-dev` or `libX11-devel` to access X window system.
|
||||
Wayland sessions are currently unsupported; running under Wayland
|
||||
typically requires an XWayland bridge and `DISPLAY` to be set.
|
||||
- Windows: no Cgo, no dependency
|
||||
- iOS/Android: collaborate with [`gomobile`](https://golang.org/x/mobile)
|
||||
|
||||
### Screenshot
|
||||
|
||||
In general, when you need test your implementation regarding images,
|
||||
There are system level shortcuts to put screenshot image into your system clipboard:
|
||||
|
||||
- On macOS, use `Ctrl+Shift+Cmd+4`
|
||||
- On Linux/Ubuntu, use `Ctrl+Shift+PrintScreen`
|
||||
- On Windows, use `Shift+Win+s`
|
||||
|
||||
As described in the API documentation, the package supports read/write
|
||||
UTF8 encoded plain text or PNG encoded image data. Thus,
|
||||
the other types of data are not supported yet, i.e. undefined behavior.
|
||||
|
||||
## Who is using this package?
|
||||
|
||||
The main purpose of building this package is to support the
|
||||
[midgard](https://changkun.de/s/midgard) project, which offers
|
||||
clipboard-based features like universal clipboard service that syncs
|
||||
clipboard content across multiple systems, allocating public accessible
|
||||
for clipboard content, etc.
|
||||
|
||||
To know more projects, check our [wiki](https://github.com/golang-design/clipboard/wiki) page.
|
||||
|
||||
## License
|
||||
|
||||
MIT | © 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
|
||||
@@ -0,0 +1,155 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
/*
|
||||
Package clipboard provides cross platform clipboard access and supports
|
||||
macOS/Linux/Windows/Android/iOS platform. Before interacting with the
|
||||
clipboard, one must call Init to assert if it is possible to use this
|
||||
package:
|
||||
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
The most common operations are `Read` and `Write`. To use them:
|
||||
|
||||
// write/read text format data of the clipboard, and
|
||||
// the byte buffer regarding the text are UTF8 encoded.
|
||||
clipboard.Write(clipboard.FmtText, []byte("text data"))
|
||||
clipboard.Read(clipboard.FmtText)
|
||||
|
||||
// write/read image format data of the clipboard, and
|
||||
// the byte buffer regarding the image are PNG encoded.
|
||||
clipboard.Write(clipboard.FmtImage, []byte("image data"))
|
||||
clipboard.Read(clipboard.FmtImage)
|
||||
|
||||
Note that read/write regarding image format assumes that the bytes are
|
||||
PNG encoded since it serves the alpha blending purpose that might be
|
||||
used in other graphical software.
|
||||
|
||||
In addition, `clipboard.Write` returns a channel that can receive an
|
||||
empty struct as a signal, which indicates the corresponding write call
|
||||
to the clipboard is outdated, meaning the clipboard has been overwritten
|
||||
by others and the previously written data is lost. For instance:
|
||||
|
||||
changed := clipboard.Write(clipboard.FmtText, []byte("text data"))
|
||||
|
||||
select {
|
||||
case <-changed:
|
||||
println(`"text data" is no longer available from clipboard.`)
|
||||
}
|
||||
|
||||
You can ignore the returning channel if you don't need this type of
|
||||
notification. Furthermore, when you need more than just knowing whether
|
||||
clipboard data is changed, use the watcher API:
|
||||
|
||||
ch := clipboard.Watch(context.TODO(), clipboard.FmtText)
|
||||
for data := range ch {
|
||||
// print out clipboard data whenever it is changed
|
||||
println(string(data))
|
||||
}
|
||||
*/
|
||||
package clipboard // import "golang.design/x/clipboard"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// activate only for running tests.
|
||||
debug = false
|
||||
errUnavailable = errors.New("clipboard unavailable")
|
||||
errUnsupported = errors.New("unsupported format")
|
||||
errNoCgo = errors.New("clipboard: cannot use when CGO_ENABLED=0")
|
||||
)
|
||||
|
||||
// Format represents the format of clipboard data.
|
||||
type Format int
|
||||
|
||||
// All sorts of supported clipboard data
|
||||
const (
|
||||
// FmtText indicates plain text clipboard format
|
||||
FmtText Format = iota
|
||||
// FmtImage indicates image/png clipboard format
|
||||
FmtImage
|
||||
)
|
||||
|
||||
var (
|
||||
// Due to the limitation on operating systems (such as darwin),
|
||||
// concurrent read can even cause panic, use a global lock to
|
||||
// guarantee one read at a time.
|
||||
lock = sync.Mutex{}
|
||||
initOnce sync.Once
|
||||
initError error
|
||||
)
|
||||
|
||||
// Init initializes the clipboard package. It returns an error
|
||||
// if the clipboard is not available to use. This may happen if the
|
||||
// target system lacks required dependency, such as libx11-dev in X11
|
||||
// environment. For example,
|
||||
//
|
||||
// err := clipboard.Init()
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//
|
||||
// If Init returns an error, any subsequent Read/Write/Watch call
|
||||
// may result in an unrecoverable panic.
|
||||
func Init() error {
|
||||
initOnce.Do(func() {
|
||||
initError = initialize()
|
||||
})
|
||||
return initError
|
||||
}
|
||||
|
||||
// Read returns a chunk of bytes of the clipboard data if it presents
|
||||
// in the desired format t presents. Otherwise, it returns nil.
|
||||
func Read(t Format) []byte {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
buf, err := read(t)
|
||||
if err != nil {
|
||||
if debug {
|
||||
fmt.Fprintf(os.Stderr, "read clipboard err: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// Write writes a given buffer to the clipboard in a specified format.
|
||||
// Write returned a receive-only channel can receive an empty struct
|
||||
// as a signal, which indicates the clipboard has been overwritten from
|
||||
// this write.
|
||||
// If format t indicates an image, then the given buf assumes
|
||||
// the image data is PNG encoded.
|
||||
func Write(t Format, buf []byte) <-chan struct{} {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
changed, err := write(t, buf)
|
||||
if err != nil {
|
||||
if debug {
|
||||
fmt.Fprintf(os.Stderr, "write to clipboard err: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// Watch returns a receive-only channel that received the clipboard data
|
||||
// whenever any change of clipboard data in the desired format happens.
|
||||
//
|
||||
// The returned channel will be closed if the given context is canceled.
|
||||
func Watch(ctx context.Context, t Format) <-chan []byte {
|
||||
return watch(ctx, t)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build android
|
||||
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, \
|
||||
"GOLANG.DESIGN/X/CLIPBOARD", __VA_ARGS__)
|
||||
|
||||
static jmethodID find_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
|
||||
jmethodID m = (*env)->GetMethodID(env, clazz, name, sig);
|
||||
if (m == 0) {
|
||||
(*env)->ExceptionClear(env);
|
||||
LOG_FATAL("cannot find method %s %s", name, sig);
|
||||
return 0;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
jobject get_clipboard(uintptr_t jni_env, uintptr_t ctx) {
|
||||
JNIEnv *env = (JNIEnv*)jni_env;
|
||||
jclass ctxClass = (*env)->GetObjectClass(env, (jobject)ctx);
|
||||
jmethodID getSystemService = find_method(env, ctxClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
|
||||
|
||||
jstring service = (*env)->NewStringUTF(env, "clipboard");
|
||||
jobject ret = (jobject)(*env)->CallObjectMethod(env, (jobject)ctx, getSystemService, service);
|
||||
jthrowable err = (*env)->ExceptionOccurred(env);
|
||||
|
||||
if (err != NULL) {
|
||||
LOG_FATAL("cannot find clipboard");
|
||||
(*env)->ExceptionClear(env);
|
||||
return NULL;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
char *clipboard_read_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) {
|
||||
JNIEnv *env = (JNIEnv*)jni_env;
|
||||
jobject mgr = get_clipboard(jni_env, ctx);
|
||||
if (mgr == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
|
||||
jmethodID getText = find_method(env, mgrClass, "getText", "()Ljava/lang/CharSequence;");
|
||||
|
||||
jobject content = (jstring)(*env)->CallObjectMethod(env, mgr, getText);
|
||||
if (content == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
jclass clzCharSequence = (*env)->GetObjectClass(env, content);
|
||||
jmethodID toString = (*env)->GetMethodID(env, clzCharSequence, "toString", "()Ljava/lang/String;");
|
||||
jobject s = (*env)->CallObjectMethod(env, content, toString);
|
||||
|
||||
const char *chars = (*env)->GetStringUTFChars(env, s, NULL);
|
||||
char *copy = strdup(chars);
|
||||
(*env)->ReleaseStringUTFChars(env, s, chars);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void clipboard_write_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *str) {
|
||||
JNIEnv *env = (JNIEnv*)jni_env;
|
||||
jobject mgr = get_clipboard(jni_env, ctx);
|
||||
if (mgr == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
|
||||
jmethodID setText = find_method(env, mgrClass, "setText", "(Ljava/lang/CharSequence;)V");
|
||||
|
||||
(*env)->CallVoidMethod(env, mgr, setText, (*env)->NewStringUTF(env, str));
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build android
|
||||
|
||||
package clipboard
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: -landroid -llog
|
||||
|
||||
#include <stdlib.h>
|
||||
char *clipboard_read_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx);
|
||||
void clipboard_write_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *str);
|
||||
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/mobile/app"
|
||||
)
|
||||
|
||||
func initialize() error { return nil }
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
switch t {
|
||||
case FmtText:
|
||||
s := ""
|
||||
if err := app.RunOnJVM(func(vm, env, ctx uintptr) error {
|
||||
cs := C.clipboard_read_string(C.uintptr_t(vm), C.uintptr_t(env), C.uintptr_t(ctx))
|
||||
if cs == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s = C.GoString(cs)
|
||||
C.free(unsafe.Pointer(cs))
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(s), nil
|
||||
case FmtImage:
|
||||
return nil, errUnsupported
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
// write writes the given data to clipboard and
|
||||
// returns true if success or false if failed.
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
done := make(chan struct{}, 1)
|
||||
switch t {
|
||||
case FmtText:
|
||||
cs := C.CString(string(buf))
|
||||
defer C.free(unsafe.Pointer(cs))
|
||||
|
||||
if err := app.RunOnJVM(func(vm, env, ctx uintptr) error {
|
||||
C.clipboard_write_string(C.uintptr_t(vm), C.uintptr_t(env), C.uintptr_t(ctx), cs)
|
||||
done <- struct{}{}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return done, nil
|
||||
case FmtImage:
|
||||
return nil, errUnsupported
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
recv := make(chan []byte, 1)
|
||||
ti := time.NewTicker(time.Second)
|
||||
last := Read(t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(recv)
|
||||
return
|
||||
case <-ti.C:
|
||||
b := Read(t)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
if bytes.Compare(last, b) != 0 {
|
||||
recv <- b
|
||||
last = b
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return recv
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build darwin && !ios
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
lastChangeCount int64
|
||||
changeCountMu sync.Mutex
|
||||
)
|
||||
|
||||
func initialize() error { return nil }
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
switch t {
|
||||
case FmtText:
|
||||
return readText()
|
||||
case FmtImage:
|
||||
return readImage()
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
func readText() ([]byte, error) {
|
||||
// Check if clipboard contains string data
|
||||
checkScript := `
|
||||
try
|
||||
set clipboardTypes to (clipboard info)
|
||||
repeat with aType in clipboardTypes
|
||||
if (first item of aType) is string then
|
||||
return "hastext"
|
||||
end if
|
||||
end repeat
|
||||
return "notext"
|
||||
on error
|
||||
return "error"
|
||||
end try
|
||||
`
|
||||
|
||||
cmd := exec.Command("osascript", "-e", checkScript)
|
||||
checkOut, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
checkOut = bytes.TrimSpace(checkOut)
|
||||
if !bytes.Equal(checkOut, []byte("hastext")) {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// Now get the actual text
|
||||
cmd = exec.Command("osascript", "-e", "get the clipboard")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
// Remove trailing newline that osascript adds
|
||||
out = bytes.TrimSuffix(out, []byte("\n"))
|
||||
|
||||
// If clipboard was set to empty string, return nil
|
||||
if len(out) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func readImage() ([]byte, error) {
|
||||
// AppleScript to read image data from clipboard as base64
|
||||
script := `
|
||||
try
|
||||
set theData to the clipboard as «class PNGf»
|
||||
return theData
|
||||
on error
|
||||
return ""
|
||||
end try
|
||||
`
|
||||
|
||||
cmd := exec.Command("osascript", "-e", script)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// Check if we got any data
|
||||
out = bytes.TrimSpace(out)
|
||||
if len(out) == 0 {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// The output is in hex format (e.g., «data PNGf89504E...»)
|
||||
// We need to extract and convert it
|
||||
outStr := string(out)
|
||||
if !strings.HasPrefix(outStr, "«data PNGf") || !strings.HasSuffix(outStr, "»") {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// Extract hex data
|
||||
hexData := strings.TrimPrefix(outStr, "«data PNGf")
|
||||
hexData = strings.TrimSuffix(hexData, "»")
|
||||
|
||||
// Convert hex to bytes
|
||||
buf := make([]byte, len(hexData)/2)
|
||||
for i := 0; i < len(hexData); i += 2 {
|
||||
b, err := strconv.ParseUint(hexData[i:i+2], 16, 8)
|
||||
if err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
buf[i/2] = byte(b)
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// write writes the given data to clipboard and
|
||||
// returns true if success or false if failed.
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
var err error
|
||||
switch t {
|
||||
case FmtText:
|
||||
err = writeText(buf)
|
||||
case FmtImage:
|
||||
err = writeImage(buf)
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update change count
|
||||
changeCountMu.Lock()
|
||||
lastChangeCount++
|
||||
currentCount := lastChangeCount
|
||||
changeCountMu.Unlock()
|
||||
|
||||
// use unbuffered channel to prevent goroutine leak
|
||||
changed := make(chan struct{}, 1)
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
changeCountMu.Lock()
|
||||
if lastChangeCount != currentCount {
|
||||
changeCountMu.Unlock()
|
||||
changed <- struct{}{}
|
||||
close(changed)
|
||||
return
|
||||
}
|
||||
changeCountMu.Unlock()
|
||||
}
|
||||
}()
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func writeText(buf []byte) error {
|
||||
if len(buf) == 0 {
|
||||
// Clear clipboard
|
||||
script := `set the clipboard to ""`
|
||||
cmd := exec.Command("osascript", "-e", script)
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Escape the text for AppleScript
|
||||
text := string(buf)
|
||||
text = strings.ReplaceAll(text, "\\", "\\\\")
|
||||
text = strings.ReplaceAll(text, "\"", "\\\"")
|
||||
|
||||
script := fmt.Sprintf(`set the clipboard to "%s"`, text)
|
||||
cmd := exec.Command("osascript", "-e", script)
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func writeImage(buf []byte) error {
|
||||
if len(buf) == 0 {
|
||||
// Clear clipboard
|
||||
script := `set the clipboard to ""`
|
||||
cmd := exec.Command("osascript", "-e", script)
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create a temporary file to store the PNG data
|
||||
tmpFile, err := os.CreateTemp("", "clipboard*.png")
|
||||
if err != nil {
|
||||
return errUnavailable
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
if _, err := tmpFile.Write(buf); err != nil {
|
||||
tmpFile.Close()
|
||||
return errUnavailable
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
// Use osascript to set clipboard to the image file
|
||||
script := fmt.Sprintf(`
|
||||
set theFile to POSIX file "%s"
|
||||
set theImage to read theFile as «class PNGf»
|
||||
set the clipboard to theImage
|
||||
`, tmpFile.Name())
|
||||
|
||||
cmd := exec.Command("osascript", "-e", script)
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
recv := make(chan []byte, 1)
|
||||
ti := time.NewTicker(time.Second)
|
||||
|
||||
// Get initial clipboard content
|
||||
var lastContent []byte
|
||||
if b := Read(t); b != nil {
|
||||
lastContent = make([]byte, len(b))
|
||||
copy(lastContent, b)
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer close(recv)
|
||||
defer ti.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ti.C:
|
||||
b := Read(t)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if content changed
|
||||
if !bytes.Equal(lastContent, b) {
|
||||
recv <- b
|
||||
lastContent = make([]byte, len(b))
|
||||
copy(lastContent, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return recv
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build ios
|
||||
|
||||
package clipboard
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c
|
||||
#cgo LDFLAGS: -framework Foundation -framework UIKit -framework MobileCoreServices
|
||||
|
||||
#import <stdlib.h>
|
||||
void clipboard_write_string(char *s);
|
||||
char *clipboard_read_string();
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func initialize() error { return nil }
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
switch t {
|
||||
case FmtText:
|
||||
return []byte(C.GoString(C.clipboard_read_string())), nil
|
||||
case FmtImage:
|
||||
return nil, errUnsupported
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
// SetContent sets the clipboard content for iOS
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
done := make(chan struct{}, 1)
|
||||
switch t {
|
||||
case FmtText:
|
||||
cs := C.CString(string(buf))
|
||||
defer C.free(unsafe.Pointer(cs))
|
||||
|
||||
C.clipboard_write_string(cs)
|
||||
return done, nil
|
||||
case FmtImage:
|
||||
return nil, errUnsupported
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
recv := make(chan []byte, 1)
|
||||
ti := time.NewTicker(time.Second)
|
||||
last := Read(t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(recv)
|
||||
return
|
||||
case <-ti.C:
|
||||
b := Read(t)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
if bytes.Compare(last, b) != 0 {
|
||||
recv <- b
|
||||
last = b
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return recv
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build ios
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <MobileCoreServices/MobileCoreServices.h>
|
||||
|
||||
void clipboard_write_string(char *s) {
|
||||
NSString *value = [NSString stringWithUTF8String:s];
|
||||
[[UIPasteboard generalPasteboard] setString:value];
|
||||
}
|
||||
|
||||
char *clipboard_read_string() {
|
||||
NSString *str = [[UIPasteboard generalPasteboard] string];
|
||||
return (char *)[str UTF8String];
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build linux && !android
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// Clipboard tools in order of preference
|
||||
clipboardTools = []struct {
|
||||
name string
|
||||
readCmd []string
|
||||
writeCmd []string
|
||||
readImg []string
|
||||
writeImg []string
|
||||
available bool
|
||||
}{
|
||||
{
|
||||
name: "xclip",
|
||||
readCmd: []string{"xclip", "-selection", "clipboard", "-o"},
|
||||
writeCmd: []string{"xclip", "-selection", "clipboard"},
|
||||
readImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png", "-o"},
|
||||
writeImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png"},
|
||||
},
|
||||
{
|
||||
name: "xsel",
|
||||
readCmd: []string{"xsel", "--clipboard", "--output"},
|
||||
writeCmd: []string{"xsel", "--clipboard", "--input"},
|
||||
readImg: []string{"xsel", "--clipboard", "--output"},
|
||||
writeImg: []string{"xsel", "--clipboard", "--input"},
|
||||
},
|
||||
{
|
||||
name: "wl-clipboard",
|
||||
readCmd: []string{"wl-paste", "-n"},
|
||||
writeCmd: []string{"wl-copy"},
|
||||
readImg: []string{"wl-paste", "-t", "image/png", "-n"},
|
||||
writeImg: []string{"wl-copy", "-t", "image/png"},
|
||||
},
|
||||
}
|
||||
|
||||
selectedTool int = -1
|
||||
toolMutex sync.Mutex
|
||||
lastChangeTime time.Time
|
||||
changeTimeMu sync.Mutex
|
||||
)
|
||||
|
||||
func initialize() error {
|
||||
toolMutex.Lock()
|
||||
defer toolMutex.Unlock()
|
||||
|
||||
if selectedTool >= 0 {
|
||||
return nil // Already initialized
|
||||
}
|
||||
|
||||
// Check which clipboard tool is available
|
||||
for i, tool := range clipboardTools {
|
||||
cmd := exec.Command("which", tool.name)
|
||||
if err := cmd.Run(); err == nil {
|
||||
clipboardTools[i].available = true
|
||||
if selectedTool < 0 {
|
||||
selectedTool = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if selectedTool < 0 {
|
||||
return fmt.Errorf(`%w: No clipboard utility found. Install one of the following:
|
||||
|
||||
For X11 systems:
|
||||
apt install -y xclip
|
||||
# or
|
||||
apt install -y xsel
|
||||
|
||||
For Wayland systems:
|
||||
apt install -y wl-clipboard
|
||||
|
||||
If running in a headless environment, you may also need:
|
||||
apt install -y xvfb
|
||||
# and run:
|
||||
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
|
||||
export DISPLAY=:99.0`, errUnavailable)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
toolMutex.Lock()
|
||||
tool := clipboardTools[selectedTool]
|
||||
toolMutex.Unlock()
|
||||
|
||||
switch t {
|
||||
case FmtText:
|
||||
return readText(tool)
|
||||
case FmtImage:
|
||||
return readImage(tool)
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
}
|
||||
|
||||
func readText(tool struct {
|
||||
name string
|
||||
readCmd []string
|
||||
writeCmd []string
|
||||
readImg []string
|
||||
writeImg []string
|
||||
available bool
|
||||
}) ([]byte, error) {
|
||||
// First check if clipboard contains text
|
||||
cmd := exec.Command(tool.readCmd[0], tool.readCmd[1:]...)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
// Check if it's because clipboard contains non-text data
|
||||
if tool.name == "xclip" {
|
||||
// xclip returns error when clipboard doesn't contain requested type
|
||||
checkCmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
|
||||
targets, _ := checkCmd.Output()
|
||||
if bytes.Contains(targets, []byte("image/png")) && !bytes.Contains(targets, []byte("UTF8_STRING")) {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
}
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func readImage(tool struct {
|
||||
name string
|
||||
readCmd []string
|
||||
writeCmd []string
|
||||
readImg []string
|
||||
writeImg []string
|
||||
available bool
|
||||
}) ([]byte, error) {
|
||||
if tool.name == "xsel" {
|
||||
// xsel doesn't support image types well, return error
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
cmd := exec.Command(tool.readImg[0], tool.readImg[1:]...)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// Verify it's PNG data
|
||||
if len(out) < 8 || !bytes.Equal(out[:8], []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
toolMutex.Lock()
|
||||
tool := clipboardTools[selectedTool]
|
||||
toolMutex.Unlock()
|
||||
|
||||
var cmd *exec.Cmd
|
||||
switch t {
|
||||
case FmtText:
|
||||
if len(buf) == 0 {
|
||||
// Write empty string
|
||||
cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
|
||||
cmd.Stdin = bytes.NewReader([]byte{})
|
||||
} else {
|
||||
cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
|
||||
cmd.Stdin = bytes.NewReader(buf)
|
||||
}
|
||||
case FmtImage:
|
||||
if tool.name == "xsel" {
|
||||
// xsel doesn't support image types well
|
||||
return nil, errUnavailable
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
// Clear clipboard
|
||||
cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
|
||||
cmd.Stdin = bytes.NewReader([]byte{})
|
||||
} else {
|
||||
cmd = exec.Command(tool.writeImg[0], tool.writeImg[1:]...)
|
||||
cmd.Stdin = bytes.NewReader(buf)
|
||||
}
|
||||
default:
|
||||
return nil, errUnsupported
|
||||
}
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// Update change time
|
||||
changeTimeMu.Lock()
|
||||
lastChangeTime = time.Now()
|
||||
currentTime := lastChangeTime
|
||||
changeTimeMu.Unlock()
|
||||
|
||||
// Create change notification channel
|
||||
changed := make(chan struct{}, 1)
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
changeTimeMu.Lock()
|
||||
if !lastChangeTime.Equal(currentTime) {
|
||||
changeTimeMu.Unlock()
|
||||
changed <- struct{}{}
|
||||
close(changed)
|
||||
return
|
||||
}
|
||||
changeTimeMu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
recv := make(chan []byte, 1)
|
||||
ti := time.NewTicker(time.Second)
|
||||
|
||||
// Get initial clipboard content
|
||||
var lastContent []byte
|
||||
if b := Read(t); b != nil {
|
||||
lastContent = make([]byte, len(b))
|
||||
copy(lastContent, b)
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer close(recv)
|
||||
defer ti.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ti.C:
|
||||
b := Read(t)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if content changed
|
||||
if !bytes.Equal(lastContent, b) {
|
||||
recv <- b
|
||||
lastContent = make([]byte, len(b))
|
||||
copy(lastContent, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return recv
|
||||
}
|
||||
|
||||
// Helper function to check clipboard content type for xclip
|
||||
func getClipboardTargets() []string {
|
||||
cmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(string(out), "\n")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build !windows && !darwin && !linux && !cgo
|
||||
|
||||
package clipboard
|
||||
|
||||
import "context"
|
||||
|
||||
func initialize() error {
|
||||
return errNoCgo
|
||||
}
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
panic("clipboard: cannot use when CGO_ENABLED=0")
|
||||
}
|
||||
|
||||
func readc(t string) ([]byte, error) {
|
||||
panic("clipboard: cannot use when CGO_ENABLED=0")
|
||||
}
|
||||
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
panic("clipboard: cannot use when CGO_ENABLED=0")
|
||||
}
|
||||
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
panic("clipboard: cannot use when CGO_ENABLED=0")
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
package clipboard_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func init() {
|
||||
clipboard.Debug = true
|
||||
}
|
||||
|
||||
func TestClipboardInit(t *testing.T) {
|
||||
t.Run("no-cgo", func(t *testing.T) {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); !ok || val != "0" {
|
||||
t.Skip("CGO_ENABLED is set to 1")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows does not need to check for cgo")
|
||||
}
|
||||
|
||||
if err := clipboard.Init(); !errors.Is(err, clipboard.ErrCgoDisabled) {
|
||||
t.Fatalf("expect ErrCgoDisabled, got: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("with-cgo", func(t *testing.T) {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("Only Linux may return error at the moment.")
|
||||
}
|
||||
|
||||
if err := clipboard.Init(); err != nil && !errors.Is(err, clipboard.ErrUnavailable) {
|
||||
t.Fatalf("expect ErrUnavailable, but got: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestClipboard(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("image", func(t *testing.T) {
|
||||
data, err := os.ReadFile("tests/testdata/clipboard.png")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read gold file: %v", err)
|
||||
}
|
||||
clipboard.Write(clipboard.FmtImage, data)
|
||||
|
||||
b := clipboard.Read(clipboard.FmtText)
|
||||
if b != nil {
|
||||
t.Fatalf("read clipboard that stores image data as text should fail, but got len: %d", len(b))
|
||||
}
|
||||
|
||||
b = clipboard.Read(clipboard.FmtImage)
|
||||
if b == nil {
|
||||
t.Fatalf("read clipboard that stores image data as image should success, but got: nil")
|
||||
}
|
||||
|
||||
img1, err := png.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatalf("write image is not png encoded: %v", err)
|
||||
}
|
||||
img2, err := png.Decode(bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatalf("read image is not png encoded: %v", err)
|
||||
}
|
||||
|
||||
w := img2.Bounds().Dx()
|
||||
h := img2.Bounds().Dy()
|
||||
|
||||
incorrect := 0
|
||||
for i := 0; i < w; i++ {
|
||||
for j := 0; j < h; j++ {
|
||||
wr, wg, wb, wa := img1.At(i, j).RGBA()
|
||||
gr, gg, gb, ga := img2.At(i, j).RGBA()
|
||||
want := color.RGBA{
|
||||
R: uint8(wr),
|
||||
G: uint8(wg),
|
||||
B: uint8(wb),
|
||||
A: uint8(wa),
|
||||
}
|
||||
got := color.RGBA{
|
||||
R: uint8(gr),
|
||||
G: uint8(gg),
|
||||
B: uint8(gb),
|
||||
A: uint8(ga),
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(want, got) {
|
||||
t.Logf("read data from clipbaord is inconsistent with previous written data, pix: (%d,%d), got: %+v, want: %+v", i, j, got, want)
|
||||
incorrect++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if incorrect > 0 {
|
||||
t.Fatalf("read data from clipboard contains too much inconsistent pixels to the previous written data, number of incorrect pixels: %v", incorrect)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("text", func(t *testing.T) {
|
||||
data := []byte("golang.design/x/clipboard")
|
||||
clipboard.Write(clipboard.FmtText, data)
|
||||
|
||||
b := clipboard.Read(clipboard.FmtImage)
|
||||
if b != nil {
|
||||
t.Fatalf("read clipboard that stores text data as image should fail, but got len: %d", len(b))
|
||||
}
|
||||
b = clipboard.Read(clipboard.FmtText)
|
||||
if b == nil {
|
||||
t.Fatal("read clipboard taht stores text data as text should success, but got: nil")
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(data, b) {
|
||||
t.Fatalf("read data from clipbaord is inconsistent with previous written data, got: %d, want: %d", len(b), len(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestClipboardMultipleWrites(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
}
|
||||
|
||||
data, err := os.ReadFile("tests/testdata/clipboard.png")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read gold file: %v", err)
|
||||
}
|
||||
chg := clipboard.Write(clipboard.FmtImage, data)
|
||||
|
||||
data = []byte("golang.design/x/clipboard")
|
||||
clipboard.Write(clipboard.FmtText, data)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
|
||||
defer cancel()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("failed to receive clipboard change notification")
|
||||
case _, ok := <-chg:
|
||||
if !ok {
|
||||
t.Fatalf("change channel is closed before receiving the changed clipboard data")
|
||||
}
|
||||
}
|
||||
_, ok := <-chg
|
||||
if ok {
|
||||
t.Fatalf("changed channel should be closed after receiving the notification")
|
||||
}
|
||||
|
||||
b := clipboard.Read(clipboard.FmtImage)
|
||||
if b != nil {
|
||||
t.Fatalf("read clipboard that should store text data as image should fail, but got: %d", len(b))
|
||||
}
|
||||
|
||||
b = clipboard.Read(clipboard.FmtText)
|
||||
if b == nil {
|
||||
t.Fatalf("read clipboard that should store text data as text should success, got: nil")
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(data, b) {
|
||||
t.Fatalf("read data from clipbaord is inconsistent with previous write, want %s, got: %s", string(data), string(b))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardConcurrentRead(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
}
|
||||
|
||||
// This test check that concurrent read/write to the clipboard does
|
||||
// not cause crashes on some specific platform, such as macOS.
|
||||
done := make(chan bool, 2)
|
||||
go func() {
|
||||
defer func() {
|
||||
done <- true
|
||||
}()
|
||||
clipboard.Read(clipboard.FmtText)
|
||||
}()
|
||||
go func() {
|
||||
defer func() {
|
||||
done <- true
|
||||
}()
|
||||
clipboard.Read(clipboard.FmtImage)
|
||||
}()
|
||||
<-done
|
||||
<-done
|
||||
}
|
||||
|
||||
func TestClipboardWriteEmpty(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
}
|
||||
|
||||
chg1 := clipboard.Write(clipboard.FmtText, nil)
|
||||
if got := clipboard.Read(clipboard.FmtText); got != nil {
|
||||
t.Fatalf("write nil to clipboard should read nil, got: %v", string(got))
|
||||
}
|
||||
clipboard.Write(clipboard.FmtText, []byte(""))
|
||||
<-chg1
|
||||
|
||||
if got := clipboard.Read(clipboard.FmtText); string(got) != "" {
|
||||
t.Fatalf("write empty string to clipboard should read empty string, got: `%v`", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardWatch(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
|
||||
t.Skip("CGO_ENABLED is set to 0")
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
|
||||
defer cancel()
|
||||
|
||||
// clear clipboard
|
||||
clipboard.Write(clipboard.FmtText, []byte(""))
|
||||
lastRead := clipboard.Read(clipboard.FmtText)
|
||||
|
||||
changed := clipboard.Watch(ctx, clipboard.FmtText)
|
||||
|
||||
want := []byte("golang.design/x/clipboard")
|
||||
go func(ctx context.Context) {
|
||||
t := time.NewTicker(time.Millisecond * 500)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
clipboard.Write(clipboard.FmtText, want)
|
||||
}
|
||||
}
|
||||
}(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if string(lastRead) == "" {
|
||||
t.Fatalf("clipboard watch never receives a notification")
|
||||
}
|
||||
t.Log(string(lastRead))
|
||||
return
|
||||
case data, ok := <-changed:
|
||||
if !ok {
|
||||
if string(lastRead) == "" {
|
||||
t.Fatalf("clipboard watch never receives a notification")
|
||||
}
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(data, want) {
|
||||
t.Fatalf("received data from watch mismatch, want: %v, got %v", string(want), string(data))
|
||||
}
|
||||
lastRead = data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkClipboard(b *testing.B) {
|
||||
b.Run("text", func(b *testing.B) {
|
||||
data := []byte("golang.design/x/clipboard")
|
||||
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
clipboard.Write(clipboard.FmtText, data)
|
||||
_ = clipboard.Read(clipboard.FmtText)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestClipboardNoCgo(t *testing.T) {
|
||||
if val, ok := os.LookupEnv("CGO_ENABLED"); !ok || val != "0" {
|
||||
t.Skip("CGO_ENABLED is set to 1")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows should always be tested")
|
||||
}
|
||||
|
||||
t.Run("Read", func(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
return
|
||||
}
|
||||
t.Fatalf("expect to fail when CGO_ENABLED=0")
|
||||
}()
|
||||
|
||||
clipboard.Read(clipboard.FmtText)
|
||||
})
|
||||
|
||||
t.Run("Write", func(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
return
|
||||
}
|
||||
t.Fatalf("expect to fail when CGO_ENABLED=0")
|
||||
}()
|
||||
|
||||
clipboard.Write(clipboard.FmtText, []byte("dummy"))
|
||||
})
|
||||
|
||||
t.Run("Watch", func(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
return
|
||||
}
|
||||
t.Fatalf("expect to fail when CGO_ENABLED=0")
|
||||
}()
|
||||
|
||||
clipboard.Watch(context.TODO(), clipboard.FmtText)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build windows
|
||||
|
||||
package clipboard
|
||||
|
||||
// Interacting with Clipboard on Windows:
|
||||
// https://docs.microsoft.com/zh-cn/windows/win32/dataxchg/using-the-clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/image/bmp"
|
||||
)
|
||||
|
||||
func initialize() error { return nil }
|
||||
|
||||
// readText reads the clipboard and returns the text data if presents.
|
||||
// The caller is responsible for opening/closing the clipboard before
|
||||
// calling this function.
|
||||
func readText() (buf []byte, err error) {
|
||||
hMem, _, err := getClipboardData.Call(cFmtUnicodeText)
|
||||
if hMem == 0 {
|
||||
return nil, err
|
||||
}
|
||||
p, _, err := gLock.Call(hMem)
|
||||
if p == 0 {
|
||||
return nil, err
|
||||
}
|
||||
defer gUnlock.Call(hMem)
|
||||
|
||||
// Find NUL terminator
|
||||
n := 0
|
||||
for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {
|
||||
ptr = unsafe.Pointer(uintptr(ptr) +
|
||||
unsafe.Sizeof(*((*uint16)(unsafe.Pointer(p)))))
|
||||
}
|
||||
|
||||
var s []uint16
|
||||
h := (*reflect.SliceHeader)(unsafe.Pointer(&s))
|
||||
h.Data = p
|
||||
h.Len = n
|
||||
h.Cap = n
|
||||
return []byte(string(utf16.Decode(s))), nil
|
||||
}
|
||||
|
||||
// writeText writes given data to the clipboard. It is the caller's
|
||||
// responsibility for opening/closing the clipboard before calling
|
||||
// this function.
|
||||
func writeText(buf []byte) error {
|
||||
r, _, err := emptyClipboard.Call()
|
||||
if r == 0 {
|
||||
return fmt.Errorf("failed to clear clipboard: %w", err)
|
||||
}
|
||||
|
||||
// empty text, we are done here.
|
||||
if len(buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
s, err := syscall.UTF16FromString(string(buf))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert given string: %w", err)
|
||||
}
|
||||
|
||||
hMem, _, err := gAlloc.Call(gmemMoveable, uintptr(len(s)*int(unsafe.Sizeof(s[0]))))
|
||||
if hMem == 0 {
|
||||
return fmt.Errorf("failed to alloc global memory: %w", err)
|
||||
}
|
||||
|
||||
p, _, err := gLock.Call(hMem)
|
||||
if p == 0 {
|
||||
return fmt.Errorf("failed to lock global memory: %w", err)
|
||||
}
|
||||
defer gUnlock.Call(hMem)
|
||||
|
||||
// no return value
|
||||
memMove.Call(p, uintptr(unsafe.Pointer(&s[0])),
|
||||
uintptr(len(s)*int(unsafe.Sizeof(s[0]))))
|
||||
|
||||
v, _, err := setClipboardData.Call(cFmtUnicodeText, hMem)
|
||||
if v == 0 {
|
||||
gFree.Call(hMem)
|
||||
return fmt.Errorf("failed to set text to clipboard: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// readImage reads the clipboard and returns PNG encoded image data
|
||||
// if presents. The caller is responsible for opening/closing the
|
||||
// clipboard before calling this function.
|
||||
func readImage() ([]byte, error) {
|
||||
hMem, _, err := getClipboardData.Call(cFmtDIBV5)
|
||||
if hMem == 0 {
|
||||
// second chance to try FmtDIB
|
||||
return readImageDib()
|
||||
}
|
||||
p, _, err := gLock.Call(hMem)
|
||||
if p == 0 {
|
||||
return nil, err
|
||||
}
|
||||
defer gUnlock.Call(hMem)
|
||||
|
||||
// inspect header information
|
||||
info := (*bitmapV5Header)(unsafe.Pointer(p))
|
||||
|
||||
// maybe deal with other formats?
|
||||
if info.BitCount != 32 {
|
||||
return nil, errUnsupported
|
||||
}
|
||||
|
||||
var data []byte
|
||||
sh := (*reflect.SliceHeader)(unsafe.Pointer(&data))
|
||||
sh.Data = uintptr(p)
|
||||
sh.Cap = int(info.Size + 4*uint32(info.Width)*uint32(info.Height))
|
||||
sh.Len = int(info.Size + 4*uint32(info.Width)*uint32(info.Height))
|
||||
img := image.NewRGBA(image.Rect(0, 0, int(info.Width), int(info.Height)))
|
||||
offset := int(info.Size)
|
||||
stride := int(info.Width)
|
||||
for y := 0; y < int(info.Height); y++ {
|
||||
for x := 0; x < int(info.Width); x++ {
|
||||
idx := offset + 4*(y*stride+x)
|
||||
xhat := (x + int(info.Width)) % int(info.Width)
|
||||
yhat := int(info.Height) - 1 - y
|
||||
r := data[idx+2]
|
||||
g := data[idx+1]
|
||||
b := data[idx+0]
|
||||
a := data[idx+3]
|
||||
img.SetRGBA(xhat, yhat, color.RGBA{r, g, b, a})
|
||||
}
|
||||
}
|
||||
// always use PNG encoding.
|
||||
var buf bytes.Buffer
|
||||
png.Encode(&buf, img)
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func readImageDib() ([]byte, error) {
|
||||
const (
|
||||
fileHeaderLen = 14
|
||||
infoHeaderLen = 40
|
||||
cFmtDIB = 8
|
||||
)
|
||||
|
||||
hClipDat, _, err := getClipboardData.Call(cFmtDIB)
|
||||
if err != nil {
|
||||
return nil, errors.New("not dib format data: " + err.Error())
|
||||
}
|
||||
pMemBlk, _, err := gLock.Call(hClipDat)
|
||||
if pMemBlk == 0 {
|
||||
return nil, errors.New("failed to call global lock: " + err.Error())
|
||||
}
|
||||
defer gUnlock.Call(hClipDat)
|
||||
|
||||
bmpHeader := (*bitmapHeader)(unsafe.Pointer(pMemBlk))
|
||||
dataSize := bmpHeader.SizeImage + fileHeaderLen + infoHeaderLen
|
||||
|
||||
if bmpHeader.SizeImage == 0 && bmpHeader.Compression == 0 {
|
||||
iSizeImage := bmpHeader.Height * ((bmpHeader.Width*uint32(bmpHeader.BitCount)/8 + 3) &^ 3)
|
||||
dataSize += iSizeImage
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
binary.Write(buf, binary.LittleEndian, uint16('B')|(uint16('M')<<8))
|
||||
binary.Write(buf, binary.LittleEndian, uint32(dataSize))
|
||||
binary.Write(buf, binary.LittleEndian, uint32(0))
|
||||
const sizeof_colorbar = 0
|
||||
binary.Write(buf, binary.LittleEndian, uint32(fileHeaderLen+infoHeaderLen+sizeof_colorbar))
|
||||
j := 0
|
||||
for i := fileHeaderLen; i < int(dataSize); i++ {
|
||||
binary.Write(buf, binary.BigEndian, *(*byte)(unsafe.Pointer(pMemBlk + uintptr(j))))
|
||||
j++
|
||||
}
|
||||
return bmpToPng(buf)
|
||||
}
|
||||
|
||||
func bmpToPng(bmpBuf *bytes.Buffer) (buf []byte, err error) {
|
||||
var f bytes.Buffer
|
||||
original_image, err := bmp.Decode(bmpBuf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = png.Encode(&f, original_image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.Bytes(), nil
|
||||
}
|
||||
|
||||
func writeImage(buf []byte) error {
|
||||
r, _, err := emptyClipboard.Call()
|
||||
if r == 0 {
|
||||
return fmt.Errorf("failed to clear clipboard: %w", err)
|
||||
}
|
||||
|
||||
// empty text, we are done here.
|
||||
if len(buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
img, err := png.Decode(bytes.NewReader(buf))
|
||||
if err != nil {
|
||||
return fmt.Errorf("input bytes is not PNG encoded: %w", err)
|
||||
}
|
||||
|
||||
offset := unsafe.Sizeof(bitmapV5Header{})
|
||||
width := img.Bounds().Dx()
|
||||
height := img.Bounds().Dy()
|
||||
imageSize := 4 * width * height
|
||||
|
||||
data := make([]byte, int(offset)+imageSize)
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
idx := int(offset) + 4*(y*width+x)
|
||||
r, g, b, a := img.At(x, height-1-y).RGBA()
|
||||
data[idx+2] = uint8(r)
|
||||
data[idx+1] = uint8(g)
|
||||
data[idx+0] = uint8(b)
|
||||
data[idx+3] = uint8(a)
|
||||
}
|
||||
}
|
||||
|
||||
info := bitmapV5Header{}
|
||||
info.Size = uint32(offset)
|
||||
info.Width = int32(width)
|
||||
info.Height = int32(height)
|
||||
info.Planes = 1
|
||||
info.Compression = 0 // BI_RGB
|
||||
info.SizeImage = uint32(4 * info.Width * info.Height)
|
||||
info.RedMask = 0xff0000 // default mask
|
||||
info.GreenMask = 0xff00
|
||||
info.BlueMask = 0xff
|
||||
info.AlphaMask = 0xff000000
|
||||
info.BitCount = 32 // we only deal with 32 bpp at the moment.
|
||||
// Use calibrated RGB values as Go's image/png assumes linear color space.
|
||||
// Other options:
|
||||
// - LCS_CALIBRATED_RGB = 0x00000000
|
||||
// - LCS_sRGB = 0x73524742
|
||||
// - LCS_WINDOWS_COLOR_SPACE = 0x57696E20
|
||||
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/eb4bbd50-b3ce-4917-895c-be31f214797f
|
||||
info.CSType = 0x73524742
|
||||
// Use GL_IMAGES for GamutMappingIntent
|
||||
// Other options:
|
||||
// - LCS_GM_ABS_COLORIMETRIC = 0x00000008
|
||||
// - LCS_GM_BUSINESS = 0x00000001
|
||||
// - LCS_GM_GRAPHICS = 0x00000002
|
||||
// - LCS_GM_IMAGES = 0x00000004
|
||||
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/9fec0834-607d-427d-abd5-ab240fb0db38
|
||||
info.Intent = 4 // LCS_GM_IMAGES
|
||||
|
||||
infob := make([]byte, int(unsafe.Sizeof(info)))
|
||||
for i, v := range *(*[unsafe.Sizeof(info)]byte)(unsafe.Pointer(&info)) {
|
||||
infob[i] = v
|
||||
}
|
||||
copy(data[:], infob[:])
|
||||
|
||||
hMem, _, err := gAlloc.Call(gmemMoveable,
|
||||
uintptr(len(data)*int(unsafe.Sizeof(data[0]))))
|
||||
if hMem == 0 {
|
||||
return fmt.Errorf("failed to alloc global memory: %w", err)
|
||||
}
|
||||
|
||||
p, _, err := gLock.Call(hMem)
|
||||
if p == 0 {
|
||||
return fmt.Errorf("failed to lock global memory: %w", err)
|
||||
}
|
||||
defer gUnlock.Call(hMem)
|
||||
|
||||
memMove.Call(p, uintptr(unsafe.Pointer(&data[0])),
|
||||
uintptr(len(data)*int(unsafe.Sizeof(data[0]))))
|
||||
|
||||
v, _, err := setClipboardData.Call(cFmtDIBV5, hMem)
|
||||
if v == 0 {
|
||||
gFree.Call(hMem)
|
||||
return fmt.Errorf("failed to set text to clipboard: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func read(t Format) (buf []byte, err error) {
|
||||
// On Windows, OpenClipboard and CloseClipboard must be executed on
|
||||
// the same thread. Thus, lock the OS thread for further execution.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
var format uintptr
|
||||
switch t {
|
||||
case FmtImage:
|
||||
format = cFmtDIBV5
|
||||
case FmtText:
|
||||
fallthrough
|
||||
default:
|
||||
format = cFmtUnicodeText
|
||||
}
|
||||
|
||||
// check if clipboard is avaliable for the requested format
|
||||
r, _, err := isClipboardFormatAvailable.Call(format)
|
||||
if r == 0 {
|
||||
return nil, errUnavailable
|
||||
}
|
||||
|
||||
// try again until open clipboard successed
|
||||
for {
|
||||
r, _, _ = openClipboard.Call()
|
||||
if r == 0 {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
defer closeClipboard.Call()
|
||||
|
||||
switch format {
|
||||
case cFmtDIBV5:
|
||||
return readImage()
|
||||
case cFmtUnicodeText:
|
||||
fallthrough
|
||||
default:
|
||||
return readText()
|
||||
}
|
||||
}
|
||||
|
||||
// write writes the given data to clipboard and
|
||||
// returns true if success or false if failed.
|
||||
func write(t Format, buf []byte) (<-chan struct{}, error) {
|
||||
errch := make(chan error)
|
||||
changed := make(chan struct{}, 1)
|
||||
go func() {
|
||||
// make sure GetClipboardSequenceNumber happens with
|
||||
// OpenClipboard on the same thread.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for {
|
||||
r, _, _ := openClipboard.Call(0)
|
||||
if r == 0 {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// var param uintptr
|
||||
switch t {
|
||||
case FmtImage:
|
||||
err := writeImage(buf)
|
||||
if err != nil {
|
||||
errch <- err
|
||||
closeClipboard.Call()
|
||||
return
|
||||
}
|
||||
case FmtText:
|
||||
fallthrough
|
||||
default:
|
||||
// param = cFmtUnicodeText
|
||||
err := writeText(buf)
|
||||
if err != nil {
|
||||
errch <- err
|
||||
closeClipboard.Call()
|
||||
return
|
||||
}
|
||||
}
|
||||
// Close the clipboard otherwise other applications cannot
|
||||
// paste the data.
|
||||
closeClipboard.Call()
|
||||
|
||||
cnt, _, _ := getClipboardSequenceNumber.Call()
|
||||
errch <- nil
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
cur, _, _ := getClipboardSequenceNumber.Call()
|
||||
if cur != cnt {
|
||||
changed <- struct{}{}
|
||||
close(changed)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := <-errch
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func watch(ctx context.Context, t Format) <-chan []byte {
|
||||
recv := make(chan []byte, 1)
|
||||
ready := make(chan struct{})
|
||||
go func() {
|
||||
// not sure if we are too slow or the user too fast :)
|
||||
ti := time.NewTicker(time.Second)
|
||||
cnt, _, _ := getClipboardSequenceNumber.Call()
|
||||
ready <- struct{}{}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(recv)
|
||||
return
|
||||
case <-ti.C:
|
||||
cur, _, _ := getClipboardSequenceNumber.Call()
|
||||
if cnt != cur {
|
||||
b := Read(t)
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
recv <- b
|
||||
cnt = cur
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
<-ready
|
||||
return recv
|
||||
}
|
||||
|
||||
const (
|
||||
cFmtBitmap = 2 // Win+PrintScreen
|
||||
cFmtUnicodeText = 13
|
||||
cFmtDIBV5 = 17
|
||||
// Screenshot taken from special shortcut is in different format (why??), see:
|
||||
// https://jpsoft.com/forums/threads/detecting-clipboard-format.5225/
|
||||
cFmtDataObject = 49161 // Shift+Win+s, returned from enumClipboardFormats
|
||||
gmemMoveable = 0x0002
|
||||
)
|
||||
|
||||
// BITMAPV5Header structure, see:
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapv5header
|
||||
type bitmapV5Header struct {
|
||||
Size uint32
|
||||
Width int32
|
||||
Height int32
|
||||
Planes uint16
|
||||
BitCount uint16
|
||||
Compression uint32
|
||||
SizeImage uint32
|
||||
XPelsPerMeter int32
|
||||
YPelsPerMeter int32
|
||||
ClrUsed uint32
|
||||
ClrImportant uint32
|
||||
RedMask uint32
|
||||
GreenMask uint32
|
||||
BlueMask uint32
|
||||
AlphaMask uint32
|
||||
CSType uint32
|
||||
Endpoints struct {
|
||||
CiexyzRed, CiexyzGreen, CiexyzBlue struct {
|
||||
CiexyzX, CiexyzY, CiexyzZ int32 // FXPT2DOT30
|
||||
}
|
||||
}
|
||||
GammaRed uint32
|
||||
GammaGreen uint32
|
||||
GammaBlue uint32
|
||||
Intent uint32
|
||||
ProfileData uint32
|
||||
ProfileSize uint32
|
||||
Reserved uint32
|
||||
}
|
||||
|
||||
type bitmapHeader struct {
|
||||
Size uint32
|
||||
Width uint32
|
||||
Height uint32
|
||||
PLanes uint16
|
||||
BitCount uint16
|
||||
Compression uint32
|
||||
SizeImage uint32
|
||||
XPelsPerMeter uint32
|
||||
YPelsPerMeter uint32
|
||||
ClrUsed uint32
|
||||
ClrImportant uint32
|
||||
}
|
||||
|
||||
// Calling a Windows DLL, see:
|
||||
// https://github.com/golang/go/wiki/WindowsDLLs
|
||||
var (
|
||||
user32 = syscall.MustLoadDLL("user32")
|
||||
// Opens the clipboard for examination and prevents other
|
||||
// applications from modifying the clipboard content.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-openclipboard
|
||||
openClipboard = user32.MustFindProc("OpenClipboard")
|
||||
// Closes the clipboard.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-closeclipboard
|
||||
closeClipboard = user32.MustFindProc("CloseClipboard")
|
||||
// Empties the clipboard and frees handles to data in the clipboard.
|
||||
// The function then assigns ownership of the clipboard to the
|
||||
// window that currently has the clipboard open.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-emptyclipboard
|
||||
emptyClipboard = user32.MustFindProc("EmptyClipboard")
|
||||
// Retrieves data from the clipboard in a specified format.
|
||||
// The clipboard must have been opened previously.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclipboarddata
|
||||
getClipboardData = user32.MustFindProc("GetClipboardData")
|
||||
// Places data on the clipboard in a specified clipboard format.
|
||||
// The window must be the current clipboard owner, and the
|
||||
// application must have called the OpenClipboard function. (When
|
||||
// responding to the WM_RENDERFORMAT message, the clipboard owner
|
||||
// must not call OpenClipboard before calling SetClipboardData.)
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setclipboarddata
|
||||
setClipboardData = user32.MustFindProc("SetClipboardData")
|
||||
// Determines whether the clipboard contains data in the specified format.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-isclipboardformatavailable
|
||||
isClipboardFormatAvailable = user32.MustFindProc("IsClipboardFormatAvailable")
|
||||
// Clipboard data formats are stored in an ordered list. To perform
|
||||
// an enumeration of clipboard data formats, you make a series of
|
||||
// calls to the EnumClipboardFormats function. For each call, the
|
||||
// format parameter specifies an available clipboard format, and the
|
||||
// function returns the next available clipboard format.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-isclipboardformatavailable
|
||||
enumClipboardFormats = user32.MustFindProc("EnumClipboardFormats")
|
||||
// Retrieves the clipboard sequence number for the current window station.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclipboardsequencenumber
|
||||
getClipboardSequenceNumber = user32.MustFindProc("GetClipboardSequenceNumber")
|
||||
// Registers a new clipboard format. This format can then be used as
|
||||
// a valid clipboard format.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclipboardformata
|
||||
registerClipboardFormatA = user32.MustFindProc("RegisterClipboardFormatA")
|
||||
|
||||
kernel32 = syscall.NewLazyDLL("kernel32")
|
||||
|
||||
// Locks a global memory object and returns a pointer to the first
|
||||
// byte of the object's memory block.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globallock
|
||||
gLock = kernel32.NewProc("GlobalLock")
|
||||
// Decrements the lock count associated with a memory object that was
|
||||
// allocated with GMEM_MOVEABLE. This function has no effect on memory
|
||||
// objects allocated with GMEM_FIXED.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalunlock
|
||||
gUnlock = kernel32.NewProc("GlobalUnlock")
|
||||
// Allocates the specified number of bytes from the heap.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalalloc
|
||||
gAlloc = kernel32.NewProc("GlobalAlloc")
|
||||
// Frees the specified global memory object and invalidates its handle.
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalfree
|
||||
gFree = kernel32.NewProc("GlobalFree")
|
||||
memMove = kernel32.NewProc("RtlMoveMemory")
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright 2021 The golang.design Initiative Authors.
|
||||
All rights reserved. Use of this source code is governed
|
||||
by a MIT license that can be found in the LICENSE file.
|
||||
|
||||
Written by Changkun Ou <changkun.de>
|
||||
-->
|
||||
<manifest
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="design.golang.clipboard.gclip"
|
||||
android:versionCode="1"
|
||||
android:versionName="1.0">
|
||||
|
||||
|
||||
<!-- In order to access the clipboard, the application manifest must
|
||||
specify the permission requirement. See the following page for
|
||||
details.
|
||||
http://developer.android.com/guide/topics/manifest/manifest-intro.html#perms -->
|
||||
<uses-permission android:name="android.permission.CLIPBOARD" />
|
||||
|
||||
<application android:label="gclip" android:debuggable="true">
|
||||
<activity android:name="org.golang.app.GoNativeActivity"
|
||||
android:label="Gclip"
|
||||
android:configChanges="orientation|keyboardHidden">
|
||||
<meta-data android:name="android.app.lib_name" android:value="Gclip" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,31 @@
|
||||
# gclip-gui
|
||||
|
||||
This is a very basic example for verification purpose that demonstrates
|
||||
how the [golang.design/x/clipboard](https://golang.design/x/clipboard)
|
||||
can interact with macOS/Linux/Windows/Android/iOS system clipboard.
|
||||
|
||||
The gclip GUI application writes a string to the system clipboard
|
||||
periodically then reads it back and renders it if possible.
|
||||
|
||||
Because of the system limitation, on mobile devices, only string data is
|
||||
supported at the moment. Hence, one must use clipboard.FmtText. Other supplied
|
||||
formats result in a panic.
|
||||
|
||||
This example is intentded as cross platform application. To build it, one
|
||||
must use [gomobile](https://golang.org/x/mobile). You may follow the instructions
|
||||
provided in the [GoMobile wiki](https://github.com/golang/go/wiki/Mobile) page.
|
||||
|
||||
|
||||
- For desktop: `go build -o gclip-gui`
|
||||
- For Android: `gomobile build -v -target=android -o gclip-gui.apk`
|
||||
- For iOS: `gomobile build -v -target=ios -bundleid design.golang.gclip-gui.app`
|
||||
|
||||
## Screenshots
|
||||
|
||||
| macOS | iOS | Windows | Android | Linux |
|
||||
|:-----:|:---:|:-------:|:-------:|:-----:|
|
||||
||||||
|
||||
|
||||
## License
|
||||
|
||||
MIT | © 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
|
||||
@@ -0,0 +1,236 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build android || ios || linux || darwin || windows
|
||||
|
||||
// This is a very basic example for verification purpose that
|
||||
// demonstrates how the golang.design/x/clipboard can interact
|
||||
// with macOS/Linux/Windows/Android/iOS system clipboard.
|
||||
//
|
||||
// The gclip GUI application writes a string to the system clipboard
|
||||
// periodically then reads it back and renders it if possible.
|
||||
//
|
||||
// Because of the system limitation, on mobile devices, only string
|
||||
// data is supported at the moment. Hence, one must use clipboard.FmtText.
|
||||
// Other supplied formats result in a panic.
|
||||
//
|
||||
// This example is intentded as cross platform application.
|
||||
// To build it, one must use gomobile (https://golang.org/x/mobile).
|
||||
// You may follow the instructions provided in the GoMobile's wiki page:
|
||||
// https://github.com/golang/go/wiki/Mobile.
|
||||
//
|
||||
// - For desktop:
|
||||
//
|
||||
// go build -o gclip-gui
|
||||
//
|
||||
// - For Android:
|
||||
//
|
||||
// gomobile build -v -target=android -o gclip-gui.apk
|
||||
//
|
||||
// - For iOS:
|
||||
//
|
||||
// gomobile build -v -target=ios -bundleid design.golang.gclip-gui.app
|
||||
//
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.design/x/clipboard"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/basicfont"
|
||||
"golang.org/x/image/math/fixed"
|
||||
"golang.org/x/mobile/app"
|
||||
"golang.org/x/mobile/event/lifecycle"
|
||||
"golang.org/x/mobile/event/paint"
|
||||
"golang.org/x/mobile/event/size"
|
||||
"golang.org/x/mobile/exp/gl/glutil"
|
||||
"golang.org/x/mobile/geom"
|
||||
"golang.org/x/mobile/gl"
|
||||
)
|
||||
|
||||
type Label struct {
|
||||
sz size.Event
|
||||
images *glutil.Images
|
||||
m *glutil.Image
|
||||
drawer *font.Drawer
|
||||
|
||||
mu sync.Mutex
|
||||
data string
|
||||
}
|
||||
|
||||
func NewLabel(images *glutil.Images) *Label {
|
||||
return &Label{
|
||||
images: images,
|
||||
data: "Hello! Gclip.",
|
||||
drawer: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Label) SetLabel(s string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
l.data = s
|
||||
}
|
||||
|
||||
const (
|
||||
lineWidth = 100
|
||||
lineHeight = 120
|
||||
)
|
||||
|
||||
func (l *Label) Draw(sz size.Event) {
|
||||
l.mu.Lock()
|
||||
s := l.data
|
||||
l.mu.Unlock()
|
||||
imgW, imgH := lineWidth*basicfont.Face7x13.Width, lineHeight*basicfont.Face7x13.Height
|
||||
if sz.WidthPx == 0 && sz.HeightPx == 0 {
|
||||
return
|
||||
}
|
||||
if imgW > sz.WidthPx {
|
||||
imgW = sz.WidthPx
|
||||
}
|
||||
|
||||
if l.sz != sz {
|
||||
l.sz = sz
|
||||
if l.m != nil {
|
||||
l.m.Release()
|
||||
}
|
||||
l.m = l.images.NewImage(imgW, imgH)
|
||||
}
|
||||
// Clear the drawing image.
|
||||
for i := 0; i < len(l.m.RGBA.Pix); i++ {
|
||||
l.m.RGBA.Pix[i] = 0
|
||||
}
|
||||
|
||||
l.drawer = &font.Drawer{
|
||||
Dst: l.m.RGBA,
|
||||
Src: image.NewUniform(color.RGBA{0, 100, 125, 255}),
|
||||
Face: basicfont.Face7x13,
|
||||
Dot: fixed.P(5, 10),
|
||||
}
|
||||
l.drawer.DrawString(s)
|
||||
l.m.Upload()
|
||||
l.m.Draw(
|
||||
sz,
|
||||
geom.Point{X: 0, Y: 50},
|
||||
geom.Point{X: geom.Pt(imgW), Y: 50},
|
||||
geom.Point{X: 0, Y: geom.Pt(imgH)},
|
||||
l.m.RGBA.Bounds(),
|
||||
)
|
||||
}
|
||||
|
||||
func (l *Label) Release() {
|
||||
if l.m != nil {
|
||||
l.m.Release()
|
||||
l.m = nil
|
||||
l.images = nil
|
||||
}
|
||||
}
|
||||
|
||||
// GclipApp is the application instance.
|
||||
type GclipApp struct {
|
||||
app app.App
|
||||
|
||||
ctx gl.Context
|
||||
siz size.Event
|
||||
|
||||
images *glutil.Images
|
||||
l *Label
|
||||
|
||||
counter int
|
||||
}
|
||||
|
||||
// WatchClipboard watches the system clipboard every seconds.
|
||||
func (g *GclipApp) WatchClipboard() {
|
||||
go func() {
|
||||
tk := time.NewTicker(time.Second)
|
||||
for range tk.C {
|
||||
// Write something to the clipboard
|
||||
w := fmt.Sprintf("(gclip: %d)", g.counter)
|
||||
clipboard.Write(clipboard.FmtText, []byte(w))
|
||||
g.counter++
|
||||
log.Println(w)
|
||||
|
||||
// Read it back and render it, if possible.
|
||||
data := clipboard.Read(clipboard.FmtText)
|
||||
if len(data) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Set the current clipboard data as label content and render on the screen.
|
||||
r := fmt.Sprintf("clipboard: %s", string(data))
|
||||
g.l.SetLabel(r)
|
||||
g.app.Send(paint.Event{})
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (g *GclipApp) OnStart(e lifecycle.Event) {
|
||||
g.ctx, _ = e.DrawContext.(gl.Context)
|
||||
g.images = glutil.NewImages(g.ctx)
|
||||
g.l = NewLabel(g.images)
|
||||
g.app.Send(paint.Event{})
|
||||
}
|
||||
|
||||
func (g *GclipApp) OnStop() {
|
||||
g.l.Release()
|
||||
g.images.Release()
|
||||
g.ctx = nil
|
||||
}
|
||||
|
||||
func (g *GclipApp) OnSize(size size.Event) {
|
||||
g.siz = size
|
||||
}
|
||||
|
||||
func (g *GclipApp) OnDraw() {
|
||||
if g.ctx == nil {
|
||||
return
|
||||
}
|
||||
defer g.app.Send(paint.Event{})
|
||||
defer g.app.Publish()
|
||||
g.ctx.ClearColor(0, 0, 0, 1)
|
||||
g.ctx.Clear(gl.COLOR_BUFFER_BIT)
|
||||
g.l.Draw(g.siz)
|
||||
}
|
||||
|
||||
func init() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
app.Main(func(a app.App) {
|
||||
gclip := GclipApp{app: a}
|
||||
gclip.app.Send(size.Event{WidthPx: 800, HeightPx: 500})
|
||||
gclip.WatchClipboard()
|
||||
for e := range gclip.app.Events() {
|
||||
switch e := gclip.app.Filter(e).(type) {
|
||||
case lifecycle.Event:
|
||||
switch e.Crosses(lifecycle.StageVisible) {
|
||||
case lifecycle.CrossOn:
|
||||
gclip.OnStart(e)
|
||||
case lifecycle.CrossOff:
|
||||
gclip.OnStop()
|
||||
os.Exit(0)
|
||||
}
|
||||
case size.Event:
|
||||
gclip.OnSize(e)
|
||||
case paint.Event:
|
||||
gclip.OnDraw()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# gclip
|
||||
|
||||
`gclip` command offers the ability to interact with the system clipboard
|
||||
from the shell. To install:
|
||||
|
||||
```bash
|
||||
$ go install golang.design/x/clipboard/cmd/gclip@latest
|
||||
```
|
||||
|
||||
```bash
|
||||
$ gclip
|
||||
gclip is a command that provides clipboard interaction.
|
||||
usage: gclip [-copy|-paste] [-f <file>]
|
||||
options:
|
||||
-copy
|
||||
copy data to clipboard
|
||||
-f string
|
||||
source or destination to a given file path
|
||||
-paste
|
||||
paste data from clipboard
|
||||
examples:
|
||||
gclip -paste paste from clipboard and prints the content
|
||||
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
|
||||
gclip -paste -f x.png paste from clipboard and save as image to x.png
|
||||
cat x.txt | gclip -copy copy content from x.txt to clipboard
|
||||
gclip -copy -f x.txt copy content from x.txt to clipboard
|
||||
gclip -copy -f x.png copy x.png as image data to clipboard
|
||||
```
|
||||
|
||||
If `-copy` is used, the command will exit when the data is no longer
|
||||
available from the clipboard. You can always send the command to the
|
||||
background using a shell `&` operator, for example:
|
||||
|
||||
```bash
|
||||
$ cat x.txt | gclip -copy &
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT | © 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
|
||||
@@ -0,0 +1,131 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
package main // go install golang.design/x/clipboard/cmd/gclip@latest
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func usage() {
|
||||
fmt.Fprintf(os.Stderr, `gclip is a command that provides clipboard interaction.
|
||||
|
||||
usage: gclip [-copy|-paste] [-f <file>]
|
||||
|
||||
options:
|
||||
`)
|
||||
flag.PrintDefaults()
|
||||
fmt.Fprintf(os.Stderr, `
|
||||
examples:
|
||||
gclip -paste paste from clipboard and prints the content
|
||||
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
|
||||
gclip -paste -f x.png paste from clipboard and save as image to x.png
|
||||
|
||||
cat x.txt | gclip -copy copy content from x.txt to clipboard
|
||||
gclip -copy -f x.txt copy content from x.txt to clipboard
|
||||
gclip -copy -f x.png copy x.png as image data to clipboard
|
||||
`)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
var (
|
||||
in = flag.Bool("copy", false, "copy data to clipboard")
|
||||
out = flag.Bool("paste", false, "paste data from clipboard")
|
||||
file = flag.String("f", "", "source or destination to a given file path")
|
||||
)
|
||||
|
||||
func init() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Usage = usage
|
||||
flag.Parse()
|
||||
if *out {
|
||||
if err := pst(); err != nil {
|
||||
usage()
|
||||
}
|
||||
return
|
||||
}
|
||||
if *in {
|
||||
if err := cpy(); err != nil {
|
||||
usage()
|
||||
}
|
||||
return
|
||||
}
|
||||
usage()
|
||||
}
|
||||
|
||||
func cpy() error {
|
||||
t := clipboard.FmtText
|
||||
ext := filepath.Ext(*file)
|
||||
|
||||
switch ext {
|
||||
case ".png":
|
||||
t = clipboard.FmtImage
|
||||
case ".txt":
|
||||
fallthrough
|
||||
default:
|
||||
t = clipboard.FmtText
|
||||
}
|
||||
|
||||
var (
|
||||
b []byte
|
||||
err error
|
||||
)
|
||||
if *file != "" {
|
||||
b, err = os.ReadFile(*file)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to read given file: %v", err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
b, err = io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to read from stdin: %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Wait until clipboard content has been changed.
|
||||
<-clipboard.Write(t, b)
|
||||
return nil
|
||||
}
|
||||
|
||||
func pst() (err error) {
|
||||
var b []byte
|
||||
|
||||
b = clipboard.Read(clipboard.FmtText)
|
||||
if b == nil {
|
||||
b = clipboard.Read(clipboard.FmtImage)
|
||||
}
|
||||
|
||||
if *file != "" && b != nil {
|
||||
err = os.WriteFile(*file, b, os.ModePerm)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to write data to file %s: %v", *file, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
for len(b) > 0 {
|
||||
n, err := os.Stdout.Write(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
//go:build cgo
|
||||
|
||||
package clipboard_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func ExampleWrite() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
clipboard.Write(clipboard.FmtText, []byte("Hello, 世界"))
|
||||
// Output:
|
||||
}
|
||||
|
||||
func ExampleRead() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println(string(clipboard.Read(clipboard.FmtText)))
|
||||
// Output:
|
||||
// Hello, 世界
|
||||
}
|
||||
|
||||
func ExampleWatch() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
|
||||
defer cancel()
|
||||
|
||||
changed := clipboard.Watch(context.Background(), clipboard.FmtText)
|
||||
go func(ctx context.Context) {
|
||||
clipboard.Write(clipboard.FmtText, []byte("你好,world"))
|
||||
}(ctx)
|
||||
fmt.Println(string(<-changed))
|
||||
// Output:
|
||||
// 你好,world
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2021 The golang.design Initiative Authors.
|
||||
// All rights reserved. Use of this source code is governed
|
||||
// by a MIT license that can be found in the LICENSE file.
|
||||
//
|
||||
// Written by Changkun Ou <changkun.de>
|
||||
|
||||
package clipboard
|
||||
|
||||
// for debugging errors
|
||||
var (
|
||||
Debug = debug
|
||||
ErrUnavailable = errUnavailable
|
||||
ErrCgoDisabled = errNoCgo
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
module golang.design/x/clipboard
|
||||
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
golang.org/x/image v0.28.0
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f
|
||||
)
|
||||
|
||||
require (
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,8 @@
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 h1:Wdx0vgH5Wgsw+lF//LJKmWOJBLWX6nprsMqnf99rYDE=
|
||||
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
|
||||
golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
|
||||
golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f h1:/n+PL2HlfqeSiDCuhdBbRNlGS/g2fM4OHufalHaTVG8=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f/go.mod h1:ESkJ836Z6LpG6mTVAhA48LpfW/8fNR0ifStlH2axyfg=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/bash
|
||||
# Test script for Linux CGO-free clipboard implementation
|
||||
|
||||
echo "Testing Linux clipboard implementation without CGO..."
|
||||
|
||||
# Check for required tools
|
||||
echo "Checking for clipboard tools..."
|
||||
for tool in xclip xsel wl-copy; do
|
||||
if command -v $tool &> /dev/null; then
|
||||
echo "✓ $tool is installed"
|
||||
else
|
||||
echo "✗ $tool is not installed"
|
||||
fi
|
||||
done
|
||||
|
||||
# Create test program
|
||||
cat > test_linux_clipboard.go << 'EOF'
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := clipboard.Init()
|
||||
if err != nil {
|
||||
log.Fatal("Failed to initialize clipboard:", err)
|
||||
}
|
||||
|
||||
// Test text
|
||||
fmt.Println("\n=== Testing Text Clipboard ===")
|
||||
testText := []byte("Hello from CGO-free Linux clipboard!")
|
||||
clipboard.Write(clipboard.FmtText, testText)
|
||||
fmt.Println("Wrote text:", string(testText))
|
||||
|
||||
readText := clipboard.Read(clipboard.FmtText)
|
||||
fmt.Println("Read text:", string(readText))
|
||||
|
||||
if string(testText) == string(readText) {
|
||||
fmt.Println("✓ Text clipboard test passed")
|
||||
} else {
|
||||
fmt.Println("✗ Text clipboard test failed")
|
||||
}
|
||||
|
||||
// Test empty write
|
||||
fmt.Println("\n=== Testing Empty Write ===")
|
||||
clipboard.Write(clipboard.FmtText, []byte{})
|
||||
emptyRead := clipboard.Read(clipboard.FmtText)
|
||||
if emptyRead == nil || len(emptyRead) == 0 {
|
||||
fmt.Println("✓ Empty write test passed")
|
||||
} else {
|
||||
fmt.Println("✗ Empty write test failed, got:", string(emptyRead))
|
||||
}
|
||||
|
||||
// Test image if requested
|
||||
if len(os.Args) > 1 && os.Args[1] == "image" {
|
||||
fmt.Println("\n=== Testing Image Clipboard ===")
|
||||
|
||||
// Try to read test image
|
||||
imageData, err := os.ReadFile("tests/testdata/clipboard.png")
|
||||
if err != nil {
|
||||
fmt.Println("Could not read test image:", err)
|
||||
return
|
||||
}
|
||||
|
||||
clipboard.Write(clipboard.FmtImage, imageData)
|
||||
fmt.Println("Wrote image data, length:", len(imageData))
|
||||
|
||||
readImage := clipboard.Read(clipboard.FmtImage)
|
||||
if readImage != nil {
|
||||
fmt.Println("Read image data, length:", len(readImage))
|
||||
if len(imageData) == len(readImage) {
|
||||
fmt.Println("✓ Image clipboard test passed")
|
||||
} else {
|
||||
fmt.Println("✗ Image lengths don't match")
|
||||
}
|
||||
} else {
|
||||
fmt.Println("✗ Failed to read image from clipboard")
|
||||
}
|
||||
|
||||
// Test that reading text from image clipboard returns nil
|
||||
textFromImage := clipboard.Read(clipboard.FmtText)
|
||||
if textFromImage == nil {
|
||||
fmt.Println("✓ Reading text from image clipboard correctly returned nil")
|
||||
} else {
|
||||
fmt.Println("✗ Reading text from image clipboard should return nil, got:", string(textFromImage))
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
# Run tests with CGO disabled
|
||||
echo -e "\n=== Running with CGO_ENABLED=0 ==="
|
||||
CGO_ENABLED=0 go run test_linux_clipboard.go
|
||||
|
||||
echo -e "\n=== Running with CGO_ENABLED=0 and image test ==="
|
||||
CGO_ENABLED=0 go run test_linux_clipboard.go image
|
||||
|
||||
# Run actual tests
|
||||
echo -e "\n=== Running go test with CGO_ENABLED=0 ==="
|
||||
CGO_ENABLED=0 go test -v -run TestClipboard
|
||||
|
||||
# Clean up
|
||||
rm -f test_linux_clipboard.go
|
||||
|
||||
echo -e "\nTest script completed!"
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2021 The golang.design Initiative Authors.
|
||||
# All rights reserved. Use of this source code is governed
|
||||
# by a MIT license that can be found in the LICENSE file.
|
||||
#
|
||||
# Written by Changkun Ou <changkun.de>
|
||||
|
||||
all: test
|
||||
|
||||
test:
|
||||
go test -v -count=1 -covermode=atomic ..
|
||||
|
||||
test-docker:
|
||||
docker build -t golang-design/x/clipboard ..
|
||||
docker run --rm --name cb golang-design/x/clipboard
|
||||
docker rmi golang-design/x/clipboard
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
# Copyright 2021 The golang.design Initiative Authors.
|
||||
# All rights reserved. Use of this source code is governed
|
||||
# by a MIT license that can be found in the LICENSE file.
|
||||
#
|
||||
# Written by Changkun Ou <changkun.de>
|
||||
|
||||
# require apt-get install xvfb
|
||||
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
|
||||
export DISPLAY=:99.0
|
||||
|
||||
go test -v -covermode=atomic ./...
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 115 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
@@ -9,10 +9,12 @@ import (
|
||||
"strings"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea/v2"
|
||||
flag "github.com/spf13/pflag"
|
||||
"github.com/sst/opencode-sdk-go"
|
||||
"github.com/sst/opencode-sdk-go/option"
|
||||
"github.com/sst/opencode/internal/app"
|
||||
"github.com/sst/opencode/internal/tui"
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
var Version = "dev"
|
||||
@@ -23,6 +25,10 @@ func main() {
|
||||
version = "v" + Version
|
||||
}
|
||||
|
||||
var model *string = flag.String("model", "", "model to begin with")
|
||||
var prompt *string = flag.String("prompt", "", "prompt to begin with")
|
||||
flag.Parse()
|
||||
|
||||
url := os.Getenv("OPENCODE_SERVER")
|
||||
|
||||
appInfoStr := os.Getenv("OPENCODE_APP_INFO")
|
||||
@@ -61,11 +67,18 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
go func() {
|
||||
err = clipboard.Init()
|
||||
if err != nil {
|
||||
slog.Error("Failed to initialize clipboard", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Create main context for the application
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
app_, err := app.New(ctx, version, appInfo, httpClient)
|
||||
app_, err := app.New(ctx, version, appInfo, httpClient, model, prompt)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
+18
-13
@@ -17,11 +17,14 @@ require (
|
||||
github.com/muesli/termenv v0.16.0
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3
|
||||
github.com/sst/opencode-sdk-go v0.1.0-alpha.8
|
||||
github.com/tidwall/gjson v1.14.4
|
||||
golang.design/x/clipboard v0.7.1
|
||||
rsc.io/qr v0.2.0
|
||||
)
|
||||
|
||||
replace github.com/sst/opencode-sdk-go => ./sdk
|
||||
replace (
|
||||
github.com/sst/opencode-sdk-go => ./sdk
|
||||
golang.design/x/clipboard => ./clipboard
|
||||
)
|
||||
|
||||
require golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
|
||||
|
||||
@@ -50,23 +53,25 @@ require (
|
||||
github.com/sosodev/duration v1.3.1 // indirect
|
||||
github.com/speakeasy-api/openapi-overlay v0.9.0 // indirect
|
||||
github.com/spf13/cobra v1.9.1 // indirect
|
||||
github.com/tidwall/gjson v1.14.4 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
|
||||
golang.org/x/mod v0.24.0 // indirect
|
||||
golang.org/x/tools v0.31.0 // indirect
|
||||
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f // indirect
|
||||
golang.org/x/mod v0.25.0 // indirect
|
||||
golang.org/x/tools v0.34.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.4
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.3.1 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.14-0.20250501183327-ad3bc78c6a81 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/dlclark/regexp2 v1.11.5 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
@@ -78,16 +83,16 @@ require (
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/rivo/uniseg v0.4.7
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/spf13/pflag v1.0.6
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
github.com/yuin/goldmark v1.7.8 // indirect
|
||||
github.com/yuin/goldmark-emoji v1.0.5 // indirect
|
||||
golang.org/x/image v0.26.0
|
||||
golang.org/x/net v0.39.0 // indirect
|
||||
golang.org/x/sync v0.13.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
golang.org/x/term v0.31.0 // indirect
|
||||
golang.org/x/text v0.24.0
|
||||
golang.org/x/image v0.28.0 // indirect
|
||||
golang.org/x/net v0.41.0 // indirect
|
||||
golang.org/x/sync v0.15.0 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/term v0.32.0 // indirect
|
||||
golang.org/x/text v0.26.0
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
|
||||
+20
-19
@@ -54,8 +54,6 @@ github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
||||
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58=
|
||||
@@ -218,14 +216,17 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
|
||||
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
|
||||
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c=
|
||||
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b h1:zELBzk+7ERc6m8BxhzU2VYjp03wlEvi+cIgYQR5H3CI=
|
||||
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
|
||||
golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
|
||||
golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f h1:/n+PL2HlfqeSiDCuhdBbRNlGS/g2fM4OHufalHaTVG8=
|
||||
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f/go.mod h1:ESkJ836Z6LpG6mTVAhA48LpfW/8fNR0ifStlH2axyfg=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
|
||||
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
@@ -236,15 +237,15 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT
|
||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
|
||||
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
|
||||
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
|
||||
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -263,28 +264,28 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
|
||||
golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
|
||||
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
|
||||
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
|
||||
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -18,20 +18,24 @@ import (
|
||||
"github.com/sst/opencode/internal/styles"
|
||||
"github.com/sst/opencode/internal/theme"
|
||||
"github.com/sst/opencode/internal/util"
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Info opencode.App
|
||||
Version string
|
||||
StatePath string
|
||||
Config *opencode.Config
|
||||
Client *opencode.Client
|
||||
State *config.State
|
||||
Provider *opencode.Provider
|
||||
Model *opencode.Model
|
||||
Session *opencode.Session
|
||||
Messages []opencode.MessageUnion
|
||||
Commands commands.CommandRegistry
|
||||
Info opencode.App
|
||||
Version string
|
||||
StatePath string
|
||||
Config *opencode.Config
|
||||
Client *opencode.Client
|
||||
State *config.State
|
||||
Provider *opencode.Provider
|
||||
Model *opencode.Model
|
||||
Session *opencode.Session
|
||||
Messages []opencode.MessageUnion
|
||||
Commands commands.CommandRegistry
|
||||
InitialModel *string
|
||||
InitialPrompt *string
|
||||
compactCancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SessionSelectedMsg = *opencode.Session
|
||||
@@ -58,6 +62,8 @@ func New(
|
||||
version string,
|
||||
appInfo opencode.App,
|
||||
httpClient *opencode.Client,
|
||||
model *string,
|
||||
prompt *string,
|
||||
) (*App, error) {
|
||||
util.RootPath = appInfo.Path.Root
|
||||
util.CwdPath = appInfo.Path.Cwd
|
||||
@@ -109,15 +115,17 @@ func New(
|
||||
slog.Debug("Loaded config", "config", configInfo)
|
||||
|
||||
app := &App{
|
||||
Info: appInfo,
|
||||
Version: version,
|
||||
StatePath: appStatePath,
|
||||
Config: configInfo,
|
||||
State: appState,
|
||||
Client: httpClient,
|
||||
Session: &opencode.Session{},
|
||||
Messages: []opencode.MessageUnion{},
|
||||
Commands: commands.LoadFromConfig(configInfo),
|
||||
Info: appInfo,
|
||||
Version: version,
|
||||
StatePath: appStatePath,
|
||||
Config: configInfo,
|
||||
State: appState,
|
||||
Client: httpClient,
|
||||
Session: &opencode.Session{},
|
||||
Messages: []opencode.MessageUnion{},
|
||||
Commands: commands.LoadFromConfig(configInfo),
|
||||
InitialModel: model,
|
||||
InitialPrompt: prompt,
|
||||
}
|
||||
|
||||
return app, nil
|
||||
@@ -140,66 +148,102 @@ func (a *App) Key(commandName commands.CommandName) string {
|
||||
return base(key) + muted(" "+command.Description)
|
||||
}
|
||||
|
||||
func (a *App) SetClipboard(text string) tea.Cmd {
|
||||
var cmds []tea.Cmd
|
||||
cmds = append(cmds, func() tea.Msg {
|
||||
clipboard.Write(clipboard.FmtText, []byte(text))
|
||||
return nil
|
||||
})
|
||||
// try to set the clipboard using OSC52 for terminals that support it
|
||||
cmds = append(cmds, tea.SetClipboard(text))
|
||||
return tea.Sequence(cmds...)
|
||||
}
|
||||
|
||||
func (a *App) InitializeProvider() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
providersResponse, err := a.Client.Config.Providers(context.Background())
|
||||
if err != nil {
|
||||
slog.Error("Failed to list providers", "error", err)
|
||||
// TODO: notify user
|
||||
return nil
|
||||
}
|
||||
providers := providersResponse.Providers
|
||||
var defaultProvider *opencode.Provider
|
||||
var defaultModel *opencode.Model
|
||||
providersResponse, err := a.Client.Config.Providers(context.Background())
|
||||
if err != nil {
|
||||
slog.Error("Failed to list providers", "error", err)
|
||||
// TODO: notify user
|
||||
return nil
|
||||
}
|
||||
providers := providersResponse.Providers
|
||||
var defaultProvider *opencode.Provider
|
||||
var defaultModel *opencode.Model
|
||||
|
||||
var anthropic *opencode.Provider
|
||||
for _, provider := range providers {
|
||||
if provider.ID == "anthropic" {
|
||||
anthropic = &provider
|
||||
var anthropic *opencode.Provider
|
||||
for _, provider := range providers {
|
||||
if provider.ID == "anthropic" {
|
||||
anthropic = &provider
|
||||
}
|
||||
}
|
||||
|
||||
// default to anthropic if available
|
||||
if anthropic != nil {
|
||||
defaultProvider = anthropic
|
||||
defaultModel = getDefaultModel(providersResponse, *anthropic)
|
||||
}
|
||||
|
||||
for _, provider := range providers {
|
||||
if defaultProvider == nil || defaultModel == nil {
|
||||
defaultProvider = &provider
|
||||
defaultModel = getDefaultModel(providersResponse, provider)
|
||||
}
|
||||
providers = append(providers, provider)
|
||||
}
|
||||
if len(providers) == 0 {
|
||||
slog.Error("No providers configured")
|
||||
return nil
|
||||
}
|
||||
|
||||
var currentProvider *opencode.Provider
|
||||
var currentModel *opencode.Model
|
||||
for _, provider := range providers {
|
||||
if provider.ID == a.State.Provider {
|
||||
currentProvider = &provider
|
||||
|
||||
for _, model := range provider.Models {
|
||||
if model.ID == a.State.Model {
|
||||
currentModel = &model
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if currentProvider == nil || currentModel == nil {
|
||||
currentProvider = defaultProvider
|
||||
currentModel = defaultModel
|
||||
}
|
||||
|
||||
// default to anthropic if available
|
||||
if anthropic != nil {
|
||||
defaultProvider = anthropic
|
||||
defaultModel = getDefaultModel(providersResponse, *anthropic)
|
||||
}
|
||||
|
||||
var initialProvider *opencode.Provider
|
||||
var initialModel *opencode.Model
|
||||
if a.InitialModel != nil && *a.InitialModel != "" {
|
||||
splits := strings.Split(*a.InitialModel, "/")
|
||||
for _, provider := range providers {
|
||||
if defaultProvider == nil || defaultModel == nil {
|
||||
defaultProvider = &provider
|
||||
defaultModel = getDefaultModel(providersResponse, provider)
|
||||
}
|
||||
providers = append(providers, provider)
|
||||
}
|
||||
if len(providers) == 0 {
|
||||
slog.Error("No providers configured")
|
||||
return nil
|
||||
}
|
||||
|
||||
var currentProvider *opencode.Provider
|
||||
var currentModel *opencode.Model
|
||||
for _, provider := range providers {
|
||||
if provider.ID == a.State.Provider {
|
||||
currentProvider = &provider
|
||||
|
||||
if provider.ID == splits[0] {
|
||||
initialProvider = &provider
|
||||
for _, model := range provider.Models {
|
||||
if model.ID == a.State.Model {
|
||||
currentModel = &model
|
||||
modelID := strings.Join(splits[1:], "/")
|
||||
if model.ID == modelID {
|
||||
initialModel = &model
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if currentProvider == nil || currentModel == nil {
|
||||
currentProvider = defaultProvider
|
||||
currentModel = defaultModel
|
||||
}
|
||||
|
||||
return ModelSelectedMsg{
|
||||
Provider: *currentProvider,
|
||||
Model: *currentModel,
|
||||
}
|
||||
}
|
||||
|
||||
if initialProvider != nil && initialModel != nil {
|
||||
currentProvider = initialProvider
|
||||
currentModel = initialModel
|
||||
}
|
||||
|
||||
var cmds []tea.Cmd
|
||||
cmds = append(cmds, util.CmdHandler(ModelSelectedMsg{
|
||||
Provider: *currentProvider,
|
||||
Model: *currentModel,
|
||||
}))
|
||||
if a.InitialPrompt != nil && *a.InitialPrompt != "" {
|
||||
cmds = append(cmds, util.CmdHandler(SendMsg{Text: *a.InitialPrompt}))
|
||||
}
|
||||
return tea.Sequence(cmds...)
|
||||
}
|
||||
|
||||
func getDefaultModel(
|
||||
@@ -263,13 +307,26 @@ func (a *App) InitializeProject(ctx context.Context) tea.Cmd {
|
||||
}
|
||||
|
||||
func (a *App) CompactSession(ctx context.Context) tea.Cmd {
|
||||
if a.compactCancel != nil {
|
||||
a.compactCancel()
|
||||
}
|
||||
|
||||
compactCtx, cancel := context.WithCancel(ctx)
|
||||
a.compactCancel = cancel
|
||||
|
||||
go func() {
|
||||
_, err := a.Client.Session.Summarize(ctx, a.Session.ID, opencode.SessionSummarizeParams{
|
||||
defer func() {
|
||||
a.compactCancel = nil
|
||||
}()
|
||||
|
||||
_, err := a.Client.Session.Summarize(compactCtx, a.Session.ID, opencode.SessionSummarizeParams{
|
||||
ProviderID: opencode.F(a.Provider.ID),
|
||||
ModelID: opencode.F(a.Model.ID),
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("Failed to compact session", "error", err)
|
||||
if compactCtx.Err() != context.Canceled {
|
||||
slog.Error("Failed to compact session", "error", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
@@ -372,6 +429,12 @@ func (a *App) SendChatMessage(
|
||||
}
|
||||
|
||||
func (a *App) Cancel(ctx context.Context, sessionID string) error {
|
||||
// Cancel any running compact operation
|
||||
if a.compactCancel != nil {
|
||||
a.compactCancel()
|
||||
a.compactCancel = nil
|
||||
}
|
||||
|
||||
_, err := a.Client.Session.Abort(ctx, sessionID)
|
||||
if err != nil {
|
||||
slog.Error("Failed to cancel session", "error", err)
|
||||
|
||||
@@ -29,7 +29,7 @@ type Command struct {
|
||||
Name CommandName
|
||||
Description string
|
||||
Keybindings []Keybinding
|
||||
Trigger string
|
||||
Trigger []string
|
||||
}
|
||||
|
||||
func (c Command) Keys() []string {
|
||||
@@ -40,6 +40,21 @@ func (c Command) Keys() []string {
|
||||
return keys
|
||||
}
|
||||
|
||||
func (c Command) HasTrigger() bool {
|
||||
return len(c.Trigger) > 0
|
||||
}
|
||||
|
||||
func (c Command) PrimaryTrigger() string {
|
||||
if len(c.Trigger) > 0 {
|
||||
return c.Trigger[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c Command) MatchesTrigger(trigger string) bool {
|
||||
return slices.Contains(c.Trigger, trigger)
|
||||
}
|
||||
|
||||
type CommandRegistry map[CommandName]Command
|
||||
|
||||
func (r CommandRegistry) Sorted() []Command {
|
||||
@@ -135,37 +150,37 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
Name: AppHelpCommand,
|
||||
Description: "show help",
|
||||
Keybindings: parseBindings("<leader>h"),
|
||||
Trigger: "help",
|
||||
Trigger: []string{"help"},
|
||||
},
|
||||
{
|
||||
Name: EditorOpenCommand,
|
||||
Description: "open editor",
|
||||
Keybindings: parseBindings("<leader>e"),
|
||||
Trigger: "editor",
|
||||
Trigger: []string{"editor"},
|
||||
},
|
||||
{
|
||||
Name: SessionNewCommand,
|
||||
Description: "new session",
|
||||
Keybindings: parseBindings("<leader>n"),
|
||||
Trigger: "new",
|
||||
Trigger: []string{"new", "clear"},
|
||||
},
|
||||
{
|
||||
Name: SessionListCommand,
|
||||
Description: "list sessions",
|
||||
Keybindings: parseBindings("<leader>l"),
|
||||
Trigger: "sessions",
|
||||
Trigger: []string{"sessions", "resume", "continue"},
|
||||
},
|
||||
{
|
||||
Name: SessionShareCommand,
|
||||
Description: "share session",
|
||||
Keybindings: parseBindings("<leader>s"),
|
||||
Trigger: "share",
|
||||
Trigger: []string{"share"},
|
||||
},
|
||||
{
|
||||
Name: SessionUnshareCommand,
|
||||
Description: "unshare session",
|
||||
Keybindings: parseBindings("<leader>u"),
|
||||
Trigger: "unshare",
|
||||
Trigger: []string{"unshare"},
|
||||
},
|
||||
{
|
||||
Name: SessionInterruptCommand,
|
||||
@@ -176,31 +191,31 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
Name: SessionCompactCommand,
|
||||
Description: "compact the session",
|
||||
Keybindings: parseBindings("<leader>c"),
|
||||
Trigger: "compact",
|
||||
Trigger: []string{"compact", "summarize"},
|
||||
},
|
||||
{
|
||||
Name: ToolDetailsCommand,
|
||||
Description: "toggle tool details",
|
||||
Keybindings: parseBindings("<leader>d"),
|
||||
Trigger: "details",
|
||||
Trigger: []string{"details"},
|
||||
},
|
||||
{
|
||||
Name: ModelListCommand,
|
||||
Description: "list models",
|
||||
Keybindings: parseBindings("<leader>m"),
|
||||
Trigger: "models",
|
||||
Trigger: []string{"models"},
|
||||
},
|
||||
{
|
||||
Name: ThemeListCommand,
|
||||
Description: "list themes",
|
||||
Keybindings: parseBindings("<leader>t"),
|
||||
Trigger: "themes",
|
||||
Trigger: []string{"themes"},
|
||||
},
|
||||
{
|
||||
Name: FileListCommand,
|
||||
Description: "list files",
|
||||
Keybindings: parseBindings("<leader>f"),
|
||||
Trigger: "files",
|
||||
Trigger: []string{"files"},
|
||||
},
|
||||
{
|
||||
Name: FileCloseCommand,
|
||||
@@ -221,7 +236,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
Name: ProjectInitCommand,
|
||||
Description: "create/update AGENTS.md",
|
||||
Keybindings: parseBindings("<leader>i"),
|
||||
Trigger: "init",
|
||||
Trigger: []string{"init"},
|
||||
},
|
||||
{
|
||||
Name: InputClearCommand,
|
||||
@@ -231,7 +246,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
{
|
||||
Name: InputPasteCommand,
|
||||
Description: "paste content",
|
||||
Keybindings: parseBindings("ctrl+v"),
|
||||
Keybindings: parseBindings("ctrl+v", "super+v"),
|
||||
},
|
||||
{
|
||||
Name: InputSubmitCommand,
|
||||
@@ -302,7 +317,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
Name: AppExitCommand,
|
||||
Description: "exit the app",
|
||||
Keybindings: parseBindings("ctrl+c", "<leader>q"),
|
||||
Trigger: "exit",
|
||||
Trigger: []string{"exit", "quit"},
|
||||
},
|
||||
}
|
||||
registry := make(CommandRegistry)
|
||||
|
||||
@@ -31,7 +31,7 @@ func (c *CommandCompletionProvider) GetEmptyMessage() string {
|
||||
|
||||
func getCommandCompletionItem(cmd commands.Command, space int, t theme.Theme) dialog.CompletionItemI {
|
||||
spacer := strings.Repeat(" ", space)
|
||||
title := " /" + cmd.Trigger + styles.NewStyle().Foreground(t.TextMuted()).Render(spacer+cmd.Description)
|
||||
title := " /" + cmd.PrimaryTrigger() + styles.NewStyle().Foreground(t.TextMuted()).Render(spacer+cmd.Description)
|
||||
value := string(cmd.Name)
|
||||
return dialog.NewCompletionItem(dialog.CompletionItem{
|
||||
Title: title,
|
||||
@@ -45,8 +45,8 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp
|
||||
|
||||
space := 1
|
||||
for _, cmd := range c.app.Commands {
|
||||
if lipgloss.Width(cmd.Trigger) > space {
|
||||
space = lipgloss.Width(cmd.Trigger)
|
||||
if cmd.HasTrigger() && lipgloss.Width(cmd.PrimaryTrigger()) > space {
|
||||
space = lipgloss.Width(cmd.PrimaryTrigger())
|
||||
}
|
||||
}
|
||||
space += 2
|
||||
@@ -56,10 +56,10 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp
|
||||
// If no query, return all commands
|
||||
items := []dialog.CompletionItemI{}
|
||||
for _, cmd := range sorted {
|
||||
if cmd.Trigger == "" {
|
||||
if !cmd.HasTrigger() {
|
||||
continue
|
||||
}
|
||||
space := space - lipgloss.Width(cmd.Trigger)
|
||||
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
||||
items = append(items, getCommandCompletionItem(cmd, space, t))
|
||||
}
|
||||
return items, nil
|
||||
@@ -70,12 +70,15 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp
|
||||
commandMap := make(map[string]dialog.CompletionItemI)
|
||||
|
||||
for _, cmd := range sorted {
|
||||
if cmd.Trigger == "" {
|
||||
if !cmd.HasTrigger() {
|
||||
continue
|
||||
}
|
||||
space := space - lipgloss.Width(cmd.Trigger)
|
||||
commandNames = append(commandNames, cmd.Trigger)
|
||||
commandMap[cmd.Trigger] = getCommandCompletionItem(cmd, space, t)
|
||||
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
||||
// Add all triggers as searchable options
|
||||
for _, trigger := range cmd.Trigger {
|
||||
commandNames = append(commandNames, trigger)
|
||||
commandMap[trigger] = getCommandCompletionItem(cmd, space, t)
|
||||
}
|
||||
}
|
||||
|
||||
// Find fuzzy matches
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/v2/spinner"
|
||||
@@ -15,10 +18,10 @@ import (
|
||||
"github.com/sst/opencode/internal/commands"
|
||||
"github.com/sst/opencode/internal/components/dialog"
|
||||
"github.com/sst/opencode/internal/components/textarea"
|
||||
"github.com/sst/opencode/internal/image"
|
||||
"github.com/sst/opencode/internal/styles"
|
||||
"github.com/sst/opencode/internal/theme"
|
||||
"github.com/sst/opencode/internal/util"
|
||||
"golang.design/x/clipboard"
|
||||
)
|
||||
|
||||
type EditorComponent interface {
|
||||
@@ -27,6 +30,7 @@ type EditorComponent interface {
|
||||
Content(width int) string
|
||||
Lines() int
|
||||
Value() string
|
||||
Length() int
|
||||
Focused() bool
|
||||
Focus() (tea.Model, tea.Cmd)
|
||||
Blur()
|
||||
@@ -35,6 +39,7 @@ type EditorComponent interface {
|
||||
Paste() (tea.Model, tea.Cmd)
|
||||
Newline() (tea.Model, tea.Cmd)
|
||||
SetInterruptKeyInDebounce(inDebounce bool)
|
||||
SetExitKeyInDebounce(inDebounce bool)
|
||||
}
|
||||
|
||||
type editorComponent struct {
|
||||
@@ -42,6 +47,7 @@ type editorComponent struct {
|
||||
textarea textarea.Model
|
||||
spinner spinner.Model
|
||||
interruptKeyInDebounce bool
|
||||
exitKeyInDebounce bool
|
||||
}
|
||||
|
||||
func (m *editorComponent) Init() tea.Cmd {
|
||||
@@ -63,8 +69,65 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
cmds = append(cmds, cmd)
|
||||
return m, tea.Batch(cmds...)
|
||||
}
|
||||
case tea.PasteMsg:
|
||||
text := string(msg)
|
||||
text = strings.ReplaceAll(text, "\\", "")
|
||||
text, err := strconv.Unquote(`"` + text + `"`)
|
||||
if err != nil {
|
||||
slog.Error("Failed to unquote text", "error", err)
|
||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
||||
return m, nil
|
||||
}
|
||||
if _, err := os.Stat(text); err != nil {
|
||||
slog.Error("Failed to paste file", "error", err)
|
||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
||||
return m, nil
|
||||
}
|
||||
|
||||
filePath := text
|
||||
ext := strings.ToLower(filepath.Ext(filePath))
|
||||
|
||||
mediaType := ""
|
||||
switch ext {
|
||||
case ".jpg":
|
||||
mediaType = "image/jpeg"
|
||||
case ".png", ".jpeg", ".gif", ".webp":
|
||||
mediaType = "image/" + ext[1:]
|
||||
case ".pdf":
|
||||
mediaType = "application/pdf"
|
||||
default:
|
||||
mediaType = "text/plain"
|
||||
}
|
||||
|
||||
fileBytes, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
slog.Error("Failed to read file", "error", err)
|
||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
||||
return m, nil
|
||||
}
|
||||
base64EncodedFile := base64.StdEncoding.EncodeToString(fileBytes)
|
||||
url := fmt.Sprintf("data:%s;base64,%s", mediaType, base64EncodedFile)
|
||||
attachmentCount := len(m.textarea.GetAttachments())
|
||||
attachmentIndex := attachmentCount + 1
|
||||
label := "File"
|
||||
if strings.HasPrefix(mediaType, "image/") {
|
||||
label = "Image"
|
||||
}
|
||||
|
||||
attachment := &textarea.Attachment{
|
||||
ID: uuid.NewString(),
|
||||
MediaType: mediaType,
|
||||
Display: fmt.Sprintf("[%s #%d]", label, attachmentIndex),
|
||||
URL: url,
|
||||
Filename: filePath,
|
||||
}
|
||||
m.textarea.InsertAttachment(attachment)
|
||||
m.textarea.InsertString(" ")
|
||||
case tea.ClipboardMsg:
|
||||
text := string(msg)
|
||||
m.textarea.InsertRunesFromUserInput([]rune(text))
|
||||
case dialog.ThemeSelectedMsg:
|
||||
m.textarea = createTextArea(&m.textarea)
|
||||
m.textarea = m.resetTextareaStyles()
|
||||
m.spinner = createSpinner()
|
||||
return m, tea.Batch(m.spinner.Tick, m.textarea.Focus())
|
||||
case dialog.CompletionSelectedMsg:
|
||||
@@ -164,7 +227,10 @@ func (m *editorComponent) Content(width int) string {
|
||||
Render(textarea)
|
||||
|
||||
hint := base(m.getSubmitKeyText()) + muted(" send ")
|
||||
if m.app.IsBusy() {
|
||||
if m.exitKeyInDebounce {
|
||||
keyText := m.getExitKeyText()
|
||||
hint = base(keyText+" again") + muted(" to exit")
|
||||
} else if m.app.IsBusy() {
|
||||
keyText := m.getInterruptKeyText()
|
||||
if m.interruptKeyInDebounce {
|
||||
hint = muted(
|
||||
@@ -230,6 +296,10 @@ func (m *editorComponent) Value() string {
|
||||
return m.textarea.Value()
|
||||
}
|
||||
|
||||
func (m *editorComponent) Length() int {
|
||||
return m.textarea.Length()
|
||||
}
|
||||
|
||||
func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
|
||||
value := strings.TrimSpace(m.Value())
|
||||
if value == "" {
|
||||
@@ -269,24 +339,31 @@ func (m *editorComponent) Clear() (tea.Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
func (m *editorComponent) Paste() (tea.Model, tea.Cmd) {
|
||||
_, text, err := image.GetImageFromClipboard()
|
||||
if err != nil {
|
||||
slog.Error(err.Error())
|
||||
imageBytes := clipboard.Read(clipboard.FmtImage)
|
||||
if imageBytes != nil {
|
||||
attachmentCount := len(m.textarea.GetAttachments())
|
||||
attachmentIndex := attachmentCount + 1
|
||||
base64EncodedFile := base64.StdEncoding.EncodeToString(imageBytes)
|
||||
attachment := &textarea.Attachment{
|
||||
ID: uuid.NewString(),
|
||||
MediaType: "image/png",
|
||||
Display: fmt.Sprintf("[Image #%d]", attachmentIndex),
|
||||
Filename: fmt.Sprintf("image-%d.png", attachmentIndex),
|
||||
URL: fmt.Sprintf("data:image/png;base64,%s", base64EncodedFile),
|
||||
}
|
||||
m.textarea.InsertAttachment(attachment)
|
||||
m.textarea.InsertString(" ")
|
||||
return m, nil
|
||||
}
|
||||
// if len(imageBytes) != 0 {
|
||||
// attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
|
||||
// attachment := app.Attachment{
|
||||
// FilePath: attachmentName,
|
||||
// FileName: attachmentName,
|
||||
// Content: imageBytes,
|
||||
// MimeType: "image/png",
|
||||
// }
|
||||
// m.attachments = append(m.attachments, attachment)
|
||||
// } else {
|
||||
m.textarea.InsertString(text)
|
||||
// }
|
||||
return m, nil
|
||||
|
||||
textBytes := clipboard.Read(clipboard.FmtText)
|
||||
if textBytes != nil {
|
||||
m.textarea.InsertRunesFromUserInput([]rune(string(textBytes)))
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// fallback to reading the clipboard using OSC52
|
||||
return m, tea.ReadClipboard
|
||||
}
|
||||
|
||||
func (m *editorComponent) Newline() (tea.Model, tea.Cmd) {
|
||||
@@ -298,6 +375,10 @@ func (m *editorComponent) SetInterruptKeyInDebounce(inDebounce bool) {
|
||||
m.interruptKeyInDebounce = inDebounce
|
||||
}
|
||||
|
||||
func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
|
||||
m.exitKeyInDebounce = inDebounce
|
||||
}
|
||||
|
||||
func (m *editorComponent) getInterruptKeyText() string {
|
||||
return m.app.Commands[commands.SessionInterruptCommand].Keys()[0]
|
||||
}
|
||||
@@ -306,13 +387,17 @@ func (m *editorComponent) getSubmitKeyText() string {
|
||||
return m.app.Commands[commands.InputSubmitCommand].Keys()[0]
|
||||
}
|
||||
|
||||
func createTextArea(existing *textarea.Model) textarea.Model {
|
||||
func (m *editorComponent) getExitKeyText() string {
|
||||
return m.app.Commands[commands.AppExitCommand].Keys()[0]
|
||||
}
|
||||
|
||||
func (m *editorComponent) resetTextareaStyles() textarea.Model {
|
||||
t := theme.CurrentTheme()
|
||||
bgColor := t.BackgroundElement()
|
||||
textColor := t.Text()
|
||||
textMutedColor := t.TextMuted()
|
||||
|
||||
ta := textarea.New()
|
||||
ta := m.textarea
|
||||
|
||||
ta.Styles.Blurred.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
|
||||
ta.Styles.Blurred.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss()
|
||||
@@ -337,17 +422,6 @@ func createTextArea(existing *textarea.Model) textarea.Model {
|
||||
Background(t.Secondary()).
|
||||
Lipgloss()
|
||||
ta.Styles.Cursor.Color = t.Primary()
|
||||
|
||||
ta.Prompt = " "
|
||||
ta.ShowLineNumbers = false
|
||||
ta.CharLimit = -1
|
||||
|
||||
if existing != nil {
|
||||
ta.SetValue(existing.Value())
|
||||
// ta.SetWidth(existing.Width())
|
||||
ta.SetHeight(existing.Height())
|
||||
}
|
||||
|
||||
return ta
|
||||
}
|
||||
|
||||
@@ -367,12 +441,19 @@ func createSpinner() spinner.Model {
|
||||
|
||||
func NewEditorComponent(app *app.App) EditorComponent {
|
||||
s := createSpinner()
|
||||
ta := createTextArea(nil)
|
||||
|
||||
return &editorComponent{
|
||||
ta := textarea.New()
|
||||
ta.Prompt = " "
|
||||
ta.ShowLineNumbers = false
|
||||
ta.CharLimit = -1
|
||||
|
||||
m := &editorComponent{
|
||||
app: app,
|
||||
textarea: ta,
|
||||
spinner: s,
|
||||
interruptKeyInDebounce: false,
|
||||
}
|
||||
m.resetTextareaStyles()
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -422,6 +422,8 @@ func renderToolDetails(
|
||||
switch todo["status"] {
|
||||
case "completed":
|
||||
body += fmt.Sprintf("- [x] %s\n", content)
|
||||
case "cancelled":
|
||||
body += fmt.Sprintf("- [~] %s\n", content)
|
||||
// case "in-progress":
|
||||
// body += fmt.Sprintf("- [ ] %s\n", content)
|
||||
default:
|
||||
|
||||
@@ -56,8 +56,8 @@ func (c *commandsComponent) View() string {
|
||||
var untriggeredCommands []commands.Command
|
||||
|
||||
for _, cmd := range c.app.Commands.Sorted() {
|
||||
if c.showAll || cmd.Trigger != "" {
|
||||
if cmd.Trigger != "" {
|
||||
if c.showAll || cmd.HasTrigger() {
|
||||
if cmd.HasTrigger() {
|
||||
triggeredCommands = append(triggeredCommands, cmd)
|
||||
} else if c.showAll {
|
||||
untriggeredCommands = append(untriggeredCommands, cmd)
|
||||
@@ -97,8 +97,8 @@ func (c *commandsComponent) View() string {
|
||||
|
||||
for _, cmd := range commandsToShow {
|
||||
trigger := ""
|
||||
if cmd.Trigger != "" {
|
||||
trigger = "/" + cmd.Trigger
|
||||
if cmd.HasTrigger() {
|
||||
trigger = "/" + cmd.PrimaryTrigger()
|
||||
} else {
|
||||
trigger = string(cmd.Name)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"slices"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
"github.com/charmbracelet/bubbles/v2/cursor"
|
||||
"github.com/charmbracelet/bubbles/v2/key"
|
||||
tea "github.com/charmbracelet/bubbletea/v2"
|
||||
@@ -653,12 +652,12 @@ func (m *Model) SetValue(s string) {
|
||||
|
||||
// InsertString inserts a string at the cursor position.
|
||||
func (m *Model) InsertString(s string) {
|
||||
m.insertRunesFromUserInput([]rune(s))
|
||||
m.InsertRunesFromUserInput([]rune(s))
|
||||
}
|
||||
|
||||
// InsertRune inserts a rune at the cursor position.
|
||||
func (m *Model) InsertRune(r rune) {
|
||||
m.insertRunesFromUserInput([]rune{r})
|
||||
m.InsertRunesFromUserInput([]rune{r})
|
||||
}
|
||||
|
||||
// InsertAttachment inserts an attachment at the cursor position.
|
||||
@@ -730,8 +729,8 @@ func (m Model) GetAttachments() []*Attachment {
|
||||
return attachments
|
||||
}
|
||||
|
||||
// insertRunesFromUserInput inserts runes at the current cursor position.
|
||||
func (m *Model) insertRunesFromUserInput(runes []rune) {
|
||||
// InsertRunesFromUserInput inserts runes at the current cursor position.
|
||||
func (m *Model) InsertRunesFromUserInput(runes []rune) {
|
||||
// Clean up any special characters in the input provided by the
|
||||
// clipboard. This avoids bugs due to e.g. tab characters and
|
||||
// whatnot.
|
||||
@@ -1429,8 +1428,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.PasteMsg:
|
||||
m.insertRunesFromUserInput([]rune(msg))
|
||||
case tea.KeyPressMsg:
|
||||
switch {
|
||||
case key.Matches(msg, m.KeyMap.DeleteAfterCursor):
|
||||
@@ -1490,8 +1487,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
m.CursorDown()
|
||||
case key.Matches(msg, m.KeyMap.WordForward):
|
||||
m.wordRight()
|
||||
case key.Matches(msg, m.KeyMap.Paste):
|
||||
return m, Paste
|
||||
case key.Matches(msg, m.KeyMap.CharacterBackward):
|
||||
m.characterLeft(false /* insideLine */)
|
||||
case key.Matches(msg, m.KeyMap.LinePrevious):
|
||||
@@ -1512,11 +1507,11 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
m.transposeLeft()
|
||||
|
||||
default:
|
||||
m.insertRunesFromUserInput([]rune(msg.Text))
|
||||
m.InsertRunesFromUserInput([]rune(msg.Text))
|
||||
}
|
||||
|
||||
case pasteMsg:
|
||||
m.insertRunesFromUserInput([]rune(msg))
|
||||
m.InsertRunesFromUserInput([]rune(msg))
|
||||
|
||||
case pasteErrMsg:
|
||||
m.Err = msg
|
||||
@@ -1908,15 +1903,6 @@ func (m *Model) splitLine(row, col int) {
|
||||
m.row++
|
||||
}
|
||||
|
||||
// Paste is a command for pasting from the clipboard into the text input.
|
||||
func Paste() tea.Msg {
|
||||
str, err := clipboard.ReadAll()
|
||||
if err != nil {
|
||||
return pasteErrMsg{err}
|
||||
}
|
||||
return pasteMsg(str)
|
||||
}
|
||||
|
||||
func wrapInterfaces(content []any, width int) [][]any {
|
||||
if width <= 0 {
|
||||
return [][]any{content}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package image
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/atotto/clipboard"
|
||||
"image"
|
||||
)
|
||||
|
||||
func GetImageFromClipboard() ([]byte, string, error) {
|
||||
text, err := clipboard.ReadAll()
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("Error reading clipboard")
|
||||
}
|
||||
|
||||
if text == "" {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
binaryData := []byte(text)
|
||||
imageBytes, err := binaryToImage(binaryData)
|
||||
if err != nil {
|
||||
return nil, text, nil
|
||||
}
|
||||
return imageBytes, "", nil
|
||||
|
||||
}
|
||||
|
||||
func binaryToImage(data []byte) ([]byte, error) {
|
||||
reader := bytes.NewReader(data)
|
||||
img, _, err := image.Decode(reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to covert bytes to image")
|
||||
}
|
||||
|
||||
return ImageToBytes(img)
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package image
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"log/slog"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
openClipboard = user32.NewProc("OpenClipboard")
|
||||
closeClipboard = user32.NewProc("CloseClipboard")
|
||||
getClipboardData = user32.NewProc("GetClipboardData")
|
||||
isClipboardFormatAvailable = user32.NewProc("IsClipboardFormatAvailable")
|
||||
globalLock = kernel32.NewProc("GlobalLock")
|
||||
globalUnlock = kernel32.NewProc("GlobalUnlock")
|
||||
globalSize = kernel32.NewProc("GlobalSize")
|
||||
)
|
||||
|
||||
const (
|
||||
CF_TEXT = 1
|
||||
CF_UNICODETEXT = 13
|
||||
CF_DIB = 8
|
||||
)
|
||||
|
||||
type BITMAPINFOHEADER struct {
|
||||
BiSize uint32
|
||||
BiWidth int32
|
||||
BiHeight int32
|
||||
BiPlanes uint16
|
||||
BiBitCount uint16
|
||||
BiCompression uint32
|
||||
BiSizeImage uint32
|
||||
BiXPelsPerMeter int32
|
||||
BiYPelsPerMeter int32
|
||||
BiClrUsed uint32
|
||||
BiClrImportant uint32
|
||||
}
|
||||
|
||||
func GetImageFromClipboard() ([]byte, string, error) {
|
||||
ret, _, _ := openClipboard.Call(0)
|
||||
if ret == 0 {
|
||||
return nil, "", fmt.Errorf("failed to open clipboard")
|
||||
}
|
||||
defer func(closeClipboard *syscall.LazyProc, a ...uintptr) {
|
||||
_, _, err := closeClipboard.Call(a...)
|
||||
if err != nil {
|
||||
slog.Error("close clipboard failed")
|
||||
return
|
||||
}
|
||||
}(closeClipboard)
|
||||
isTextAvailable, _, _ := isClipboardFormatAvailable.Call(uintptr(CF_TEXT))
|
||||
isUnicodeTextAvailable, _, _ := isClipboardFormatAvailable.Call(uintptr(CF_UNICODETEXT))
|
||||
|
||||
if isTextAvailable != 0 || isUnicodeTextAvailable != 0 {
|
||||
// Get text from clipboard
|
||||
var formatToUse uintptr = CF_TEXT
|
||||
if isUnicodeTextAvailable != 0 {
|
||||
formatToUse = CF_UNICODETEXT
|
||||
}
|
||||
|
||||
hClipboardText, _, _ := getClipboardData.Call(formatToUse)
|
||||
if hClipboardText != 0 {
|
||||
textPtr, _, _ := globalLock.Call(hClipboardText)
|
||||
if textPtr != 0 {
|
||||
defer func(globalUnlock *syscall.LazyProc, a ...uintptr) {
|
||||
_, _, err := globalUnlock.Call(a...)
|
||||
if err != nil {
|
||||
slog.Error("Global unlock failed")
|
||||
return
|
||||
}
|
||||
}(globalUnlock, hClipboardText)
|
||||
|
||||
// Get clipboard text
|
||||
var clipboardText string
|
||||
if formatToUse == CF_UNICODETEXT {
|
||||
// Convert wide string to Go string
|
||||
clipboardText = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(textPtr))[:])
|
||||
} else {
|
||||
// Get size of ANSI text
|
||||
size, _, _ := globalSize.Call(hClipboardText)
|
||||
if size > 0 {
|
||||
// Convert ANSI string to Go string
|
||||
textBytes := make([]byte, size)
|
||||
copy(textBytes, (*[1 << 20]byte)(unsafe.Pointer(textPtr))[:size:size])
|
||||
clipboardText = bytesToString(textBytes)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the text is not empty
|
||||
if clipboardText != "" {
|
||||
return nil, clipboardText, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hClipboardData, _, _ := getClipboardData.Call(uintptr(CF_DIB))
|
||||
if hClipboardData == 0 {
|
||||
return nil, "", fmt.Errorf("failed to get clipboard data")
|
||||
}
|
||||
|
||||
dataPtr, _, _ := globalLock.Call(hClipboardData)
|
||||
if dataPtr == 0 {
|
||||
return nil, "", fmt.Errorf("failed to lock clipboard data")
|
||||
}
|
||||
defer func(globalUnlock *syscall.LazyProc, a ...uintptr) {
|
||||
_, _, err := globalUnlock.Call(a...)
|
||||
if err != nil {
|
||||
slog.Error("Global unlock failed")
|
||||
return
|
||||
}
|
||||
}(globalUnlock, hClipboardData)
|
||||
|
||||
bmiHeader := (*BITMAPINFOHEADER)(unsafe.Pointer(dataPtr))
|
||||
|
||||
width := int(bmiHeader.BiWidth)
|
||||
height := int(bmiHeader.BiHeight)
|
||||
if height < 0 {
|
||||
height = -height
|
||||
}
|
||||
bitsPerPixel := int(bmiHeader.BiBitCount)
|
||||
|
||||
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
|
||||
var bitsOffset uintptr
|
||||
if bitsPerPixel <= 8 {
|
||||
numColors := uint32(1) << bitsPerPixel
|
||||
if bmiHeader.BiClrUsed > 0 {
|
||||
numColors = bmiHeader.BiClrUsed
|
||||
}
|
||||
bitsOffset = unsafe.Sizeof(*bmiHeader) + uintptr(numColors*4)
|
||||
} else {
|
||||
bitsOffset = unsafe.Sizeof(*bmiHeader)
|
||||
}
|
||||
|
||||
for y := range height {
|
||||
for x := range width {
|
||||
|
||||
srcY := height - y - 1
|
||||
if bmiHeader.BiHeight < 0 {
|
||||
srcY = y
|
||||
}
|
||||
|
||||
var pixelPointer unsafe.Pointer
|
||||
var r, g, b, a uint8
|
||||
|
||||
switch bitsPerPixel {
|
||||
case 24:
|
||||
stride := (width*3 + 3) &^ 3
|
||||
pixelPointer = unsafe.Pointer(dataPtr + bitsOffset + uintptr(srcY*stride+x*3))
|
||||
b = *(*byte)(pixelPointer)
|
||||
g = *(*byte)(unsafe.Add(pixelPointer, 1))
|
||||
r = *(*byte)(unsafe.Add(pixelPointer, 2))
|
||||
a = 255
|
||||
case 32:
|
||||
pixelPointer = unsafe.Pointer(dataPtr + bitsOffset + uintptr(srcY*width*4+x*4))
|
||||
b = *(*byte)(pixelPointer)
|
||||
g = *(*byte)(unsafe.Add(pixelPointer, 1))
|
||||
r = *(*byte)(unsafe.Add(pixelPointer, 2))
|
||||
a = *(*byte)(unsafe.Add(pixelPointer, 3))
|
||||
if a == 0 {
|
||||
a = 255
|
||||
}
|
||||
default:
|
||||
return nil, "", fmt.Errorf("unsupported bit count: %d", bitsPerPixel)
|
||||
}
|
||||
|
||||
img.Set(x, y, color.RGBA{R: r, G: g, B: b, A: a})
|
||||
}
|
||||
}
|
||||
|
||||
imageBytes, err := ImageToBytes(img)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return imageBytes, "", nil
|
||||
}
|
||||
|
||||
func bytesToString(b []byte) string {
|
||||
i := bytes.IndexByte(b, 0)
|
||||
if i == -1 {
|
||||
return string(b)
|
||||
}
|
||||
return string(b[:i])
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package image
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss/v2"
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/lucasb-eyer/go-colorful"
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
func ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {
|
||||
fileInfo, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error getting file info: %w", err)
|
||||
}
|
||||
|
||||
if fileInfo.Size() > sizeLimit {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func ToString(width int, img image.Image) string {
|
||||
img = imaging.Resize(img, width, 0, imaging.Lanczos)
|
||||
b := img.Bounds()
|
||||
imageWidth := b.Max.X
|
||||
h := b.Max.Y
|
||||
str := strings.Builder{}
|
||||
|
||||
for heightCounter := 0; heightCounter < h; heightCounter += 2 {
|
||||
for x := range imageWidth {
|
||||
c1, _ := colorful.MakeColor(img.At(x, heightCounter))
|
||||
color1 := lipgloss.Color(c1.Hex())
|
||||
|
||||
var color2 color.Color
|
||||
if heightCounter+1 < h {
|
||||
c2, _ := colorful.MakeColor(img.At(x, heightCounter+1))
|
||||
color2 = lipgloss.Color(c2.Hex())
|
||||
} else {
|
||||
color2 = color1
|
||||
}
|
||||
|
||||
str.WriteString(lipgloss.NewStyle().Foreground(color1).
|
||||
Background(color2).Render("▀"))
|
||||
}
|
||||
|
||||
str.WriteString("\n")
|
||||
}
|
||||
|
||||
return str.String()
|
||||
}
|
||||
|
||||
func ImagePreview(width int, filename string) (string, error) {
|
||||
imageContent, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer imageContent.Close()
|
||||
|
||||
img, _, err := image.Decode(imageContent)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
imageString := ToString(width, img)
|
||||
|
||||
return imageString, nil
|
||||
}
|
||||
|
||||
func ImageToBytes(image image.Image) ([]byte, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
err := png.Encode(buf, image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -32,15 +32,27 @@ import (
|
||||
// InterruptDebounceTimeoutMsg is sent when the interrupt key debounce timeout expires
|
||||
type InterruptDebounceTimeoutMsg struct{}
|
||||
|
||||
// ExitDebounceTimeoutMsg is sent when the exit key debounce timeout expires
|
||||
type ExitDebounceTimeoutMsg struct{}
|
||||
|
||||
// InterruptKeyState tracks the state of interrupt key presses for debouncing
|
||||
type InterruptKeyState int
|
||||
|
||||
// ExitKeyState tracks the state of exit key presses for debouncing
|
||||
type ExitKeyState int
|
||||
|
||||
const (
|
||||
InterruptKeyIdle InterruptKeyState = iota
|
||||
InterruptKeyFirstPress
|
||||
)
|
||||
|
||||
const (
|
||||
ExitKeyIdle ExitKeyState = iota
|
||||
ExitKeyFirstPress
|
||||
)
|
||||
|
||||
const interruptDebounceTimeout = 1 * time.Second
|
||||
const exitDebounceTimeout = 1 * time.Second
|
||||
const fileViewerFullWidthCutoff = 160
|
||||
|
||||
type appModel struct {
|
||||
@@ -59,6 +71,7 @@ type appModel struct {
|
||||
isLeaderSequence bool
|
||||
toastManager *toast.ToastManager
|
||||
interruptKeyState InterruptKeyState
|
||||
exitKeyState ExitKeyState
|
||||
lastScroll time.Time
|
||||
messagesRight bool
|
||||
fileViewer fileviewer.Model
|
||||
@@ -252,7 +265,13 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// 6. Handle interrupt key debounce for session interrupt
|
||||
// 6 Handle input clear command
|
||||
inputClearCommand := a.app.Commands[commands.InputClearCommand]
|
||||
if inputClearCommand.Matches(msg, a.isLeaderSequence) && a.editor.Length() > 0 {
|
||||
return a, util.CmdHandler(commands.ExecuteCommandMsg(inputClearCommand))
|
||||
}
|
||||
|
||||
// 7. Handle interrupt key debounce for session interrupt
|
||||
interruptCommand := a.app.Commands[commands.SessionInterruptCommand]
|
||||
if interruptCommand.Matches(msg, a.isLeaderSequence) && a.app.IsBusy() {
|
||||
switch a.interruptKeyState {
|
||||
@@ -271,7 +290,26 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Check again for commands that don't require leader (excluding interrupt when busy)
|
||||
// 8. Handle exit key debounce for app exit when using non-leader command
|
||||
exitCommand := a.app.Commands[commands.AppExitCommand]
|
||||
if exitCommand.Matches(msg, a.isLeaderSequence) {
|
||||
switch a.exitKeyState {
|
||||
case ExitKeyIdle:
|
||||
// First exit key press - start debounce timer
|
||||
a.exitKeyState = ExitKeyFirstPress
|
||||
a.editor.SetExitKeyInDebounce(true)
|
||||
return a, tea.Tick(exitDebounceTimeout, func(t time.Time) tea.Msg {
|
||||
return ExitDebounceTimeoutMsg{}
|
||||
})
|
||||
case ExitKeyFirstPress:
|
||||
// Second exit key press within timeout - actually exit
|
||||
a.exitKeyState = ExitKeyIdle
|
||||
a.editor.SetExitKeyInDebounce(false)
|
||||
return a, util.CmdHandler(commands.ExecuteCommandMsg(exitCommand))
|
||||
}
|
||||
}
|
||||
|
||||
// 9. Check again for commands that don't require leader (excluding interrupt when busy and exit when in debounce)
|
||||
matches := a.app.Commands.Matches(msg, a.isLeaderSequence)
|
||||
if len(matches) > 0 {
|
||||
// Skip interrupt key if we're in debounce mode and app is busy
|
||||
@@ -281,8 +319,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return a, util.CmdHandler(commands.ExecuteCommandsMsg(matches))
|
||||
}
|
||||
|
||||
// 7. Fallback to editor. This is for other characters
|
||||
// like backspace, tab, etc.
|
||||
// 10. Fallback to editor. This is for other characters like backspace, tab, etc.
|
||||
updatedEditor, cmd := a.editor.Update(msg)
|
||||
a.editor = updatedEditor.(chat.EditorComponent)
|
||||
return a, cmd
|
||||
@@ -499,6 +536,10 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
// Reset interrupt key state after timeout
|
||||
a.interruptKeyState = InterruptKeyIdle
|
||||
a.editor.SetInterruptKeyInDebounce(false)
|
||||
case ExitDebounceTimeoutMsg:
|
||||
// Reset exit key state after timeout
|
||||
a.exitKeyState = ExitKeyIdle
|
||||
a.editor.SetExitKeyInDebounce(false)
|
||||
case dialog.FindSelectedMsg:
|
||||
return a.openFile(msg.FilePath)
|
||||
}
|
||||
@@ -841,7 +882,7 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
||||
return a, toast.NewErrorToast("Failed to share session")
|
||||
}
|
||||
shareUrl := response.Share.URL
|
||||
cmds = append(cmds, tea.SetClipboard(shareUrl))
|
||||
cmds = append(cmds, a.app.SetClipboard(shareUrl))
|
||||
cmds = append(cmds, toast.NewSuccessToast("Share URL copied to clipboard!"))
|
||||
case commands.SessionUnshareCommand:
|
||||
if a.app.Session.ID == "" {
|
||||
@@ -975,7 +1016,7 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
||||
case commands.MessagesCopyCommand:
|
||||
selected := a.messages.Selected()
|
||||
if selected != "" {
|
||||
cmd = tea.SetClipboard(selected)
|
||||
cmd = a.app.SetClipboard(selected)
|
||||
cmds = append(cmds, cmd)
|
||||
cmd = toast.NewSuccessToast("Message copied to clipboard")
|
||||
cmds = append(cmds, cmd)
|
||||
@@ -1015,6 +1056,7 @@ func NewModel(app *app.App) tea.Model {
|
||||
fileCompletionActive: false,
|
||||
toastManager: toast.NewToastManager(),
|
||||
interruptKeyState: InterruptKeyIdle,
|
||||
exitKeyState: ExitKeyIdle,
|
||||
fileViewer: fileviewer.New(app),
|
||||
messagesRight: app.State.MessagesRight,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
configured_endpoints: 20
|
||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-4955370de3d0a21bb41c4e51257210b3284deb5bc3dbace6e7572de0d1635c9e.yml
|
||||
openapi_spec_hash: b7591d636977423cd7455aa02caa718f
|
||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-c06a9b8d8284683e8350fdd3eceff0b5756877f7b67e974acd565409b67d32a0.yml
|
||||
openapi_spec_hash: 5933bca0c79177065374ac724a6bc986
|
||||
config_hash: de53ecf98e1038f2cc2fd273b582f082
|
||||
|
||||
@@ -397,14 +397,18 @@ func (r configProviderModelsLimitJSON) RawJSON() string {
|
||||
type Keybinds struct {
|
||||
// Exit the application
|
||||
AppExit string `json:"app_exit"`
|
||||
// Show help dialog
|
||||
AppHelp string `json:"app_help"`
|
||||
// Open external editor
|
||||
EditorOpen string `json:"editor_open"`
|
||||
// Show help dialog
|
||||
Help string `json:"help"`
|
||||
// Navigate to next history item
|
||||
HistoryNext string `json:"history_next"`
|
||||
// Navigate to previous history item
|
||||
HistoryPrevious string `json:"history_previous"`
|
||||
// Close file
|
||||
FileClose string `json:"file_close"`
|
||||
// Toggle split/unified diff
|
||||
FileDiffToggle string `json:"file_diff_toggle"`
|
||||
// List files
|
||||
FileList string `json:"file_list"`
|
||||
// Search file
|
||||
FileSearch string `json:"file_search"`
|
||||
// Clear input field
|
||||
InputClear string `json:"input_clear"`
|
||||
// Insert newline in input
|
||||
@@ -415,6 +419,8 @@ type Keybinds struct {
|
||||
InputSubmit string `json:"input_submit"`
|
||||
// Leader key for keybind combinations
|
||||
Leader string `json:"leader"`
|
||||
// Copy message
|
||||
MessagesCopy string `json:"messages_copy"`
|
||||
// Navigate to first message
|
||||
MessagesFirst string `json:"messages_first"`
|
||||
// Scroll messages down by half page
|
||||
@@ -423,6 +429,8 @@ type Keybinds struct {
|
||||
MessagesHalfPageUp string `json:"messages_half_page_up"`
|
||||
// Navigate to last message
|
||||
MessagesLast string `json:"messages_last"`
|
||||
// Toggle layout
|
||||
MessagesLayoutToggle string `json:"messages_layout_toggle"`
|
||||
// Navigate to next message
|
||||
MessagesNext string `json:"messages_next"`
|
||||
// Scroll messages down by one page
|
||||
@@ -431,6 +439,8 @@ type Keybinds struct {
|
||||
MessagesPageUp string `json:"messages_page_up"`
|
||||
// Navigate to previous message
|
||||
MessagesPrevious string `json:"messages_previous"`
|
||||
// Revert message
|
||||
MessagesRevert string `json:"messages_revert"`
|
||||
// List available models
|
||||
ModelList string `json:"model_list"`
|
||||
// Initialize project configuration
|
||||
@@ -445,6 +455,8 @@ type Keybinds struct {
|
||||
SessionNew string `json:"session_new"`
|
||||
// Share current session
|
||||
SessionShare string `json:"session_share"`
|
||||
// Unshare current session
|
||||
SessionUnshare string `json:"session_unshare"`
|
||||
// List available themes
|
||||
ThemeList string `json:"theme_list"`
|
||||
// Show tool details
|
||||
@@ -455,23 +467,28 @@ type Keybinds struct {
|
||||
// keybindsJSON contains the JSON metadata for the struct [Keybinds]
|
||||
type keybindsJSON struct {
|
||||
AppExit apijson.Field
|
||||
AppHelp apijson.Field
|
||||
EditorOpen apijson.Field
|
||||
Help apijson.Field
|
||||
HistoryNext apijson.Field
|
||||
HistoryPrevious apijson.Field
|
||||
FileClose apijson.Field
|
||||
FileDiffToggle apijson.Field
|
||||
FileList apijson.Field
|
||||
FileSearch apijson.Field
|
||||
InputClear apijson.Field
|
||||
InputNewline apijson.Field
|
||||
InputPaste apijson.Field
|
||||
InputSubmit apijson.Field
|
||||
Leader apijson.Field
|
||||
MessagesCopy apijson.Field
|
||||
MessagesFirst apijson.Field
|
||||
MessagesHalfPageDown apijson.Field
|
||||
MessagesHalfPageUp apijson.Field
|
||||
MessagesLast apijson.Field
|
||||
MessagesLayoutToggle apijson.Field
|
||||
MessagesNext apijson.Field
|
||||
MessagesPageDown apijson.Field
|
||||
MessagesPageUp apijson.Field
|
||||
MessagesPrevious apijson.Field
|
||||
MessagesRevert apijson.Field
|
||||
ModelList apijson.Field
|
||||
ProjectInit apijson.Field
|
||||
SessionCompact apijson.Field
|
||||
@@ -479,6 +496,7 @@ type keybindsJSON struct {
|
||||
SessionList apijson.Field
|
||||
SessionNew apijson.Field
|
||||
SessionShare apijson.Field
|
||||
SessionUnshare apijson.Field
|
||||
ThemeList apijson.Field
|
||||
ToolDetails apijson.Field
|
||||
raw string
|
||||
|
||||
@@ -29,7 +29,7 @@ func NewDecoder(res *http.Response) Decoder {
|
||||
decoder = t(res.Body)
|
||||
} else {
|
||||
scn := bufio.NewScanner(res.Body)
|
||||
scn.Buffer(nil, bufio.MaxScanTokenSize<<4)
|
||||
scn.Buffer(nil, (bufio.MaxScanTokenSize<<4)*10)
|
||||
decoder = &eventStreamDecoder{rc: res.Body, scn: scn}
|
||||
}
|
||||
return decoder
|
||||
|
||||
@@ -5,4 +5,7 @@ set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
echo "==> Running Go build"
|
||||
go build ./...
|
||||
go build .
|
||||
|
||||
# Compile the tests but don't run them
|
||||
go test -c .
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
For,
|
||||
Show,
|
||||
Match,
|
||||
Switch,
|
||||
onMount,
|
||||
Suspense,
|
||||
onCleanup,
|
||||
@@ -12,13 +10,13 @@ import {
|
||||
} from "solid-js"
|
||||
import { DateTime } from "luxon"
|
||||
import { createStore, reconcile } from "solid-js/store"
|
||||
import { IconOpenAI, IconGemini, IconOpencode, IconAnthropic } from "./icons/custom"
|
||||
import { IconSparkles, IconArrowDown } from "./icons"
|
||||
import { IconArrowDown } from "./icons"
|
||||
import { IconOpencode } from "./icons/custom"
|
||||
import styles from "./share.module.css"
|
||||
import type { MessageV2 } from "opencode/session/message-v2"
|
||||
import type { Message } from "opencode/session/message"
|
||||
import type { Session } from "opencode/session/index"
|
||||
import { Part } from "./share/part"
|
||||
import { Part, ProviderIcon } from "./share/part"
|
||||
|
||||
type Status = "disconnected" | "connecting" | "connected" | "error" | "reconnecting"
|
||||
|
||||
@@ -46,23 +44,6 @@ function getStatusText(status: [Status, string?]): string {
|
||||
}
|
||||
}
|
||||
|
||||
function ProviderIcon(props: { provider: string; size?: number }) {
|
||||
const size = props.size || 16
|
||||
return (
|
||||
<Switch fallback={<IconSparkles width={size} height={size} />}>
|
||||
<Match when={props.provider === "openai"}>
|
||||
<IconOpenAI width={size} height={size} />
|
||||
</Match>
|
||||
<Match when={props.provider === "anthropic"}>
|
||||
<IconAnthropic width={size} height={size} />
|
||||
</Match>
|
||||
<Match when={props.provider === "gemini"}>
|
||||
<IconGemini width={size} height={size} />
|
||||
</Match>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Share(props: {
|
||||
id: string
|
||||
api: string
|
||||
@@ -319,7 +300,7 @@ export default function Share(props: {
|
||||
{([provider, model]) => (
|
||||
<li data-slot="item">
|
||||
<div data-slot="icon" title={provider}>
|
||||
<ProviderIcon provider={provider} />
|
||||
<ProviderIcon model={model} />
|
||||
</div>
|
||||
<span data-slot="model">{model}</span>
|
||||
</li>
|
||||
|
||||
@@ -49,3 +49,12 @@ export function IconOpencode(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
// https://icones.js.org/collection/ri?s=meta&icon=ri:meta-fill
|
||||
export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M16.92 4.5c-1.851 0-3.298 1.394-4.608 3.165C10.512 5.373 9.007 4.5 7.206 4.5C3.534 4.5.72 9.28.72 14.338c0 3.165 1.531 5.162 4.096 5.162c1.846 0 3.174-.87 5.535-4.997c0 0 .984-1.737 1.66-2.934q.356.574.75 1.238l1.107 1.862c2.156 3.608 3.358 4.831 5.534 4.831c2.5 0 3.89-2.024 3.89-5.255c0-5.297-2.877-9.745-6.372-9.745m-8.37 8.886c-1.913 3-2.575 3.673-3.64 3.673c-1.097 0-1.749-.963-1.749-2.68c0-3.672 1.831-7.427 4.014-7.427c1.182 0 2.17.682 3.683 2.848c-1.437 2.204-2.307 3.586-2.307 3.586m7.224-.377L14.45 10.8a45 45 0 0 0-1.032-1.608c1.193-1.841 2.176-2.759 3.347-2.759c2.43 0 4.375 3.58 4.375 7.976c0 1.676-.549 2.649-1.686 2.649c-1.09 0-1.61-.72-3.68-4.05" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
display: flex;
|
||||
gap: 0.5rem 0.875rem;
|
||||
flex-wrap: wrap;
|
||||
max-width: var(--lg-tool-width);
|
||||
|
||||
[data-slot="item"] {
|
||||
display: flex;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
pre {
|
||||
--shiki-dark-bg: var(--sl-color-bg-surface) !important;
|
||||
background-color: var(--sl-color-bg-surface) !important;
|
||||
line-height: 1.6;
|
||||
font-size: 0.75rem;
|
||||
white-space: pre-wrap;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { type JSX, splitProps, createResource, Suspense } from "solid-js"
|
||||
import { codeToHtml } from "shiki"
|
||||
import style from "./content-code.module.css"
|
||||
import { createResource, Suspense } from "solid-js"
|
||||
import { transformerNotationDiff } from "@shikijs/transformers"
|
||||
import style from "./content-code.module.css"
|
||||
|
||||
interface Props {
|
||||
code: string
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
.root {
|
||||
background-color: var(--sl-color-bg-surface);
|
||||
padding: 0.5rem calc(0.5rem + 3px);
|
||||
border-radius: 0.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
align-self: flex-start;
|
||||
max-width: var(--md-tool-width);
|
||||
|
||||
[data-section="content"] {
|
||||
pre {
|
||||
margin-bottom: 0.5rem;
|
||||
line-height: 1.5;
|
||||
font-size: 0.75rem;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
span {
|
||||
margin-right: 0.25rem;
|
||||
&:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
span[data-color="red"] {
|
||||
color: var(--sl-color-red);
|
||||
}
|
||||
span[data-color="dimmed"] {
|
||||
color: var(--sl-color-text-dimmed);
|
||||
}
|
||||
span[data-marker="label"] {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
span[data-separator] {
|
||||
margin-right: 0.375rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-expanded="true"] {
|
||||
[data-section="content"] {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
&[data-expanded="false"] {
|
||||
[data-section="content"] {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 7;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
flex: 0 0 auto;
|
||||
padding: 2px 0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import style from "./content-error.module.css"
|
||||
import { type JSX, createSignal } from "solid-js"
|
||||
import { createOverflow } from "./common"
|
||||
|
||||
interface Props extends JSX.HTMLAttributes<HTMLDivElement> {
|
||||
expand?: boolean
|
||||
}
|
||||
export function ContentError(props: Props) {
|
||||
const [expanded, setExpanded] = createSignal(false)
|
||||
const overflow = createOverflow()
|
||||
|
||||
return (
|
||||
<div
|
||||
class={style.root}
|
||||
data-expanded={expanded() || props.expand === true ? true : undefined}
|
||||
>
|
||||
<div data-section="content" ref={overflow.ref}>
|
||||
{props.children}
|
||||
</div>
|
||||
{((!props.expand && overflow.status) || expanded()) && (
|
||||
<button
|
||||
type="button"
|
||||
data-element-button-text
|
||||
onClick={() => setExpanded((e) => !e)}
|
||||
>
|
||||
{expanded() ? "Show less" : "Show more"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,31 +1,42 @@
|
||||
import { createMemo, createSignal, For, Match, Show, Switch, type JSX, type ParentProps } from "solid-js"
|
||||
import map from "lang-map"
|
||||
import { DateTime } from "luxon"
|
||||
import {
|
||||
For,
|
||||
Show,
|
||||
Match,
|
||||
Switch,
|
||||
type JSX,
|
||||
createMemo,
|
||||
createSignal,
|
||||
type ParentProps
|
||||
} from "solid-js"
|
||||
import {
|
||||
IconCheckCircle,
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconHashtag,
|
||||
IconSparkles,
|
||||
IconGlobeAlt,
|
||||
IconDocument,
|
||||
IconQueueList,
|
||||
IconUserCircle,
|
||||
IconCommandLine,
|
||||
IconCheckCircle,
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconDocumentPlus,
|
||||
IconPencilSquare,
|
||||
IconRectangleStack,
|
||||
IconMagnifyingGlass,
|
||||
IconDocumentMagnifyingGlass,
|
||||
} from "../icons"
|
||||
import styles from "./part.module.css"
|
||||
import type { MessageV2 } from "opencode/session/message-v2"
|
||||
import { ContentText } from "./content-text"
|
||||
import { ContentMarkdown } from "./content-markdown"
|
||||
import { DateTime } from "luxon"
|
||||
import CodeBlock from "../CodeBlock"
|
||||
import map from "lang-map"
|
||||
import type { Diagnostic } from "vscode-languageserver-types"
|
||||
|
||||
import { IconMeta, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom"
|
||||
import { ContentCode } from "./content-code"
|
||||
import { ContentDiff } from "./content-diff"
|
||||
import { ContentText } from "./content-text"
|
||||
import { ContentError } from "./content-error"
|
||||
import { ContentMarkdown } from "./content-markdown"
|
||||
import type { MessageV2 } from "opencode/session/message-v2"
|
||||
import type { Diagnostic } from "vscode-languageserver-types"
|
||||
|
||||
import styles from "./part.module.css"
|
||||
|
||||
export interface PartProps {
|
||||
index: number
|
||||
@@ -65,6 +76,15 @@ export function Part(props: PartProps) {
|
||||
}}
|
||||
>
|
||||
<Switch>
|
||||
<Match when={props.message.role === "user" && props.part.type === "text"}>
|
||||
<IconUserCircle width={18} height={18} />
|
||||
</Match>
|
||||
<Match when={props.message.role === "user" && props.part.type === "file"}>
|
||||
<IconDocument width={18} height={18} />
|
||||
</Match>
|
||||
<Match when={props.part.type === "step-start" && props.message.role === "assistant" && props.message.modelID}>
|
||||
{model => <ProviderIcon model={model()} size={18} />}
|
||||
</Match>
|
||||
<Match when={props.part.type === "tool" && props.part.tool === "todowrite"}>
|
||||
<IconQueueList width={18} height={18} />
|
||||
</Match>
|
||||
@@ -112,7 +132,8 @@ export function Part(props: PartProps) {
|
||||
<div data-component="content">
|
||||
{props.message.role === "user" && props.part.type === "text" && (
|
||||
<>
|
||||
<ContentText text={props.part.text} expand={props.last} /> <Spacer />
|
||||
<ContentText text={props.part.text} expand={props.last} />
|
||||
<Spacer />
|
||||
</>
|
||||
)}
|
||||
{props.message.role === "assistant" && props.part.type === "text" && (
|
||||
@@ -130,12 +151,28 @@ export function Part(props: PartProps) {
|
||||
<Spacer />
|
||||
</>
|
||||
)}
|
||||
{props.message.role === "user" && props.part.type === "file" && (
|
||||
<div data-component="tool-title">
|
||||
<span data-slot="name">Read</span>
|
||||
<span data-slot="target" title={props.part.filename}>
|
||||
{props.part.filename}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "step-start" && props.message.role === "assistant" && (
|
||||
<div data-component="step-start">
|
||||
<div data-slot="provider">{props.message.providerID}</div>
|
||||
<div data-slot="model">{props.message.modelID}</div>
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "tool" &&
|
||||
props.part.state.status === "error" && (
|
||||
<div data-component="tool">
|
||||
<ContentError>
|
||||
{formatErrorString(props.part.state.error)}
|
||||
</ContentError>
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "tool" &&
|
||||
props.part.state.status === "completed" &&
|
||||
props.message.role === "assistant" && (
|
||||
@@ -420,11 +457,11 @@ export function WebFetchTool(props: ToolProps) {
|
||||
<div data-component="tool-result">
|
||||
<Switch>
|
||||
<Match when={props.state.metadata?.error}>
|
||||
<div data-component="error">{formatErrorString(props.state.output)}</div>
|
||||
<ContentError>{formatErrorString(props.state.output)}</ContentError>
|
||||
</Match>
|
||||
<Match when={props.state.output}>
|
||||
<ResultsButton>
|
||||
<CodeBlock lang={props.state.input.format || "text"} code={props.state.output} />
|
||||
<ContentCode lang={props.state.input.format || "text"} code={props.state.output} />
|
||||
</ResultsButton>
|
||||
</Match>
|
||||
</Switch>
|
||||
@@ -447,7 +484,7 @@ export function ReadTool(props: ToolProps) {
|
||||
<div data-component="tool-result">
|
||||
<Switch>
|
||||
<Match when={props.state.metadata?.error}>
|
||||
<div data-component="error">{formatErrorString(props.state.output)}</div>
|
||||
<ContentError>{formatErrorString(props.state.output)}</ContentError>
|
||||
</Match>
|
||||
<Match when={typeof props.state.metadata?.preview === "string"}>
|
||||
<ResultsButton showCopy="Show preview" hideCopy="Hide preview">
|
||||
@@ -483,7 +520,7 @@ export function WriteTool(props: ToolProps) {
|
||||
<div data-component="tool-result">
|
||||
<Switch>
|
||||
<Match when={props.state.metadata?.error}>
|
||||
<div data-component="error">{formatErrorString(props.state.output)}</div>
|
||||
<ContentError>{formatErrorString(props.state.output)}</ContentError>
|
||||
</Match>
|
||||
<Match when={props.state.input?.content}>
|
||||
<ResultsButton showCopy="Show contents" hideCopy="Hide contents">
|
||||
@@ -511,7 +548,7 @@ export function EditTool(props: ToolProps) {
|
||||
<div data-component="tool-result">
|
||||
<Switch>
|
||||
<Match when={props.state.metadata?.error}>
|
||||
<div data-component="error">{formatErrorString(props.state.metadata?.message || "")}</div>
|
||||
<ContentError>{formatErrorString(props.state.metadata?.message || "")}</ContentError>
|
||||
</Match>
|
||||
<Match when={props.state.metadata?.diff}>
|
||||
<div data-component="diff">
|
||||
@@ -662,3 +699,35 @@ function flattenToolArgs(obj: any, prefix: string = ""): Array<[string, any]> {
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
function getProvider(model: string) {
|
||||
const lowerModel = model.toLowerCase()
|
||||
|
||||
if (/claude|anthropic/.test(lowerModel)) return "anthropic"
|
||||
if (/gpt|o[1-4]|codex|openai/.test(lowerModel)) return "openai"
|
||||
if (/gemini|palm|bard|google/.test(lowerModel)) return "gemini"
|
||||
if (/llama|meta/.test(lowerModel)) return "meta"
|
||||
|
||||
return "any"
|
||||
}
|
||||
|
||||
export function ProviderIcon(props: { model: string; size?: number }) {
|
||||
const provider = getProvider(props.model)
|
||||
const size = props.size || 16
|
||||
return (
|
||||
<Switch fallback={<IconSparkles width={size} height={size} />}>
|
||||
<Match when={provider === "openai"}>
|
||||
<IconOpenAI width={size} height={size} />
|
||||
</Match>
|
||||
<Match when={provider === "anthropic"}>
|
||||
<IconAnthropic width={size} height={size} />
|
||||
</Match>
|
||||
<Match when={provider === "gemini"}>
|
||||
<IconGemini width={size} height={size} />
|
||||
</Match>
|
||||
<Match when={provider === "meta"}>
|
||||
<IconMeta width={size} height={size} />
|
||||
</Match>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -81,23 +81,14 @@ If you have both global and project-specific rules, opencode will combine them t
|
||||
|
||||
## Custom Instructions
|
||||
|
||||
You can also specify custom instruction files using the `instructions` configuration in your `opencode.json` or global `~/.config/opencode/config.json`:
|
||||
You can specify custom instruction files in your `opencode.json` or the global `~/.config/opencode/config.json`. This allows you and your team to reuse existing rules rather than having to duplicate them to AGENTS.md.
|
||||
|
||||
Example:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"instructions": [".cursor/rules/*.md"]
|
||||
}
|
||||
```
|
||||
|
||||
You can specify multiple files like `CONTRIBUTING.md` and `docs/guidelines.md`, and use glob patterns to match multiple files.
|
||||
|
||||
For example, to reuse your existing Cursor rules:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"instructions": [".cursor/rules/*.md"]
|
||||
"instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -9,6 +9,18 @@ By default, opencode uses our own `opencode` theme.
|
||||
|
||||
---
|
||||
|
||||
## Terminal requirements
|
||||
|
||||
For themes to display correctly with their full color palette, your terminal must support **truecolor** (24-bit color). Most modern terminals support this by default, but you may need to enable it:
|
||||
|
||||
- **Check support**: Run `echo $COLORTERM` - it should output `truecolor` or `24bit`
|
||||
- **Enable truecolor**: Set the environment variable `COLORTERM=truecolor` in your shell profile
|
||||
- **Terminal compatibility**: Ensure your terminal emulator supports 24-bit color (most modern terminals like iTerm2, Alacritty, Kitty, Windows Terminal, and recent versions of GNOME Terminal do)
|
||||
|
||||
Without truecolor support, themes may appear with reduced color accuracy or fall back to the nearest 256-color approximation.
|
||||
|
||||
---
|
||||
|
||||
## Built-in themes
|
||||
|
||||
opencode comes with several built-in themes.
|
||||
|
||||
@@ -23,9 +23,8 @@ const models: Set<string> = new Set();
|
||||
const version = data.info.version ? `v${data.info.version}` : "v0.0.1";
|
||||
|
||||
Object.values(data.messages).forEach((d) => {
|
||||
const assistant = d.metadata?.assistant;
|
||||
if (assistant) {
|
||||
models.add(assistant.modelID);
|
||||
if (d.role === "assistant" && d.modelID) {
|
||||
models.add(d.modelID);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -39,8 +38,19 @@ const encodedTitle = encodeURIComponent(
|
||||
)
|
||||
);
|
||||
|
||||
const ogImage = `${config.socialCard}/opencode-share/${encodedTitle}.png?model=${Array.from(models).join(",")}&version=${version}&id=${id}`;
|
||||
const modelsArray = Array.from(models);
|
||||
let modelParam;
|
||||
if (modelsArray.length === 1) {
|
||||
modelParam = modelsArray[0];
|
||||
}
|
||||
else if (modelsArray.length === 2) {
|
||||
modelParam = encodeURIComponent(`${modelsArray[0]} & ${modelsArray[1]}`);
|
||||
}
|
||||
else {
|
||||
modelParam = encodeURIComponent(`${modelsArray[0]} & ${modelsArray.length - 1} others`);
|
||||
}
|
||||
|
||||
const ogImage = `${config.socialCard}/opencode-share/${encodedTitle}.png?model=${modelParam}&version=${version}&id=${id}`;
|
||||
---
|
||||
<StarlightPage
|
||||
hasSidebar={false}
|
||||
|
||||
Reference in New Issue
Block a user