gugu

module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT

README

Gugu Logo

Gugu

English | 中文

A Go TUI (Terminal User Interface) framework inspired by ratatui.

Gugu provides a complete set of tools for building rich terminal applications: layout system, text rendering, style system, terminal backends, and a wide range of built-in widgets.

Features

  • Layout System - Flexible constraint-based layout with Flex, Spacing, Margin, and Padding
  • Text System - Full Unicode/UTF-8 support with grapheme-aware rendering, styled spans, and word wrapping
  • Style System - ANSI 16 colors, 256-color, TrueColor RGB, modifiers, Material Design & Tailwind palettes
  • Terminal Backends - ANSI, Native (macOS/Linux/BSD via x/sys/unix), Windows (Console API + VT), Test backend, with NewDefaultBackend() picking the right one per platform
  • Double Buffering - Efficient diff-based rendering, only changed cells are written
  • Rich Widgets - Block, Paragraph, List, Table, Input, Tabs, Gauge, BarChart, Chart, Canvas, Scrollbar, Sparkline, Calendar, Clear, Fill
  • Stateful Widgets - List, Table, Scrollbar with external state management
  • Input Handling - Full keyboard (F1-F12, modifiers, UTF-8) and mouse (SGR extended) support
  • Builder API - Fluent builders for Layout, Span, Line, Text, and Table Row
  • Border Merging - Automatic border intersection detection and merging
  • OSC 8 Hyperlinks - Clickable terminal hyperlinks
  • Serde Support - JSON serialization for Style, Color, Modifier
  • Test Utilities - TestBackend, buffer assertion helpers, and teatest integration test framework
  • Program Framework - Elm Architecture (Model/Update/View/Cmd/Msg) with built-in event loop, signal handling, SIGWINCH auto-resize, panic recovery, FPS throttling, cross-goroutine p.Send, and Batch/Sequence/Tick/Every commands
  • ProgramOption System - WithAltScreen / WithMouseCellMotion / WithBracketedPaste / WithReportFocus / WithFPS / WithFilter / WithColorProfile / WithoutSignalHandler and more
  • ColorProfile Detection - Automatic NO_COLOR / COLORTERM / TERM-based capability detection with graceful downgrade to ASCII / ANSI / ANSI256 / TrueColor
  • Modern Terminal Features - Runtime AltScreen switching, bracketed paste events, focus/blur events, OSC 8 hyperlinks, OSC 52 clipboard, DECSCUSR cursor styles, OSC 2 window title — all via opt-in optional backend capability interfaces

Quick Start

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "github.com/rleecn/gugu/layout"
    "github.com/rleecn/gugu/style"
    "github.com/rleecn/gugu/terminal"
    "github.com/rleecn/gugu/widgets"
)

func main() {
    backend := terminal.NewDefaultBackend()
    term, err := terminal.New(backend)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Failed: %v\n", err)
        os.Exit(1)
    }

    backend.EnterAlternateScreen()
    backend.EnableRawMode()
    backend.HideCursor()
    defer func() {
        backend.ShowCursor(0, 0)
        backend.DisableRawMode()
        backend.ExitAlternateScreen()
    }()

    // Note: SIGWINCH is Unix-only; on Windows poll backend.Size() on a ticker
    // instead (see examples/ for the cross-platform pattern).
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGWINCH, syscall.SIGINT, syscall.SIGTERM)

    // Key input channel
    keyCh := make(chan terminal.KeyEvent, 1)
    go func() {
        buf := make([]byte, 256)
        for {
            n, err := os.Stdin.Read(buf)
            if err != nil || n == 0 {
                close(keyCh)
                return
            }
            i := 0
            for i < n {
                ev, consumed := terminal.ParseKeySequence(buf[i:n])
                if consumed == 0 {
                    i++
                    continue
                }
                i += consumed
                keyCh <- ev
            }
        }
    }()

    // Draw
    frame := terminal.NewFrame(term)
    area := frame.Area()

    block := widgets.NewBlock().
        SetBorders(widgets.BorderAll).
        SetTitle(" Hello, Gugu! ").
        SetTitleStyle(style.NewStyle().Bold().SetFg(style.Yellow))

    para := widgets.NewParagraph("Welcome to Gugu TUI Framework!\n\nPress q to quit.").
        SetBlock(block).
        SetStyle(style.NewStyle().SetFg(style.White))

    frame.RenderWidget(para, area)
    term.Draw()
    term.Flush()

    // Wait for exit
    for {
        select {
        case <-sigCh:
            return
        case ev, ok := <-keyCh:
            if !ok || (ev.Code == terminal.KeyChar && ev.Text == "q") {
                return
            }
        }
    }
}

Architecture

gugu/
├── buffer/       # Cell grid and diff engine
├── layout/       # Constraint-based layout system
├── style/        # Colors, modifiers, palettes, serde
├── symbols/      # Unicode border, bar, Braille, pixel symbols
├── terminal/     # Terminal backends, Frame, key/mouse parsing
├── text/         # Span, Line, Text, grapheme segmentation
└── widgets/      # Built-in widget implementations

See docs/architecture.md for detailed architecture documentation.

Widgets

Widget Description
Block Container with borders, titles, padding, shadow
Paragraph Multi-line text with wrap, alignment, scroll, mask
List Selectable list with highlight, scroll, direction
Table Tabular data with column constraints, cell/column selection
Input Single-line input with UTF-8, selection, clipboard, validation
Tabs Horizontal tab bar with styled titles
Gauge Progress bar with Unicode support
LineGauge Thin line progress indicator
BarChart Vertical bar chart
Chart Line chart and scatter plot with axes and legend
Canvas Braille-based pixel-level drawing (line, rect, circle)
Scrollbar Vertical/horizontal scrollbar with custom symbols
Sparkline Mini inline chart
Calendar Monthly calendar with date highlighting
Clear Clear an area (for overlays)
Fill Fill an area with a symbol

Layout

// Vertical layout: header(3) + content(fill) + footer(3)
areas := layout.Vertical(
    layout.NewLength(3),
    layout.NewFill(1),
    layout.NewLength(3),
).Split(area)

// Horizontal layout: sidebar(30) + main(fill)
areas := layout.Horizontal(
    layout.NewLength(30),
    layout.NewFill(1),
).Split(area)

// With Flex, Spacing, Margin
areas := layout.Vertical(
    layout.NewPercentage(25),
    layout.NewPercentage(75),
).SetFlex(layout.FlexSpaceBetween).
  SetSpacing(1).
  SetMargin(layout.Margin{Horizontal: 2}).
  Split(area)

Style

// Chained style
sty := style.NewStyle().SetFg(style.White).SetBg(style.Blue).Bold()

// RGB and indexed colors
sty := style.NewStyle().SetFg(style.Rgb(255, 128, 0))
sty := style.NewStyle().SetFg(style.Indexed(202))

// Material Design palette
sty := style.NewStyle().SetFg(style.Material.Blue[500])

// Tailwind CSS palette
sty := style.NewStyle().SetFg(style.Tailwind.Sky[400])

// Parse color from string
c := style.ParseColor("#ff8800")
c := style.ParseColor("index:202")
c := style.ParseColor("light-red")

Text

// Styled spans
line := text.NewLine(
    text.NewSpan("Hello ").SetStyle(style.NewStyle().SetFg(style.Green)),
    text.NewSpan("World").SetStyle(style.NewStyle().SetFg(style.Yellow).Bold()),
)

// Builder API
span := text.NewSpanBuilder("Hello").Fg(style.Red).Bold().Build()
line := text.NewLineBuilder().Span(span).Text(" World").Build()

// Shorthand functions
line := text.L(text.S("Hello", style.NewStyle().SetFg(style.Red)), text.NewSpan(" World"))

Terminal Backends

// Default backend for the current platform (recommended for cross-platform code)
backend := terminal.NewDefaultBackend()

// Native backend (macOS/Linux/BSD, termios raw mode via x/sys/unix)
backend := terminal.NewNativeBackend()

// Cross-platform backend (alias of NativeBackend on Unix; Console API on Windows)
backend := terminal.NewCrossBackend()

// ANSI backend (writes to any io.Writer)
backend := terminal.NewAnsiBackend(os.Stdout)

// Test backend (for unit testing)
backend := terminal.NewTestBackend(80, 24)
Platform availability
Factory macOS Linux BSD Windows
NewDefaultBackend() Native Native Native Windows (Console API)
NewNativeBackend() — (termios is Unix-only)
NewCrossBackend() ✓ (= Native) ✓ (= Native) ✓ (= Native) ✓ (Console API)
NewAnsiBackend(w)

Notes:

  • NewDefaultBackend() is the only entry point guaranteed to compile on every platform — use it unless you have a platform-specific reason. NewNativeBackend does not exist on Windows, and NewAnsiBackend alone cannot provide raw mode or terminal size.
  • On Unix, CrossBackend is a type alias of NativeBackend (both return *NativeBackend, the values are interchangeable). After the termios layer was rewritten on top of golang.org/x/sys/unix, the two implementations became identical across macOS/Linux/BSD; the CrossBackend name is kept for API compatibility with existing callers.
  • Historically the two factories had mutually exclusive platform coverage (NativeBackend was darwin-only, CrossBackend was linux/windows-only), which made code calling either one fail to compile on the other platforms. The unification removed that trap; NewDefaultBackend() was added as the cross-platform entry point.

Viewport Modes

// Fullscreen (default)
term, _ := terminal.New(backend)

// Inline (embedded in shell session)
term, _ := terminal.NewInline(backend, 20)

// Fixed (render at specific position)
term, _ := terminal.NewFixed(backend, 10, 5, 40, 20)

Examples

See the examples directory:

  • demo/ - Full application demo with sidebar, input, and navigation
  • widgets/ - Scrollbar, Tabs, Gauge, Clear/Fill demo
  • layout/ - Layout constraints and Flex demo
  • paragraph/ - Text wrapping, alignment, and scrolling demo
  • list/ - Selectable list with state management demo
  • table/ - Table with column selection demo
  • style/ - Colors, modifiers, and palettes demo
  • canvas/ - Braille drawing demo
  • chart/ - Line chart and scatter plot demo
  • barchart/ - Bar chart with multi-group comparison demo
  • sparkline/ - Rolling sparkline charts with simulated CPU/memory/network metrics
  • input/ - Text input with UTF-8 and selection demo
  • calendar/ - Monthly calendar demo
  • program/ - Program framework (Elm architecture) demo with Tick and cross-goroutine Send
  • progress/ - Progress bar driven by a background task via p.Send
  • spinner/ - Simple spinner built with Tick
  • textarea/ - Multi-line text editor with cursor movement, line splitting, and scrolling
  • http/ - Async HTTP client demonstrating Cmd/Msg with spinner and status machine
  • file-picker/ - File browser with directory navigation via List widget and ListState

Running Examples

# Run the main demo
go run ./examples/demo

# Run the widgets demo
go run ./examples/widgets

# Run a specific feature example
go run ./examples/layout

License

MIT

Directories

Path Synopsis
Package colorprofile 检测当前终端的颜色能力,并提供颜色降级映射。
Package colorprofile 检测当前终端的颜色能力,并提供颜色降级映射。
examples
barchart command
Package main 演示 BarChart widget:垂直柱状图对比多组数据。
Package main 演示 BarChart widget:垂直柱状图对比多组数据。
calendar command
Calendar example demonstrates a monthly calendar with date highlighting.
Calendar example demonstrates a monthly calendar with date highlighting.
canvas command
Canvas example demonstrates Braille-based pixel-level drawing.
Canvas example demonstrates Braille-based pixel-level drawing.
chart command
Chart example demonstrates bar charts and line charts.
Chart example demonstrates bar charts and line charts.
demo command
file-picker command
Package main 演示用 program 框架实现一个文件选择器。
Package main 演示用 program 框架实现一个文件选择器。
http command
Package main 演示用 program 框架发起异步 HTTP 请求。
Package main 演示用 program 框架发起异步 HTTP 请求。
input command
Input example demonstrates text input with UTF-8 support, selection, and clipboard.
Input example demonstrates text input with UTF-8 support, selection, and clipboard.
layout command
Layout example demonstrates constraint-based layout splitting, Flex modes, margin, spacing, and nested layouts.
Layout example demonstrates constraint-based layout splitting, Flex modes, margin, spacing, and nested layouts.
list command
List example demonstrates a selectable list with highlight, scrolling, and state management.
List example demonstrates a selectable list with highlight, scrolling, and state management.
paragraph command
Paragraph example demonstrates text wrapping, alignment, scrolling, and styled text.
Paragraph example demonstrates text wrapping, alignment, scrolling, and styled text.
program command
Package main 演示 program 包提供的 Elm Architecture 模式。
Package main 演示 program 包提供的 Elm Architecture 模式。
progress command
Package main 演示用 program + Gauge widget + Tick 实现一个进度条。
Package main 演示用 program + Gauge widget + Tick 实现一个进度条。
sparkline command
Package main 演示 Sparkline widget:用 Unicode block 字符渲染滚动更新的迷你图表。
Package main 演示 Sparkline widget:用 Unicode block 字符渲染滚动更新的迷你图表。
spinner command
Package main 演示用 program + Tick 实现一个简单的 spinner。
Package main 演示用 program + Tick 实现一个简单的 spinner。
style command
Style example demonstrates colors, modifiers, and color palettes.
Style example demonstrates colors, modifiers, and color palettes.
table command
Table example demonstrates tabular data with row/column selection.
Table example demonstrates tabular data with row/column selection.
textarea command
Package main 演示用 program 框架实现一个多行文本编辑器。
Package main 演示用 program 框架实现一个多行文本编辑器。
widgets command
Package symbols provides Unicode symbol sets for terminal UI rendering.
Package symbols provides Unicode symbol sets for terminal UI rendering.
Package teatest 提供 gugu TUI 应用的集成测试框架。
Package teatest 提供 gugu TUI 应用的集成测试框架。

Jump to

Keyboard shortcuts

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