tui

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GradientUpDown = iota
	GradientDownUp
	GradientLeftRight
	GradientRightLeft
)

Gradient direction constants for TUI usage

View Source
const (
	ShadowLight = iota
	ShadowMedium
	ShadowDark
)

Shadow style constants for TUI usage

Variables

View Source
var ANSIColorMap = map[string]string{
	"30": "#000000",
	"31": "#CD3131",
	"32": "#0DBC79",
	"33": "#E5E510",
	"34": "#2472C8",
	"35": "#BC3FBC",
	"36": "#11A8CD",
	"37": "#E5E5E5",
	"90": "#808080",
	"91": "#FF9999",
	"92": "#99FF99",
	"93": "#FFFF99",
	"94": "#66BBFF",
	"95": "#FF99FF",
	"96": "#99FFFF",
	"97": "#FFFFFF",
}

ANSIColorMap provides mappings from ANSI color codes to hex values This is the canonical color mapping used throughout the library

Functions

func ApplyHorizontalAlignment

func ApplyHorizontalAlignment(line string, canvasWidth int, alignment HorizontalAlignment) string

ApplyHorizontalAlignment applies horizontal alignment to a single line of text.

func ApplyVerticalAlignment

func ApplyVerticalAlignment(lines []string, canvasHeight int, alignment VerticalAlignment) []string

ApplyVerticalAlignment applies vertical alignment to a set of lines.

func CreateAnimationPreview

func CreateAnimationPreview(animName, theme, file string, width, height int) string

CreateAnimationPreview creates a static preview of the animation config

func DetectHalfPixelUsage

func DetectHalfPixelUsage(text string, fontData FontData, scaleFactor float64) bool

DetectHalfPixelUsage checks if the current text rendering would use half-pixels that would interfere with shadow rendering. This function should only return true when shadows would actually cause visual artifacts.

func ExportBitArt

func ExportBitArt(filename string, content []string, target int) error

ExportBitArt handles export target selection and saves accordingly.

This function serves as a router for exporting ASCII art to different targets. It automatically strips ANSI color codes and ensures the filename has a .txt extension.

Parameters:

  • filename: The base filename for the export (extension added if missing)
  • content: The ASCII art content as an array of lines (may contain ANSI codes)
  • target: The export destination (0 = syscgo assets, 1 = sysc-walls daemon)

Returns:

  • nil on success
  • error if the export fails or target is unknown

Example:

art := []string{"\x1b[31mHello\x1b[0m", "\x1b[32mWorld\x1b[0m"}
err := ExportBitArt("greeting", art, 1)
if err != nil {
    log.Fatal(err)
}

func ExportToSyscWalls

func ExportToSyscWalls(filename, content string) error

ExportToSyscWalls exports ASCII art to the sysc-walls screensaver daemon.

The function saves the provided content to ~/.local/share/syscgo/walls/filename and updates the sysc-walls configuration file at ~/.config/sysc-walls/daemon.conf to use the exported artwork.

The filename is automatically sanitized to prevent path traversal attacks. Only alphanumeric characters, dots, hyphens, underscores, and spaces are allowed. The .txt extension is added automatically if not present.

Files and directories are created with user-only permissions (0600 for files, 0700 for directories) to protect user privacy.

Parameters:

  • filename: The name for the exported file (e.g., "my-art.txt"). Path separators and shell metacharacters are automatically stripped.
  • content: The ASCII art content to export (plain text).

Returns:

  • nil on success
  • error if filename is invalid, file cannot be written, or config update fails

Example:

art := "HELLO\nWORLD"
err := ExportToSyscWalls("greeting.txt", art)
if err != nil {
    log.Fatal(err)
}

Security:

  • Filenames are sanitized to prevent directory traversal
  • Only safe characters allowed in filenames
  • Files created with 0600 permissions (user-only read/write)
  • Directories created with 0700 permissions (user-only access)

func FindFontPath

func FindFontPath(fontName string) (string, error)

FindFontPath returns the full path to a font file by name

func GetRenderedDimensions

func GetRenderedDimensions(opts TUIRenderOptions) (width, height int)

GetRenderedDimensions calculates the final dimensions of rendered text

func LaunchAnimation

func LaunchAnimation(animName, theme, file, duration string) error

LaunchAnimation launches the actual animation in the CLI

func ListAvailableFonts

func ListAvailableFonts() []string

ListAvailableFonts returns a list of .bit font files from the assets/fonts directory

func RenderBitText

func RenderBitText(opts TUIRenderOptions) []string

RenderBitText renders text using a bitmap font with styling options This wraps BIT's proven rendering engine

func RenderTextWithFont

func RenderTextWithFont(text string, fontData FontData, options RenderOptions) []string

RenderTextWithFont renders text using the specified font with advanced rendering options

Types

type AnimationWrapper

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

AnimationWrapper wraps any animation type to provide a common interface

func (*AnimationWrapper) Render

func (a *AnimationWrapper) Render() string

func (*AnimationWrapper) Reset

func (a *AnimationWrapper) Reset()

func (*AnimationWrapper) Update

func (a *AnimationWrapper) Update()

type BitFont

type BitFont struct {
	Name       string              `json:"name"`
	Author     string              `json:"author"`
	License    string              `json:"license"`
	Characters map[string][]string `json:"characters"`
}

BitFont represents a bitmap font loaded from a .bit JSON file

func LoadBitFont

func LoadBitFont(path string) (*BitFont, error)

LoadBitFont loads a .bit font file from the given path

func (*BitFont) GetCharWidth

func (f *BitFont) GetCharWidth(char rune) int

GetCharWidth returns the width of a character in this font

func (*BitFont) GetHeight

func (f *BitFont) GetHeight() int

GetHeight returns the height of characters in this font

func (*BitFont) GetMaxWidth

func (f *BitFont) GetMaxWidth(text string) int

GetMaxWidth returns the maximum width needed for the given text

func (*BitFont) RenderText

func (f *BitFont) RenderText(text string) []string

RenderText converts a string to ASCII art using this font

type DescenderInfo

type DescenderInfo struct {
	HasDescender    bool
	BaselineHeight  int // Height of the main character body (excluding descender)
	DescenderHeight int // Height of the descender part
	TotalHeight     int // Total character height
	VerticalOffset  int // How much to offset this character vertically
}

DescenderInfo holds information about a character's descender properties

type ExportError added in v1.0.2

type ExportError struct {
	// Operation indicates which stage failed: "validate", "write", or "config"
	Operation string
	// Path is the file or directory path that was being accessed
	Path string
	// Err is the underlying error that caused the failure
	Err error
}

ExportError represents an error during export operation.

This structured error type provides context about which stage of the export failed (validation, file writing, or config update) and which path was involved.

Example usage:

if err != nil {
    var exportErr *ExportError
    if errors.As(err, &exportErr) {
        log.Printf("Export failed at %s stage for %s", exportErr.Operation, exportErr.Path)
    }
}

func (*ExportError) Error added in v1.0.2

func (e *ExportError) Error() string

Error implements the error interface, providing a formatted error message.

func (*ExportError) Unwrap added in v1.0.2

func (e *ExportError) Unwrap() error

Unwrap returns the underlying error, enabling error chain inspection with errors.Is and errors.As.

type FilenameValidator added in v1.0.2

type FilenameValidator struct {
	// MaxLength is the maximum allowed filename length in bytes (default: 255)
	MaxLength int
	// AllowedPattern is the regex pattern for valid characters
	AllowedPattern *regexp.Regexp
}

FilenameValidator validates filenames for export operations.

This validator ensures filenames are safe for use in filesystem operations, preventing path traversal, shell injection, and other security issues.

Example usage:

validator := NewFilenameValidator()
if err := validator.Validate("my-file.txt"); err != nil {
    log.Fatal(err)
}

safeName := validator.SanitizeFilename("unsafe/../file.txt")
// safeName will be "file.txt" with path components removed

func NewFilenameValidator added in v1.0.2

func NewFilenameValidator() *FilenameValidator

NewFilenameValidator creates a validator with secure default settings.

Default configuration:

  • MaxLength: 255 bytes (typical filesystem limit)
  • AllowedPattern: ^[a-zA-Z0-9_. -]+$ (alphanumeric, underscore, dot, space, hyphen)

Returns:

  • A configured FilenameValidator ready for use

func (*FilenameValidator) SanitizeFilename added in v1.0.2

func (v *FilenameValidator) SanitizeFilename(filename string) string

SanitizeFilename attempts to make a filename safe by removing or replacing unsafe characters.

The sanitization process:

  1. Strips directory components using filepath.Base()
  2. Replaces unsafe characters with underscores
  3. Truncates to maximum length if needed

Only alphanumeric characters, spaces, hyphens, underscores, and dots are preserved. All other characters are replaced with underscores.

Parameters:

  • filename: The potentially unsafe filename

Returns:

  • A sanitized filename safe for use

Example:

safe := validator.SanitizeFilename("../bad;file|name$.txt")
// Returns: "bad_file_name_.txt"

safe := validator.SanitizeFilename("/path/to/file.txt")
// Returns: "file.txt"

func (*FilenameValidator) Validate added in v1.0.2

func (v *FilenameValidator) Validate(filename string) error

Validate checks if a filename is safe and valid.

The validation performs multiple checks:

  • UTF-8 validity
  • Length limits
  • Special directory names (".", "..")
  • Character whitelist (alphanumeric, underscore, dot, space, hyphen)

Parameters:

  • filename: The filename to validate

Returns:

  • nil if valid
  • error describing the validation failure

Example:

err := validator.Validate("../../../etc/passwd")
// Returns error: "filename contains unsafe characters"

func (*FilenameValidator) ValidateAndSanitize added in v1.0.2

func (v *FilenameValidator) ValidateAndSanitize(filename string) (sanitized string, modified bool)

ValidateAndSanitize performs validation and returns a sanitized version if validation fails.

This is a convenience method that combines Validate and SanitizeFilename. If the filename is already valid, it returns the original. If invalid, it returns a sanitized version.

Parameters:

  • filename: The filename to validate and potentially sanitize

Returns:

  • sanitized: A safe filename (either original or sanitized)
  • modified: true if sanitization was needed, false if original was valid

Example:

safe, modified := validator.ValidateAndSanitize("good-file.txt")
// Returns: "good-file.txt", false

safe, modified := validator.ValidateAndSanitize("bad;file.txt")
// Returns: "bad_file.txt", true

type FontData

type FontData struct {
	Name       string
	Author     string
	License    string
	Characters map[string][]string
}

FontData represents BIT's font structure

type GradientDirection

type GradientDirection int

GradientDirection from BIT

const (
	UpDown GradientDirection = iota
	DownUp
	LeftRight
	RightLeft
)

type HorizontalAlignment

type HorizontalAlignment int

HorizontalAlignment represents the horizontal alignment of a character or line.

const (
	// AlignLeft aligns the left of the character/line to the left of the canvas.
	AlignLeft HorizontalAlignment = iota
	// AlignCenter aligns the center of the character/line to the center of the canvas.
	AlignCenter
	// AlignRight aligns the right of the character/line to the right of the canvas.
	AlignRight
)

type Model

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

Model represents the TUI state

func NewModel

func NewModel() Model

NewModel creates a new TUI model with default values

func (Model) Init

func (m Model) Init() tea.Cmd

Init initializes the model

func (Model) Update

func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages and updates the model

func (Model) View

func (m Model) View() string

View renders the TUI

type RenderOptions

type RenderOptions struct {
	CharSpacing            int
	WordSpacing            int
	LineSpacing            int
	Alignment              TextAlignment
	TextColor              string
	GradientColor          string
	GradientDirection      GradientDirection
	UseGradient            bool
	ScaleFactor            float64
	ShadowEnabled          bool
	ShadowHorizontalOffset int
	ShadowVerticalOffset   int
	ShadowStyle            ShadowStyle
	TextLines              []string
}

RenderOptions is BIT's full rendering options structure

type ShadowStyle

type ShadowStyle int

ShadowStyle from BIT

const (
	LightShade ShadowStyle = iota
	MediumShade
	DarkShade
)

type ShadowStyleOption

type ShadowStyleOption struct {
	Name string
	Char rune
	Hex  string
}

ShadowStyleOption represents shadow style options

type Styles

type Styles struct {
	Canvas          lipgloss.Style
	Selector        lipgloss.Style
	SelectorFocused lipgloss.Style
	SelectorLabel   lipgloss.Style
	SelectorValue   lipgloss.Style
	GuidanceBox     lipgloss.Style
	Help            lipgloss.Style
	Background      lipgloss.Style
}

Styles holds lipgloss styles for the TUI

func NewStyles

func NewStyles() Styles

NewStyles creates the dark theme styles

type TUIRenderOptions

type TUIRenderOptions struct {
	Font          *BitFont
	Text          string
	Alignment     int
	Color         string
	Scale         float64
	Shadow        bool
	ShadowOffsetX int
	ShadowOffsetY int
	ShadowStyle   int
	CharSpacing   int
	WordSpacing   int
	LineSpacing   int
	UseGradient   bool
	GradientColor string
	GradientDir   int
	MaxWidth      int // Canvas width for alignment
}

TUIRenderOptions holds simplified configuration for rendering text in the TUI This is our wrapper around BIT's RenderOptions

type TextAlignment

type TextAlignment int

TextAlignment from BIT - using the same values as HorizontalAlignment

const (
	LeftAlign TextAlignment = iota
	CenterAlign
	RightAlign
)

type TickMsg

type TickMsg time.Time

TickMsg is sent when animation should update

type ValidationError added in v1.0.2

type ValidationError struct {
	// Filename is the invalid filename that was rejected
	Filename string
	// Reason explains why the filename was rejected
	Reason string
}

ValidationError represents a filename validation failure.

This error type is used specifically for filename validation issues, providing detailed information about what was invalid.

func (*ValidationError) Error added in v1.0.2

func (e *ValidationError) Error() string

Error implements the error interface.

type VerticalAlignment

type VerticalAlignment int

VerticalAlignment represents the vertical alignment of a character or line.

const (
	// AlignTop aligns the top of the character/line to the top of the canvas.
	AlignTop VerticalAlignment = iota
	// AlignMiddle aligns the middle of the character/line to the middle of the canvas.
	AlignMiddle
	// AlignBottom aligns the bottom of the character/line to the bottom of the canvas.
	AlignBottom
)

Jump to

Keyboard shortcuts

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