Debian Codegraph @

widgets/term/term.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package term
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "runtime/debug"
9 "strconv"
10 "strings"
11 "sync"
12 "sync/atomic"
13 "syscall"
14 "time"
15
16 "git.sr.ht/~rockorager/vaxis"
17 "git.sr.ht/~rockorager/vaxis/ansi"
18 "git.sr.ht/~rockorager/vaxis/log"
19 "github.com/creack/pty"
20 "github.com/mattn/go-sixel"
21 )
22
23 type (
24 column int
25 row int
26 )
27
28 // Model models a virtual terminal
29 type Model struct {
30 // If true, OSC8 enables the output of OSC8 strings. Otherwise, any OSC8
31 // sequences will be stripped
32 OSC8 bool
33 // Set the TERM environment variable to be passed to the command's
34 // environment. If not set, xterm-256color will be used
35 TERM string
36
37 mu sync.Mutex
38
39 vx *vaxis.Vaxis
40
41 activeScreen [][]cell
42 altScreen [][]cell
43 primaryScreen [][]cell
44
45 charsets charsets
46 cursor cursor
47 margin margin
48 mode mode
49 sShift charset
50 tabStop []column
51 // lastCol is a flag indicating we printed in the last col
52 lastCol bool
53
54 primaryState cursorState
55 altState cursorState
56
57 cmd *exec.Cmd
58 dirty bool
59 parser *ansi.Parser
60 pty *os.File
61 rows int
62 cols int
63
64 eventHandler func(vaxis.Event)
65 events chan vaxis.Event
66 focused int32
67 graphics []*Image
68 timer *time.Timer
69 }
70
71 type cursorState struct {
72 charsets charsets
73 cursor cursor
74 decawm bool
75 decom bool
76 }
77
78 type margin struct {
79 top row
80 bottom row
81 left column
82 right column
83 }
84
85 func New() *Model {
86 m := &Model{
87 OSC8: true,
88 charsets: charsets{
89 designations: map[charsetDesignator]charset{
90 g0: ascii,
91 g1: ascii,
92 g2: ascii,
93 g3: ascii,
94 },
95 },
96 mode: mode{
97 decawm: true,
98 dectcem: true,
99 },
100 primaryState: cursorState{
101 charsets: charsets{
102 designations: map[charsetDesignator]charset{
103 g0: ascii,
104 g1: ascii,
105 g2: ascii,
106 g3: ascii,
107 },
108 },
109 decawm: true,
110 },
111 altState: cursorState{
112 charsets: charsets{
113 designations: map[charsetDesignator]charset{
114 g0: ascii,
115 g1: ascii,
116 g2: ascii,
117 g3: ascii,
118 },
119 },
120 decawm: true,
121 },
122 eventHandler: func(ev vaxis.Event) {},
123 // Buffering to 2 events. If there is ever a case where one
124 // sequence can trigger two events, this should be increased
125 events: make(chan vaxis.Event, 2),
126 timer: time.NewTimer(0),
127 }
128 m.setDefaultTabStops()
129 return m
130 }
131
132 func (vt *Model) StartWithSize(cmd *exec.Cmd, width int, height int) error {
133 if cmd == nil {
134 return fmt.Errorf("no command to run")
135 }
136 vt.cmd = cmd
137
138 if vt.TERM == "" {
139 vt.TERM = "xterm-kitty"
140 }
141
142 env := os.Environ()
143 if cmd.Env != nil {
144 env = cmd.Env
145 }
146 cmd.Env = append(env, "TERM="+vt.TERM)
147
148 // Start the command with a pty.
149 var err error
150 winsize := pty.Winsize{
151 Cols: uint16(width),
152 Rows: uint16(height),
153 }
154 vt.pty, err = pty.StartWithAttrs(
155 cmd,
156 &winsize,
157 &syscall.SysProcAttr{
158 Setsid: true,
159 Setctty: true,
160 Ctty: 1,
161 })
162 if err != nil {
163 return err
164 }
165
166 vt.resize(width, height)
167 vt.parser = ansi.NewParser(vt.pty)
168 go func() {
169 defer vt.recover()
170 for {
171 select {
172 case seq := <-vt.parser.Next():
173 switch seq := seq.(type) {
174 case ansi.EOF:
175 err := cmd.Wait()
176 vt.eventHandler(EventClosed{
177 Term: vt,
178 Error: err,
179 })
180 return
181 default:
182 vt.update(seq)
183 }
184 case ev := <-vt.events:
185 vt.eventHandler(ev)
186 case <-vt.timer.C:
187 vt.mu.Lock()
188 vt.timer.Stop()
189 vt.mu.Unlock()
190 vt.eventHandler(vaxis.Redraw{})
191 }
192 }
193 }()
194 return nil
195 }
196
197 // Start starts the terminal with the specified command. Start returns when the
198 // command has been successfully started.
199 func (vt *Model) Start(cmd *exec.Cmd) error {
200 return vt.StartWithSize(cmd, 80, 24)
201 }
202
203 // Update is called from the host application. This is user input
204 func (vt *Model) Update(msg vaxis.Event) {
205 vt.mu.Lock()
206 defer vt.mu.Unlock()
207 vt.invalidate()
208 switch msg := msg.(type) {
209 case vaxis.Key:
210 str := encodeXterm(msg, vt.mode.deckpam, vt.mode.decckm)
211 vt.pty.WriteString(str)
212 case vaxis.PasteStartEvent:
213 if vt.mode.paste {
214 vt.pty.WriteString("\x1B[200~")
215 return
216 }
217 case vaxis.PasteEndEvent:
218 if vt.mode.paste {
219 vt.pty.WriteString("\x1B[201~")
220 return
221 }
222 case vaxis.Mouse:
223 mouse := vt.handleMouse(msg)
224 vt.pty.WriteString(mouse)
225 return
226 case vaxis.ColorThemeUpdate:
227 if vt.mode.colorScheme {
228 vt.pty.WriteString(fmt.Sprintf("\x1b[?997;%dn", msg.Mode))
229 return
230 }
231 }
232 }
233
234 // only call invalidate while a lock is held
235 func (vt *Model) invalidate() {
236 if vt.dirty {
237 return
238 }
239 vt.dirty = true
240 vt.timer.Reset(8 * time.Millisecond)
241 }
242
243 // update is called from the PTY routine...this is updating the internal model
244 // based on the underlying process
245 func (vt *Model) update(seq ansi.Sequence) {
246 vt.mu.Lock()
247 defer vt.mu.Unlock()
248 defer vt.parser.Finish(seq)
249 defer vt.invalidate()
250 switch seq := seq.(type) {
251 case ansi.Print:
252 vt.print(seq)
253 case ansi.C0:
254 vt.c0(rune(seq))
255 case ansi.ESC:
256 esc := append(seq.Intermediate, seq.Final)
257 vt.esc(string(esc))
258 case ansi.CSI:
259 csi := append(seq.Intermediate, seq.Final)
260 vt.csi(string(csi), seq.Parameters)
261 case ansi.OSC:
262 vt.osc(string(seq.Payload))
263 case ansi.DCS:
264 switch seq.Final {
265 case 'q': // mayb sixel
266 if len(seq.Intermediate) > 0 {
267 return
268 }
269 if len(seq.Parameters) > 0 {
270 return
271 }
272 // Write the raw sequence to the writer
273 buf := bytes.NewBuffer(nil)
274 // DCS
275 buf.Write([]byte{'\x1B', 'P'})
276 // Params
277 for i, p := range seq.Parameters {
278 buf.WriteString(strconv.Itoa(p))
279 if i <= len(seq.Parameters)-1 {
280 buf.WriteByte(';')
281 }
282 }
283 // Final
284 buf.WriteByte('q')
285 // Data
286 buf.WriteString(string(seq.Data))
287 // ST
288 buf.Write([]byte{0x1B, '\\'})
289 // Decode the sixel
290 log.Info("SIXEL %d", buf.Len())
291 dec := sixel.NewDecoder(buf)
292 img := &Image{}
293 img.origin.row = int(vt.cursor.row)
294 img.origin.col = int(vt.cursor.col)
295 err := dec.Decode(&img.img)
296 if err != nil {
297 log.Error("couldn't decode sixel: %v", err)
298 return
299 }
300 vt.graphics = append(vt.graphics, img)
301 }
302 case ansi.APC:
303 vt.postEvent(EventAPC{Payload: seq.Data})
304 }
305 }
306
307 func (vt *Model) String() string {
308 vt.mu.Lock()
309 defer vt.mu.Unlock()
310 str := strings.Builder{}
311 for row := range vt.activeScreen {
312 for col := range vt.activeScreen[row] {
313 _, _ = str.WriteString(vt.activeScreen[row][col].rune())
314 }
315 if row < vt.height()-1 {
316 str.WriteRune('\n')
317 }
318 }
319 return str.String()
320 }
321
322 func (vt *Model) postEvent(ev vaxis.Event) {
323 vt.events <- ev
324 }
325
326 func (vt *Model) Attach(fn func(ev vaxis.Event)) {
327 vt.mu.Lock()
328 defer vt.mu.Unlock()
329 vt.eventHandler = fn
330 }
331
332 func (vt *Model) Detach() {
333 vt.mu.Lock()
334 defer vt.mu.Unlock()
335 vt.eventHandler = func(ev vaxis.Event) {}
336 }
337
338 func (vt *Model) recover() {
339 err := recover()
340 if err == nil {
341 return
342 }
343 ret := strings.Builder{}
344 ret.WriteString(fmt.Sprintf("cursor row=%d col=%d\n", vt.cursor.row, vt.cursor.col))
345 ret.WriteString(fmt.Sprintf("margin left=%d right=%d\n", vt.margin.left, vt.margin.right))
346 ret.WriteString(fmt.Sprintf("%s\n", err))
347 ret.Write(debug.Stack())
348
349 vt.postEvent(EventPanic(fmt.Errorf(ret.String())))
350 vt.Close()
351 }
352
353 func (vt *Model) Resize(w int, h int) {
354 vt.resize(w, h)
355 _ = pty.Setsize(vt.pty, &pty.Winsize{
356 Cols: uint16(w),
357 Rows: uint16(h),
358 })
359 }
360
361 func (vt *Model) resize(w int, h int) {
362 primary := vt.primaryScreen
363 vt.altScreen = make([][]cell, h)
364 vt.primaryScreen = make([][]cell, h)
365 for i := range vt.altScreen {
366 vt.altScreen[i] = make([]cell, w)
367 vt.primaryScreen[i] = make([]cell, w)
368 }
369 last := vt.cursor.row
370 vt.margin.bottom = row(h) - 1
371 vt.margin.right = column(w) - 1
372 vt.cursor.row = 0
373 vt.cursor.col = 0
374 vt.lastCol = false
375 vt.activeScreen = vt.primaryScreen
376
377 // transfer primary to new, skipping the last row
378 for row := 0; row < len(primary); row += 1 {
379 if row == int(last) {
380 break
381 }
382 wrapped := false
383 for col := 0; col < len(primary[0]); col += 1 {
384 cell := primary[row][col]
385 vt.cursor.Style = cell.Style
386 vt.print(ansi.Print{
387 Grapheme: cell.Character.Grapheme,
388 Width: cell.Character.Width,
389 })
390 wrapped = cell.wrapped
391 }
392 if !wrapped {
393 vt.nel()
394 }
395 }
396 switch vt.mode.smcup {
397 case false:
398 vt.activeScreen = vt.primaryScreen
399 default:
400 vt.activeScreen = vt.altScreen
401 }
402 }
403
404 func (vt *Model) width() int {
405 if len(vt.activeScreen) > 0 {
406 return len(vt.activeScreen[0])
407 }
408 return 0
409 }
410
411 func (vt *Model) height() int {
412 return len(vt.activeScreen)
413 }
414
415 // print sets the current cell contents to the given rune. The attributes will
416 // be copied from the current cursor attributes
417 func (vt *Model) print(seq ansi.Print) {
418 if len(seq.Grapheme) == 1 &&
419 vt.charsets.designations[vt.charsets.selected] == decSpecialAndLineDrawing {
420 shifted, ok := decSpecial[seq.Grapheme[0]]
421 if ok {
422 seq.Grapheme = string(shifted)
423 }
424 }
425
426 // If we are single-shifted, move the previous charset into the current
427 if vt.charsets.singleShift {
428 vt.charsets.selected = vt.charsets.saved
429 }
430
431 w := seq.Width
432
433 // handle wrapping
434 var wrap bool
435 // We printed in the last column last time
436 if vt.lastCol {
437 wrap = true
438 }
439 // We don't have room for this character so wrap
440 if vt.cursor.col+column(w)-1 > vt.margin.right {
441 wrap = true
442 }
443 // We aren't in wrap mode, never wrap
444 if !vt.mode.decawm {
445 wrap = false
446 }
447
448 if wrap {
449 vt.lastCol = false
450 vt.activeScreen[vt.cursor.row][vt.width()-1].wrapped = true
451 vt.nel()
452 }
453
454 col := vt.cursor.col
455 rw := vt.cursor.row
456
457 if vt.mode.irm {
458 line := vt.activeScreen[rw]
459 for i := vt.margin.right; i > col; i -= 1 {
460 line[i] = line[i-column(w)]
461 }
462 }
463 if col > column(vt.width())-1 {
464 col = column(vt.width()) - 1
465 }
466 if rw > row(vt.height()-1) {
467 rw = row(vt.height() - 1)
468 }
469
470 if w == 0 {
471 if col-1 < 0 {
472 return
473 }
474 return
475 }
476 cell := cell{
477 Cell: vaxis.Cell{
478 Character: vaxis.Character{
479 Grapheme: seq.Grapheme,
480 Width: seq.Width,
481 },
482 Style: vt.cursor.Style,
483 },
484 }
485
486 vt.activeScreen[rw][col] = cell
487
488 // Set trailing cells to a space if wide rune
489 for i := column(1); i < column(w); i += 1 {
490 if col+i > vt.margin.right {
491 break
492 }
493 vt.activeScreen[rw][col+i].Character.Grapheme = " "
494 vt.activeScreen[rw][col+i].Style = vt.cursor.Style
495 }
496
497 switch {
498 case !vt.mode.decawm && vt.cursor.col+column(w) > vt.margin.right:
499 default:
500 vt.cursor.col += column(w)
501 }
502 if vt.cursor.col >= vt.margin.right+1 && vt.mode.decawm {
503 vt.lastCol = true
504 }
505 }
506
507 // scrollUp shifts all text upward by n rows. Semantically, this is backwards -
508 // usually scroll up would mean you shift rows down
509 func (vt *Model) scrollUp(n int) {
510 for row := range vt.activeScreen {
511 if row > int(vt.margin.bottom) {
512 continue
513 }
514 if row < int(vt.margin.top) {
515 continue
516 }
517 if row+n > int(vt.margin.bottom) {
518 for col := vt.margin.left; col <= vt.margin.right; col += 1 {
519 vt.activeScreen[row][col].erase(vt.cursor.Style.Background)
520 }
521 continue
522 }
523 copy(vt.activeScreen[row], vt.activeScreen[row+n])
524 }
525 }
526
527 // scrollDown shifts all lines down by n rows.
528 func (vt *Model) scrollDown(n int) {
529 for r := vt.margin.bottom; r >= vt.margin.top; r -= 1 {
530 if r-row(n) < vt.margin.top {
531 for col := vt.margin.left; col <= vt.margin.right; col += 1 {
532 vt.activeScreen[r][col].erase(vt.cursor.Style.Background)
533 }
534 continue
535 }
536 copy(vt.activeScreen[r], vt.activeScreen[r-row(n)])
537 }
538 }
539
540 func (vt *Model) Close() {
541 vt.mu.Lock()
542 defer vt.mu.Unlock()
543 if vt.cmd != nil && vt.cmd.Process != nil {
544 vt.cmd.Process.Kill()
545 vt.cmd.Wait()
546 }
547 vt.pty.Close()
548 }
549
550 func (vt *Model) Draw(win vaxis.Window) {
551 vt.mu.Lock()
552 defer vt.mu.Unlock()
553 vt.dirty = false
554 width, height := win.Size()
555 if int(width) != vt.width() || int(height) != vt.height() {
556 win.Width = width
557 win.Height = height
558 vt.Resize(width, height)
559 }
560 for row := 0; row < vt.height(); row += 1 {
561 for col := 0; col < vt.width(); {
562 cell := vt.activeScreen[row][col]
563 w := cell.Width
564
565 if cell.Grapheme == "" {
566 cell.Grapheme = " "
567 }
568
569 win.SetCell(col, row, cell.Cell)
570 if w == 0 {
571 w = 1
572 }
573 col += w
574 }
575 }
576 if vt.mode.dectcem && atomicLoad(&vt.focused) {
577 win.ShowCursor(int(vt.cursor.col), int(vt.cursor.row), vt.cursor.style)
578 }
579 vx := win.Vx
580 vt.vx = vx
581 outer:
582 for _, img := range vt.graphics {
583 for _, imgVx := range img.vaxii {
584 if vx != imgVx.vx {
585 continue
586 }
587 // We have already created an image for this
588 // Vaxis. All we have to do is draw it
589 win := win.New(img.origin.col, img.origin.row, -1, -1)
590 imgVx.vxImage.Draw(win)
591 continue outer
592 }
593 // We haven't encountered this vaxis before
594 vxImg, err := vx.NewImage(img.img)
595 if err != nil {
596 log.Error("couldn't create Vaxis image: %v", err)
597 continue
598 }
599 // We "resize" the image to the full window size. This will
600 // trigger the encoding
601 vxImg.Resize(win.Size())
602 img.vaxii = append(img.vaxii, &vaxisImage{
603 vx: vx,
604 vxImage: vxImg,
605 })
606 }
607 }
608
609 func (vt *Model) Focus() {
610 vt.mu.Lock()
611 defer vt.mu.Unlock()
612 atomicStore(&vt.focused, true)
613 if vt.mode.focusEvents {
614 vt.pty.WriteString("\x1b[I")
615 }
616 }
617
618 func (vt *Model) Blur() {
619 vt.mu.Lock()
620 defer vt.mu.Unlock()
621 atomicStore(&vt.focused, false)
622 if vt.mode.focusEvents {
623 vt.pty.WriteString("\x1b[O")
624 }
625 }
626
627 // func (vt *VT) HandleEvent(e tcell.Event) bool {
628 // vt.mu.Lock()
629 // defer vt.mu.Unlock()
630 // switch e := e.(type) {
631 // case *tcell.EventKey:
632 // vt.pty.WriteString(keyCode(e))
633 // return true
634 // case *tcell.EventPaste:
635 // switch {
636 // case vt.mode&paste == 0:
637 // return false
638 // case e.Start():
639 // vt.pty.WriteString(info.PasteStart)
640 // return true
641 // case e.End():
642 // vt.pty.WriteString(info.PasteEnd)
643 // return true
644 // }
645 // case *tcell.EventMouse:
646 // str := vt.handleMouse(e)
647 // vt.pty.WriteString(str)
648 // }
649 // return false
650 // }
651
652 func atomicLoad(val *int32) bool {
653 return atomic.LoadInt32(val) == 1
654 }
655
656 func atomicStore(addr *int32, val bool) {
657 if val {
658 atomic.StoreInt32(addr, 1)
659 } else {
660 atomic.StoreInt32(addr, 0)
661 }
662 }