Debian Codegraph @

vt/emulator.go

raw
1 package vt
2
3 import (
4 "image/color"
5 "io"
6
7 uv "github.com/charmbracelet/ultraviolet"
8 "github.com/charmbracelet/ultraviolet/screen"
9 "github.com/charmbracelet/x/ansi"
10 "github.com/charmbracelet/x/ansi/parser"
11 )
12
13 // Logger represents a logger interface.
14 type Logger interface {
15 Printf(format string, v ...any)
16 }
17
18 // Emulator represents a virtual terminal emulator.
19 type Emulator struct {
20 handlers
21
22 // The terminal's indexed 256 colors.
23 colors [256]color.Color
24
25 // Both main and alt screens and a pointer to the currently active screen.
26 scrs [2]Screen
27 scr *Screen
28
29 // Character sets
30 charsets [4]CharSet
31
32 // log is the logger to use.
33 logger Logger
34
35 // terminal default colors.
36 defaultFg, defaultBg, defaultCur color.Color
37 fgColor, bgColor, curColor color.Color
38
39 // Terminal modes.
40 modes ansi.Modes
41
42 // The last written character.
43 lastChar rune // either ansi.Rune or ansi.Grapheme
44 // A slice of runes to compose a grapheme.
45 grapheme []rune
46
47 // The ANSI parser to use.
48 parser *ansi.Parser
49 // The last parser state.
50 lastState parser.State
51
52 cb Callbacks
53
54 // The terminal's icon name and title.
55 iconName, title string
56 // The current reported working directory. This is not validated.
57 cwd string
58
59 // tabstop is the list of tab stops.
60 tabstops *uv.TabStops
61
62 // I/O pipes.
63 pr *io.PipeReader
64 pw *io.PipeWriter
65
66 // The GL and GR character set identifiers.
67 gl, gr int
68 gsingle int // temporarily select GL or GR
69
70 // Indicates if the terminal is closed.
71 closed bool
72
73 // atPhantom indicates if the cursor is out of bounds.
74 // When true, and a character is written, the cursor is moved to the next line.
75 atPhantom bool
76 }
77
78 // NewEmulator creates a new virtual terminal emulator.
79 func NewEmulator(w, h int) *Emulator {
80 t := new(Emulator)
81 t.scrs[0] = *NewScreen(w, h)
82 t.scrs[1] = *NewScreen(w, h)
83 t.scr = &t.scrs[0]
84 t.scrs[0].cb = &t.cb
85 t.scrs[1].cb = &t.cb
86 t.parser = ansi.NewParser()
87 t.parser.SetParamsSize(parser.MaxParamsSize)
88 t.parser.SetDataSize(1024 * 1024 * 4) // 4MB data buffer
89 t.parser.SetHandler(ansi.Handler{
90 Print: t.handlePrint,
91 Execute: t.handleControl,
92 HandleCsi: t.handleCsi,
93 HandleEsc: t.handleEsc,
94 HandleDcs: t.handleDcs,
95 HandleOsc: t.handleOsc,
96 HandleApc: t.handleApc,
97 HandlePm: t.handlePm,
98 HandleSos: t.handleSos,
99 })
100 t.pr, t.pw = io.Pipe()
101 t.resetModes()
102 t.tabstops = uv.DefaultTabStops(w)
103 t.registerDefaultHandlers()
104
105 return t
106 }
107
108 // SetLogger sets the terminal's logger.
109 func (e *Emulator) SetLogger(l Logger) {
110 e.logger = l
111 }
112
113 // SetCallbacks sets the terminal's callbacks.
114 func (e *Emulator) SetCallbacks(cb Callbacks) {
115 e.cb = cb
116 e.scrs[0].cb = &e.cb
117 e.scrs[1].cb = &e.cb
118 }
119
120 // Touched returns the touched lines in the current screen buffer.
121 func (e *Emulator) Touched() []*uv.LineData {
122 return e.scr.Touched()
123 }
124
125 // String returns a string representation of the underlying screen buffer.
126 func (e *Emulator) String() string {
127 s := e.scr.buf.String()
128 return uv.TrimSpace(s)
129 }
130
131 // Render renders a snapshot of the terminal screen as a string with styles and
132 // links encoded as ANSI escape codes.
133 func (e *Emulator) Render() string {
134 return e.scr.buf.Render()
135 }
136
137 var _ uv.Screen = (*Emulator)(nil)
138
139 // Bounds returns the bounds of the terminal.
140 func (e *Emulator) Bounds() uv.Rectangle {
141 return e.scr.Bounds()
142 }
143
144 // CellAt returns the current focused screen cell at the given x, y position.
145 // It returns nil if the cell is out of bounds.
146 func (e *Emulator) CellAt(x, y int) *uv.Cell {
147 return e.scr.CellAt(x, y)
148 }
149
150 // SetCell sets the current focused screen cell at the given x, y position.
151 func (e *Emulator) SetCell(x, y int, c *uv.Cell) {
152 e.scr.SetCell(x, y, c)
153 }
154
155 // WidthMethod returns the width method used by the terminal.
156 func (e *Emulator) WidthMethod() uv.WidthMethod {
157 if e.isModeSet(ansi.UnicodeCoreMode) {
158 return ansi.GraphemeWidth
159 }
160 return ansi.WcWidth
161 }
162
163 // Draw implements the [uv.Drawable] interface.
164 func (e *Emulator) Draw(scr uv.Screen, area uv.Rectangle) {
165 bg := uv.EmptyCell
166 bg.Style.Bg = e.BackgroundColor()
167 screen.FillArea(scr, &bg, area)
168 for y := range e.Touched() {
169 if y < 0 || y >= e.Height() {
170 continue
171 }
172 for x := 0; x < e.Width(); {
173 w := 1
174 cell := e.CellAt(x, y)
175 if cell != nil {
176 cell = cell.Clone()
177 if cell.Width > 1 {
178 w = cell.Width
179 }
180 if cell.Style.Bg == nil && e.bgColor != nil {
181 cell.Style.Bg = e.bgColor
182 }
183 if cell.Style.Fg == nil && e.fgColor != nil {
184 cell.Style.Fg = e.fgColor
185 }
186 scr.SetCell(x+area.Min.X, y+area.Min.Y, cell)
187 }
188 x += w
189 }
190 }
191 }
192
193 // Height returns the height of the terminal.
194 func (e *Emulator) Height() int {
195 return e.scr.Height()
196 }
197
198 // Width returns the width of the terminal.
199 func (e *Emulator) Width() int {
200 return e.scr.Width()
201 }
202
203 // CursorPosition returns the terminal's cursor position.
204 func (e *Emulator) CursorPosition() uv.Position {
205 x, y := e.scr.CursorPosition()
206 return uv.Pos(x, y)
207 }
208
209 // Resize resizes the terminal.
210 func (e *Emulator) Resize(width int, height int) {
211 x, y := e.scr.CursorPosition()
212 if e.atPhantom {
213 if x < width-1 {
214 e.atPhantom = false
215 x++
216 }
217 }
218
219 if y < 0 {
220 y = 0
221 }
222 if y >= height {
223 y = height - 1
224 }
225 if x < 0 {
226 x = 0
227 }
228 if x >= width {
229 x = width - 1
230 }
231
232 e.scrs[0].Resize(width, height)
233 e.scrs[1].Resize(width, height)
234 e.tabstops = uv.DefaultTabStops(width)
235
236 e.setCursor(x, y)
237
238 if e.isModeSet(ansi.InBandResizeMode) {
239 _, _ = io.WriteString(e.pw, ansi.InBandResize(e.Height(), e.Width(), 0, 0))
240 }
241 }
242
243 // Read reads data from the terminal input buffer.
244 func (e *Emulator) Read(p []byte) (n int, err error) {
245 if e.closed {
246 return 0, io.EOF
247 }
248
249 return e.pr.Read(p) //nolint:wrapcheck
250 }
251
252 // Close closes the terminal.
253 func (e *Emulator) Close() error {
254 if e.closed {
255 return nil
256 }
257
258 e.closed = true
259 return e.pw.CloseWithError(io.EOF)
260 }
261
262 // Write writes data to the terminal output buffer.
263 func (e *Emulator) Write(p []byte) (n int, err error) {
264 if e.closed {
265 return 0, io.ErrClosedPipe
266 }
267
268 for i := range p {
269 e.parser.Advance(p[i])
270 state := e.parser.State()
271 // flush grapheme if we transitioned to a non-utf8 state or we have
272 // written the whole byte slice.
273 if len(e.grapheme) > 0 {
274 if (e.lastState == parser.GroundState && state != parser.Utf8State) || i == len(p)-1 {
275 e.flushGrapheme()
276 }
277 }
278 e.lastState = state
279 }
280 return len(p), nil
281 }
282
283 // WriteString writes a string to the terminal output buffer.
284 func (e *Emulator) WriteString(s string) (n int, err error) {
285 return io.WriteString(e, s) //nolint:wrapcheck
286 }
287
288 // InputPipe returns the terminal's input pipe.
289 // This can be used to send input to the terminal.
290 func (e *Emulator) InputPipe() io.Writer {
291 return e.pw
292 }
293
294 // Paste pastes text into the terminal.
295 // If bracketed paste mode is enabled, the text is bracketed with the
296 // appropriate escape sequences.
297 func (e *Emulator) Paste(text string) {
298 if e.isModeSet(ansi.BracketedPasteMode) {
299 _, _ = io.WriteString(e.pw, ansi.BracketedPasteStart)
300 defer io.WriteString(e.pw, ansi.BracketedPasteEnd) //nolint:errcheck
301 }
302
303 _, _ = io.WriteString(e.pw, text)
304 }
305
306 // SendText sends arbitrary text to the terminal.
307 func (e *Emulator) SendText(text string) {
308 _, _ = io.WriteString(e.pw, text)
309 }
310
311 // SendKeys sends multiple keys to the terminal.
312 func (e *Emulator) SendKeys(keys ...uv.KeyEvent) {
313 for _, k := range keys {
314 e.SendKey(k)
315 }
316 }
317
318 // ForegroundColor returns the terminal's foreground color. This returns nil if
319 // the foreground color is not set which means the outer terminal color is
320 // used.
321 func (e *Emulator) ForegroundColor() color.Color {
322 if e.fgColor == nil {
323 return e.defaultFg
324 }
325 return e.fgColor
326 }
327
328 // SetForegroundColor sets the terminal's foreground color.
329 func (e *Emulator) SetForegroundColor(c color.Color) {
330 if c == nil {
331 c = e.defaultFg
332 }
333 e.fgColor = c
334 if e.cb.ForegroundColor != nil {
335 e.cb.ForegroundColor(c)
336 }
337 }
338
339 // SetDefaultForegroundColor sets the terminal's default foreground color.
340 func (e *Emulator) SetDefaultForegroundColor(c color.Color) {
341 e.defaultFg = c
342 }
343
344 // BackgroundColor returns the terminal's background color. This returns nil if
345 // the background color is not set which means the outer terminal color is
346 // used.
347 func (e *Emulator) BackgroundColor() color.Color {
348 if e.bgColor == nil {
349 return e.defaultBg
350 }
351 return e.bgColor
352 }
353
354 // SetBackgroundColor sets the terminal's background color.
355 func (e *Emulator) SetBackgroundColor(c color.Color) {
356 if c == nil {
357 c = e.defaultBg
358 }
359 e.bgColor = c
360 if e.cb.BackgroundColor != nil {
361 e.cb.BackgroundColor(c)
362 }
363 }
364
365 // SetDefaultBackgroundColor sets the terminal's default background color.
366 func (e *Emulator) SetDefaultBackgroundColor(c color.Color) {
367 e.defaultBg = c
368 }
369
370 // CursorColor returns the terminal's cursor color. This returns nil if the
371 // cursor color is not set which means the outer terminal color is used.
372 func (e *Emulator) CursorColor() color.Color {
373 if e.curColor == nil {
374 return e.defaultCur
375 }
376 return e.curColor
377 }
378
379 // SetCursorColor sets the terminal's cursor color.
380 func (e *Emulator) SetCursorColor(c color.Color) {
381 if c == nil {
382 c = e.defaultCur
383 }
384 e.curColor = c
385 if e.cb.CursorColor != nil {
386 e.cb.CursorColor(c)
387 }
388 }
389
390 // SetDefaultCursorColor sets the terminal's default cursor color.
391 func (e *Emulator) SetDefaultCursorColor(c color.Color) {
392 e.defaultCur = c
393 }
394
395 // IndexedColor returns a terminal's indexed color. An indexed color is a color
396 // between 0 and 255.
397 func (e *Emulator) IndexedColor(i int) color.Color {
398 if i < 0 || i > 255 {
399 return nil
400 }
401
402 c := e.colors[i]
403 if c == nil {
404 // Return the default color.
405 return ansi.IndexedColor(i) //nolint:gosec
406 }
407
408 return c
409 }
410
411 // SetIndexedColor sets a terminal's indexed color.
412 // The index must be between 0 and 255.
413 func (e *Emulator) SetIndexedColor(i int, c color.Color) {
414 if i < 0 || i > 255 {
415 return
416 }
417
418 e.colors[i] = c
419 }
420
421 // resetTabStops resets the terminal tab stops to the default set.
422 func (e *Emulator) resetTabStops() {
423 e.tabstops = uv.DefaultTabStops(e.Width())
424 }
425
426 func (e *Emulator) logf(format string, v ...any) {
427 if e.logger != nil {
428 e.logger.Printf(format, v...)
429 }
430 }