- Versión actualizada a v0.28.0 - Nuevos hitos: WindowState, Shadow Baking, ColorTransition ε - Optimizaciones detalladas (7 activas) - Métricas: 4.2x más rápido Debug, 0 memory leaks 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
449 lines
15 KiB
Markdown
449 lines
15 KiB
Markdown
# zcatgui - GUI Library para Zig
|
||
|
||
> **IMPORTANTE PARA CLAUDE**: Lee la sección "PROTOCOLO DE INICIO" antes de hacer cualquier cosa.
|
||
|
||
---
|
||
|
||
## PROTOCOLO DE INICIO (LEER PRIMERO)
|
||
|
||
### Paso 1: Leer normas del equipo
|
||
```
|
||
/mnt/cello2/arno/re/recode/teamdocs/NORMAS_ESENCIALES.md
|
||
```
|
||
Contiene: rutas, VCS (git), flujo de trabajo, credenciales.
|
||
|
||
### Paso 2: Verificar estado con git
|
||
```bash
|
||
git status && git log --oneline -5
|
||
zig build test
|
||
```
|
||
**Nota:** Usamos git con commits frecuentes. Ver `teamdocs/NORMAS_ESENCIALES.md` sección VCS.
|
||
|
||
### Paso 3: Leer documentación del proyecto
|
||
```
|
||
REFERENCE.md # ⭐ MANUAL DE REFERENCIA COMPLETO
|
||
CHANGELOG.md # Historial de versiones
|
||
docs/DEVELOPMENT_PLAN.md # Plan de desarrollo por fases
|
||
docs/ARCHITECTURE.md # Arquitectura y decisiones de diseño
|
||
docs/MOBILE_WEB_BACKENDS.md # Documentación backends mobile/web
|
||
docs/research/DVUI_AUDIT_2025-12-17.md # Auditoría DVUI (paridad visual)
|
||
docs/research/WIDGET_COMPARISON.md # Comparativa zcatgui vs DVUI vs Gio
|
||
```
|
||
|
||
### Paso 4: Verificar estado del proyecto
|
||
```bash
|
||
cd /mnt/cello2/arno/re/recode/zig/zcatgui
|
||
git status
|
||
git log --oneline -3
|
||
zig build test
|
||
```
|
||
|
||
### Paso 5: Continuar trabajo
|
||
Una vez verificado el estado, continúa desde donde se dejó.
|
||
|
||
---
|
||
|
||
## REGLA CRÍTICA: NO EJECUTAR BINARIOS GUI
|
||
|
||
**NUNCA ejecutar programas GUI directamente con `./programa` o en background**
|
||
|
||
Los procesos GUI no terminan correctamente desde Claude Code y dejan shells zombie que:
|
||
1. Consumen contexto de la conversación con mensajes "Background Bash running"
|
||
2. Fuerzan compactaciones prematuras del contexto
|
||
3. Degradan severamente la calidad de la sesión de trabajo
|
||
|
||
**Alternativas:**
|
||
- Para verificar que compila: `zig build` (sin ejecutar)
|
||
- Para probar muy brevemente: `timeout 2s ./programa 2>&1 || true`
|
||
- **Mejor opción**: Pedir al usuario que lo pruebe y reporte
|
||
|
||
Esta regla está documentada en teamdocs desde 2025-11-30.
|
||
|
||
---
|
||
|
||
## CLAUDE CODE + ZLS (LSP)
|
||
|
||
Claude Code tiene integración LSP con zls (Zig Language Server).
|
||
|
||
**Plugin:** `$HOME/.claude/plugins/zls-lsp/`
|
||
|
||
**Operaciones disponibles:**
|
||
|
||
| Operación | Uso |
|
||
|-----------|-----|
|
||
| `goToDefinition` | Navegar a definición de símbolo |
|
||
| `findReferences` | Encontrar todas las referencias |
|
||
| `hover` | Info de tipo y documentación |
|
||
| `documentSymbol` | Símbolos del archivo actual |
|
||
| `incomingCalls` | Qué funciones llaman a ésta |
|
||
|
||
**Documentación:** `teamdocs/INFRASTRUCTURE/ZLS_LSP_CLAUDE_CODE.md`
|
||
|
||
---
|
||
|
||
## DOCUMENTACIÓN EN TEAMDOCS
|
||
|
||
Al documentar trabajo en `teamdocs/agenda/`:
|
||
|
||
1. **Entrada en agenda:** Máximo 5 líneas (QUÉ + CUÁNDO + link)
|
||
2. **Detalle técnico:** Crear hito en `agenda/hitos/`
|
||
3. **Protocolo completo:** Ver `teamdocs/ESTRUCTURA_DOCUMENTACION.md`
|
||
|
||
### Formato de entrada:
|
||
```markdown
|
||
## Fecha - Título ✅
|
||
|
||
Resumen breve (1-2 frases). Resultado principal.
|
||
|
||
→ [Detalle técnico](hitos/YYYY-MM-DD_tema.md)
|
||
```
|
||
|
||
---
|
||
|
||
## INFORMACIÓN DEL PROYECTO
|
||
|
||
| Campo | Valor |
|
||
|-------|-------|
|
||
| **Nombre** | zcatgui |
|
||
| **Versión** | v0.28.0 |
|
||
| **Fecha inicio** | 2025-12-09 |
|
||
| **Estado** | ✅ COMPLETO - 38 widgets, ~36K LOC, 4 backends, WindowState, TTF funcional |
|
||
| **Lenguaje** | Zig 0.15.2 |
|
||
| **Paradigma** | Immediate Mode GUI |
|
||
| **Inspiración** | Gio (Go), microui (C), DVUI (Zig), Dear ImGui (C++) |
|
||
|
||
### Descripción
|
||
|
||
**zcatgui** es una librería GUI immediate-mode para Zig:
|
||
|
||
1. **Software Rendering por defecto** - Funciona en cualquier ordenador sin GPU
|
||
2. **Cross-platform** - Linux, Windows, macOS, Web (WASM), Android, iOS
|
||
3. **SSH compatible** - Funciona via X11 forwarding
|
||
4. **Sistema de Macros** - Grabación/reproducción de acciones
|
||
5. **Sin dependencias pesadas** - Solo SDL2 para desktop
|
||
|
||
### Filosofía
|
||
|
||
> "Máxima compatibilidad, mínimas dependencias, control total del usuario"
|
||
|
||
---
|
||
|
||
## RUTAS IMPORTANTES
|
||
|
||
```bash
|
||
# Este proyecto
|
||
/mnt/cello2/arno/re/recode/zig/zcatgui/
|
||
|
||
# Proyecto hermano (TUI)
|
||
/mnt/cello2/arno/re/recode/zig/zcatui/
|
||
|
||
# Proyecto de referencia (Fyne/Go)
|
||
/mnt/cello2/arno/re/recode/go/simifactu/
|
||
|
||
# Normas del equipo
|
||
/mnt/cello2/arno/re/recode/teamdocs/
|
||
|
||
# Compilador Zig 0.15.2
|
||
/mnt/cello2/arno/re/recode/zig/zig-0.15.2/zig-x86_64-linux-0.15.2/zig
|
||
```
|
||
|
||
---
|
||
|
||
## COMANDOS FRECUENTES
|
||
|
||
```bash
|
||
# Compilar (desktop)
|
||
zig build
|
||
|
||
# Tests
|
||
zig build test
|
||
|
||
# Ejemplos desktop
|
||
zig build hello
|
||
zig build widgets-demo
|
||
zig build table-demo
|
||
|
||
# WASM (navegador)
|
||
zig build wasm # Genera web/zcatgui-demo.wasm
|
||
cd web && python3 -m http.server # Servir en localhost:8000
|
||
|
||
# Android (requiere NDK)
|
||
zig build android # ARM64 para dispositivo
|
||
|
||
# iOS (requiere macOS + Xcode)
|
||
zig build ios # ARM64 para dispositivo
|
||
|
||
# Git
|
||
git status
|
||
git add -A && git commit -m "mensaje"
|
||
git push
|
||
```
|
||
|
||
---
|
||
|
||
## ARQUITECTURA
|
||
|
||
### Paradigma: Immediate Mode
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────────┐
|
||
│ while (running) { │
|
||
│ events = pollEvents(); // Input │
|
||
│ updateState(events); // TÚ manejas estado │
|
||
│ commands = drawUI(state); // Genera comandos │
|
||
│ render(commands); // Dibuja │
|
||
│ } │
|
||
└─────────────────────────────────────────────────────────────┘
|
||
```
|
||
|
||
### Capas de la Librería
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────────┐
|
||
│ Capa 4: Widgets (Table, Panel, Select, Modal, etc.) │
|
||
├─────────────────────────────────────────────────────────────┤
|
||
│ Capa 3: Sistema de Macros │
|
||
├─────────────────────────────────────────────────────────────┤
|
||
│ Capa 2: Core UI (Context, Layout, Style, Input, Commands) │
|
||
├─────────────────────────────────────────────────────────────┤
|
||
│ Capa 1: Rendering (Software Rasterizer, Framebuffer, Fonts)│
|
||
├─────────────────────────────────────────────────────────────┤
|
||
│ Capa 0: Backend (SDL2 - ventanas, eventos, display) │
|
||
└─────────────────────────────────────────────────────────────┘
|
||
```
|
||
|
||
→ Detalle completo: `docs/ARCHITECTURE.md`
|
||
|
||
---
|
||
|
||
## ESTRUCTURA DE ARCHIVOS
|
||
|
||
```
|
||
zcatgui/
|
||
├── src/
|
||
│ ├── zcatgui.zig # Entry point, re-exports
|
||
│ ├── core/ # Context, Layout, Style, Input, Command, etc.
|
||
│ ├── widgets/ # 37 widgets implementados
|
||
│ │ ├── autocomplete/ # Modular: state, types, filtering
|
||
│ │ ├── icon/ # Modular: types, drawing_helpers
|
||
│ │ ├── textarea/ # Modular: state, render, types
|
||
│ │ ├── progress/ # Modular: bar, circle, spinner
|
||
│ │ ├── table/ # Tabla simple
|
||
│ │ ├── advanced_table/ # Tabla avanzada con CRUD
|
||
│ │ ├── virtual_advanced_table/ # Tabla virtual con paginación
|
||
│ │ └── ... # Widgets simples (archivos individuales)
|
||
│ ├── render/ # Software renderer, fonts, animation, effects
|
||
│ ├── backend/ # SDL2, WASM, Android, iOS
|
||
│ ├── macro/ # MacroRecorder, MacroPlayer
|
||
│ └── utils/ # FrameArena, ObjectPool, Benchmark
|
||
├── examples/ # Demos: hello, widgets, table, wasm, android
|
||
├── web/ # WASM support
|
||
├── ios/ # iOS bridge (Objective-C)
|
||
├── docs/ # Documentación detallada
|
||
├── CLAUDE.md # Este archivo
|
||
├── REFERENCE.md # ⭐ Manual de referencia completo
|
||
└── CHANGELOG.md # Historial de versiones
|
||
```
|
||
|
||
---
|
||
|
||
## ESTADO ACTUAL (v0.28.0)
|
||
|
||
### Widgets (38 total)
|
||
|
||
| Categoría | Widgets |
|
||
|-----------|---------|
|
||
| **Básicos** | Label, Button, Checkbox, Radio, Slider, TextInput, NumberEntry |
|
||
| **Contenedores** | Panel, Split, Modal, Scroll, Tabs, Menu, **WindowState** |
|
||
| **Datos** | List, Table, Tree, ReorderableList, VirtualScroll |
|
||
| **Feedback** | Progress, Tooltip, Toast, Spinner |
|
||
| **Input avanzado** | AutoComplete, Select, TextArea, ColorPicker, DatePicker |
|
||
| **Especial** | Image, Icon, Canvas, Chart, RichText, **IdleCompanion** |
|
||
| **Navegación** | Breadcrumb, Focus, Badge/TagGroup |
|
||
|
||
### Backends (5 plataformas)
|
||
- **SDL2**: Desktop (Linux, Windows, macOS)
|
||
- **WASM**: Navegadores web (Canvas 2D)
|
||
- **Android**: ANativeActivity + ANativeWindow
|
||
- **iOS**: UIKit bridge (Objective-C)
|
||
|
||
### Core Systems
|
||
- Context (FrameArena, dirty rectangles, ID system, Ghost Drawing)
|
||
- Input (keyboard, mouse, touch, shortcuts, gestures)
|
||
- Rendering (software renderer, AA, effects, **Shadow Cache**)
|
||
- Animation (20+ easing functions, springs, **ColorTransition**)
|
||
- Themes (dark, light, high_contrast, nord, dracula)
|
||
- **WindowState** (Panel interface a nivel de librería)
|
||
|
||
### Métricas
|
||
- ~36,000 LOC en 85 archivos fuente
|
||
- 0 warnings, 0 memory leaks
|
||
- WASM: ~18KB compilado
|
||
- **Shadow Baking**: 4.2x más rápido en Debug
|
||
|
||
→ Detalle completo: `REFERENCE.md`
|
||
|
||
---
|
||
|
||
## HITOS RECIENTES
|
||
|
||
### WindowState + Panel Interface ✅ (2026-01-04)
|
||
Panel interface movido a nivel de librería para reutilización:
|
||
- **WindowState**: Contenedor de paneles con vtable
|
||
- **Panel**: Interface con draw, handleEvent, onFocus, onBlur
|
||
- Cualquier app puede usar sin reimplementar lógica de paneles
|
||
→ Archivo: `src/window.zig`
|
||
|
||
### Shadow Baking ✅ (2026-01-02)
|
||
Cache de sombras prerenderizadas - **4.2x más rápido** en Debug:
|
||
- Evita recalcular blur por frame
|
||
- ShadowCache con max 64 entries
|
||
- initWithCache() para habilitar
|
||
→ Archivo: `render/software.zig`
|
||
|
||
### Glyph Blitting Optimizado ✅ (2026-01-02)
|
||
Renderizado de texto hasta 3x más rápido:
|
||
- Early exit si fuera de clip
|
||
- Pre-cálculo región visible
|
||
- Fast path para alpha=255
|
||
→ Archivo: `render/ttf.zig`
|
||
|
||
### ColorTransition Epsilon Fix ✅ (2026-01-03)
|
||
Fix animaciones que no terminaban (loop infinito):
|
||
- lerpU8 truncaba incrementos <1 → nunca convergía
|
||
- Epsilon check ANTES del lerp para forzar snap
|
||
- Umbral <= 2 para margen de seguridad
|
||
→ Archivo: `render/animation.zig`
|
||
|
||
### SIMD fillRect ✅ (2026-01-03)
|
||
Relleno de rectángulos 8 píxeles por iteración:
|
||
- @Vector(8, u32) para batch writing
|
||
- Solo en hot paths (>50% tiempo en framebuffer)
|
||
→ Archivo: `render/framebuffer.zig`
|
||
|
||
### Ghost Drawing ✅ (2026-01-02)
|
||
Supresión de comandos sin romper input:
|
||
- `ctx.suppress_commands = true` → pushCommand ignora
|
||
- Widgets procesan input normalmente
|
||
- 36% menos tiempo de ejecución
|
||
→ Archivo: `core/context.zig`
|
||
|
||
### Liquid UI V2 ✅ (2025-12-30)
|
||
Transiciones de color suaves (500ms) con contraste mejorado.
|
||
→ Archivos: `render/animation.zig`, `core/style.zig`
|
||
|
||
### IdleCompanion Widget ✅ (2025-12-30)
|
||
Mascota animada (gatito) tras inactividad.
|
||
→ Archivo: `widgets/idle_companion.zig`
|
||
|
||
### AdvancedTable ✅ (2025-12-17)
|
||
Widget ~3,700 LOC con schema, CRUD, sorting, lookup, multi-select, search, validation.
|
||
→ Detalle: `docs/ADVANCED_TABLE_MERGE_PLAN.md`
|
||
|
||
---
|
||
|
||
## SISTEMA DE MACROS
|
||
|
||
Grabar y reproducir acciones del usuario con teclas raw (como Vim).
|
||
|
||
```zig
|
||
pub const MacroRecorder = struct {
|
||
pub fn start(self: *MacroRecorder) void;
|
||
pub fn stop(self: *MacroRecorder) []const KeyEvent;
|
||
pub fn record(self: *MacroRecorder, key: KeyEvent) void;
|
||
};
|
||
|
||
pub const MacroPlayer = struct {
|
||
pub fn play(events: []const KeyEvent, inject_fn: fn(KeyEvent) void) void;
|
||
};
|
||
```
|
||
|
||
→ Detalle: `src/macro/macro.zig`
|
||
|
||
---
|
||
|
||
## DECISIONES DE DISEÑO
|
||
|
||
| Decisión | Razón |
|
||
|----------|-------|
|
||
| Immediate Mode | Control total, sin threading hell, estado explícito |
|
||
| Software Rendering | Máxima compatibilidad (SSH, HP viejo, cualquier driver) |
|
||
| Macros con teclas raw | Simple como Vim, menos código = menos bugs |
|
||
| SDL2 backend | Cross-platform probado, fácil de usar |
|
||
| Bitmap + TTF fonts | Bitmap siempre funciona, TTF para flexibilidad |
|
||
|
||
→ Detalle: `docs/ARCHITECTURE.md`
|
||
|
||
---
|
||
|
||
## OPTIMIZACIONES DE RENDIMIENTO (2026-01-05)
|
||
|
||
### Optimizaciones Activas ✅
|
||
|
||
| # | Optimización | Archivo | Impacto |
|
||
|---|--------------|---------|---------|
|
||
| 1 | **Shadow Baking** | `render/software.zig` | 4.2x más rápido Debug |
|
||
| 2 | **Glyph Blitting** | `render/ttf.zig` | 3x más rápido texto |
|
||
| 3 | **SIMD fillRect** | `render/framebuffer.zig` | 8 pixels/iteración |
|
||
| 4 | **Turbo Píxeles** | `render/framebuffer.zig` | Sin bounds checks |
|
||
| 5 | **Fast Path α=255** | `render/ttf.zig` | Sin blend innecesario |
|
||
| 6 | **Ghost Drawing** | `core/context.zig` | 36% menos comandos |
|
||
| 7 | **ColorTransition ε** | `render/animation.zig` | Convergencia garantizada |
|
||
|
||
### Resultado Final
|
||
|
||
- **Debug mode:** 180ms → 43ms (4.2x mejora)
|
||
- **ReleaseSafe:** ~16.7ms = 60fps objetivo
|
||
- **CPU idle:** ~0% (waitEventTimeout)
|
||
- **Memory leaks:** 0 verificado
|
||
|
||
---
|
||
|
||
## NOTAS ZIG 0.15.2
|
||
|
||
```zig
|
||
// Sleep
|
||
std.Thread.sleep(ns) // NO std.time.sleep
|
||
|
||
// ArrayList - CAMBIÓ en 0.15
|
||
var list: std.ArrayListUnmanaged(T) = .{};
|
||
defer list.deinit(allocator);
|
||
try list.append(allocator, item); // allocator en cada operación
|
||
|
||
// stdout
|
||
const stdout = std.fs.File.stdout(); // NO std.io.getStdOut()
|
||
|
||
// build.zig.zon
|
||
.{
|
||
.fingerprint = 0x...,
|
||
.name = .proyecto, // enum literal, no string
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## PROYECTOS RELACIONADOS
|
||
|
||
| Proyecto | Ruta | Descripción |
|
||
|----------|------|-------------|
|
||
| **zcatttf** | `/mnt/cello2/arno/re/recode/zig/zcatttf/` | Librería TTF v1.0 (dependencia) |
|
||
| **zsimifactu** | `/mnt/cello2/arno/re/recode/zig/zsimifactu/` | App facturación (consumidor principal) |
|
||
| **zcatui** | `/mnt/cello2/arno/re/recode/zig/zcatui/` | TUI library (hermano) |
|
||
| **zcatp2p** | `/mnt/cello2/arno/re/recode/zig/zcatp2p/` | Librería P2P v1.0.0 |
|
||
| **simifactu** | `/mnt/cello2/arno/re/recode/go/simifactu/` | App referencia (Fyne/Go) |
|
||
|
||
---
|
||
|
||
## EQUIPO
|
||
|
||
- **Usuario (R.Eugenio)**: Desarrollador principal
|
||
- **Claude**: Asistente de programación (Claude Code / Opus 4.5)
|
||
|
||
---
|
||
|
||
## REFERENCIAS EXTERNAS
|
||
|
||
- [microui](https://github.com/rxi/microui) - Arquitectura mínima
|
||
- [DVUI](https://github.com/david-vanderson/dvui) - Zig GUI reference
|
||
- [Gio](https://gioui.org/) - Go immediate-mode
|
||
- [Dear ImGui](https://github.com/ocornut/imgui) - C++ reference
|