Repository navigation
Expand file tree
/
Copy pathpanel.go
More file actions
610 lines (534 loc) · 17.1 KB
/
Copy pathpanel.go
File metadata and controls
610 lines (534 loc) · 17.1 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// 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.
//go:generate stringer -type=Layer,FocusPolicy,Edge -linecomment -output panel_string.go
package katnip
import (
"context"
"fmt"
"io"
"maps"
"os"
"os/exec"
"slices"
"strconv"
"syscall"
"github.com/codelif/shmstream"
)
// Panel is one kitty desktop panel and the process running inside it.
//
// A panel is either its own kitty process (see [NewPanel]) or one window of
// an instance that hosts many (see [Host.NewPanel]). The two behave the same
// from here: start it, wait for it, stop it, and talk to the process over
// its stream.
type Panel struct {
// Cmd is the underlying process for a panel that owns its kitty. It is
// nil for a hosted panel, which has no process of its own.
//
// Deprecated: set Config.Env rather than reaching in here; a hosted
// panel has no Cmd to reach into.
Cmd *exec.Cmd
// host is set for a panel living in an instance somebody else owns.
host *Host
// id tags a hosted panel's window so it can be addressed after
// creation, without depending on a window id that nothing guarantees.
id string
// windowID is what kitty called the window, kept for diagnostics.
windowID uint64
// hostEnv is the environment for a hosted panel's process, which is
// passed at launch rather than inherited.
hostEnv []string
// done is closed once a hosted panel's window is gone.
done chan struct{}
// waitErr is why the panel ended, read only after done is closed.
waitErr error
name string
config Config
started bool
shmStream *shmstream.StreamBuffer
shmIo io.ReadWriter
shmErr error
}
type PanelHandler interface {
Run(k *Kitty, rw io.ReadWriter) int
}
type PanelFunc func(k *Kitty, rw io.ReadWriter) int
func (f PanelFunc) Run(k *Kitty, rw io.ReadWriter) int {
return f(k, rw)
}
type Layer int
const (
LayerBackground Layer = iota + 1 // background
LayerBottom // bottom
LayerTop // top
LayerOverlay // overlay
)
type FocusPolicy int
const (
FocusExclusive FocusPolicy = iota + 1 // exclusive
FocusNotAllowed // not-allowed
FocusOnDemand // on-demand
)
type Edge int
const (
EdgeBackground Edge = iota + 1 // background
EdgeBottom // bottom
EdgeCenter // center
EdgeCenterSized // center-sized
EdgeLeft // left
EdgeNone // none
EdgeRight // right
EdgeTop // top
)
// Unit is how [Config.Size] is counted. Margins are always pixels.
type Unit int
const (
UnitCells Unit = iota
UnitPixels
)
type Vector struct {
X, Y int
}
type Margins struct {
Top, Bottom, Left, Right int
}
// Config describes a panel. It covers the panel kitten's options as of kitty
// 0.48; the ones that only apply to a panel owning its own kitty process are
// marked, and are ignored by [Host.NewPanel].
type Config struct {
// Position is the top left margin, in pixels. Only meaningful for
// EdgeNone and EdgeCenter panels.
Position Vector
// Size is columns by lines, counted in SizeUnit. Zero on an axis
// leaves it to kitty, which for an edge panel means "fill it".
Size Vector
SizeUnit Unit
// Margin is the full set of margins; Bottom and Right have no Position
// equivalent. Top and Left here win over Position when non-zero.
Margin Margins
Layer Layer
FocusPolicy FocusPolicy
Edge Edge
OutputName string
Class string
HideOnFocusLoss bool
// OSWindowTag is the WM_NAME part of the X11 window property; kitty
// falls back to Class when it is empty.
OSWindowTag string
// ExclusiveZone is how much space the panel reserves, in pixels. Nil
// leaves kitty's default, which derives it from Edge and Size. It only
// has an effect on an edge panel when OverrideExclusiveZone is also
// set. Wayland only.
ExclusiveZone *int
OverrideExclusiveZone bool
// GrabKeyboard routes the OS's global shortcuts to this panel.
// Own-process only.
GrabKeyboard bool
// StartAsHidden maps the panel hidden. Own-process only: it is a kitty
// process flag, so a hosted panel has to be created and then hidden.
StartAsHidden bool
// SingleInstance and InstanceGroup ask kitty to put this panel in an
// existing panel process instead of starting one.
//
// Deprecated: this does not do what it looks like it does, and [Host]
// is the supported way to share one process. Three things go wrong.
// The launching process exits immediately with no window id and no
// handle, so there is nothing to Wait on unless
// WaitForSingleInstanceWindowClose is set. ListenOn is silently
// dropped for every invocation after the first, so a per-panel control
// socket is impossible. And KittyOverrides from a later invocation
// reload config for the whole instance, resizing panels that were
// already up. The instance is also keyed on a hardcoded "panel"
// prefix, so these panels can never join a plain kitty instance.
SingleInstance bool
InstanceGroup string
// WaitForSingleInstanceWindowClose keeps the launching process alive
// until the panel's window closes, instead of exiting immediately.
// Only meaningful with SingleInstance. Note that killing that process
// does not close the panel it opened.
WaitForSingleInstanceWindowClose bool
// ToggleVisibility flips an existing instance's panels instead of
// creating one. MoveToActiveMonitor moves them while showing.
// Both are SingleInstance only.
ToggleVisibility bool
MoveToActiveMonitor bool
// ListenOn is a remote control socket for the panel's own kitty, in
// kitty's address form, e.g. "unix:/run/user/1000/panel". Rarely
// needed: a panel controls itself over its own terminal, see
// [NewSelfKitty]. Own-process only.
ListenOn string
// Detach forks the panel off the controlling terminal; the parent
// exits at once, so there is nothing left to Wait on.
// Own-process only.
Detach bool
// DetachedLog collects the detached panel's output.
DetachedLog string
DebugRendering bool
DebugInput bool
// ConfigFile is kitty's --config. "NONE" ignores the user's
// kitty.conf. Own-process only: a hosted panel takes the config of the
// instance hosting it, see [HostConfig].
ConfigFile string
// Command is what runs inside the panel. Empty re-executes the current
// binary, which with [Register] is how a panel gets its handler.
Command []string
// Env is added to the panel process's environment.
Env []string
// appended to the last, can be used to add unspecified options
Overrides map[string]string
// Easier way to add -o options. Own-process only.
KittyOverrides []string
// kitty command to be invoked, default: kitty
//
// one usecase: when multiple versions of kitty are installed and maintained using symlinks
KittyCmd string
}
const kittyCmd = "kitty"
func (u Unit) suffix() string {
if u == UnitPixels {
return "px"
}
return ""
}
// marginTop and marginLeft prefer the Margins form, falling back to the
// older Position field.
func (c Config) marginTop() int {
if c.Margin.Top != 0 {
return c.Margin.Top
}
return c.Position.Y
}
func (c Config) marginLeft() int {
if c.Margin.Left != 0 {
return c.Margin.Left
}
return c.Position.X
}
// panelSettings renders the layer shell options in kitty's key=value form.
// The panel kitten takes them with a leading "--", and launch --os-panel
// takes them exactly like this, so both backends share one mapping.
//
// Only options that reach kitty's LayerShellConfig belong here. Anything
// that configures the kitty process rather than the surface is emitted by
// the own-process backend instead, because a hosted panel cannot have it.
func (c Config) panelSettings() []string {
var s []string
add := func(k string, v any) { s = append(s, fmt.Sprintf("%s=%v", k, v)) }
if c.Layer > 0 {
add("layer", c.Layer)
}
if c.FocusPolicy > 0 {
add("focus-policy", c.FocusPolicy)
}
if c.Edge > 0 {
add("edge", c.Edge)
}
if c.Size.X != 0 {
add("columns", strconv.Itoa(c.Size.X)+c.SizeUnit.suffix())
}
if c.Size.Y != 0 {
add("lines", strconv.Itoa(c.Size.Y)+c.SizeUnit.suffix())
}
if m := c.marginLeft(); m != 0 {
add("margin-left", m)
}
if m := c.marginTop(); m != 0 {
add("margin-top", m)
}
if c.Margin.Bottom != 0 {
add("margin-bottom", c.Margin.Bottom)
}
if c.Margin.Right != 0 {
add("margin-right", c.Margin.Right)
}
if c.OutputName != "" {
add("output-name", c.OutputName)
}
if c.HideOnFocusLoss {
add("hide-on-focus-loss", "yes")
}
if c.ExclusiveZone != nil {
add("exclusive-zone", *c.ExclusiveZone)
}
if c.OverrideExclusiveZone {
add("override-exclusive-zone", "yes")
}
return s
}
// class is the Wayland namespace / X11 WM_CLASS for the panel's surface.
func (c Config) class(name string) string {
if c.Class != "" {
return c.Class
}
return name
}
// command is what runs inside the panel. The default re-executes this
// binary, which is what [Register] dispatches on.
func (c Config) command() []string {
if len(c.Command) > 0 {
return c.Command
}
return []string{fmt.Sprintf("/proc/%d/exe", os.Getpid())}
}
// NewPanel builds a panel that owns its own kitty process. Nothing starts
// until [Panel.Start] or [Panel.Run].
//
// To put many panels in one kitty process instead, see [Spawn] and
// [Host.NewPanel].
func NewPanel(name string, config Config) *Panel {
args := []string{"+kitten", "panel"}
// The panel talks to kitty over its own terminal rather than a socket,
// so remote control has to be allowed from there.
args = append(args, "-o", "allow_remote_control=yes")
for _, kv := range config.panelSettings() {
args = append(args, "--"+kv)
}
if config.ConfigFile != "" {
args = append(args, "--config", config.ConfigFile)
}
args = append(args, "--class", config.class(name))
if config.OSWindowTag != "" {
args = append(args, "--os-window-tag", config.OSWindowTag)
}
if config.StartAsHidden {
args = append(args, "--start-as-hidden")
}
if config.GrabKeyboard {
args = append(args, "--grab-keyboard")
}
if config.InstanceGroup != "" {
args = append(args,
"--single-instance",
"--instance-group", config.InstanceGroup,
)
} else if config.SingleInstance {
args = append(args, "--single-instance")
}
if config.WaitForSingleInstanceWindowClose {
args = append(args, "--wait-for-single-instance-window-close")
}
if config.ToggleVisibility {
args = append(args, "--toggle-visibility")
}
if config.MoveToActiveMonitor {
args = append(args, "--move-to-active-monitor")
}
if config.ListenOn != "" {
args = append(args, "--listen-on", config.ListenOn)
}
if config.Detach {
args = append(args, "--detach")
}
if config.DetachedLog != "" {
args = append(args, "--detached-log", config.DetachedLog)
}
if config.DebugRendering {
args = append(args, "--debug-rendering")
}
if config.DebugInput {
args = append(args, "--debug-input")
}
for _, o := range config.KittyOverrides {
args = append(args, "-o", o)
}
// Sorted so the same Config always produces the same command line.
for _, k := range slices.Sorted(maps.Keys(config.Overrides)) {
args = append(args, k, config.Overrides[k])
}
args = append(args, config.command()...)
kc := kittyCmd
if config.KittyCmd != "" {
kc = config.KittyCmd
}
cmd := exec.Command(kc, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGTERM}
cmd.Env = append(os.Environ(), GetEnvPair("INSTANCE", name))
cmd.Env = append(cmd.Env, config.Env...)
p := &Panel{
Cmd: cmd,
name: name,
config: config,
}
p.openStream(func(kv string) { cmd.Env = append(cmd.Env, kv) })
return p
}
// openStream creates the panel's side channel and tells the child where to
// find it. A panel without one still works; it just has no wire.
func (p *Panel) openStream(setEnv func(string)) {
shmStream, err := shmstream.New(shmstream.Config{Bidirectional: true})
if err != nil {
p.shmErr = fmt.Errorf("creating the panel stream: %w", err)
return
}
p.shmStream = shmStream
setEnv(GetEnvPair("SHM_PATH", shmStream.Path()))
reader, _ := shmStream.NewReader()
writer, _ := shmStream.NewWriter()
p.shmIo = &struct {
io.Reader
io.Writer
}{reader, writer}
}
func (p *Panel) cleanup() {
if p.shmStream != nil {
p.shmStream.Close()
p.shmStream = nil
p.shmIo = nil
}
}
// ShmPath is where another process can attach to this panel's stream, with
// [OpenStream]. Empty when the panel has no stream.
func (p *Panel) ShmPath() string {
if p.shmStream == nil {
return ""
}
return p.shmStream.Path()
}
// EndStream marks the panel's side of the stream finished: a Read on it
// returns io.EOF instead of blocking forever, here and in a process that
// took the stream over with [OpenStream]. Call it once the panel process is
// gone — a reader has no other way to notice that.
func (p *Panel) EndStream() {
if p.shmStream != nil {
p.shmStream.CloseRead()
}
}
// Close ends the stream and unmaps it from this process. The mapping is a
// megabyte per panel and nothing else frees it, so call this once the panel
// is gone and nothing here is still reading its stream — the memory goes
// away under a concurrent Read.
func (p *Panel) Close() {
p.EndStream()
p.cleanup()
}
// Stream is an existing panel stream attached from a process other than the
// one that spawned the panel. It takes the spawner's side of the wire, so the
// spawner must stop reading and writing it first.
type Stream struct {
buf *shmstream.StreamBuffer
io.ReadWriter
}
// OpenStream attaches to the panel stream at path (see [Panel.ShmPath]),
// taking the spawner's side of it. Reading resumes exactly where the spawner
// left off; the cursors live in the shared memory, not in either process.
func OpenStream(path string) (*Stream, error) {
buf, err := shmstream.OpenAs(path, true)
if err != nil {
return nil, err
}
reader, err := buf.NewReader()
if err != nil {
buf.Close()
return nil, err
}
writer, err := buf.NewWriter()
if err != nil {
buf.Close()
return nil, err
}
return &Stream{buf: buf, ReadWriter: &struct {
io.Reader
io.Writer
}{reader, writer}}, nil
}
// Close unmaps the stream from this process.
func (s *Stream) Close() { s.buf.Close() }
// Run starts the panel and waits for it. Not available for a hosted panel,
// which has no process to block on here.
func (p *Panel) Run() error {
if p.host != nil {
return fmt.Errorf("katnip: a hosted panel has no process to run; use Start and Wait")
}
if p.started {
return fmt.Errorf("panel already started")
}
p.started = true
return p.Cmd.Run()
}
func (p *Panel) Start() error {
if p.started {
return fmt.Errorf("panel already started")
}
p.started = true
if p.shmErr != nil {
return p.shmErr
}
if p.host != nil {
return p.host.start(p)
}
return p.Cmd.Start()
}
// Wait returns once the panel is gone.
func (p *Panel) Wait() error {
if p.host != nil {
<-p.done
return p.waitErr
}
return p.Cmd.Wait()
}
// Stop asks the process in the panel to exit, the way ctrl-c would.
func (p *Panel) Stop() error {
if p.host != nil {
return p.host.signal(p, "SIGINT")
}
if p.Cmd.Process == nil {
return fmt.Errorf("panel not started")
}
return p.Cmd.Process.Signal(os.Interrupt)
}
// Kill takes the panel away without asking.
func (p *Panel) Kill() error {
if p.host != nil {
return p.host.closeWindow(p)
}
if p.Cmd.Process == nil {
return fmt.Errorf("panel not started")
}
return p.Cmd.Process.Kill()
}
func (p *Panel) Reader() io.Reader {
return p.shmIo
}
func (p *Panel) Writer() io.Writer {
return p.shmIo
}
func (p *Panel) ReadWriter() io.ReadWriter {
return p.shmIo
}
// ReadOutput reads all available output from the panel
// Returns empty slice if no shared memory reader is available
func (p *Panel) ReadOutput() ([]byte, error) {
if p.shmIo == nil {
return []byte{}, nil
}
// Read available data
buf := make([]byte, 4096)
n, err := p.shmIo.Read(buf)
if err != nil && err != io.EOF {
return nil, err
}
return buf[:n], nil
}
func NewPanelContext(ctx context.Context, name string, config Config) *Panel {
p := NewPanel(name, config)
cmd := exec.CommandContext(ctx, p.Cmd.Args[0], p.Cmd.Args[1:]...)
cmd.Env = p.Cmd.Env
cmd.SysProcAttr = p.Cmd.SysProcAttr
p.Cmd = cmd
return p
}