termenv_unix.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
  2. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  3. package termenv
  4. import (
  5. "fmt"
  6. "io"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "golang.org/x/sys/unix"
  11. )
  12. const (
  13. // timeout for OSC queries
  14. OSCTimeout = 5 * time.Second
  15. )
  16. // ColorProfile returns the supported color profile:
  17. // Ascii, ANSI, ANSI256, or TrueColor.
  18. func (o *Output) ColorProfile() Profile {
  19. if !o.isTTY() {
  20. return Ascii
  21. }
  22. if o.environ.Getenv("GOOGLE_CLOUD_SHELL") == "true" {
  23. return TrueColor
  24. }
  25. term := o.environ.Getenv("TERM")
  26. colorTerm := o.environ.Getenv("COLORTERM")
  27. switch strings.ToLower(colorTerm) {
  28. case "24bit":
  29. fallthrough
  30. case "truecolor":
  31. if strings.HasPrefix(term, "screen") {
  32. // tmux supports TrueColor, screen only ANSI256
  33. if o.environ.Getenv("TERM_PROGRAM") != "tmux" {
  34. return ANSI256
  35. }
  36. }
  37. return TrueColor
  38. case "yes":
  39. fallthrough
  40. case "true":
  41. return ANSI256
  42. }
  43. switch term {
  44. case "xterm-kitty", "wezterm":
  45. return TrueColor
  46. case "linux":
  47. return ANSI
  48. }
  49. if strings.Contains(term, "256color") {
  50. return ANSI256
  51. }
  52. if strings.Contains(term, "color") {
  53. return ANSI
  54. }
  55. if strings.Contains(term, "ansi") {
  56. return ANSI
  57. }
  58. return Ascii
  59. }
  60. func (o Output) foregroundColor() Color {
  61. s, err := o.termStatusReport(10)
  62. if err == nil {
  63. c, err := xTermColor(s)
  64. if err == nil {
  65. return c
  66. }
  67. }
  68. colorFGBG := o.environ.Getenv("COLORFGBG")
  69. if strings.Contains(colorFGBG, ";") {
  70. c := strings.Split(colorFGBG, ";")
  71. i, err := strconv.Atoi(c[0])
  72. if err == nil {
  73. return ANSIColor(i)
  74. }
  75. }
  76. // default gray
  77. return ANSIColor(7)
  78. }
  79. func (o Output) backgroundColor() Color {
  80. s, err := o.termStatusReport(11)
  81. if err == nil {
  82. c, err := xTermColor(s)
  83. if err == nil {
  84. return c
  85. }
  86. }
  87. colorFGBG := o.environ.Getenv("COLORFGBG")
  88. if strings.Contains(colorFGBG, ";") {
  89. c := strings.Split(colorFGBG, ";")
  90. i, err := strconv.Atoi(c[len(c)-1])
  91. if err == nil {
  92. return ANSIColor(i)
  93. }
  94. }
  95. // default black
  96. return ANSIColor(0)
  97. }
  98. func (o *Output) waitForData(timeout time.Duration) error {
  99. fd := o.TTY().Fd()
  100. tv := unix.NsecToTimeval(int64(timeout))
  101. var readfds unix.FdSet
  102. readfds.Set(int(fd))
  103. for {
  104. n, err := unix.Select(int(fd)+1, &readfds, nil, nil, &tv)
  105. if err == unix.EINTR {
  106. continue
  107. }
  108. if err != nil {
  109. return err
  110. }
  111. if n == 0 {
  112. return fmt.Errorf("timeout")
  113. }
  114. break
  115. }
  116. return nil
  117. }
  118. func (o *Output) readNextByte() (byte, error) {
  119. if !o.unsafe {
  120. if err := o.waitForData(OSCTimeout); err != nil {
  121. return 0, err
  122. }
  123. }
  124. var b [1]byte
  125. n, err := o.TTY().Read(b[:])
  126. if err != nil {
  127. return 0, err
  128. }
  129. if n == 0 {
  130. panic("read returned no data")
  131. }
  132. return b[0], nil
  133. }
  134. // readNextResponse reads either an OSC response or a cursor position response:
  135. // - OSC response: "\x1b]11;rgb:1111/1111/1111\x1b\\"
  136. // - cursor position response: "\x1b[42;1R"
  137. func (o *Output) readNextResponse() (response string, isOSC bool, err error) {
  138. start, err := o.readNextByte()
  139. if err != nil {
  140. return "", false, err
  141. }
  142. // first byte must be ESC
  143. for start != ESC {
  144. start, err = o.readNextByte()
  145. if err != nil {
  146. return "", false, err
  147. }
  148. }
  149. response += string(start)
  150. // next byte is either '[' (cursor position response) or ']' (OSC response)
  151. tpe, err := o.readNextByte()
  152. if err != nil {
  153. return "", false, err
  154. }
  155. response += string(tpe)
  156. var oscResponse bool
  157. switch tpe {
  158. case '[':
  159. oscResponse = false
  160. case ']':
  161. oscResponse = true
  162. default:
  163. return "", false, ErrStatusReport
  164. }
  165. for {
  166. b, err := o.readNextByte()
  167. if err != nil {
  168. return "", false, err
  169. }
  170. response += string(b)
  171. if oscResponse {
  172. // OSC can be terminated by BEL (\a) or ST (ESC)
  173. if b == BEL || strings.HasSuffix(response, string(ESC)) {
  174. return response, true, nil
  175. }
  176. } else {
  177. // cursor position response is terminated by 'R'
  178. if b == 'R' {
  179. return response, false, nil
  180. }
  181. }
  182. // both responses have less than 25 bytes, so if we read more, that's an error
  183. if len(response) > 25 {
  184. break
  185. }
  186. }
  187. return "", false, ErrStatusReport
  188. }
  189. func (o Output) termStatusReport(sequence int) (string, error) {
  190. // screen/tmux can't support OSC, because they can be connected to multiple
  191. // terminals concurrently.
  192. term := o.environ.Getenv("TERM")
  193. if strings.HasPrefix(term, "screen") || strings.HasPrefix(term, "tmux") {
  194. return "", ErrStatusReport
  195. }
  196. tty := o.TTY()
  197. if tty == nil {
  198. return "", ErrStatusReport
  199. }
  200. if !o.unsafe {
  201. fd := int(tty.Fd())
  202. // if in background, we can't control the terminal
  203. if !isForeground(fd) {
  204. return "", ErrStatusReport
  205. }
  206. t, err := unix.IoctlGetTermios(fd, tcgetattr)
  207. if err != nil {
  208. return "", fmt.Errorf("%s: %s", ErrStatusReport, err)
  209. }
  210. defer unix.IoctlSetTermios(fd, tcsetattr, t) //nolint:errcheck
  211. noecho := *t
  212. noecho.Lflag = noecho.Lflag &^ unix.ECHO
  213. noecho.Lflag = noecho.Lflag &^ unix.ICANON
  214. if err := unix.IoctlSetTermios(fd, tcsetattr, &noecho); err != nil {
  215. return "", fmt.Errorf("%s: %s", ErrStatusReport, err)
  216. }
  217. }
  218. // first, send OSC query, which is ignored by terminal which do not support it
  219. fmt.Fprintf(tty, OSC+"%d;?"+ST, sequence)
  220. // then, query cursor position, should be supported by all terminals
  221. fmt.Fprintf(tty, CSI+"6n")
  222. // read the next response
  223. res, isOSC, err := o.readNextResponse()
  224. if err != nil {
  225. return "", fmt.Errorf("%s: %s", ErrStatusReport, err)
  226. }
  227. // if this is not OSC response, then the terminal does not support it
  228. if !isOSC {
  229. return "", ErrStatusReport
  230. }
  231. // read the cursor query response next and discard the result
  232. _, _, err = o.readNextResponse()
  233. if err != nil {
  234. return "", err
  235. }
  236. // fmt.Println("Rcvd", res[1:])
  237. return res, nil
  238. }
  239. // EnableVirtualTerminalProcessing enables virtual terminal processing on
  240. // Windows for w and returns a function that restores w to its previous state.
  241. // On non-Windows platforms, or if w does not refer to a terminal, then it
  242. // returns a non-nil no-op function and no error.
  243. func EnableVirtualTerminalProcessing(_ io.Writer) (func() error, error) {
  244. return func() error { return nil }, nil
  245. }