Documentation
¶
Overview ¶
Package live draws terminal output that changes in place, and keeps the terminal usable when the program drawing it stops unexpectedly.
Live redraws a block of lines in place: each Live.Draw replaces the previous block instead of adding to the scrollback. Blocks sets a command's step-by-step detail lines apart from the results it reports.
Cursor hides and shows a terminal's cursor, and InstallSignalRestore makes sure a hidden cursor is shown again when the process is interrupted, terminated or suspended. OnRestore lets other code that changed the terminal, its input mode for example, put it back on the same occasions. A cursor is a property of the terminal, not of any one writer, and signal handlers are process-wide, so this part of the package keeps process-wide state: a registry of hidden cursors, counted per terminal, the functions registered with OnRestore, and at most one installed signal handler. Everything else is per instance.
Nothing on the way out of the process waits for the terminal: a terminal that takes no more output, or a registered function that does not return, holds a signal up for a moment and no longer.
None of the types here decide whether drawing is appropriate. Check term.CanAnimate before drawing in place: escape sequences that move the cursor ruin a log file or a pipe.
Redrawing in place counts the rows a block takes up, and when the window of the terminal changes its width, it counts them at the new width. That is right for the terminals that wrap their lines again for the new width, which most do. On one that cuts its lines off instead (xterm, GNU screen, the Linux console), a block with a line wider than the narrowed window is taken for taller than it is, and the next draw erases that many rows above it. The package cannot tell the two kinds apart.
Index ¶
Examples ¶
Constants ¶
const ( // HideCursorSequence hides the terminal cursor (DECTCEM reset). HideCursorSequence = "\x1b[?25l" // ShowCursorSequence shows the terminal cursor (DECTCEM set). ShowCursorSequence = "\x1b[?25h" )
Variables ¶
This section is empty.
Functions ¶
func HideCursor ¶
HideCursor hides the cursor of the terminal w writes to and returns the function that shows it again. The function is idempotent, so it can be deferred and also called earlier.
func InstallSignalRestore ¶
func InstallSignalRestore() (uninstall func())
InstallSignalRestore keeps a hidden cursor from staying hidden when the process never reaches its deferred cleanup. It returns the function that uninstalls the handler again; that function is safe to call more than once.
On Unix, terminating signals (SIGINT, SIGTERM, SIGHUP, SIGQUIT) show every hidden Cursor, call the functions registered with OnRestore, and are then re-raised with their default disposition, so the exit status and SIGQUIT's goroutine dump are unchanged. A terminal that does not take the show sequence, or a registered function that does not return, holds the signal up for a moment and no longer.
SIGTSTP (Ctrl-Z) shows the cursors and stops the process where the kernel would have stopped it: not in an orphaned process group, such as a command started by ssh or docker exec without a shell around it, where nothing could continue the process again and Ctrl-Z keeps doing nothing. Once SIGCONT continues the process the cursors are hidden again, unless the process was continued in the background, as a shell's bg does: there they stay visible until a SIGCONT finds the process in the foreground. The process stops itself with SIGTTIN, the terminal's stop signal that has its default disposition, so a shell that names the signal a job was stopped by names that one. SIGTTIN and SIGTTOU are otherwise left alone: they mean the terminal is denied to the process, and writing to it would only raise another one. A process started with the terminal's stop signals ignored, as a shell starts the commands of a command substitution, is not stopped either: the cursors show for a moment and are hidden again. Elsewhere, os.Interrupt and SIGTERM show the cursors, call the registered functions and end the process with exit status 1.
SIGKILL and SIGSTOP cannot be caught; a process ended or stopped by them leaves the cursor hidden.
Signal dispositions are process-wide, so one handler serves every caller: calls are counted, the first one installs the handler, and it stays installed until every returned function has been called.
Installing the handler also means the signals it handles no longer end the process before the handler has run; a program that handles SIGINT itself should call RestoreAll from its own handler instead.
func OnRestore ¶ added in v0.7.0
func OnRestore(restore func()) (remove func())
OnRestore registers restore to be called where the process is about to end without reaching its deferred calls: by RestoreAll, by the signal handler of InstallSignalRestore before it raises a terminating signal again, and by Cursor.RestoreOnPanic before it panics again. It is meant for what a program changed about its terminal besides the cursor, such as its input mode. The returned function takes restore out again; it is safe to call more than once.
restore is called on a goroutine of its own, at the same time as the other registered functions and possibly while the code it cleans up after is still running, and it is called every time one of those paths is taken, so it has to be safe to call more than once and from any goroutine. It gets a moment, the 100 milliseconds a stalled terminal gets everywhere on these paths, shared with all other registered functions: after that the process goes on, and dies, without waiting for it.
restore is not called when the process is suspended with SIGTSTP, since nothing would undo it when the process continues. A program that has to follow a suspension handles SIGTSTP and SIGCONT itself.
Example ¶
package main
import (
"fmt"
"github.com/mittwald/cli-kit/live"
)
func main() {
// A prompt that put the terminal into raw mode registers how to put it
// back, for the exits that skip its deferred calls.
remove := live.OnRestore(func() { fmt.Println("terminal mode restored") })
defer remove()
// The signal handler of InstallSignalRestore does this before it ends
// the process.
live.RestoreAll()
}
Output: terminal mode restored
func RestoreAll ¶
func RestoreAll()
RestoreAll shows every cursor this process hid and has not shown again, and calls the functions registered with OnRestore. It waits no longer than a moment for a frame in progress, for a terminal that does not take the show sequence, or for a registered function, so it is safe to call on any exit path: a stalled terminal cannot keep it from returning.
Call it on the way out only. A function a prompt registered puts the terminal back into its mode while the prompt may still be waiting, so an answer that was to stay hidden would be echoed from then on.
Types ¶
type Blocks ¶
type Blocks struct {
// contains filtered or unexported fields
}
Blocks sets a command's progress lines apart from the results it reports. Detail lines are written as a block of their own, with a blank line before and after it, and painted in the theme's Status style on a terminal that takes color. A detail line that should stand out, a warning by default, is left unpainted. Plain lines are everything else; the first plain line after a block closes it.
Both writers expect whole lines per write, the way fmt.Fprintln writes them; a write may hold several lines, and an empty write does nothing. A Blocks is safe for concurrent use.
Example ¶
package main
import (
"fmt"
"os"
"github.com/mittwald/cli-kit/live"
)
func main() {
blocks := live.NewBlocks(os.Stdout)
fmt.Fprintln(blocks.Plain(), "Building release 1.4.2")
fmt.Fprintln(blocks.Detail(), "compiling 12 packages")
fmt.Fprintln(blocks.Detail(), "linking binary")
fmt.Fprintln(blocks.Plain(), "Built release 1.4.2")
}
Output: Building release 1.4.2 compiling 12 packages linking binary Built release 1.4.2
func NewBlocks ¶
func NewBlocks(w io.Writer, options ...BlocksOption) *Blocks
NewBlocks returns a Blocks writing to w. Detail lines are painted when term.Colored(w) reports true.
func (*Blocks) Close ¶
func (b *Blocks) Close()
Close ends an open block. Call it before output that Blocks does not see, such as a line written to the other stream of the same terminal. Closing a closed block writes nothing.
func (*Blocks) Detail ¶
Detail returns the writer for progress lines. The writer also has Close and Spaced methods that act on b, for callers that hold only the writer.
type BlocksOption ¶
type BlocksOption func(*Blocks)
BlocksOption configures a Blocks.
func WithDetailStyle ¶
func WithDetailStyle(style theme.Style) BlocksOption
WithDetailStyle paints detail lines in style instead of the active theme's Status style.
func WithHighlight ¶
func WithHighlight(highlight func(text string) bool) BlocksOption
WithHighlight decides which detail lines are left unpainted so they stand out from the rest of the block. It is asked about every line of a write on its own, without the line's newline. The default leaves lines containing "WARNING" or "ERROR" unpainted.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor tracks whether a program hid the cursor of the terminal it writes to, so that every way out of the program can show it again: a deferred call, a recovered panic, or a signal handler installed by InstallSignalRestore.
A terminal has one cursor, however many Cursor values write to it, so the Cursors of one terminal count together: the terminal's cursor is hidden by the first of them that hides it and shown again when the last of them shows it. A progress bar that finishes therefore does not show a cursor the application around it still hides. Two Cursors share a terminal when they were created for the same writer, or for writers that wrap it with an Unwrap() io.Writer method; on Unix also when their writers are files open on the same terminal device, such as os.Stdout and os.Stderr of an interactive program, and on Windows when both are consoles. A terminal opened through /dev/tty counts as one of its own.
A Cursor also serializes output to its terminal. Code that draws frames holds Cursor.Lock while it writes, so a show sequence written from a signal handler never lands in the middle of a frame.
A hidden Cursor is recorded in a process-wide registry until it is shown again; that registry is what the signal handler and RestoreAll use. Hide, Show and the lock are safe for concurrent use.
Example ¶
package main
import (
"fmt"
"os"
"github.com/mittwald/cli-kit/live"
)
func main() {
// Show the cursor again if the program is interrupted while it is hidden.
defer live.InstallSignalRestore()()
cursor := live.NewCursor(os.Stderr)
cursor.Hide()
defer cursor.Show()
go func() {
defer cursor.RestoreOnPanic()
cursor.Lock()
defer cursor.Unlock()
fmt.Fprint(os.Stderr, "\rworking…")
}()
}
Output:
func NewCursor ¶
NewCursor returns a Cursor for the terminal w writes to. It does not write anything.
func (*Cursor) Hide ¶
func (c *Cursor) Hide()
Hide hides the cursor and records it, so a signal handler can show it again. Hiding a hidden cursor writes nothing, and so does hiding the cursor of a terminal that another Cursor already keeps hidden.
func (*Cursor) Lock ¶
func (c *Cursor) Lock()
Lock serializes a write to the terminal with the cursor's own writes. Hold it while writing a frame; do not call Hide or Show while holding it.
func (*Cursor) RestoreOnPanic ¶
func (c *Cursor) RestoreOnPanic()
RestoreOnPanic shows every cursor this process hid, as RestoreAll does, calls the functions registered with OnRestore, and panics again with the value it recovered. A panic in a goroutine runs only that goroutine's deferred calls before the process dies, so every goroutine that draws while the cursor is hidden should start with
defer cursor.RestoreOnPanic()
Showing c alone would not do: a terminal that another Cursor hid as well stays hidden until that one shows it, and in a dying process it never gets to. A program that recovers the panic further up and goes on finds all its cursors shown.
It has to be called directly by a deferred statement. A nil Cursor passes the panic on all the same.
func (*Cursor) Show ¶
func (c *Cursor) Show()
Show ends what Cursor.Hide began: the cursor is visible again unless another Cursor of the same terminal still keeps it hidden. It is idempotent, so it can be deferred, called at an output boundary, and called again from a signal handler without writing a stray sequence.
type Live ¶
type Live struct {
// contains filtered or unexported fields
}
Live is a block of lines that a terminal shows as it is now: each Live.Draw replaces the lines the previous draw showed instead of adding to the scrollback.
Nothing else may write to the terminal between two draws, because the block is found again by counting rows up from the cursor. For the same reason a block has to fit on the screen: the cursor cannot move above the top of the screen, so rows that scrolled off cannot be redrawn.
The rows are counted at the width the terminal has when the block is drawn over, which is right for a terminal that wraps its lines again when its window changes width, as most do. A terminal that cuts its lines off instead, such as xterm, GNU screen or the Linux console, keeps a line on the one row it had; the next draw after such a window was made narrower moves up too far and erases the rows above the block that it takes for the block's.
A Live is not safe for concurrent use.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/mittwald/cli-kit/live"
)
func main() {
var screen bytes.Buffer
block := live.New(&screen)
_ = block.Draw([]string{"downloading: 10%"})
_ = block.Draw([]string{"downloading: 60%"})
fmt.Printf("%q\n", screen.String())
}
Output: "\x1b[Jdownloading: 10%\n\r\x1b[1A\x1b[Jdownloading: 60%\n"
func (*Live) Clear ¶
Clear erases the block the last draw showed and leaves the cursor where the block started, so the next output takes its place. A block that did not fit on the screen cannot be taken back and is left as it is.
func (*Live) Draw ¶
Draw replaces what the previous draw showed with lines, and leaves the cursor at the start of the row below them, so output written after the last draw follows it like any other output. Drawing the lines already on screen writes nothing, and drawing no lines at all is Live.Clear.
A line is drawn as the terminal shows it: one wider than the terminal wraps onto further rows, a tab moves to the next of the tab stops every 8 columns, and a line with newlines in it is drawn as the lines between them, a carriage return before a newline left out. The redraw counts the rows on that basis, so lines must hold no other control character and no escape sequence but colors and hyperlinks; term.Sanitize makes text from elsewhere fit to draw.
Lines that do not fit lose their first lines until they do, and a single remaining line that still wraps past the bottom of the screen is cut short. A block cut down this way can still be redrawn in place; a block running off the screen would pile up in the scrollback. Callers that know which lines matter least should keep within Live.Fits themselves. On a terminal one row high nothing fits, and each draw goes below the previous one.