robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Barrett Ruthfix(tty): filter terminal probes by channel #403568bf7fc810a

master
5.6 KiB207 linesraw
1---Kitty graphics protocol implementation for vim.ui.img.
2local M = {}
3
4local generate_id = (function()
5  local bit = require('bit')
6  local NVIM_PID_BITS = 10
7
8  local nvim_pid = 0
9  local cnt = 30
10
11  ---@return integer
12  return function()
13    if nvim_pid == 0 then
14      local pid = vim.fn.getpid()
15      nvim_pid = bit.band(bit.bxor(pid, bit.rshift(pid, 5), bit.rshift(pid, NVIM_PID_BITS)), 0x3FF)
16    end
17    cnt = cnt + 1
18    return bit.bor(bit.lshift(nvim_pid, 24 - NVIM_PID_BITS), cnt)
19  end
20end)()
21
22---Build a Kitty graphics protocol escape sequence.
23---@param control table<string, string|number>
24---@param payload? string
25---@return string
26local function seq(control, payload)
27  local parts = { '\027_G' }
28
29  local tmp = {}
30  for k, v in pairs(control) do
31    table.insert(tmp, k .. '=' .. v)
32  end
33  if #tmp > 0 then
34    table.insert(parts, table.concat(tmp, ','))
35  end
36
37  if payload and payload ~= '' then
38    table.insert(parts, ';')
39    table.insert(parts, payload)
40  end
41
42  table.insert(parts, '\027\\')
43  return table.concat(parts)
44end
45
46---Transmit image bytes to kitty in base64 chunks using direct transmission.
47---
48---Large images may cause the terminal to hang or the escape sequence to get
49---interrupted mid-write. A future filepath option (t=f) could let the
50---terminal read the file directly, avoiding this issue for local sessions.
51---@param id integer kitty image id
52---@param data string raw image bytes
53local function transmit(id, data)
54  local chunk_size = 4096
55  local base64_data = vim.base64.encode(data)
56  local pos = 1
57  local len = #base64_data
58
59  while pos <= len do
60    local end_pos = math.min(pos + chunk_size - 1, len)
61    local chunk = base64_data:sub(pos, end_pos)
62    local is_last = end_pos >= len
63
64    local control = {}
65
66    if pos == 1 then
67      control.f = '100' -- PNG format
68      control.a = 't' -- Transmit without displaying
69      control.t = 'd' -- Direct transmission
70      control.i = id
71      control.q = '2' -- Suppress responses
72    end
73
74    control.m = is_last and '0' or '1'
75
76    vim.api.nvim_ui_send(seq(control, chunk))
77    pos = end_pos + 1
78  end
79end
80
81---Send a kitty place/display command with cursor management.
82---@param img_id integer kitty image id
83---@param placement_id integer kitty placement id
84---@param opts vim.ui.img.Opts
85local function place(img_id, placement_id, opts)
86  local cursor_save = '\0277'
87  local cursor_hide = '\027[?25l'
88  local cursor_move = string.format('\027[%d;%dH', opts.row or 1, opts.col or 1)
89  local cursor_restore = '\0278'
90  local cursor_show = '\027[?25h'
91
92  ---@type table<string, string|number>
93  local control = {
94    a = 'p',
95    i = img_id,
96    p = placement_id,
97    C = '1', -- Don't move the cursor at all
98    q = '2', -- Suppress responses
99  }
100
101  if opts.width then
102    control.c = opts.width
103  end
104  if opts.height then
105    control.r = opts.height
106  end
107  if opts.zindex then
108    control.z = opts.zindex
109  end
110
111  vim.api.nvim_ui_send(
112    cursor_save .. cursor_hide .. cursor_move .. seq(control) .. cursor_restore .. cursor_show
113  )
114end
115
116---Transmit image bytes and place the image. Returns both IDs.
117---@param data string raw image bytes
118---@param opts vim.ui.img.Opts
119---@return integer img_id
120---@return integer placement_id
121function M.set(data, opts)
122  local img_id = generate_id()
123  local placement_id = generate_id()
124
125  transmit(img_id, data)
126  place(img_id, placement_id, opts)
127
128  return img_id, placement_id
129end
130
131---Update an existing placement (flicker-free, reuses same IDs).
132---@param img_id integer
133---@param placement_id integer
134---@param opts vim.ui.img.Opts
135function M.update(img_id, placement_id, opts)
136  place(img_id, placement_id, opts)
137end
138
139---Delete an image and all its placements from the terminal.
140---When {img_id} is `math.huge`, deletes all images.
141---@param img_id integer
142function M.delete(img_id)
143  if img_id == math.huge then
144    -- delete all placements and free stored image data (if not referenced elsewhere, e.g. scrollback)
145    vim.api.nvim_ui_send(seq({
146      a = 'd',
147      d = 'A',
148      q = '2',
149    }))
150  else
151    vim.api.nvim_ui_send(seq({
152      a = 'd',
153      d = 'i',
154      i = img_id,
155      q = '2', -- Suppress responses
156    }))
157  end
158end
159
160--- Query whether this terminal supports the kitty graphics protocol.
161--- Blocks until the terminal responds or times out.
162---
163---@param opts? {timeout?: integer, chan?: integer} timeout in milliseconds (default: 1000)
164---@return boolean supported
165---@return string? msg error detail if terminal responded but not with OK
166function M.supported(opts)
167  opts = opts or {}
168  local timeout = opts.timeout or 1000
169
170  -- Do not use APC on terminals that echo unknown sequences
171  if vim.env.TERM_PROGRAM == 'Apple_Terminal' then
172    return false
173  end
174
175  local query_id = generate_id()
176
177  ---@type boolean?
178  local result
179  ---@type string?
180  local msg
181
182  vim.tty.query_apc(
183    seq({ a = 'q', i = query_id, s = 1, v = 1 }),
184    { timeout = timeout, chan = opts.chan },
185    function(resp)
186      -- kitty APC response: \027_G[<fields>,]i=<id>[,<fields>];<status>
187      -- status is "OK" or an error code+message like "ENODATA:Missing image data"
188      local id = resp:match('^\027_G[^;]*i=(%d+)')
189      local status = resp:match(';(.-)%s*$')
190      if id and tonumber(id) == query_id and status then
191        result = true
192        msg = status ~= 'OK' and status or nil
193        return true
194      end
195    end
196  )
197
198  -- Wait in a blocking fashion for the response, checking
199  -- at least every 200ms, or faster if the timeout is small
200  vim.wait(timeout + 100, function()
201    return result ~= nil
202  end, math.max(math.min(math.ceil(timeout / 10), 200), 1))
203
204  return result == true, msg
205end
206
207return M