Debian Codegraph @

tty/tty_unix.go

raw symbols SCIP
1 // Copyright 2025 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
16 // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos
17
18 package tty
19
20 import (
21 "errors"
22 "fmt"
23 "os"
24 "os/signal"
25 "strconv"
26 "syscall"
27 "time"
28
29 "golang.org/x/sys/unix"
30 "golang.org/x/term"
31 )
32
33 // Use -1 to differentiate from stdin (fd=0).
34 const uninitializedTtyFd = -1
35
36 // devTty is an implementation of the Tty API based upon /dev/tty.
37 type devTty struct {
38 fd int
39 f *os.File
40 saved *term.State
41 sig chan os.Signal
42 dev string
43 started bool
44 }
45
46 func (tty *devTty) Read(b []byte) (int, error) {
47 return tty.f.Read(b)
48 }
49
50 func (tty *devTty) Write(b []byte) (int, error) {
51 return tty.f.Write(b)
52 }
53
54 func (tty *devTty) Close() error {
55 return tty.f.Close()
56 }
57
58 func (tty *devTty) Start() error {
59
60 if tty.started {
61 return nil
62 }
63 // We open another copy of /dev/tty. This is a workaround for unusual behavior
64 // observed in macOS, apparently caused when a subshell (for example) closes our
65 // own tty device (when it exits for example). Getting a fresh new one seems to
66 // resolve the problem. (We believe this is a bug in the macOS tty driver that
67 // fails to account for dup() references to the same file before applying close()
68 // related behaviors to the tty.) (Note that when using stdin/stdout instead of
69 // /dev/tty this problem is not observed.)
70 var err error
71 if tty.f, err = os.OpenFile(tty.dev, os.O_RDWR, 0); err != nil {
72 return err
73 }
74
75 tty.fd = int(tty.f.Fd())
76
77 if !term.IsTerminal(tty.fd) {
78 tty.f.Close()
79 return errors.New("device is not a terminal")
80 }
81
82 _ = tty.f.SetReadDeadline(time.Time{})
83 saved, err := term.MakeRaw(tty.fd) // also sets vMin and vTime
84 if err != nil {
85 tty.f.Close()
86 return err
87 }
88 if err = tcFlushInput(tty.fd); err != nil {
89 _ = term.Restore(tty.fd, saved)
90 tty.f.Close()
91 return err
92 }
93 tty.saved = saved
94 tty.started = true
95
96 return nil
97 }
98
99 func (tty *devTty) Drain() error {
100 _ = tty.f.SetReadDeadline(time.Now())
101 if err := tcSetBufParams(tty.fd, 0, 0); err != nil {
102 return err
103 }
104 return nil
105 }
106
107 func (tty *devTty) Stop() error {
108 // unconditionally set this, because we cannot recover
109 // if we fail anyway, so this gives the best hope of
110 // picking up the pieces in such a circumstance
111 tty.started = false
112
113 if err := term.Restore(tty.fd, tty.saved); err != nil {
114 return err
115 }
116 _ = tty.f.SetReadDeadline(time.Now())
117
118 tty.NotifyResize(nil)
119
120 // close our tty device -- we'll get another one if we Start again later.
121 _ = tty.f.Close()
122 tty.fd = uninitializedTtyFd
123
124 return nil
125 }
126
127 func (tty *devTty) WindowSize() (WindowSize, error) {
128 size := WindowSize{}
129 fd := tty.fd
130 if tty.fd == uninitializedTtyFd {
131 // If WindowSize is called when the tty isn't yet running, the fd for /dev/tty won't be initialized,
132 // so open the file just long enough to retrieve the window size.
133 f, err := os.OpenFile(tty.dev, os.O_RDWR, 0)
134 if err != nil {
135 return size, err
136 }
137 defer func() { _ = f.Close() }()
138 fd = int(f.Fd())
139 }
140
141 ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
142 if err != nil {
143 return size, err
144 }
145 w := int(ws.Col)
146 h := int(ws.Row)
147 if w == 0 {
148 w, _ = strconv.Atoi(os.Getenv("COLUMNS"))
149 }
150 if w == 0 {
151 w = 80 // default
152 }
153 if h == 0 {
154 h, _ = strconv.Atoi(os.Getenv("LINES"))
155 }
156 if h == 0 {
157 h = 25 // default
158 }
159 size.Width = w
160 size.Height = h
161 size.PixelWidth = int(ws.Xpixel)
162 size.PixelHeight = int(ws.Ypixel)
163 return size, nil
164 }
165
166 func (tty *devTty) NotifyResize(resizeQ chan<- bool) {
167
168 sigQ := tty.sig
169 tty.sig = nil
170
171 if sigQ != nil {
172 signal.Stop(sigQ)
173 close(sigQ)
174 }
175
176 if resizeQ == nil {
177 return
178 }
179
180 sigQ = make(chan os.Signal, 1)
181 signal.Notify(sigQ, syscall.SIGWINCH)
182
183 tty.sig = sigQ
184
185 go func() {
186 for range sigQ {
187 select {
188 case resizeQ <- true:
189 default: // queue full, so nvm.
190 }
191 }
192 }()
193 }
194
195 // NewDevTty opens a /dev/tty based Tty.
196 func NewDevTty() (Tty, error) {
197 return NewDevTtyFromDev("/dev/tty")
198 }
199
200 // NewDevTtyFromDev opens a tty device given a path. This can be useful to bind to other nodes.
201 func NewDevTtyFromDev(dev string) (Tty, error) {
202 tty := &devTty{
203 fd: uninitializedTtyFd,
204 dev: dev,
205 sig: make(chan os.Signal),
206 }
207 // Only open the file long enough to check that the device
208 // represents a TTY. We will reopen it in start. We do collect
209 // the terminal state so we can restore it later though.
210 if f, err := os.OpenFile(dev, os.O_RDWR, 0); err != nil {
211 return nil, err
212 } else {
213 defer func() { _ = f.Close() }()
214 fd := int(f.Fd())
215 if !term.IsTerminal(fd) {
216 return nil, errors.New("not a terminal")
217 }
218 if tty.saved, err = term.GetState(fd); err != nil {
219 return nil, fmt.Errorf("failed to get state: %w", err)
220 }
221 }
222 return tty, nil
223 }