robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
8bf7fc810a
master
1---Kitty graphics protocol implementation for vim.ui.img. 2local M ={} 3 4local generate_id =( function () 5local bit =require ( 'bit' ) 6local NVIM_PID_BITS =10 7 8local nvim_pid =0 9local cnt =30 10 11---@return integer 12return function () 13if nvim_pid == 0 then 14local pid =vim . fn . getpid () 15nvim_pid =bit . band ( bit . bxor ( pid , bit . rshift ( pid , 5 ), bit . rshift ( pid , NVIM_PID_BITS )), 0x3FF ) 16end 17cnt =cnt + 1 18return bit . bor ( bit . lshift ( nvim_pid , 24 - NVIM_PID_BITS ), cnt ) 19end 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 ) 27local parts ={ '\027_G' } 28 29local tmp ={} 30for k , v in pairs ( control ) do 31table . insert ( tmp , k .. '=' .. v ) 32end 33if # tmp > 0 then 34table . insert ( parts , table . concat ( tmp , ',' )) 35end 36 37if payload and payload ~= '' then 38table . insert ( parts , ';' ) 39table . insert ( parts , payload ) 40end 41 42table . insert ( parts , '\027\\' ) 43return 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 ) 54local chunk_size =4096 55local base64_data =vim . base64 . encode ( data ) 56local pos =1 57local len =# base64_data 58 59while pos <= len do 60local end_pos =math . min ( pos + chunk_size - 1 , len ) 61local chunk =base64_data : sub ( pos , end_pos ) 62local is_last =end_pos >= len 63 64local control ={} 65 66if pos == 1 then 67control . f ='100' -- PNG format 68control . a ='t' -- Transmit without displaying 69control . t ='d' -- Direct transmission 70control . i =id 71control . q ='2' -- Suppress responses 72end 73 74control . m =is_last and '0' or '1' 75 76vim . api . nvim_ui_send ( seq ( control , chunk )) 77pos =end_pos + 1 78end 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 ) 86local cursor_save ='\0277' 87local cursor_hide ='\027[?25l' 88local cursor_move =string . format ( '\027[%d;%dH' , opts . row or 1 , opts . col or 1 ) 89local cursor_restore ='\0278' 90local cursor_show ='\027[?25h' 91 92---@type table<string, string|number> 93local control ={ 94a ='p' , 95i =img_id , 96p =placement_id , 97C ='1' , -- Don't move the cursor at all 98q ='2' , -- Suppress responses 99} 100 101if opts . width then 102control . c =opts . width 103end 104if opts . height then 105control . r =opts . height 106end 107if opts . zindex then 108control . z =opts . zindex 109end 110 111vim . api . nvim_ui_send ( 112cursor_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 ) 122local img_id =generate_id () 123local placement_id =generate_id () 124 125transmit ( img_id , data ) 126place ( img_id , placement_id , opts ) 127 128return 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 ) 136place ( 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 ) 143if img_id == math . huge then 144-- delete all placements and free stored image data (if not referenced elsewhere, e.g. scrollback) 145vim . api . nvim_ui_send ( seq ( { 146a ='d' , 147d ='A' , 148q ='2' , 149} )) 150else 151vim . api . nvim_ui_send ( seq ( { 152a ='d' , 153d ='i' , 154i =img_id , 155q ='2' , -- Suppress responses 156} )) 157end 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 ) 167opts =opts or {} 168local timeout =opts . timeout or 1000 169 170-- Do not use APC on terminals that echo unknown sequences 171if vim . env . TERM_PROGRAM == 'Apple_Terminal' then 172return false 173end 174 175local query_id =generate_id () 176 177---@type boolean? 178local result 179---@type string? 180local msg 181 182vim . tty . query_apc ( 183seq ( { a ='q' , i =query_id , s =1 , v =1 } ), 184{ timeout =timeout , chan =opts . chan } , 185function ( 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" 188local id =resp : match ( '^\027_G[^;]*i=(%d+)' ) 189local status =resp : match ( ';(.-)%s*$' ) 190if id and tonumber ( id ) == query_id and status then 191result =true 192msg =status ~= 'OK' and status or nil 193return true 194end 195end 196) 197 198-- Wait in a blocking fashion for the response, checking 199-- at least every 200ms, or faster if the timeout is small 200vim . wait ( timeout + 100 , function () 201return result ~= nil 202end , math . max ( math . min ( math . ceil ( timeout / 10 ), 200 ), 1 )) 203 204return result == true , msg 205end 206 207return M