Debian Codegraph @

lib/ui/context.go

raw
1 package ui
2
3 import (
4 "fmt"
5
6 "go.rockorager.dev/vaxis"
7 )
8
9 // A context allows you to draw in a sub-region of the terminal
10 type Context struct {
11 window vaxis.Window
12 x, y int
13 onPopover func(*Popover)
14 }
15
16 func (ctx *Context) Width() int {
17 width, _ := ctx.window.Size()
18 return width
19 }
20
21 func (ctx *Context) Height() int {
22 _, height := ctx.window.Size()
23 return height
24 }
25
26 // returns the vaxis Window for this context
27 func (ctx *Context) Window() vaxis.Window {
28 return ctx.window
29 }
30
31 func NewContext(vx *vaxis.Vaxis, p func(*Popover)) *Context {
32 win := vx.Window()
33 return &Context{win, 0, 0, p}
34 }
35
36 func (ctx *Context) Subcontext(x, y, width, height int) *Context {
37 if x < 0 || y < 0 {
38 panic(fmt.Errorf("Attempted to create context with negative offset"))
39 }
40 win := ctx.window.New(x, y, width, height)
41 return &Context{win, ctx.x + x, ctx.y + y, ctx.onPopover}
42 }
43
44 func (ctx *Context) SetCell(x, y int, ch rune, style vaxis.Style) {
45 width, height := ctx.window.Size()
46 if x >= width || y >= height {
47 // no-op when dims are inadequate
48 return
49 }
50 ctx.window.SetCell(x, y, vaxis.Cell{
51 Character: vaxis.Character{
52 Grapheme: string(ch),
53 },
54 Style: style,
55 })
56 }
57
58 func (ctx *Context) Printf(x, y int, style vaxis.Style,
59 format string, a ...any,
60 ) int {
61 width, height := ctx.window.Size()
62
63 if x >= width || y >= height {
64 // no-op when dims are inadequate
65 return 0
66 }
67
68 str := fmt.Sprintf(format, a...)
69
70 buf := StyledString(str)
71 ApplyAttrs(buf, style)
72
73 old_x := x
74
75 newline := func() bool {
76 x = old_x
77 y++
78 return y < height
79 }
80 for _, sr := range buf.Cells {
81 switch sr.Grapheme {
82 case "\n":
83 if !newline() {
84 return buf.Len()
85 }
86 case "\r":
87 x = old_x
88 default:
89 ctx.window.SetCell(x, y, sr)
90 x += sr.Width
91 if x == old_x+width {
92 if !newline() {
93 return buf.Len()
94 }
95 }
96 }
97 }
98
99 return buf.Len()
100 }
101
102 func (ctx *Context) Fill(x, y, width, height int, rune rune, style vaxis.Style) {
103 win := ctx.window.New(x, y, width, height)
104 win.Fill(vaxis.Cell{
105 Character: vaxis.Character{
106 Grapheme: string(rune),
107 Width: 1,
108 },
109 Style: style,
110 })
111 }
112
113 func (ctx *Context) SetCursor(x, y int, style vaxis.CursorStyle) {
114 ctx.window.ShowCursor(x, y, style)
115 }
116
117 func (ctx *Context) HideCursor() {
118 ctx.window.Vx.HideCursor()
119 }
120
121 func (ctx *Context) Popover(x, y, width, height int, d Drawable) {
122 ctx.onPopover(&Popover{
123 x: ctx.x + x,
124 y: ctx.y + y,
125 width: width,
126 height: height,
127 content: d,
128 })
129 }
130
131 func (ctx *Context) Size() (int, int) {
132 return ctx.window.Size()
133 }