txt

package module
v0.9.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2026 License: MIT, Unlicense Imports: 17 Imported by: 0

README

txt

txt is a Go package for building text-based user interfaces that run in either a terminal (TUI) or a graphical window (GUI) — selected at build time via build tags. The same application code runs unchanged in both environments.

Quick start

package main

import (
    "context"
    "os"

    vw "git.sr.ht/~slukits/txt"
    "git.sr.ht/~slukits/txt/lyt"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    ui := new(vw.UI)
    vw.Apply(ui,
        vw.TerminalBackend(),
        vw.SetQuitting(func(err error) { cancel(); os.Exit(0) }),
        vw.SetReceiver(func(k vw.Key) vw.ReConfig {
            if k.Rune == 'q' {
                cancel()
                os.Exit(0)
            }
            return vw.NoReConfig
        }),
        vw.SetContent(&myContent{}),
    )
    if err := vw.Display(ctx, ui); err != nil {
        panic(err)
    }
}

type myContent struct{ idx int }

func (c *myContent) Init(cols, rows int) lyt.Settings {
    c.idx = 0
    return *new(lyt.Settings).
        Add(lyt.Background(lyt.Black)).
        Add(lyt.Foreground(lyt.White))
}

func (c *myContent) Next() (rune, lyt.Settings) {
    text := []rune("hello, txt")
    if c.idx >= len(text) {
        return 0, nil
    }
    r := text[c.idx]
    c.idx++
    return r, nil
}

func (c *myContent) Done(_ error) {}

Build for terminal (default) or GUI:

go build .                           # terminal + graphical
go build -tags terminal_only .       # terminal only
go build -tags graphical_only .      # GUI window only

API

UI setup
ui := new(vw.UI)
ui, err := vw.Apply(ui, option1, option2, ...)

Apply registers the UI in an internal settings context if needed, applies all given settings in order, and returns the configured UI. It fails on the first setting that returns an error.

Register(ui *UI, scc *settings.Contexts) *UI attaches a UI to an existing settings.Contexts when sharing a settings tree with other components.

Display
err := vw.Display(ctx, ui)

Starts the event loop for ui. Display requires at least one of SetReceiver or SetQuitting to be set, and a backend. It blocks in the current goroutine (the main goroutine in production) until the backend's own event pump exits. Canceling ctx stops the loop.

Use ui.WaitForCleanup(timeout) after canceling ctx to synchronize before exiting:

cancel()
if err := ui.WaitForCleanup(time.Second); err != nil {
    log.Fatal(err)
}
Backends
Setting Build tag constraint Description
TerminalBackend() !graphical_only tcell-based TUI
GraphicalBackend() !terminal_only window-based GUI
Event callbacks
// Called when the user requests the application to close.
vw.SetQuitting(func(err error) { ... })

// Called on every key event; may return layout reconfiguration.
vw.SetReceiver(func(k vw.Key) vw.ReConfig { ... })

// Called if the event-polling goroutine panics.
vw.SetPanicking(func(v any) { ... })
Keys

Key carries a rune, a SpecialKey, and a ModifierMask. Helper constructors:

vw.MkRuneKey('a', vw.Ctrl)
vw.MkSpecialKey(vw.KeyUp, vw.NoModifier)
vw.ParseKey(s)   // round-trips k.String()

Special keys: KeyUp, KeyDown, KeyLeft, KeyRight, KeyPgUp, KeyPgDn, KeyHome, KeyEnd, KeyInsert, KeyDelete, KeyEsc, KeyTab, KeyF1–KeyF12.

Modifiers: Shift, Ctrl, Alt, Dbl (double-click), NoModifier.

Content

Content is the interface for rendering:

type Content interface {
    // Called at the start of each repaint; returns initial layout.
    Init(columns, rows int) lyt.Settings

    // Called repeatedly for each rune; nil Settings means no change.
    // Return zero rune to signal end of content.
    Next() (rune, lyt.Settings)

    // Called when the display is filled or content is exhausted.
    // err is non-nil if a layout setting was invalid.
    Done(error)
}

Setting a new content via SetContent triggers a repaint.

Layout settings (lyt package)

lyt.Settings is a []lyt.Setting. Build one with chained Add calls:

ss := new(lyt.Settings).
    Add(lyt.Background(lyt.Navy)).
    Add(lyt.Foreground(lyt.White)).
    Add(lyt.Cursor())
Setting Effect
Background(c Color) background color from this rune onward
Foreground(c Color) foreground color from this rune onward
Cursor() marks this cell as the cursor
Invert() swap fg/bg for subsequent paints
InvertLine() invert the entire line
Goto(col, row) move paint position; usable with zero rune
Visual effects
// Visual bell over a region of the display.
(&lyt.Bell{}).With(
    lyt.BellSize{X: 10, Y: 3},
    lyt.BellDuration(300 * time.Millisecond),
).Setting()

// Blinking cursor (stop it explicitly when done).
bc := new(lyt.BlinkingCursor).With(
    lyt.CursorInterval(250 * time.Millisecond),
)
ss.Add(bc.Setting())
// ...
bc.Stop()
Colors

lyt.Color is the xterm 256-color palette, exported as named constants: lyt.Black, lyt.White, lyt.Red, lyt.Green, lyt.Blue, and the full set of xterm names (lyt.DeepSkyBlue1, lyt.Grey53, …).

State inspection
info := ui.Stat()
// info.Backend    — type string of the active backend
// info.IsPolling  — true while the event loop is running
// info.IsConsumed — true if a receiver or quitter is set
// info.Columns    — last known terminal/window width
// info.Rows       — last known terminal/window height

Testing

The vwtest subpackage provides a mock backend for unit tests:

fx, ui := vwtest.View(t, vw.SetReceiver(...))
fx.SendRune('q')
fx.SendQuit()

License

GPL-3.0-or-later

Documentation

Index

Constants

View Source
const (
	ModeUnknown = backends.ModeUnknown
	ModeDark    = backends.ModeDark
	ModeLight   = backends.ModeLight
)

Variables

View Source
var ErrNoBackendSet = errors.New(
	"vw: display: ui needs a backend set")
View Source
var ErrTimeout = errors.New("vw: ui: wait for cleanup: timeout")
View Source
var ErrUINotConsumed = errors.New(
	"vw: display: ui needs at least vw.Receiver or vw.Quitter")
View Source
var NoReConfig = ReConfig{}

NoReConfig is used by an receiver to signal no configuration changes.

Functions

func Display

func Display(ctx context.Context, ui *UI) error

Display sets up the ui for reporting events to set callbacks and for receiving content to be displayed. Display will fail if it is not consumed -- i.e. neither vw.Quitting nor vw.Receiver was set -- and if it has no backend set.

func DummyBackend

func DummyBackend() settings.Setting

func GraphicalBackend

func GraphicalBackend() settings.Setting

func HintColorMode added in v0.9.12

func HintColorMode(m ColorMode) settings.Setting

HintColorMode hints the color mode for when the backend can't auto-detect it. Has no effect on the color mode while non-default colors are set; takes effect once SetColors(DefaultColor, DefaultColor) restores backend defaults.

func SetBackend

func SetBackend(bui backends.UIer) settings.Setting

SetBackend sets the used backend.

func SetColors added in v0.9.7

func SetColors(fg, bg lyt.Color, ml ModeListener) settings.Setting

SetColors overrides the backend's default fg/bg colors. ml is called when the derived color mode changes; pass nil if not needed.

func SetContent

func SetContent(p Content) settings.Setting

SetContent from which are the runes retrieved to display.

func SetPanicking

func SetPanicking(p Panicking) settings.Setting

SetPanicking sets the listener for panic events.

func SetQuitting

func SetQuitting(q Quitting) settings.Setting

SetQuitting sets the listener for quit events.

func SetReceiver

func SetReceiver(r Receiver) settings.Setting

SetReceiver sets the listener for keyboard events.

func TerminalBackend

func TerminalBackend() settings.Setting

Types

type ColorMode added in v0.9.7

type ColorMode = backends.ColorMode

ColorMode classifies a fg/bg color pair as dark, light, or unknown.

type Content

type Content interface {

	// Init is the first call initiating a new painting of the display
	// content having given columns and rows available.
	Init(columns, rows int) lyt.Settings

	// Next is asked for the next rune to display until either both
	// return values are zero or the display is filled.
	Next() (rune, lyt.Settings)

	// Done is called when either no more runes provided or the display
	// is full or a combination of lyt.Settings can't be applied
	// typically because the position would leave the available space.
	// In the later case an error is reported.
	Done(error)
}

Content provides the content for the display and is set using SetContent. Setting a content indicates also the redrawing of the display (except for the first time).

type Info

type Info struct {
	IsConsumed bool
	IsPolling  bool
	IsTerminal bool
	Backend    string
	Columns    int
	Rows       int
	FgColor    lyt.Color
	BgColor    lyt.Color
	ColorMode  ColorMode
}

Info holds information about an UI's current state.

type ModeListener added in v0.9.12

type ModeListener func(ColorMode)

ModeListener is called by SetColors when the derived color mode changes as a result of the new colors.

type Panicking

type Panicking func(any)

Panicking -- if set by SetPanicking -- is called if the receiver of events from the respective ui-backend has panicked.

type Quitting

type Quitting func(error)

A Quitting -- if set by SetQuitter -- is called if the user uses ui controls to indicate that the application should be closed.

type ReConfig

type ReConfig = backends.ReConfig

ReConfig allows the Receiver to reconfigure view behavior in response to key events. Returning view.NoReConfig means no reconfiguration.

type Receiver

type Receiver func(key.Key) ReConfig

A Receiver -- if set by SetReceiver -- is called if a key event is reported from the backend.

type UI

type UI struct {
	// contains filtered or unexported fields
}

UI instance is used to set up the ui and retrieve its current state. An UI instance must not be copied after its first use. An UI is typically created by vw.Apply e.g.:

ui, err := vw.Apply(nil,
	SetQuitting(...),
	SetReceiver(...),
	// ....
)

and then displayed with vw.Display.

func Apply

func Apply(ui *UI, ss ...settings.Setting) (*UI, error)

Apply given settings ss to given ui instance g and return ui or fail if one of ss fails. Note ui is created if nil.

func Register

func Register(ui *UI, scc *settings.Contexts) *UI

Register given ui at given settings context scc. Register panics if scc already contains an ui.

func (*UI) CanDetermineColorMode added in v0.9.11

func (ui *UI) CanDetermineColorMode() bool

CanDetermineColorMode reports whether the backend can detect color-mode changes mid-session. TUI: true iff COLORFGBG is set. GUI/mock: always true. No backend: false.

func (*UI) DetectColorMode added in v0.9.13

func (ui *UI) DetectColorMode() ColorMode

DetectColorMode returns the backend's current detected color mode, bypassing any consumer override. Consumers use this to watch for OS/terminal theme changes. No backend: ModeUnknown.

func (*UI) Stat

func (ui *UI) Stat() Info

Stat reports information about the current state of given ui.

func (*UI) WaitForCleanup

func (ui *UI) WaitForCleanup(timeout time.Duration) error

Directories

Path Synopsis
internal
gui
lyt
package lyt is an indirection that translates consumer space layout settings (see vw/lyt-package) into backend layout aspects (see internal/backends.)
package lyt is an indirection that translates consumer space layout settings (see vw/lyt-package) into backend layout aspects (see internal/backends.)
tui
ui
Package key provides key constants in their own name space.
Package key provides key constants in their own name space.
Package lyt makes internal constants and types for the layout available to a consumer of the vw package without filling its name space.
Package lyt makes internal constants and types for the layout available to a consumer of the vw package without filling its name space.
pkg
er

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址