Debian Codegraph @

tty/tty_plan9.go

raw symbols SCIP
1 //go:build plan9
2 // +build plan9
3
4 // Copyright 2025 The TCell Authors
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17
18 package tty
19
20 import (
21 "bufio"
22 "errors"
23 "fmt"
24 "io"
25 "os"
26 "strconv"
27 "strings"
28 "sync"
29 "sync/atomic"
30 )
31
32 // p9Tty implements tcell.Tty using Plan 9's /dev/cons and /dev/consctl.
33 // Raw mode is enabled by writing "rawon" to /dev/consctl while the fd stays open.
34 // Resize notifications are read from /dev/wctl: the first read returns geometry,
35 // subsequent reads block until the window changes (rio(4)).
36 //
37 // References:
38 // - kbdfs(8): cons/consctl rawon|rawoff semantics
39 // - rio(4): wctl geometry and blocking-on-change behavior
40 // - vt(1): VT100 emulator typically used for TUI programs on Plan 9
41 //
42 // Limitations:
43 // - We assume VT100-level capabilities (often no colors, no mouse).
44 // - Window size is conservative: we return 80x24 unless overridden.
45 // Set LINES/COLUMNS (or TCELL_LINES/TCELL_COLS) to refine.
46 // - Mouse and bracketed paste are not wired; terminfo/xterm queries
47 // are not attempted because vt(1) may not support them.
48 type p9Tty struct {
49 cons *os.File // /dev/cons (read+write)
50 consctl *os.File // /dev/consctl (write "rawon"/"rawoff")
51 wctl *os.File // /dev/wctl (resize notifications)
52
53 closed atomic.Bool
54 started bool
55
56 onResize atomic.Value // resize channel
57 wg sync.WaitGroup
58 stopCh chan struct{}
59 }
60
61 func NewDevTty() (Tty, error) { // tcell signature
62 return newPlan9TTY()
63 }
64
65 func NewStdIoTty() (Tty, error) { // also required by tcell
66 // On Plan 9 there is no POSIX tty discipline on stdin/stdout;
67 // use /dev/cons explicitly for robustness.
68 return newPlan9TTY()
69 }
70
71 func NewDevTtyFromDev(_ string) (Tty, error) { // required by tcell
72 // Plan 9 does not have multiple "ttys" in the POSIX sense;
73 // always bind to /dev/cons and /dev/consctl.
74 return newPlan9TTY()
75 }
76
77 func newPlan9TTY() (Tty, error) {
78 cons, err := os.OpenFile("/dev/cons", os.O_RDWR, 0)
79 if err != nil {
80 return nil, fmt.Errorf("open /dev/cons: %w", err)
81 }
82 consctl, err := os.OpenFile("/dev/consctl", os.O_WRONLY, 0)
83 if err != nil {
84 _ = cons.Close()
85 return nil, fmt.Errorf("open /dev/consctl: %w", err)
86 }
87 // /dev/wctl may not exist (console without rio); best-effort.
88 wctl, _ := os.OpenFile("/dev/wctl", os.O_RDWR, 0)
89
90 t := &p9Tty{
91 cons: cons,
92 consctl: consctl,
93 wctl: wctl,
94 stopCh: make(chan struct{}),
95 }
96 return t, nil
97 }
98
99 func (t *p9Tty) Start() error {
100
101 if t.started {
102 return nil
103 }
104 if t.closed.Load() {
105 return errors.New("tty closed")
106 }
107
108 // Recreate stop channel if absent or closed (supports resume).
109 if t.stopCh == nil || isClosed(t.stopCh) {
110 t.stopCh = make(chan struct{})
111 }
112
113 // Put console into raw mode; remains active while consctl is open.
114 if _, err := t.consctl.Write([]byte("rawon")); err != nil {
115 return fmt.Errorf("enable raw mode: %w", err)
116 }
117
118 // Reopen /dev/wctl on resume; best-effort (system console may lack it).
119 if t.wctl == nil {
120 if f, err := os.OpenFile("/dev/wctl", os.O_RDWR, 0); err == nil {
121 t.wctl = f
122 }
123 }
124
125 if t.wctl != nil {
126 t.wg.Add(1)
127 go t.watchResize()
128 }
129 t.started = true
130 return nil
131 }
132
133 func (t *p9Tty) Drain() error {
134 // Per tcell docs, this may reasonably be a no-op on non-POSIX ttys.
135 // Read deadlines are not available on plan9 os.File; we rely on Stop().
136 return nil
137 }
138
139 func (t *p9Tty) Stop() error {
140
141 // Signal watcher to stop (if not already).
142 if t.stopCh != nil && !isClosed(t.stopCh) {
143 close(t.stopCh)
144 }
145
146 // Exit raw mode first.
147 _, _ = t.consctl.Write([]byte("rawoff"))
148
149 // Closing wctl unblocks watchResize; nil it so Start() can reopen later.
150 if t.wctl != nil {
151 _ = t.wctl.Close()
152 t.wctl = nil
153 }
154
155 // Ensure watcher goroutine has exited before returning.
156 t.wg.Wait()
157 t.started = false
158 return nil
159 }
160
161 func (t *p9Tty) Close() error {
162
163 if t.closed.Swap(true) {
164 return nil
165 }
166
167 if t.stopCh != nil && !isClosed(t.stopCh) {
168 close(t.stopCh)
169 }
170 _, _ = t.consctl.Write([]byte("rawoff"))
171
172 _ = t.cons.Close()
173 _ = t.consctl.Close()
174 if t.wctl != nil {
175 _ = t.wctl.Close()
176 t.wctl = nil
177 }
178
179 t.wg.Wait()
180 return nil
181 }
182
183 func (t *p9Tty) Read(p []byte) (int, error) {
184 return t.cons.Read(p)
185 }
186
187 func (t *p9Tty) Write(p []byte) (int, error) {
188 return t.cons.Write(p)
189 }
190
191 func (t *p9Tty) NotifyResize(resizeQ chan<- bool) {
192 t.onResize.Store(resizeQ)
193 }
194
195 func (t *p9Tty) WindowSize() (WindowSize, error) {
196 // Strategy:
197 // 1) honor explicit overrides (TCELL_LINES/TCELL_COLS, LINES/COLUMNS),
198 // 2) otherwise return conservative 80x24.
199 // Reading /dev/wctl gives pixel geometry, but char cell metrics are
200 // not generally available to non-draw clients; vt(1) is fixed-cell.
201 lines, cols := envInt("TCELL_LINES"), envInt("TCELL_COLS")
202 if lines == 0 {
203 lines = envInt("LINES")
204 }
205 if cols == 0 {
206 cols = envInt("COLUMNS")
207 }
208 if lines <= 0 {
209 lines = 24
210 }
211 if cols <= 0 {
212 cols = 80
213 }
214 return WindowSize{Width: cols, Height: lines}, nil
215 }
216
217 // watchResize blocks on /dev/wctl reads; each read returns when the window
218 // changes size/position/state, per rio(4). We ignore the parsed geometry and
219 // just notify tcell to re-query WindowSize().
220 func (t *p9Tty) watchResize() {
221 defer t.wg.Done()
222
223 r := bufio.NewReader(t.wctl)
224 for {
225 select {
226 case <-t.stopCh:
227 return
228 default:
229 }
230 // Each read delivers something like:
231 // " minx miny maxx maxy visible current\n"
232 // We don't need to parse here; just signal.
233 _, err := r.ReadString('\n')
234 if err != nil {
235 if errors.Is(err, io.EOF) {
236 return
237 }
238 // transient errors: continue
239 }
240 if rq, ok := t.onResize.Load().(chan<- bool); ok && rq != nil {
241 select {
242 case rq <- true:
243 default:
244 }
245 }
246 }
247 }
248
249 func envInt(name string) int {
250 if s := strings.TrimSpace(os.Getenv(name)); s != "" {
251 if v, err := strconv.Atoi(s); err == nil {
252 return v
253 }
254 }
255 return 0
256 }
257
258 // helper: safe check if a channel is closed
259 func isClosed(ch <-chan struct{}) bool {
260 select {
261 case <-ch:
262 return true
263 default:
264 return false
265 }
266 }