dotmax 0.1.7

High-performance terminal braille rendering for images, animations, and graphics
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Interactive Image Browser - Test UI for Image Rendering
//!
//! This example provides an interactive terminal UI for testing image rendering
//! with different settings and browsing through test images.
//!
//! # Controls
//!
//! - **Left/Right Arrow**: Previous/Next image
//! - **C**: Cycle color mode (Monochrome → Grayscale → `TrueColor`)
//! - **D**: Cycle dithering algorithm (Floyd-Steinberg → Bayer → Atkinson → None)
//! - **O**: Toggle threshold mode (Auto Otsu ↔ Manual)
//! - **+/-**: Increase/Decrease manual threshold by 10 (range: 0-255, only in Manual mode)
//! - **b/B**: Increase/Decrease brightness by 0.05 (lowercase = up, uppercase = down)
//! - **t/T**: Increase/Decrease contrast by 0.05 (lowercase = up, uppercase = down)
//! - **g/G**: Increase/Decrease gamma by 0.05 (lowercase = up, uppercase = down)
//! - **R**: Reset all adjustments to defaults
//! - **Q or Esc**: Quit

#![allow(
    clippy::uninlined_format_args,
    clippy::cast_lossless,
    clippy::unnecessary_wraps,
    clippy::needless_pass_by_ref_mut,
    clippy::missing_const_for_fn,
    clippy::items_after_statements,
    clippy::map_unwrap_or
)]
//!
//! # Usage
//!
//! ```bash
//! cargo run --example image_browser --features image,svg
//! ```

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use crossterm::terminal::{self, ClearType};
use crossterm::{cursor, execute};
use dotmax::image::{ColorMode, DitheringMethod, ImageRenderer};
use dotmax::TerminalRenderer;
use std::fs;
use std::io;
use std::path::PathBuf;
use std::time::{Duration, Instant};

/// Threshold mode selection for binary conversion
#[derive(Debug, Clone, Copy, Default)]
enum ThresholdMode {
    #[default]
    Auto, // Use Otsu automatic thresholding
    Manual(u8), // Use manual threshold value (0-255)
}

#[derive(Debug, Clone)]
struct RenderSettings {
    color_mode: ColorMode,
    dithering: DitheringMethod,
    brightness: f32,
    contrast: f32,
    gamma: f32,
    threshold_mode: ThresholdMode,
}

impl RenderSettings {
    fn new() -> Self {
        Self {
            color_mode: ColorMode::Monochrome,
            dithering: DitheringMethod::FloydSteinberg,
            brightness: 1.0,
            contrast: 1.0,
            gamma: 1.0,
            threshold_mode: ThresholdMode::default(),
        }
    }

    fn reset(&mut self) {
        *self = Self::new();
    }

    fn cycle_color_mode(&mut self) {
        self.color_mode = match self.color_mode {
            ColorMode::Monochrome => ColorMode::Grayscale,
            ColorMode::Grayscale => ColorMode::TrueColor,
            ColorMode::TrueColor => ColorMode::Monochrome,
        };
    }

    fn cycle_dithering(&mut self) {
        self.dithering = match self.dithering {
            DitheringMethod::FloydSteinberg => DitheringMethod::Bayer,
            DitheringMethod::Bayer => DitheringMethod::Atkinson,
            DitheringMethod::Atkinson => DitheringMethod::None,
            DitheringMethod::None => DitheringMethod::FloydSteinberg,
        };
    }

    fn adjust_brightness(&mut self, delta: f32) {
        self.brightness = (self.brightness + delta).clamp(0.0, 2.0);
        // Round to 2 decimal places for cleaner display
        self.brightness = (self.brightness * 100.0).round() / 100.0;
    }

    fn adjust_contrast(&mut self, delta: f32) {
        self.contrast = (self.contrast + delta).clamp(0.0, 2.0);
        // Round to 2 decimal places for cleaner display
        self.contrast = (self.contrast * 100.0).round() / 100.0;
    }

    fn adjust_gamma(&mut self, delta: f32) {
        self.gamma = (self.gamma + delta).clamp(0.1, 3.0);
        // Round to 2 decimal places for cleaner display
        self.gamma = (self.gamma * 100.0).round() / 100.0;
    }

    /// Toggle threshold mode between Auto (Otsu) and Manual
    /// When switching to Manual, initialize to 128 (mid-point) or preserve last manual value
    fn toggle_threshold_mode(&mut self) {
        self.threshold_mode = match self.threshold_mode {
            ThresholdMode::Auto => ThresholdMode::Manual(128), // Default to mid-point
            ThresholdMode::Manual(_) => ThresholdMode::Auto,
        };
    }

    /// Adjust manual threshold value by delta
    /// Only applies when in Manual mode; no-op if in Auto mode
    /// Value clamped to [0, 255] range
    fn adjust_threshold(&mut self, delta: i16) {
        if let ThresholdMode::Manual(ref mut val) = self.threshold_mode {
            // Clamp to valid u8 range [0, 255]
            // Cast is safe because clamp ensures result is in [0, 255]
            #[allow(clippy::cast_sign_loss)]
            let new_val = (*val as i16 + delta).clamp(0, 255) as u8;
            *val = new_val;
        }
        // If Auto mode, do nothing (user must toggle to Manual first)
    }

    fn display_string(&self) -> String {
        let threshold_str = match self.threshold_mode {
            ThresholdMode::Auto => "Auto (Otsu)".to_string(),
            ThresholdMode::Manual(val) => format!("Manual ({})", val),
        };
        format!(
            "Color: {:?} | Dither: {:?} | Threshold: {} | Brightness: {:.1} | Contrast: {:.1} | Gamma: {:.1}",
            self.color_mode, self.dithering, threshold_str, self.brightness, self.contrast, self.gamma
        )
    }
}

struct ImageBrowser {
    images: Vec<PathBuf>,
    current_index: usize,
    settings: RenderSettings,
    renderer: TerminalRenderer,
    last_resize_time: Option<Instant>,
    pending_resize: bool,
}

impl ImageBrowser {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let images = Self::discover_images()?;

        if images.is_empty() {
            return Err("No images found in tests/fixtures/images or tests/fixtures/svg".into());
        }

        Ok(Self {
            images,
            current_index: 0,
            settings: RenderSettings::new(),
            renderer: TerminalRenderer::new()?,
            last_resize_time: None,
            pending_resize: false,
        })
    }

    fn discover_images() -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
        let mut images = Vec::new();

        // Scan tests/fixtures/images directory
        let images_dir = PathBuf::from("tests/fixtures/images");
        if images_dir.exists() {
            Self::scan_directory(&images_dir, &mut images)?;
        }

        // Scan tests/fixtures/svg directory (if svg feature enabled)
        #[cfg(feature = "svg")]
        {
            let svg_dir = PathBuf::from("tests/fixtures/svg");
            if svg_dir.exists() {
                Self::scan_directory(&svg_dir, &mut images)?;
            }
        }

        // Filter out known test files that are intentionally corrupted
        images.retain(|path| {
            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            !filename.contains("corrupted") && !filename.contains("malformed")
        });

        images.sort();
        Ok(images)
    }

    fn scan_directory(
        dir: &PathBuf,
        images: &mut Vec<PathBuf>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() {
                if let Some(ext) = path.extension() {
                    let ext = ext.to_string_lossy().to_lowercase();
                    if matches!(
                        ext.as_str(),
                        "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "tiff" | "svg"
                    ) {
                        images.push(path);
                    }
                }
            }
        }
        Ok(())
    }

    fn current_image(&self) -> &PathBuf {
        &self.images[self.current_index]
    }

    fn next_image(&mut self) {
        self.current_index = (self.current_index + 1) % self.images.len();
    }

    fn prev_image(&mut self) {
        self.current_index = if self.current_index == 0 {
            self.images.len() - 1
        } else {
            self.current_index - 1
        };
    }

    fn render_current(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Clear screen
        execute!(
            io::stdout(),
            terminal::Clear(ClearType::All),
            cursor::MoveTo(0, 0)
        )?;

        let path = self.current_image().clone();
        let is_svg = path.extension().map(|e| e == "svg").unwrap_or(false);

        // Try to render image with current settings
        match self.try_render_image(is_svg) {
            Ok(grid) => {
                // Render to terminal
                self.renderer.render(&grid)?;
            }
            Err(e) => {
                // Display error message
                println!("\n\n");
                println!("╔════════════════════════════════════════════════════════════════════╗");
                println!("║                          ERROR LOADING IMAGE                       ║");
                println!("╠════════════════════════════════════════════════════════════════════╣");
                println!("║ Image: {:60} ║", path.display().to_string());
                println!("║ Error: {:60} ║", format!("{}", e));
                println!("╠════════════════════════════════════════════════════════════════════╣");
                println!("║ Press ← or → to try another image, or Q to quit                   ║");
                println!("╚════════════════════════════════════════════════════════════════════╝");
            }
        }

        // Display UI footer
        self.display_footer()?;

        // Flush output
        use std::io::Write;
        io::stdout().flush()?;

        Ok(())
    }

    fn try_render_image(
        &mut self,
        is_svg: bool,
    ) -> Result<dotmax::BrailleGrid, Box<dyn std::error::Error>> {
        let path = self.current_image();

        // Render image with current settings
        let mut builder = ImageRenderer::new()
            .dithering(self.settings.dithering)
            .color_mode(self.settings.color_mode);

        // Apply adjustments if not default
        if (self.settings.brightness - 1.0).abs() > 0.001 {
            builder = builder.brightness(self.settings.brightness)?;
        }
        if (self.settings.contrast - 1.0).abs() > 0.001 {
            builder = builder.contrast(self.settings.contrast)?;
        }
        if (self.settings.gamma - 1.0).abs() > 0.001 {
            builder = builder.gamma(self.settings.gamma)?;
        }

        // Apply manual threshold if in Manual mode
        // If Auto mode, do not call .threshold() to allow Otsu to execute
        builder = match self.settings.threshold_mode {
            ThresholdMode::Manual(value) => builder.threshold(value),
            ThresholdMode::Auto => builder, // Don't call .threshold(), use Otsu
        };

        // Load image (SVG or raster)
        #[cfg(feature = "svg")]
        let builder = if is_svg {
            let (width, height) = self.renderer.get_terminal_size()?;
            builder.load_svg_from_path(path, width as u32 * 2, height as u32 * 4)?
        } else {
            builder.load_from_path(path)?
        };

        #[cfg(not(feature = "svg"))]
        let builder = builder.load_from_path(path)?;

        let mut builder = builder.resize_to_terminal()?;
        let grid = builder.render()?;

        Ok(grid)
    }

    fn display_footer(&self) -> Result<(), Box<dyn std::error::Error>> {
        let (_width, height) = self.renderer.get_terminal_size()?;

        // Move cursor to bottom area (leave some space)
        if height > 10 {
            execute!(io::stdout(), cursor::MoveTo(0, height.saturating_sub(8)))?;
        } else {
            println!("\n");
        }

        // Display current image info
        println!(
            "\n┌─────────────────────────────────────────────────────────────────────────────┐"
        );
        println!(
            "│ Image: {}/{} - {}",
            self.current_index + 1,
            self.images.len(),
            self.current_image().display()
        );
        println!("{}", self.settings.display_string());
        println!("");
        println!("│ Controls: ← → (prev/next) | C (color) | D (dither) | R (reset) | Q (quit)");
        println!("│ Adjust:   b/B (+/- brightness) | t/T (+/- contrast) | g/G (+/- gamma)");
        println!("│ Threshold: O (toggle Otsu/Manual) | +/- (adjust manual threshold)");
        println!("└─────────────────────────────────────────────────────────────────────────────┘");

        Ok(())
    }

    fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Enable raw mode for key input
        terminal::enable_raw_mode()?;

        // Initial render
        self.render_current()?;

        // Debounce delay for resize events (milliseconds)
        const RESIZE_DEBOUNCE_MS: u64 = 150;

        loop {
            // Poll for events with timeout
            if event::poll(Duration::from_millis(50))? {
                match event::read()? {
                    // Handle terminal resize events - debounced re-render
                    Event::Resize(width, height) => {
                        tracing::info!("Terminal resized to {}x{}", width, height);
                        // Mark that a resize occurred and record the time
                        self.last_resize_time = Some(Instant::now());
                        self.pending_resize = true;
                        // Don't render immediately - wait for debounce
                    }
                    // Handle keyboard events
                    Event::Key(key) => {
                        match self.handle_key(key)? {
                            ControlFlow::Continue => {
                                self.render_current()?;
                            }
                            ControlFlow::Skip => {
                                // No render needed
                            }
                            ControlFlow::Quit => break,
                        }
                    }
                    // Ignore other events (mouse, focus, etc.)
                    _ => {}
                }
            }

            // Check if we have a pending resize that has stabilized
            if self.pending_resize {
                if let Some(last_resize) = self.last_resize_time {
                    if last_resize.elapsed() >= Duration::from_millis(RESIZE_DEBOUNCE_MS) {
                        // Resize has stabilized - render now
                        self.pending_resize = false;
                        self.last_resize_time = None;
                        self.render_current()?;
                    }
                }
            }
        }

        // Cleanup
        terminal::disable_raw_mode()?;
        execute!(
            io::stdout(),
            terminal::Clear(ClearType::All),
            cursor::MoveTo(0, 0)
        )?;
        println!("Image browser closed.");

        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent) -> Result<ControlFlow, Box<dyn std::error::Error>> {
        // Only process key press events, ignore release
        // On some systems, we get Press + Release, on others we might get Repeat
        // We want to ignore Release events specifically (skip re-render)
        if matches!(key.kind, KeyEventKind::Release) {
            return Ok(ControlFlow::Skip);
        }

        match key.code {
            // Navigation
            KeyCode::Left => {
                self.prev_image();
                Ok(ControlFlow::Continue)
            }
            KeyCode::Right => {
                self.next_image();
                Ok(ControlFlow::Continue)
            }

            // Settings - cycle through options
            KeyCode::Char('c' | 'C') => {
                self.settings.cycle_color_mode();
                Ok(ControlFlow::Continue)
            }
            KeyCode::Char('d' | 'D') => {
                self.settings.cycle_dithering();
                Ok(ControlFlow::Continue)
            }

            // Brightness (±0.05 for finer control)
            KeyCode::Char('b') => {
                self.settings.adjust_brightness(0.05);
                Ok(ControlFlow::Continue)
            }
            KeyCode::Char('B') => {
                self.settings.adjust_brightness(-0.05);
                Ok(ControlFlow::Continue)
            }

            // Contrast (±0.05 for finer control)
            KeyCode::Char('t') => {
                self.settings.adjust_contrast(0.05);
                Ok(ControlFlow::Continue)
            }
            KeyCode::Char('T') => {
                self.settings.adjust_contrast(-0.05);
                Ok(ControlFlow::Continue)
            }

            // Gamma (±0.05 for finer control)
            KeyCode::Char('g') => {
                self.settings.adjust_gamma(0.05);
                Ok(ControlFlow::Continue)
            }
            KeyCode::Char('G') => {
                self.settings.adjust_gamma(-0.05);
                Ok(ControlFlow::Continue)
            }

            // Threshold mode toggle (O = capital O)
            KeyCode::Char('o' | 'O') => {
                self.settings.toggle_threshold_mode();
                Ok(ControlFlow::Continue)
            }

            // Manual threshold adjustment (+ and -)
            KeyCode::Char('+') => {
                self.settings.adjust_threshold(10);
                Ok(ControlFlow::Continue)
            }
            KeyCode::Char('-') => {
                self.settings.adjust_threshold(-10);
                Ok(ControlFlow::Continue)
            }

            // Reset
            KeyCode::Char('r' | 'R') => {
                self.settings.reset();
                Ok(ControlFlow::Continue)
            }

            // Quit
            KeyCode::Char('q' | 'Q') | KeyCode::Esc => Ok(ControlFlow::Quit),

            // Unhandled keys - no re-render needed
            _ => Ok(ControlFlow::Skip),
        }
    }
}

enum ControlFlow {
    Continue, // Re-render needed
    Skip,     // No re-render needed
    Quit,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Interactive Image Browser ===");
    println!("Scanning for images in tests/fixtures/...");

    let mut browser = ImageBrowser::new()?;

    println!("Found {} images", browser.images.len());
    println!("Starting browser... (Press Q to quit)");

    std::thread::sleep(Duration::from_secs(1));

    browser.run()?;

    Ok(())
}