chromacat 0.1.0

A versatile command-line tool for applying color gradients to text output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# ChromaCat: System Architecture & Technical Reference 🎨

> _Building a performant, extensible terminal colorizer_ ✨

## Table of Contents

1. [Introduction]#introduction
2. [System Overview]#system-overview
3. [Pattern System Architecture]#pattern-system-architecture
4. [Rendering Pipeline]#rendering-pipeline
5. [Theme System]#theme-system
6. [Terminal Integration]#terminal-integration
7. [Animation Framework]#animation-framework
8. [Performance Optimization]#performance-optimization
9. [Error Handling]#error-handling
10. [Testing Strategy]#testing-strategy
11. [Development Guide]#development-guide

## Introduction

ChromaCat represents a sophisticated approach to terminal colorization, blending high performance with artistic expression. This document details the architectural decisions, implementation strategies, and technical considerations that power ChromaCat's capabilities.

### Design Philosophy

Our architecture embraces three core principles:

1. **Performance**: Every component is optimized for minimal overhead and maximum efficiency
2. **Extensibility**: The system is designed for easy addition of new patterns and features
3. **Reliability**: Robust error handling and graceful degradation ensure stable operation

## System Overview

At its heart, ChromaCat operates through a pipeline of specialized components:

```mermaid
graph TD
    CLI[CLI Interface] --> InputHandler[Input Handler]
    CLI --> PatternEngine[Pattern Engine]
    CLI --> Renderer[Renderer]
    InputHandler --> RenderBuffer[Render Buffer]
    PatternEngine --> RenderBuffer
    ThemeSystem[Theme System] --> PatternEngine
    RenderBuffer --> Renderer
    Renderer --> Terminal[Terminal Output]

    subgraph "Pattern System"
        PatternEngine --> Patterns[Pattern Registry]
        PatternEngine --> Utils[Pattern Utils]
        Patterns --> Effects[Effect Implementations]
    end

    style CLI fill:#f9f,stroke:#333,stroke-width:2px
    style PatternEngine fill:#bbf,stroke:#333,stroke-width:2px
    style Renderer fill:#bfb,stroke:#333,stroke-width:2px
    style ThemeSystem fill:#fbb,stroke:#333,stroke-width:2px
```

### Core Components

The system is built around several key components, each with specific responsibilities:

```rust
pub struct ChromaCat {
    cli: Cli,
    engine: PatternEngine,
    renderer: Renderer,
    theme_system: ThemeSystem,
}
```

## Pattern System Architecture

The pattern system represents ChromaCat's artistic core, transforming mathematical expressions into stunning visual effects.

### Pattern Registry

The registry serves as the central orchestrator for all visual effects:

```rust
pub struct PatternRegistry {
    patterns: HashMap<String, PatternMetadata>,
}

pub struct PatternMetadata {
    id: &'static str,
    name: &'static str,
    description: &'static str,
    default_params: Arc<Box<dyn PatternParam + Send + Sync>>,
}
```

Pattern registration happens through a declarative macro system:

```rust
define_pattern_registry! {
    "horizontal" => {
        variant: Horizontal,
        params: HorizontalParams
    },
    "plasma" => {
        variant: Plasma,
        params: PlasmaParams
    },
    // Additional patterns...
}
```

### Pattern Implementation

Each pattern implements a trait that defines its behavior:

```rust
pub trait Pattern {
    fn generate(&self, x: f64, y: f64, time: f64, params: &PatternParams) -> f64;
    fn validate_params(&self, params: &str) -> Result<(), String>;
    fn default_params(&self) -> PatternParams;
}
```

For example, here's how the plasma pattern creates its psychedelic effect:

```rust
impl Pattern for PlasmaPattern {
    fn generate(&self, x: f64, y: f64, time: f64, params: &PlasmaParams) -> f64 {
        let time_sin = self.utils.fast_sin(time * PI);

        // Calculate primary wave components
        let wave1 = self.calculate_primary_wave(x, y, time_sin, params.frequency);
        let wave2 = self.calculate_secondary_wave(x, y, time_sin, params.scale);

        // Combine waves with complexity factor
        self.combine_waves(wave1, wave2, params.complexity)
    }
}
```

## Rendering Pipeline

The rendering system transforms pattern values into vibrant terminal output through several sophisticated stages.

### Double-Buffered Architecture

ChromaCat employs an advanced double-buffering strategy:

```rust
pub struct RenderBuffer {
    front: Vec<Vec<BufferCell>>,
    back: Vec<Vec<BufferCell>>,
    term_size: (u16, u16),
    line_info: Vec<(usize, usize)>,
}

#[derive(Debug, Clone, PartialEq)]
struct BufferCell {
    ch: char,
    color: Color,
    dirty: bool,
}
```

### Color Pipeline

The color transformation process follows a sophisticated pipeline:

```mermaid
graph LR
    A[Pattern Value] --> B[Gradient Mapping]
    B --> C[Color Space Conversion]
    C --> D[Terminal Color Codes]
    D --> E[ANSI Output]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#ddf,stroke:#333,stroke-width:2px
    style D fill:#fbb,stroke:#333,stroke-width:2px
    style E fill:#bfb,stroke:#333,stroke-width:2px
```

### Frame Generation

The animation system produces smooth transitions through careful timing:

```rust
impl Renderer {
    pub fn render_frame(&mut self, text: &str, delta: f64) -> Result<()> {
        // Calculate precise frame timing
        let frame_time = self.calculate_frame_time(delta);

        // Update pattern state
        self.engine.update(frame_time);

        // Update visible buffer region
        self.update_visible_region()?;

        // Render to terminal
        self.draw_frame()?;

        Ok(())
    }
}
```

## Theme System

ChromaCat's theme system provides rich color manipulation capabilities:

```rust
pub struct ThemeDefinition {
    name: String,
    desc: String,
    colors: Vec<ColorStop>,
    dist: Distribution,
    repeat: Repeat,
    speed: f32,
    ease: Easing,
}
```

### Color Distribution

Themes support various distribution patterns:

```mermaid
graph LR
    A[Even] --> B[Front-loaded]
    B --> C[Back-loaded]
    C --> D[Center-focused]
    D --> E[Alternating]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#ddf,stroke:#333,stroke-width:2px
    style D fill:#fbb,stroke:#333,stroke-width:2px
    style E fill:#bfb,stroke:#333,stroke-width:2px
```

### Gradient Generation

The gradient system creates smooth color transitions:

```rust
impl ThemeDefinition {
    pub fn create_gradient(&self) -> Result<Box<dyn Gradient + Send + Sync>> {
        let mut builder = GradientBuilder::new();

        // Configure color stops
        for color in &self.colors {
            builder.add_color(color.position, color.to_rgb());
        }

        // Apply distribution and easing
        builder.distribution(self.dist)
               .easing(self.ease)
               .build()
    }
}
```

## Terminal Integration

The terminal integration layer provides robust handling of terminal capabilities:

```rust
pub struct TerminalState {
    term_size: (u16, u16),
    colors_enabled: bool,
    alternate_screen: bool,
    raw_mode: bool,
    cursor_hidden: bool,
    is_tty: bool,
}
```

### Terminal Management

The system carefully manages terminal state:

```rust
impl TerminalState {
    pub fn setup(&mut self) -> Result<()> {
        // Enable raw mode if needed
        if !self.raw_mode {
            enable_raw_mode()?;
            self.raw_mode = true;
        }

        // Configure terminal state
        queue!(
            stdout(),
            EnterAlternateScreen,
            Hide,
            SetTitle("ChromaCat")
        )?;

        Ok(())
    }
}
```

## Animation Framework

The animation system provides smooth visual transitions:

```rust
pub struct AnimationConfig {
    fps: u32,
    cycle_duration: Duration,
    infinite: bool,
    smooth: bool,
    frame_metrics: FrameMetrics,
}
```

### Frame Timing

Precise frame timing ensures smooth animation:

```rust
impl Renderer {
    fn calculate_frame_time(&self, delta: f64) -> f64 {
        let target_duration = Duration::from_secs_f64(1.0 / self.config.fps as f64);
        let actual_duration = Duration::from_secs_f64(delta);

        if actual_duration < target_duration {
            thread::sleep(target_duration - actual_duration);
        }

        actual_duration.as_secs_f64()
    }
}
```

## Performance Optimization

ChromaCat employs several optimization strategies:

### Pattern Optimization

```rust
impl PatternUtils {
    #[inline(always)]
    pub fn fast_sin(&self, angle: f64) -> f64 {
        let normalized_angle = angle.rem_euclid(2.0 * PI);
        let index = ((normalized_angle * 180.0 / PI) as usize) % 360;
        self.sin_table[index]
    }
}
```

### Render Optimization

```rust
impl RenderBuffer {
    #[inline]
    fn update_region(&mut self, start: usize, end: usize) -> Result<()> {
        for y in start..end {
            if y >= self.back.len() { break; }
            for x in 0..self.term_size.0 as usize {
                let cell = &mut self.back[y][x];
                if cell.dirty {
                    self.update_cell(x, y)?;
                    cell.dirty = false;
                }
            }
        }
        Ok(())
    }
}
```

## Error Handling

ChromaCat implements a comprehensive error handling strategy:

```rust
pub enum ChromaCatError {
    IoError(io::Error),
    InvalidParameter { name: String, value: f64, min: f64, max: f64 },
    InvalidTheme(String),
    GradientError(String),
    PatternError { pattern: String, param: String, message: String },
    RenderError(String),
    TerminalError(String),
}
```

### Error Recovery

The system implements graceful degradation:

```rust
impl ChromaCat {
    fn handle_error(&mut self, error: ChromaCatError) -> Result<()> {
        match error {
            ChromaCatError::TerminalError(_) => self.terminal.try_recover()?,
            ChromaCatError::RenderError(_) => self.renderer.reset()?,
            _ => self.fallback_mode()?,
        }
        Ok(())
    }
}
```

## Testing Strategy

ChromaCat employs a comprehensive testing approach:

### Unit Testing

```rust
#[cfg(test)]
mod tests {
    #[test]
    fn test_pattern_generation() {
        let pattern = PlasmaPattern::new();
        let params = PlasmaParams::default();

        // Test pattern values
        let value = pattern.generate(0.5, 0.5, 0.0, &params);
        assert!((0.0..=1.0).contains(&value));
    }
}
```

### Integration Testing

```rust
#[test]
fn test_animation_pipeline() {
    let mut cat = ChromaCat::new(test_config());

    // Test full animation cycle
    for frame in 0..60 {
        assert!(cat.render_frame(frame as f64 / 60.0).is_ok());
    }
}
```

## Development Guide

### Getting Started

1. Clone the repository:

   ```bash
   git clone https://github.com/hyperb1iss/chromacat
   cd chromacat
   ```

2. Build the project:

   ```bash
   cargo build --release
   ```

3. Run tests:
   ```bash
   cargo test
   ```

### Contributing

When contributing to ChromaCat:

1. Follow the Rust style guide
2. Maintain test coverage
3. Document public APIs
4. Consider performance implications

## Conclusion

ChromaCat's architecture provides a robust foundation for terminal colorization while maintaining extensibility and performance. The modular design allows for easy addition of new patterns and features while ensuring maintainable code and reliable operation.

---

<div align="center">

For more information, visit our [GitHub repository](https://github.com/hyperb1iss/chromacat)

</div>