termenv_unix.go 5.9 KB

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