Repository navigation
Expand file tree
/
Copy pathkitty.go
More file actions
439 lines (383 loc) · 11.8 KB
/
Copy pathkitty.go
File metadata and controls
439 lines (383 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright (c) 2025 Harsh Sharma <harsh@codelif.in>
//
// 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.
package katnip
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"os"
"sync"
"time"
)
const esc byte = 0x1b
var (
kittyMsgPrefix = []byte("\x1bP@kitty-cmd")
kittyMsgSuffix = []byte("\x1b\\")
kittyMinVersion = [3]uint64{0, 42, 2}
)
// rcTimeout bounds a request/response round trip on the socket transport. A
// wedged kitty must not park the caller forever holding the lock.
const rcTimeout = 5 * time.Second
type kittySockMsg struct {
Command string `json:"cmd"`
Version [3]uint64 `json:"version"`
NoResponse bool `json:"no_response,omitempty"`
KittyWindowId uint64 `json:"kitty_window_id,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
}
// transport carries remote control frames to kitty. Two of them exist: a
// panel's own terminal, and an instance's unix socket.
type transport interface {
// send writes one framed message.
send(frame []byte) error
// receive reads one framed response. Only valid when duplex reports true.
receive() ([]byte, error)
duplex() bool
close() error
}
// ttyTransport talks to kitty over the panel's own terminal, by writing the
// remote control escape sequence into the output stream. kitty answers on
// stdin, which a TUI already owns, so this side never reads: commands go out
// with no_response and "self", which needs no window id and no socket. That
// works the same whether the panel is its own kitty process or one window of
// many, which is the point.
//
// The writer must not interleave with the rest of the terminal output. For a
// vaxis app that is its control writer, not stdout.
type ttyTransport struct {
mu sync.Mutex
w io.Writer
}
func (t *ttyTransport) send(frame []byte) error {
t.mu.Lock()
defer t.mu.Unlock()
w := t.w
if w == nil {
w = os.Stdout
}
if _, err := w.Write(frame); err != nil {
return fmt.Errorf("writing remote control frame: %w", err)
}
return nil
}
func (t *ttyTransport) receive() ([]byte, error) {
return nil, fmt.Errorf("katnip: this client talks over its own terminal and cannot read responses")
}
func (t *ttyTransport) duplex() bool { return false }
func (t *ttyTransport) close() error { return nil }
func (t *ttyTransport) setWriter(w io.Writer) {
t.mu.Lock()
defer t.mu.Unlock()
t.w = w
}
// sockTransport talks to a kitty instance over its --listen-on socket. It
// dials lazily and drops the connection after a failed write, so the next
// command redials instead of the client needing to be rebuilt.
type sockTransport struct {
path string
conn net.Conn
reader *bufio.Reader
}
func (t *sockTransport) connect() error {
if t.conn != nil {
return nil
}
conn, err := net.Dial("unix", t.path)
if err != nil {
return fmt.Errorf("failed to connect to kitty socket: %w", err)
}
t.conn = conn
t.reader = bufio.NewReader(conn)
return nil
}
func (t *sockTransport) send(frame []byte) error {
if err := t.connect(); err != nil {
return err
}
t.conn.SetWriteDeadline(time.Now().Add(rcTimeout))
defer func() {
if t.conn != nil {
t.conn.SetWriteDeadline(time.Time{})
}
}()
if _, err := t.conn.Write(frame); err != nil {
t.drop()
return fmt.Errorf("failed to write message: %w", err)
}
return nil
}
func (t *sockTransport) receive() ([]byte, error) {
if t.conn == nil {
return nil, fmt.Errorf("katnip: not connected")
}
t.conn.SetReadDeadline(time.Now().Add(rcTimeout))
defer func() {
if t.conn != nil {
t.conn.SetReadDeadline(time.Time{})
}
}()
if _, err := io.ReadFull(t.reader, make([]byte, len(kittyMsgPrefix))); err != nil {
t.drop()
return nil, fmt.Errorf("failed to read response header: %w", err)
}
frame, err := t.readFrame()
if err != nil {
t.drop()
return nil, err
}
return frame, nil
}
func (t *sockTransport) readFrame() ([]byte, error) {
var buf bytes.Buffer
for {
b, err := t.reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("reading frame: %w", err)
}
if b == esc {
next, err := t.reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("reading frame: %w", err)
}
if next == '\\' {
return buf.Bytes(), nil
}
buf.WriteByte(b)
buf.WriteByte(next)
continue
}
buf.WriteByte(b)
}
}
func (t *sockTransport) drop() {
if t.conn != nil {
t.conn.Close()
}
t.conn = nil
t.reader = nil
}
func (t *sockTransport) duplex() bool { return true }
func (t *sockTransport) close() error {
if t.conn == nil {
return nil
}
err := t.conn.Close()
t.drop()
return err
}
// Kitty sends remote control commands to kitty.
type Kitty struct {
mu sync.Mutex
tr transport
// self addresses every command at the window this process runs in,
// which is what a panel controlling itself wants. Without it a command
// lands on whichever window kitty considers active, which for a panel
// is somebody else's.
self bool
}
// NewSelfKitty returns a client that controls the panel this process runs in,
// by writing remote control escape sequences to w. Every command carries
// "self", so it needs neither a socket nor a window id.
//
// w must not interleave with the rest of the terminal output; pass nil and
// call [Kitty.SetWriter] once the TUI exists. Until then commands go to
// os.Stdout.
func NewSelfKitty(w io.Writer) *Kitty {
return &Kitty{tr: &ttyTransport{w: w}, self: true}
}
// SetWriter points a self client at its terminal. Call it as soon as
// whatever owns the terminal is up.
func (k *Kitty) SetWriter(w io.Writer) {
k.mu.Lock()
defer k.mu.Unlock()
if t, ok := k.tr.(*ttyTransport); ok {
t.setWriter(w)
}
}
// NewKitty returns a client that talks to a kitty instance over its
// --listen-on socket.
//
// Deprecated: a panel controlling itself should use [NewSelfKitty], which
// needs no socket and no window id. This remains for driving an instance
// from the outside, which is what [Host] does.
func NewKitty(socketPath string) *Kitty {
return &Kitty{tr: &sockTransport{path: socketPath}}
}
func (k *Kitty) Close() error {
k.mu.Lock()
defer k.mu.Unlock()
return k.tr.close()
}
func packMsg(msg []byte) []byte {
frame := make([]byte, 0, len(kittyMsgPrefix)+len(msg)+len(kittyMsgSuffix))
frame = append(frame, kittyMsgPrefix...)
frame = append(frame, msg...)
frame = append(frame, kittyMsgSuffix...)
return frame
}
// withSelf adds "self" to a payload that does not already say who it is for.
// A caller that set "self" or "match" itself is left alone.
func withSelf(p []byte) ([]byte, error) {
fields := map[string]json.RawMessage{}
if len(p) > 0 {
if err := json.Unmarshal(p, &fields); err != nil {
return nil, fmt.Errorf("payload must be a JSON object to be self-addressed: %w", err)
}
}
if _, ok := fields["self"]; ok {
return p, nil
}
if _, ok := fields["match"]; ok {
return p, nil
}
fields["self"] = json.RawMessage("true")
return json.Marshal(fields)
}
// Dispatch sends a command without waiting for a result. Over a panel's own
// terminal there is nothing to wait for, so a command kitty rejects fails
// silently; use [Kitty.Command] when the answer matters.
func (k *Kitty) Dispatch(cmd string, payload any) error {
k.mu.Lock()
defer k.mu.Unlock()
_, err := k.command(cmd, payload, false)
return err
}
// Command sends a command and returns kitty's response. It needs a transport
// that can read, so it is for driving an instance over a socket, not for a
// panel talking to itself.
func (k *Kitty) Command(cmd string, payload any) (map[string]any, error) {
k.mu.Lock()
defer k.mu.Unlock()
return k.command(cmd, payload, true)
}
func (k *Kitty) command(cmd string, payload any, wantResponse bool) (map[string]any, error) {
var p []byte
var err error
// easiest way to induce omitempty for payload
if payload != nil {
p, err = json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to mashal payload: %w", err)
}
}
if k.self {
if p, err = withSelf(p); err != nil {
return nil, err
}
}
// Asking for a response over a panel's terminal would leave the reply
// in the TUI's input stream, so that combination is refused rather than
// silently answered with nothing.
if wantResponse && !k.tr.duplex() {
_, err := k.tr.receive()
return nil, err
}
msg := kittySockMsg{
Command: cmd,
Version: kittyMinVersion,
NoResponse: !wantResponse,
Payload: p,
}
msgBytes, err := json.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("failed to mashal message: %w", err)
}
if err := k.tr.send(packMsg(msgBytes)); err != nil {
return nil, err
}
if !wantResponse {
return nil, nil
}
respBytes, err := k.tr.receive()
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var resp map[string]any
if err = json.Unmarshal(respBytes, &resp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
respOk, ok := resp["ok"].(bool)
if !ok {
return nil, fmt.Errorf("invalid response schema: field 'ok' is missing/invalid.")
}
if !respOk {
respError, ok := resp["error"].(string)
if !ok {
return nil, fmt.Errorf("invalid response schema: field 'error' is missing/invalid")
}
return nil, fmt.Errorf("kitty error: %s", respError)
}
return resp, nil
}
// SetFontSize changes the font size of this panel's OS window.
//
// It goes through the action command rather than set-font-size, because
// set-font-size ignores who asked and always resizes kitty's active OS
// window.
func (k *Kitty) SetFontSize(size int) error {
return k.Dispatch("action", map[string]any{
"action": fmt.Sprintf("change_font_size current %d", size),
})
}
func (k *Kitty) SetOpacity(opacity float64) error {
return k.Dispatch("set-background-opacity", map[string]float64{"opacity": opacity})
}
// Resize sets the panel's size in cells. kitty's "incremental" means "change
// only the settings I named", not "treat these as offsets": the values are
// absolute.
func (k *Kitty) Resize(columns, lines int) error {
return k.Dispatch("resize-os-window", map[string]any{
"action": "os-panel",
"incremental": true,
"os_panel": []string{
fmt.Sprintf("lines=%d", lines),
fmt.Sprintf("columns=%d", columns),
},
})
}
// Move places the panel at the given margins from the top left of its
// output. Only meaningful for a panel on no edge.
func (k *Kitty) Move(x, y int) error {
return k.Dispatch("resize-os-window", map[string]any{
"action": "os-panel",
"incremental": true,
"os_panel": []string{
fmt.Sprintf("margin-left=%d", x),
fmt.Sprintf("margin-top=%d", y),
},
})
}
func (k *Kitty) Show() error {
return k.Dispatch("resize-os-window", map[string]string{
"action": "show",
})
}
func (k *Kitty) Hide() error {
return k.Dispatch("resize-os-window", map[string]string{
"action": "hide",
})
}
func (k *Kitty) ToggleVisibility() error {
return k.Dispatch("resize-os-window", map[string]string{
"action": "toggle-visibility",
})
}