webui

package
v0.0.0-...-8023560 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2025 License: MIT Imports: 23 Imported by: 0

README

webui

A web-based interface package for dgamelaunch-style terminal games with real-time rendering, tileset support, and browser-based terminal emulation.


Installation

go get github.com/opd-ai/go-gamelaunch-client/pkg/webui

Features

Core Web Interface
  • Browser-Based Terminal Emulation - Full terminal rendering in web browsers using HTML5 Canvas with WebGL acceleration
  • Real-Time Game Updates - Efficient state synchronization with diff-based polling and minimal bandwidth usage
  • JSON-RPC 2.0 API - Standard RPC communication protocol for game state management and user input handling
  • Embedded Static Assets - Self-contained web server with embedded HTML, CSS, and JavaScript resources
  • CORS Support - Configurable cross-origin resource sharing for flexible deployment scenarios
Terminal Display Features
  • ANSI Color Processing - Complete 256-color palette support with true color RGB rendering
  • Text Attribute Rendering - Bold, inverse, blinking, and underlined text display
  • Cursor Management - Real-time cursor position tracking with visibility control
  • Screen Buffer Management - Efficient memory usage with incremental screen updates
  • Terminal Resize Handling - Dynamic viewport adjustment with proper aspect ratio maintenance
Tileset and Graphics Support
  • YAML-Based Tileset Configuration - Flexible tile mapping system with character-to-sprite associations
  • Multi-Format Image Support - PNG, JPEG, and GIF tileset source images
  • Dynamic Tileset Loading - Runtime tileset switching without server restart
  • Sprite Caching System - Optimized tile rendering with memory-efficient caching
  • Special Tile Handling - Multi-tile entities and animated sprite support
Input Management
  • Comprehensive Keyboard Support - Full keyboard event capture including special keys and modifiers
  • Mouse Event Processing - Click and movement event handling for interactive gameplay
  • Input Event Buffering - Efficient batching of user inputs to reduce network overhead
  • Focus Management - Proper keyboard focus handling for seamless gameplay experience
Connection and State Management
  • WebView Integration - Implements dgclient.View interface for seamless integration with SSH client
  • State Version Tracking - Monotonic versioning system for reliable state synchronization
  • Change Detection - Efficient diff algorithms to minimize data transfer
  • Concurrent Client Support - Multiple browser sessions with independent state management
  • Connection Status Monitoring - Real-time connection health indicators and error reporting
Performance Optimizations
  • Incremental Rendering - Only updates changed screen regions for optimal performance
  • Viewport Management - Smart scrolling and clipping for large terminal buffers
  • Memory Management - Efficient buffer allocation with automatic garbage collection
  • Network Optimization - Compressed state diffs and smart polling intervals
Error Handling and Recovery
  • Graceful Degradation - Fallback rendering modes for limited browser capabilities
  • Connection Recovery - Automatic reconnection with exponential backoff
  • Client-Side Error Reporting - Comprehensive error logging and user feedback
  • Resource Cleanup - Proper resource management and memory leak prevention
Accessibility Features
  • Screen Reader Support - ARIA labels and semantic markup for assistive technologies
  • Keyboard Navigation - Full keyboard accessibility without mouse dependency
  • High Contrast Support - Configurable color schemes for visual accessibility
  • Responsive Design - Mobile-friendly interface with touch input support
Developer Features
  • Modular Architecture - Cleanly separated concerns with well-defined interfaces
  • Configuration Flexibility - Extensive customization options for deployment scenarios
  • Debug Support - Built-in debugging tools and verbose logging capabilities
  • API Documentation - Comprehensive JSON-RPC method documentation
  • Testing Infrastructure - Mock implementations and test utilities for development

Architecture

The webui package implements a layered architecture designed for scalability and maintainability:

View Layer: WebView implements the dgclient.View interface, providing seamless integration with SSH terminal sessions while managing screen buffer state and terminal emulation.

Server Layer: WebUI provides HTTP server functionality with JSON-RPC endpoints, static file serving, and WebSocket-like long polling for real-time communication.

Client Layer: Browser-based JavaScript frontend handles canvas rendering, input event management, and RPC communication with automatic reconnection and error recovery.

State Management: Centralized state tracking with version control enables efficient synchronization between server terminal state and multiple connected browser clients.

The package integrates seamlessly with the dgclient library's SSH connectivity while providing a modern web-based interface for traditional terminal games, bridging classic roguelike gaming with contemporary web technologies.

Documentation

Index

Constants

View Source
const (
	ParseError     = -32700
	InvalidRequest = -32600
	MethodNotFound = -32601
	InvalidParams  = -32602
	InternalError  = -32603
)

Standard JSON-RPC error codes

Variables

This section is empty.

Functions

func Color256

func Color256(u uint8) *color.Color

Color256 converts a 256-color index to a hex color string

func CreateWebView

func CreateWebView(opts dgclient.ViewOptions) (dgclient.View, error)

CreateWebView creates a new WebView that implements dgclient.View

func SaveTilesetConfig

func SaveTilesetConfig(tileset *TilesetConfig, path string) error

SaveTilesetConfig saves a tileset configuration to a YAML file

Types

type Cell

type Cell struct {
	Char    rune   `json:"char"`
	FgColor string `json:"fg_color"`
	BgColor string `json:"bg_color"`
	Bold    bool   `json:"bold"`
	Inverse bool   `json:"inverse"`
	Blink   bool   `json:"blink"`
	TileX   int    `json:"tile_x,omitempty"`
	TileY   int    `json:"tile_y,omitempty"`
	Changed bool   `json:"-"`
}

Cell represents a single character cell with rendering attributes

type CellDiff

type CellDiff struct {
	X    int  `json:"x"`
	Y    int  `json:"y"`
	Cell Cell `json:"cell"`
}

CellDiff represents a change to a specific cell

type ColorConverter

type ColorConverter struct{}

ColorConverter handles ANSI color parsing and conversion using fatih/color library

func NewColorConverter

func NewColorConverter() *ColorConverter

NewColorConverter creates a new color converter with ANSI256 profile NewColorConverter creates a new color converter

func (*ColorConverter) ProcessSGRParams

func (cc *ColorConverter) ProcessSGRParams(params []string) (fgColor, bgColor string, bold, inverse, blink bool)

ProcessSGRParams processes SGR (Select Graphic Rendition) parameters Returns foreground color, background color, and text attributes

type Empty

type Empty struct{}

type GameInputParams

type GameInputParams struct {
	Events []InputEvent `json:"events"`
}

type GamePollParams

type GamePollParams struct {
	Version uint64 `json:"version"`
	Timeout int    `json:"timeout,omitempty"`
}

Parameter types for RPC methods

type GameService

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

Service structs for Gorilla RPC

func (*GameService) GetState

func (s *GameService) GetState(r *http.Request, args *Empty, reply *map[string]interface{}) error

Game service methods

func (*GameService) Poll

func (s *GameService) Poll(r *http.Request, args *GamePollParams, reply *map[string]interface{}) error

func (*GameService) SendInput

func (s *GameService) SendInput(r *http.Request, args *GameInputParams, reply *map[string]interface{}) error

type GameState

type GameState struct {
	Buffer    [][]Cell `json:"buffer"`
	Width     int      `json:"width"`
	Height    int      `json:"height"`
	CursorX   int      `json:"cursor_x"`
	CursorY   int      `json:"cursor_y"`
	Version   uint64   `json:"version"`
	Timestamp int64    `json:"timestamp"`
}

GameState represents the current state of the game screen

type InputEvent

type InputEvent struct {
	Type      string `json:"type"`
	Key       string `json:"key,omitempty"`
	KeyCode   int    `json:"keyCode,omitempty"`
	Data      string `json:"data,omitempty"`
	Timestamp int64  `json:"timestamp"`
}

type RPCError

type RPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

type RPCHandler

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

RPCHandler maintains compatibility with existing code

func NewRPCHandler

func NewRPCHandler(webui *WebUI) *RPCHandler

NewRPCHandler creates a new RPC handler with Gorilla RPC integration

func (*RPCHandler) GetRPCServer

func (h *RPCHandler) GetRPCServer() *rpc.Server

GetRPCServer returns the underlying Gorilla RPC server for HTTP integration

func (*RPCHandler) HandleRequest

func (h *RPCHandler) HandleRequest(ctx context.Context, req *RPCRequest) *RPCResponse

HandleRequest preserves the original signature for compatibility

type RPCRequest

type RPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      interface{}     `json:"id"`
}

Legacy types preserved for compatibility

type RPCResponse

type RPCResponse struct {
	JSONRPC string      `json:"jsonrpc"`
	Result  interface{} `json:"result,omitempty"`
	Error   *RPCError   `json:"error,omitempty"`
	ID      interface{} `json:"id"`
}

type SessionService

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

func (*SessionService) Info

func (s *SessionService) Info(r *http.Request, args *Empty, reply *map[string]interface{}) error

Session service methods

type SpecialTile

type SpecialTile struct {
	ID    string    `yaml:"id"`
	Tiles []TileRef `yaml:"tiles"`
}

SpecialTile represents multi-tile entities

type StateDiff

type StateDiff struct {
	Version   uint64     `json:"version"`
	Changes   []CellDiff `json:"changes"`
	CursorX   int        `json:"cursor_x"`
	CursorY   int        `json:"cursor_y"`
	Timestamp int64      `json:"timestamp"`
}

StateDiff represents changes between game states

type StateManager

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

StateManager manages game state versions and change tracking

func NewStateManager

func NewStateManager() *StateManager

NewStateManager creates a new state manager

func (*StateManager) GetCurrentState

func (sm *StateManager) GetCurrentState() *GameState

GetCurrentState returns the current state

func (*StateManager) GetCurrentVersion

func (sm *StateManager) GetCurrentVersion() uint64

GetCurrentVersion returns the current version number

func (*StateManager) PollChanges

func (sm *StateManager) PollChanges(clientVersion uint64, timeout time.Duration) (*StateDiff, error)

PollChanges waits for changes since the given client version

func (*StateManager) PollChangesWithContext

func (sm *StateManager) PollChangesWithContext(pollCtx context.Context, version uint64) (*StateDiff, error)

PollChangesWithContext waits for changes with a context It is a context-aware version of PollChanges

func (*StateManager) UpdateState

func (sm *StateManager) UpdateState(state *GameState)

UpdateState updates the current state and notifies waiters

type TileMapping

type TileMapping struct {
	Char    string `yaml:"char"`
	X       int    `yaml:"x"`
	Y       int    `yaml:"y"`
	FgColor string `yaml:"fg_color,omitempty"`
	BgColor string `yaml:"bg_color,omitempty"`
	// contains filtered or unexported fields
}

TileMapping maps characters to tile coordinates

type TileRef

type TileRef struct {
	X int `yaml:"x"`
	Y int `yaml:"y"`
}

TileRef references a specific tile

type TilesetConfig

type TilesetConfig struct {
	Name         string        `yaml:"name"`
	Version      string        `yaml:"version"`
	TileWidth    int           `yaml:"tile_width"`
	TileHeight   int           `yaml:"tile_height"`
	SourceImage  string        `yaml:"source_image"`
	Mappings     []TileMapping `yaml:"mappings"`
	SpecialTiles []SpecialTile `yaml:"special_tiles"`
	// contains filtered or unexported fields
}

TilesetConfig represents a tileset configuration

func DefaultTilesetConfig

func DefaultTilesetConfig() *TilesetConfig

DefaultTilesetConfig returns a basic ASCII tileset configuration

func LoadTilesetConfig

func LoadTilesetConfig(path string) (*TilesetConfig, error)

LoadTilesetConfig loads a tileset from a YAML file

func (*TilesetConfig) Clone

func (tc *TilesetConfig) Clone() *TilesetConfig

Clone creates a deep copy of the tileset configuration

func (*TilesetConfig) GetImageData

func (tc *TilesetConfig) GetImageData() image.Image

GetImageData returns the loaded image data

func (*TilesetConfig) GetMapping

func (tc *TilesetConfig) GetMapping(char rune) *TileMapping

GetMapping returns the tile mapping for a character

func (*TilesetConfig) GetTileCount

func (tc *TilesetConfig) GetTileCount() (int, int)

GetTileCount returns the number of tiles in the tileset

func (*TilesetConfig) ToJSON

func (tc *TilesetConfig) ToJSON() map[string]interface{}

ToJSON returns a JSON representation for client-side use

type TilesetService

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

func (*TilesetService) Fetch

func (s *TilesetService) Fetch(r *http.Request, args *Empty, reply *map[string]interface{}) error

Tileset service methods

func (*TilesetService) Update

func (s *TilesetService) Update(r *http.Request, args *json.RawMessage, reply *map[string]interface{}) error

type WebUI

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

WebUI provides a web-based interface for dgclient

func NewWebUI

func NewWebUI(opts WebUIOptions) (*WebUI, error)

NewWebUI creates a new WebUI instance

func (*WebUI) GetTileset

func (w *WebUI) GetTileset() *TilesetConfig

GetTileset returns the current tileset configuration

func (*WebUI) GetView

func (w *WebUI) GetView() *WebView

GetView returns the current view

func (*WebUI) ServeHTTP

func (w *WebUI) ServeHTTP(rw http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*WebUI) SetView

func (w *WebUI) SetView(view *WebView)

SetView sets the view for the WebUI

func (*WebUI) Start

func (w *WebUI) Start(addr string) error

Start starts the WebUI server

func (*WebUI) StartWithContext

func (w *WebUI) StartWithContext(ctx context.Context, addr string) error

StartWithContext starts the WebUI server with context for graceful shutdown

func (*WebUI) UpdateTileset

func (w *WebUI) UpdateTileset(tileset *TilesetConfig) error

UpdateTileset updates the tileset configuration

type WebUIOptions

type WebUIOptions struct {
	// View to use for rendering
	View *WebView

	// Tileset configuration
	TilesetPath string
	Tileset     *TilesetConfig

	// Server configuration
	ListenAddr  string
	PollTimeout time.Duration

	// CORS settings
	AllowOrigins []string

	// Static file serving
	StaticPath string // Optional: override embedded files
}

WebUIOptions contains configuration for WebUI

type WebView

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

WebView implements dgclient.View for web browser rendering

func NewWebView

func NewWebView(opts dgclient.ViewOptions) (*WebView, error)

NewWebView creates a new web-based view

func (*WebView) Clear

func (v *WebView) Clear() error

Clear clears the display

func (*WebView) Close

func (v *WebView) Close() error

Close cleans up resources

func (*WebView) GetCurrentState

func (v *WebView) GetCurrentState() *GameState

GetCurrentState returns the current game state

func (*WebView) GetSize

func (v *WebView) GetSize() (int, int)

GetSize returns current dimensions

func (*WebView) GetStateManager

func (v *WebView) GetStateManager() *StateManager

GetStateManager returns the state manager for this view

func (*WebView) HandleInput

func (v *WebView) HandleInput() ([]byte, error)

HandleInput reads and returns user input

func (*WebView) Init

func (v *WebView) Init() error

Init initializes the web view

func (*WebView) Render

func (v *WebView) Render(data []byte) error

Render processes terminal data and updates the screen buffer

func (*WebView) SendInput

func (v *WebView) SendInput(data []byte)

SendInput queues input from web client

func (*WebView) SetSize

func (v *WebView) SetSize(width, height int) error

SetSize updates the view dimensions

func (*WebView) SetTileset

func (v *WebView) SetTileset(tileset *TilesetConfig)

SetTileset updates the tileset configuration

func (*WebView) WaitForUpdate

func (v *WebView) WaitForUpdate(timeout time.Duration) bool

WaitForUpdate waits for the next screen update

Jump to

Keyboard shortcuts

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