standard_renderer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package tea
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/muesli/ansi/compressor"
  10. "github.com/muesli/reflow/truncate"
  11. "github.com/muesli/termenv"
  12. )
  13. const (
  14. // defaultFramerate specifies the maximum interval at which we should
  15. // update the view.
  16. defaultFramerate = time.Second / 60
  17. )
  18. // standardRenderer is a framerate-based terminal renderer, updating the view
  19. // at a given framerate to avoid overloading the terminal emulator.
  20. //
  21. // In cases where very high performance is needed the renderer can be told
  22. // to exclude ranges of lines, allowing them to be written to directly.
  23. type standardRenderer struct {
  24. mtx *sync.Mutex
  25. out *termenv.Output
  26. buf bytes.Buffer
  27. queuedMessageLines []string
  28. framerate time.Duration
  29. ticker *time.Ticker
  30. done chan struct{}
  31. lastRender string
  32. linesRendered int
  33. useANSICompressor bool
  34. once sync.Once
  35. // cursor visibility state
  36. cursorHidden bool
  37. // essentially whether or not we're using the full size of the terminal
  38. altScreenActive bool
  39. // renderer dimensions; usually the size of the window
  40. width int
  41. height int
  42. // lines explicitly set not to render
  43. ignoreLines map[int]struct{}
  44. }
  45. // newRenderer creates a new renderer. Normally you'll want to initialize it
  46. // with os.Stdout as the first argument.
  47. func newRenderer(out *termenv.Output, useANSICompressor bool) renderer {
  48. r := &standardRenderer{
  49. out: out,
  50. mtx: &sync.Mutex{},
  51. done: make(chan struct{}),
  52. framerate: defaultFramerate,
  53. useANSICompressor: useANSICompressor,
  54. queuedMessageLines: []string{},
  55. }
  56. if r.useANSICompressor {
  57. r.out = termenv.NewOutput(&compressor.Writer{Forward: out})
  58. }
  59. return r
  60. }
  61. // start starts the renderer.
  62. func (r *standardRenderer) start() {
  63. if r.ticker == nil {
  64. r.ticker = time.NewTicker(r.framerate)
  65. } else {
  66. // If the ticker already exists, it has been stopped and we need to
  67. // reset it.
  68. r.ticker.Reset(r.framerate)
  69. }
  70. // Since the renderer can be restarted after a stop, we need to reset
  71. // the done channel and its corresponding sync.Once.
  72. r.once = sync.Once{}
  73. go r.listen()
  74. }
  75. // stop permanently halts the renderer, rendering the final frame.
  76. func (r *standardRenderer) stop() {
  77. // flush locks the mutex
  78. r.flush()
  79. r.mtx.Lock()
  80. defer r.mtx.Unlock()
  81. r.out.ClearLine()
  82. r.once.Do(func() {
  83. r.done <- struct{}{}
  84. })
  85. if r.useANSICompressor {
  86. if w, ok := r.out.TTY().(io.WriteCloser); ok {
  87. _ = w.Close()
  88. }
  89. }
  90. }
  91. // kill halts the renderer. The final frame will not be rendered.
  92. func (r *standardRenderer) kill() {
  93. r.mtx.Lock()
  94. defer r.mtx.Unlock()
  95. r.out.ClearLine()
  96. r.once.Do(func() {
  97. r.done <- struct{}{}
  98. })
  99. }
  100. // listen waits for ticks on the ticker, or a signal to stop the renderer.
  101. func (r *standardRenderer) listen() {
  102. for {
  103. select {
  104. case <-r.done:
  105. r.ticker.Stop()
  106. return
  107. case <-r.ticker.C:
  108. r.flush()
  109. }
  110. }
  111. }
  112. // flush renders the buffer.
  113. func (r *standardRenderer) flush() {
  114. r.mtx.Lock()
  115. defer r.mtx.Unlock()
  116. if r.buf.Len() == 0 || r.buf.String() == r.lastRender {
  117. // Nothing to do
  118. return
  119. }
  120. // Output buffer
  121. buf := &bytes.Buffer{}
  122. out := termenv.NewOutput(buf)
  123. newLines := strings.Split(r.buf.String(), "\n")
  124. // If we know the output's height, we can use it to determine how many
  125. // lines we can render. We drop lines from the top of the render buffer if
  126. // necessary, as we can't navigate the cursor into the terminal's scrollback
  127. // buffer.
  128. if r.height > 0 && len(newLines) > r.height {
  129. newLines = newLines[len(newLines)-r.height:]
  130. }
  131. numLinesThisFlush := len(newLines)
  132. oldLines := strings.Split(r.lastRender, "\n")
  133. skipLines := make(map[int]struct{})
  134. flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive
  135. // Add any queued messages to this render
  136. if flushQueuedMessages {
  137. newLines = append(r.queuedMessageLines, newLines...)
  138. r.queuedMessageLines = []string{}
  139. }
  140. // Clear any lines we painted in the last render.
  141. if r.linesRendered > 0 {
  142. for i := r.linesRendered - 1; i > 0; i-- {
  143. // If the number of lines we want to render hasn't increased and
  144. // new line is the same as the old line we can skip rendering for
  145. // this line as a performance optimization.
  146. if (len(newLines) <= len(oldLines)) && (len(newLines) > i && len(oldLines) > i) && (newLines[i] == oldLines[i]) {
  147. skipLines[i] = struct{}{}
  148. } else if _, exists := r.ignoreLines[i]; !exists {
  149. out.ClearLine()
  150. }
  151. out.CursorUp(1)
  152. }
  153. if _, exists := r.ignoreLines[0]; !exists {
  154. // We need to return to the start of the line here to properly
  155. // erase it. Going back the entire width of the terminal will
  156. // usually be farther than we need to go, but terminal emulators
  157. // will stop the cursor at the start of the line as a rule.
  158. //
  159. // We use this sequence in particular because it's part of the ANSI
  160. // standard (whereas others are proprietary to, say, VT100/VT52).
  161. // If cursor previous line (ESC[ + <n> + F) were better supported
  162. // we could use that above to eliminate this step.
  163. out.CursorBack(r.width)
  164. out.ClearLine()
  165. }
  166. }
  167. // Merge the set of lines we're skipping as a rendering optimization with
  168. // the set of lines we've explicitly asked the renderer to ignore.
  169. if r.ignoreLines != nil {
  170. for k, v := range r.ignoreLines {
  171. skipLines[k] = v
  172. }
  173. }
  174. // Paint new lines
  175. for i := 0; i < len(newLines); i++ {
  176. if _, skip := skipLines[i]; skip {
  177. // Unless this is the last line, move the cursor down.
  178. if i < len(newLines)-1 {
  179. out.CursorDown(1)
  180. }
  181. } else {
  182. line := newLines[i]
  183. // Truncate lines wider than the width of the window to avoid
  184. // wrapping, which will mess up rendering. If we don't have the
  185. // width of the window this will be ignored.
  186. //
  187. // Note that on Windows we only get the width of the window on
  188. // program initialization, so after a resize this won't perform
  189. // correctly (signal SIGWINCH is not supported on Windows).
  190. if r.width > 0 {
  191. line = truncate.String(line, uint(r.width))
  192. }
  193. _, _ = out.WriteString(line)
  194. if i < len(newLines)-1 {
  195. _, _ = out.WriteString("\r\n")
  196. }
  197. }
  198. }
  199. r.linesRendered = numLinesThisFlush
  200. // Make sure the cursor is at the start of the last line to keep rendering
  201. // behavior consistent.
  202. if r.altScreenActive {
  203. // This case fixes a bug in macOS terminal. In other terminals the
  204. // other case seems to do the job regardless of whether or not we're
  205. // using the full terminal window.
  206. out.MoveCursor(r.linesRendered, 0)
  207. } else {
  208. out.CursorBack(r.width)
  209. }
  210. _, _ = r.out.Write(buf.Bytes())
  211. r.lastRender = r.buf.String()
  212. r.buf.Reset()
  213. }
  214. // write writes to the internal buffer. The buffer will be outputted via the
  215. // ticker which calls flush().
  216. func (r *standardRenderer) write(s string) {
  217. r.mtx.Lock()
  218. defer r.mtx.Unlock()
  219. r.buf.Reset()
  220. // If an empty string was passed we should clear existing output and
  221. // rendering nothing. Rather than introduce additional state to manage
  222. // this, we render a single space as a simple (albeit less correct)
  223. // solution.
  224. if s == "" {
  225. s = " "
  226. }
  227. _, _ = r.buf.WriteString(s)
  228. }
  229. func (r *standardRenderer) repaint() {
  230. r.lastRender = ""
  231. }
  232. func (r *standardRenderer) clearScreen() {
  233. r.mtx.Lock()
  234. defer r.mtx.Unlock()
  235. r.out.ClearScreen()
  236. r.out.MoveCursor(1, 1)
  237. r.repaint()
  238. }
  239. func (r *standardRenderer) altScreen() bool {
  240. r.mtx.Lock()
  241. defer r.mtx.Unlock()
  242. return r.altScreenActive
  243. }
  244. func (r *standardRenderer) enterAltScreen() {
  245. r.mtx.Lock()
  246. defer r.mtx.Unlock()
  247. if r.altScreenActive {
  248. return
  249. }
  250. r.altScreenActive = true
  251. r.out.AltScreen()
  252. // Ensure that the terminal is cleared, even when it doesn't support
  253. // alt screen (or alt screen support is disabled, like GNU screen by
  254. // default).
  255. //
  256. // Note: we can't use r.clearScreen() here because the mutex is already
  257. // locked.
  258. r.out.ClearScreen()
  259. r.out.MoveCursor(1, 1)
  260. // cmd.exe and other terminals keep separate cursor states for the AltScreen
  261. // and the main buffer. We have to explicitly reset the cursor visibility
  262. // whenever we enter AltScreen.
  263. if r.cursorHidden {
  264. r.out.HideCursor()
  265. } else {
  266. r.out.ShowCursor()
  267. }
  268. r.repaint()
  269. }
  270. func (r *standardRenderer) exitAltScreen() {
  271. r.mtx.Lock()
  272. defer r.mtx.Unlock()
  273. if !r.altScreenActive {
  274. return
  275. }
  276. r.altScreenActive = false
  277. r.out.ExitAltScreen()
  278. // cmd.exe and other terminals keep separate cursor states for the AltScreen
  279. // and the main buffer. We have to explicitly reset the cursor visibility
  280. // whenever we exit AltScreen.
  281. if r.cursorHidden {
  282. r.out.HideCursor()
  283. } else {
  284. r.out.ShowCursor()
  285. }
  286. r.repaint()
  287. }
  288. func (r *standardRenderer) showCursor() {
  289. r.mtx.Lock()
  290. defer r.mtx.Unlock()
  291. r.cursorHidden = false
  292. r.out.ShowCursor()
  293. }
  294. func (r *standardRenderer) hideCursor() {
  295. r.mtx.Lock()
  296. defer r.mtx.Unlock()
  297. r.cursorHidden = true
  298. r.out.HideCursor()
  299. }
  300. func (r *standardRenderer) enableMouseCellMotion() {
  301. r.mtx.Lock()
  302. defer r.mtx.Unlock()
  303. r.out.EnableMouseCellMotion()
  304. }
  305. func (r *standardRenderer) disableMouseCellMotion() {
  306. r.mtx.Lock()
  307. defer r.mtx.Unlock()
  308. r.out.DisableMouseCellMotion()
  309. }
  310. func (r *standardRenderer) enableMouseAllMotion() {
  311. r.mtx.Lock()
  312. defer r.mtx.Unlock()
  313. r.out.EnableMouseAllMotion()
  314. }
  315. func (r *standardRenderer) disableMouseAllMotion() {
  316. r.mtx.Lock()
  317. defer r.mtx.Unlock()
  318. r.out.DisableMouseAllMotion()
  319. }
  320. // setIgnoredLines specifies lines not to be touched by the standard Bubble Tea
  321. // renderer.
  322. func (r *standardRenderer) setIgnoredLines(from int, to int) {
  323. // Lock if we're going to be clearing some lines since we don't want
  324. // anything jacking our cursor.
  325. if r.linesRendered > 0 {
  326. r.mtx.Lock()
  327. defer r.mtx.Unlock()
  328. }
  329. if r.ignoreLines == nil {
  330. r.ignoreLines = make(map[int]struct{})
  331. }
  332. for i := from; i < to; i++ {
  333. r.ignoreLines[i] = struct{}{}
  334. }
  335. // Erase ignored lines
  336. if r.linesRendered > 0 {
  337. buf := &bytes.Buffer{}
  338. out := termenv.NewOutput(buf)
  339. for i := r.linesRendered - 1; i >= 0; i-- {
  340. if _, exists := r.ignoreLines[i]; exists {
  341. out.ClearLine()
  342. }
  343. out.CursorUp(1)
  344. }
  345. out.MoveCursor(r.linesRendered, 0) // put cursor back
  346. _, _ = r.out.Write(buf.Bytes())
  347. }
  348. }
  349. // clearIgnoredLines returns control of any ignored lines to the standard
  350. // Bubble Tea renderer. That is, any lines previously set to be ignored can be
  351. // rendered to again.
  352. func (r *standardRenderer) clearIgnoredLines() {
  353. r.ignoreLines = nil
  354. }
  355. // insertTop effectively scrolls up. It inserts lines at the top of a given
  356. // area designated to be a scrollable region, pushing everything else down.
  357. // This is roughly how ncurses does it.
  358. //
  359. // To call this function use command ScrollUp().
  360. //
  361. // For this to work renderer.ignoreLines must be set to ignore the scrollable
  362. // region since we are bypassing the normal Bubble Tea renderer here.
  363. //
  364. // Because this method relies on the terminal dimensions, it's only valid for
  365. // full-window applications (generally those that use the alternate screen
  366. // buffer).
  367. //
  368. // This method bypasses the normal rendering buffer and is philosophically
  369. // different than the normal way we approach rendering in Bubble Tea. It's for
  370. // use in high-performance rendering, such as a pager that could potentially
  371. // be rendering very complicated ansi. In cases where the content is simpler
  372. // standard Bubble Tea rendering should suffice.
  373. func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {
  374. r.mtx.Lock()
  375. defer r.mtx.Unlock()
  376. buf := &bytes.Buffer{}
  377. out := termenv.NewOutput(buf)
  378. out.ChangeScrollingRegion(topBoundary, bottomBoundary)
  379. out.MoveCursor(topBoundary, 0)
  380. out.InsertLines(len(lines))
  381. _, _ = out.WriteString(strings.Join(lines, "\r\n"))
  382. out.ChangeScrollingRegion(0, r.height)
  383. // Move cursor back to where the main rendering routine expects it to be
  384. out.MoveCursor(r.linesRendered, 0)
  385. _, _ = r.out.Write(buf.Bytes())
  386. }
  387. // insertBottom effectively scrolls down. It inserts lines at the bottom of
  388. // a given area designated to be a scrollable region, pushing everything else
  389. // up. This is roughly how ncurses does it.
  390. //
  391. // To call this function use the command ScrollDown().
  392. //
  393. // See note in insertTop() for caveats, how this function only makes sense for
  394. // full-window applications, and how it differs from the normal way we do
  395. // rendering in Bubble Tea.
  396. func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {
  397. r.mtx.Lock()
  398. defer r.mtx.Unlock()
  399. buf := &bytes.Buffer{}
  400. out := termenv.NewOutput(buf)
  401. out.ChangeScrollingRegion(topBoundary, bottomBoundary)
  402. out.MoveCursor(bottomBoundary, 0)
  403. _, _ = out.WriteString("\r\n" + strings.Join(lines, "\r\n"))
  404. out.ChangeScrollingRegion(0, r.height)
  405. // Move cursor back to where the main rendering routine expects it to be
  406. out.MoveCursor(r.linesRendered, 0)
  407. _, _ = r.out.Write(buf.Bytes())
  408. }
  409. // handleMessages handles internal messages for the renderer.
  410. func (r *standardRenderer) handleMessages(msg Msg) {
  411. switch msg := msg.(type) {
  412. case repaintMsg:
  413. // Force a repaint by clearing the render cache as we slide into a
  414. // render.
  415. r.mtx.Lock()
  416. r.repaint()
  417. r.mtx.Unlock()
  418. case WindowSizeMsg:
  419. r.mtx.Lock()
  420. r.width = msg.Width
  421. r.height = msg.Height
  422. r.repaint()
  423. r.mtx.Unlock()
  424. case clearScrollAreaMsg:
  425. r.clearIgnoredLines()
  426. // Force a repaint on the area where the scrollable stuff was in this
  427. // update cycle
  428. r.mtx.Lock()
  429. r.repaint()
  430. r.mtx.Unlock()
  431. case syncScrollAreaMsg:
  432. // Re-render scrolling area
  433. r.clearIgnoredLines()
  434. r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary)
  435. r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)
  436. // Force non-scrolling stuff to repaint in this update cycle
  437. r.mtx.Lock()
  438. r.repaint()
  439. r.mtx.Unlock()
  440. case scrollUpMsg:
  441. r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)
  442. case scrollDownMsg:
  443. r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)
  444. case printLineMessage:
  445. if !r.altScreenActive {
  446. lines := strings.Split(msg.messageBody, "\n")
  447. r.mtx.Lock()
  448. r.queuedMessageLines = append(r.queuedMessageLines, lines...)
  449. r.repaint()
  450. r.mtx.Unlock()
  451. }
  452. }
  453. }
  454. // HIGH-PERFORMANCE RENDERING STUFF
  455. type syncScrollAreaMsg struct {
  456. lines []string
  457. topBoundary int
  458. bottomBoundary int
  459. }
  460. // SyncScrollArea performs a paint of the entire region designated to be the
  461. // scrollable area. This is required to initialize the scrollable region and
  462. // should also be called on resize (WindowSizeMsg).
  463. //
  464. // For high-performance, scroll-based rendering only.
  465. func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {
  466. return func() Msg {
  467. return syncScrollAreaMsg{
  468. lines: lines,
  469. topBoundary: topBoundary,
  470. bottomBoundary: bottomBoundary,
  471. }
  472. }
  473. }
  474. type clearScrollAreaMsg struct{}
  475. // ClearScrollArea deallocates the scrollable region and returns the control of
  476. // those lines to the main rendering routine.
  477. //
  478. // For high-performance, scroll-based rendering only.
  479. func ClearScrollArea() Msg {
  480. return clearScrollAreaMsg{}
  481. }
  482. type scrollUpMsg struct {
  483. lines []string
  484. topBoundary int
  485. bottomBoundary int
  486. }
  487. // ScrollUp adds lines to the top of the scrollable region, pushing existing
  488. // lines below down. Lines that are pushed out the scrollable region disappear
  489. // from view.
  490. //
  491. // For high-performance, scroll-based rendering only.
  492. func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {
  493. return func() Msg {
  494. return scrollUpMsg{
  495. lines: newLines,
  496. topBoundary: topBoundary,
  497. bottomBoundary: bottomBoundary,
  498. }
  499. }
  500. }
  501. type scrollDownMsg struct {
  502. lines []string
  503. topBoundary int
  504. bottomBoundary int
  505. }
  506. // ScrollDown adds lines to the bottom of the scrollable region, pushing
  507. // existing lines above up. Lines that are pushed out of the scrollable region
  508. // disappear from view.
  509. //
  510. // For high-performance, scroll-based rendering only.
  511. func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {
  512. return func() Msg {
  513. return scrollDownMsg{
  514. lines: newLines,
  515. topBoundary: topBoundary,
  516. bottomBoundary: bottomBoundary,
  517. }
  518. }
  519. }
  520. type printLineMessage struct {
  521. messageBody string
  522. }
  523. // Println prints above the Program. This output is unmanaged by the program and
  524. // will persist across renders by the Program.
  525. //
  526. // Unlike fmt.Println (but similar to log.Println) the message will be print on
  527. // its own line.
  528. //
  529. // If the altscreen is active no output will be printed.
  530. func Println(args ...interface{}) Cmd {
  531. return func() Msg {
  532. return printLineMessage{
  533. messageBody: fmt.Sprint(args...),
  534. }
  535. }
  536. }
  537. // Printf prints above the Program. It takes a format template followed by
  538. // values similar to fmt.Printf. This output is unmanaged by the program and
  539. // will persist across renders by the Program.
  540. //
  541. // Unlike fmt.Printf (but similar to log.Printf) the message will be print on
  542. // its own line.
  543. //
  544. // If the altscreen is active no output will be printed.
  545. func Printf(template string, args ...interface{}) Cmd {
  546. return func() Msg {
  547. return printLineMessage{
  548. messageBody: fmt.Sprintf(template, args...),
  549. }
  550. }
  551. }