treemd 0.7.0

A markdown navigator with tree-based structural navigation and syntax highlighting
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Image utilities for TUI rendering.
//!
//! Provides non-blocking terminal image encoding, static image loading, and
//! memory-bounded streaming GIF compositing for inline rendering.

use std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::{Duration, Instant};

use image::Rgba;
use image::RgbaImage;
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui_image::protocol::StatefulProtocol;
use ratatui_image::{Resize, ResizeEncodeRender};

/// How often the event loop checks for completed image work while an encode is pending.
pub const IMAGE_WORK_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16);

struct ResizeJob {
    protocol: StatefulProtocol,
    resize: Resize,
    size: Size,
    protocol_id: u64,
    generation: u64,
}

pub(crate) struct ResizeResult {
    protocol: StatefulProtocol,
    protocol_id: u64,
    generation: u64,
    size: Size,
    error: Option<String>,
}

/// A single background worker shared by all images in an [`App`](crate::tui::App).
///
/// `ratatui-image` deliberately separates resize/encode from rendering because
/// graphics protocols can be expensive to prepare. Keeping one ordered worker
/// avoids both frame stalls and an unbounded thread per cached image.
pub(crate) struct ImageWorker {
    request_tx: mpsc::Sender<ResizeJob>,
    result_rx: mpsc::Receiver<ResizeResult>,
    pending: Arc<AtomicUsize>,
    next_protocol_id: AtomicU64,
}

impl ImageWorker {
    pub(crate) fn new() -> Self {
        let (request_tx, request_rx) = mpsc::channel::<ResizeJob>();
        let (result_tx, result_rx) = mpsc::channel::<ResizeResult>();
        let pending = Arc::new(AtomicUsize::new(0));

        let _ = thread::Builder::new()
            .name("treemd-image-resize".to_string())
            .spawn(move || {
                while let Ok(mut job) = request_rx.recv() {
                    let error = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        job.protocol.resize_encode(&job.resize, job.size);
                        job.protocol
                            .last_encoding_result()
                            .and_then(Result::err)
                            .map(|error| error.to_string())
                    }))
                    .unwrap_or_else(|_| Some("image encoder panicked".to_string()));
                    if result_tx
                        .send(ResizeResult {
                            protocol: job.protocol,
                            protocol_id: job.protocol_id,
                            generation: job.generation,
                            size: job.size,
                            error,
                        })
                        .is_err()
                    {
                        break;
                    }
                }
            });

        Self {
            request_tx,
            result_rx,
            pending,
            next_protocol_id: AtomicU64::new(1),
        }
    }

    pub(crate) fn wrap(&self, protocol: StatefulProtocol) -> AsyncProtocol {
        AsyncProtocol {
            inner: Some(protocol),
            fallback: None,
            request_tx: self.request_tx.clone(),
            pending: Arc::clone(&self.pending),
            protocol_id: self.next_protocol_id.fetch_add(1, Ordering::Relaxed),
            generation: 0,
            in_flight_generation: None,
            last_size: Size::default(),
            failed_size: None,
            has_completed_frame: false,
        }
    }

    pub(crate) fn drain(&self) -> Vec<ResizeResult> {
        let results: Vec<_> = self.result_rx.try_iter().collect();
        if !results.is_empty() {
            self.pending.fetch_sub(results.len(), Ordering::AcqRel);
        }
        results
    }

    pub(crate) fn has_pending(&self) -> bool {
        self.pending.load(Ordering::Acquire) > 0
    }
}

/// Non-blocking state for `ratatui_image::StatefulImage`.
///
/// Rendering submits resize/encode work and continues with the last completed
/// frame. A generation counter discards stale responses after a newer image or
/// terminal size supersedes them.
pub(crate) struct AsyncProtocol {
    inner: Option<StatefulProtocol>,
    /// Last successfully encoded frame, retained while its replacement is prepared.
    fallback: Option<StatefulProtocol>,
    request_tx: mpsc::Sender<ResizeJob>,
    pending: Arc<AtomicUsize>,
    protocol_id: u64,
    generation: u64,
    in_flight_generation: Option<u64>,
    last_size: Size,
    failed_size: Option<Size>,
    has_completed_frame: bool,
}

impl AsyncProtocol {
    pub(crate) fn size_for(&mut self, resize: Resize, available: Size) -> Size {
        if let Some(protocol) = self.inner.as_ref().or(self.fallback.as_ref()) {
            self.last_size = protocol.size_for(resize, available);
        }
        Size {
            width: self.last_size.width.min(available.width),
            height: self.last_size.height.min(available.height),
        }
    }

    pub(crate) fn replace_protocol(&mut self, protocol: StatefulProtocol) {
        // Keep the completed frame visible until the replacement has finished
        // resize/encode. This is especially important for animated images:
        // dropping it here produces a blank flash on every GIF frame.
        if let Some(previous) = self.inner.take() {
            self.fallback = Some(previous);
        }
        self.inner = Some(protocol);
        self.generation = self.generation.wrapping_add(1);
        self.last_size = Size::default();
        self.failed_size = None;
    }

    /// Whether resize/encode work is currently outstanding for this protocol.
    pub(crate) fn has_in_flight_work(&self) -> bool {
        self.in_flight_generation.is_some()
    }

    /// Whether at least one frame has completed encoding successfully.
    pub(crate) fn has_completed_frame(&self) -> bool {
        self.has_completed_frame
    }

    pub(crate) fn matches(&self, result: &ResizeResult) -> bool {
        self.protocol_id == result.protocol_id
    }

    pub(crate) fn update(&mut self, result: ResizeResult) -> Option<String> {
        if self.in_flight_generation == Some(result.generation) {
            self.in_flight_generation = None;
        }

        if self.generation == result.generation {
            if result.error.is_some() && self.fallback.is_some() {
                // Preserve the previously completed frame on an encode error.
                self.inner = None;
            } else {
                self.inner = Some(result.protocol);
            }
            self.failed_size = result.error.as_ref().map(|_| result.size);
            if result.error.is_none() {
                self.fallback = None;
                self.has_completed_frame = true;
            }
            result.error
        } else {
            None
        }
    }
}

impl ResizeEncodeRender for AsyncProtocol {
    fn needs_resize(&self, resize: &Resize, size: Size) -> Option<Size> {
        self.inner
            .as_ref()
            .and_then(|protocol| protocol.needs_resize(resize, size))
            .filter(|requested| Some(*requested) != self.failed_size)
    }

    fn resize_encode(&mut self, resize: &Resize, size: Size) {
        let Some(protocol) = self.inner.take() else {
            return;
        };

        self.generation = self.generation.wrapping_add(1);
        self.in_flight_generation = Some(self.generation);
        self.pending.fetch_add(1, Ordering::AcqRel);
        let job = ResizeJob {
            protocol,
            resize: resize.clone(),
            size,
            protocol_id: self.protocol_id,
            generation: self.generation,
        };

        if let Err(error) = self.request_tx.send(job) {
            self.pending.fetch_sub(1, Ordering::AcqRel);
            let mut job = error.0;
            job.protocol.resize_encode(&job.resize, job.size);
            let failed = job
                .protocol
                .last_encoding_result()
                .and_then(Result::err)
                .is_some();
            self.failed_size = failed.then_some(job.size);
            self.has_completed_frame |= !failed;
            self.in_flight_generation = None;
            self.inner = Some(job.protocol);
            if !failed {
                self.fallback = None;
            }
        }
    }

    fn render(&mut self, area: Rect, buffer: &mut Buffer) {
        if let Some(protocol) = self.inner.as_mut().or(self.fallback.as_mut()) {
            protocol.render(area, buffer);
        }
    }
}

/// Errors that can occur during image loading and caching
#[derive(Debug, Clone)]
pub enum ImageError {
    /// Image file not found
    NotFound,
    /// Invalid image format
    InvalidFormat(String),
}

impl std::fmt::Display for ImageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImageError::NotFound => write!(f, "Image not found"),
            ImageError::InvalidFormat(s) => write!(f, "Invalid format: {}", s),
        }
    }
}

impl std::error::Error for ImageError {}

/// Namespace for image loading static methods.
pub struct ImageCache;

/// GIF frame with timing information
#[derive(Clone)]
pub struct GifFrame {
    pub image: image::DynamicImage,
    /// Delay in milliseconds
    pub delay_ms: u32,
}

/// Result of advancing a streaming inline GIF.
pub(crate) enum GifAdvance {
    Waiting,
    Frame(image::DynamicImage),
    Finished,
    Failed(String),
}

/// A memory-bounded GIF player for inline images.
///
/// The modal viewer deliberately keeps every frame for random access. Inline
/// images only need forward playback, so retaining a compositing canvas and
/// decoder avoids expanding a long README recording into hundreds of full-size
/// RGBA frames.
pub(crate) struct StreamingGif {
    path: PathBuf,
    decoder: gif::Decoder<BufReader<File>>,
    canvas: RgbaImage,
    previous_disposal: gif::DisposalMethod,
    previous_rect: (u32, u32, u32, u32),
    restore_previous: Option<RgbaImage>,
    repeat: gif::Repeat,
    completed_repeats: u16,
    frames_in_first_pass: usize,
    current_delay: Duration,
    last_frame_update: Instant,
    active: bool,
}

impl StreamingGif {
    /// Open a GIF and return its composited first frame.
    pub(crate) fn open(path: &Path) -> Result<(Self, image::DynamicImage), ImageError> {
        let decoder = Self::open_decoder(path)?;
        let width = u32::from(decoder.width());
        let height = u32::from(decoder.height());
        let repeat = decoder.repeat();
        let mut animation = Self {
            path: path.to_path_buf(),
            decoder,
            canvas: RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0])),
            previous_disposal: gif::DisposalMethod::Keep,
            previous_rect: (0, 0, 0, 0),
            restore_previous: None,
            repeat,
            completed_repeats: 0,
            frames_in_first_pass: 0,
            current_delay: Duration::from_millis(20),
            last_frame_update: Instant::now(),
            active: false,
        };

        let Some((image, delay)) = animation.decode_next()? else {
            return Err(ImageError::InvalidFormat(
                "GIF contains no image frames".to_string(),
            ));
        };
        animation.frames_in_first_pass = 1;
        animation.current_delay = delay;
        Ok((animation, image))
    }

    fn open_decoder(path: &Path) -> Result<gif::Decoder<BufReader<File>>, ImageError> {
        let file = File::open(path).map_err(|_| ImageError::NotFound)?;
        let mut options = gif::DecodeOptions::new();
        options.set_color_output(gif::ColorOutput::RGBA);
        options
            .read_info(BufReader::new(file))
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))
    }

    fn reset_decoder(&mut self) -> Result<(), ImageError> {
        self.decoder = Self::open_decoder(&self.path)?;
        self.canvas = RgbaImage::from_pixel(
            u32::from(self.decoder.width()),
            u32::from(self.decoder.height()),
            Rgba([0, 0, 0, 0]),
        );
        self.previous_disposal = gif::DisposalMethod::Keep;
        self.previous_rect = (0, 0, 0, 0);
        self.restore_previous = None;
        Ok(())
    }

    fn decode_next(&mut self) -> Result<Option<(image::DynamicImage, Duration)>, ImageError> {
        match self.previous_disposal {
            gif::DisposalMethod::Background => {
                ImageCache::clear_gif_rect(&mut self.canvas, self.previous_rect);
            }
            gif::DisposalMethod::Previous => {
                if let Some(previous) = self.restore_previous.take() {
                    self.canvas = previous;
                }
            }
            gif::DisposalMethod::Any | gif::DisposalMethod::Keep => {}
        }

        let frame = self
            .decoder
            .read_next_frame()
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))?;
        let Some(frame) = frame else {
            return Ok(None);
        };

        let restore_for_this_frame =
            (frame.dispose == gif::DisposalMethod::Previous).then(|| self.canvas.clone());
        let width = self.canvas.width();
        let height = self.canvas.height();
        ImageCache::composite_gif_frame(&mut self.canvas, frame, width, height);

        let delay =
            Duration::from_millis(u64::from(frame.delay) * 10).max(Duration::from_millis(20));
        self.previous_disposal = frame.dispose;
        self.previous_rect = (
            frame.left.into(),
            frame.top.into(),
            frame.width.into(),
            frame.height.into(),
        );
        self.restore_previous = restore_for_this_frame;

        Ok(Some((
            image::DynamicImage::ImageRgba8(self.canvas.clone()),
            delay,
        )))
    }

    /// Start or stop playback without decoding a frame.
    ///
    /// GIFs are deliberately inactive when opened so the composited first frame
    /// remains a still. A viewer can explicitly activate the frame clock.
    pub(crate) fn set_active(&mut self, active: bool) {
        if active && !self.active {
            self.last_frame_update = Instant::now();
        }
        self.active = active;
    }

    pub(crate) fn time_until_next_frame(&self) -> Option<Duration> {
        if !self.active {
            return None;
        }
        Some(
            self.current_delay
                .saturating_sub(self.last_frame_update.elapsed())
                .max(Duration::from_millis(1)),
        )
    }

    pub(crate) fn advance(&mut self) -> GifAdvance {
        if !self.active || self.last_frame_update.elapsed() < self.current_delay {
            return GifAdvance::Waiting;
        }

        match self.decode_next() {
            Ok(Some((image, delay))) => {
                self.frames_in_first_pass = self.frames_in_first_pass.saturating_add(1);
                self.current_delay = delay;
                self.last_frame_update = Instant::now();
                GifAdvance::Frame(image)
            }
            Ok(None) if self.frames_in_first_pass <= 1 => GifAdvance::Finished,
            Ok(None) => {
                let should_repeat = match self.repeat {
                    gif::Repeat::Infinite => true,
                    gif::Repeat::Finite(repeats) => self.completed_repeats < repeats,
                };
                if !should_repeat {
                    return GifAdvance::Finished;
                }

                self.completed_repeats = self.completed_repeats.saturating_add(1);
                match self.reset_decoder().and_then(|()| self.decode_next()) {
                    Ok(Some((image, delay))) => {
                        self.current_delay = delay;
                        self.last_frame_update = Instant::now();
                        GifAdvance::Frame(image)
                    }
                    Ok(None) => GifAdvance::Finished,
                    Err(error) => GifAdvance::Failed(error.to_string()),
                }
            }
            Err(error) => GifAdvance::Failed(error.to_string()),
        }
    }
}

impl ImageCache {
    /// Composite a GIF frame onto a canvas, handling transparency
    fn composite_gif_frame(canvas: &mut RgbaImage, frame: &gif::Frame, width: u32, height: u32) {
        let frame_buffer = &frame.buffer;
        let frame_width = frame.width as u32;
        let frame_height = frame.height as u32;
        let left = frame.left as u32;
        let top = frame.top as u32;

        for y in 0..frame_height {
            for x in 0..frame_width {
                let src_idx = ((y * frame_width + x) * 4) as usize;
                if src_idx + 3 < frame_buffer.len() {
                    let pixel = Rgba([
                        frame_buffer[src_idx],
                        frame_buffer[src_idx + 1],
                        frame_buffer[src_idx + 2],
                        frame_buffer[src_idx + 3],
                    ]);

                    let canvas_x = left + x;
                    let canvas_y = top + y;

                    if canvas_x < width && canvas_y < height && pixel[3] > 0 {
                        canvas.put_pixel(canvas_x, canvas_y, pixel);
                    }
                }
            }
        }
    }

    /// Read GIF timing without retaining decoded RGBA canvases.
    ///
    /// The decoder reuses its frame buffer, so memory remains bounded even for
    /// long terminal recordings that a capable terminal will animate itself.
    pub fn extract_gif_frame_delays(path: &Path) -> Result<Vec<u32>, ImageError> {
        let file = File::open(path).map_err(|_| ImageError::NotFound)?;
        let mut options = gif::DecodeOptions::new();
        options.set_color_output(gif::ColorOutput::Indexed);
        let mut decoder = options
            .read_info(BufReader::new(file))
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))?;
        let mut delays = Vec::new();

        while let Some(frame) = decoder
            .read_next_frame()
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))?
        {
            delays.push((u32::from(frame.delay) * 10).max(20));
        }

        if delays.is_empty() {
            Err(ImageError::InvalidFormat(
                "GIF contains no image frames".to_string(),
            ))
        } else {
            Ok(delays)
        }
    }

    /// Decode one composited GIF frame with bounded memory.
    ///
    /// Used only for deliberate pause/step actions during terminal-native
    /// playback; normal playback never expands all frames into memory.
    pub fn extract_gif_frame(
        path: &Path,
        target_index: usize,
    ) -> Result<image::DynamicImage, ImageError> {
        let file = File::open(path).map_err(|_| ImageError::NotFound)?;
        let mut options = gif::DecodeOptions::new();
        options.set_color_output(gif::ColorOutput::RGBA);
        let mut decoder = options
            .read_info(BufReader::new(file))
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))?;
        let width = u32::from(decoder.width());
        let height = u32::from(decoder.height());
        let mut canvas = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0]));
        let mut previous_disposal = gif::DisposalMethod::Keep;
        let mut previous_rect = (0, 0, 0, 0);
        let mut restore_previous: Option<RgbaImage> = None;
        let mut index = 0;

        while let Some(frame) = decoder
            .read_next_frame()
            .map_err(|error| ImageError::InvalidFormat(error.to_string()))?
        {
            match previous_disposal {
                gif::DisposalMethod::Background => {
                    Self::clear_gif_rect(&mut canvas, previous_rect);
                }
                gif::DisposalMethod::Previous => {
                    if let Some(previous) = restore_previous.take() {
                        canvas = previous;
                    }
                }
                gif::DisposalMethod::Any | gif::DisposalMethod::Keep => {}
            }

            let restore_for_this_frame =
                (frame.dispose == gif::DisposalMethod::Previous).then(|| canvas.clone());
            Self::composite_gif_frame(&mut canvas, frame, width, height);
            if index == target_index {
                return Ok(image::DynamicImage::ImageRgba8(canvas));
            }

            previous_disposal = frame.dispose;
            previous_rect = (
                frame.left.into(),
                frame.top.into(),
                frame.width.into(),
                frame.height.into(),
            );
            restore_previous = restore_for_this_frame;
            index += 1;
        }

        Err(ImageError::InvalidFormat(format!(
            "GIF frame {target_index} is out of range"
        )))
    }

    fn clear_gif_rect(canvas: &mut RgbaImage, rect: (u32, u32, u32, u32)) {
        let (left, top, width, height) = rect;
        for y in top..top.saturating_add(height).min(canvas.height()) {
            for x in left..left.saturating_add(width).min(canvas.width()) {
                canvas.put_pixel(x, y, Rgba([0, 0, 0, 0]));
            }
        }
    }

    /// Extract all frames from a GIF file with timing information.
    ///
    /// Returns a vector of frames with their delays in milliseconds.
    /// For non-GIF images, returns a single frame with 0ms delay (static).
    /// Maintains a persistent canvas to properly handle GIF disposal methods.
    pub fn extract_all_frames(path: &Path) -> Result<Vec<GifFrame>, ImageError> {
        use std::fs::File;

        let file = File::open(path).map_err(|_| ImageError::NotFound)?;
        let reader = BufReader::new(file);

        let mut options = gif::DecodeOptions::new();
        options.set_color_output(gif::ColorOutput::RGBA);

        match options.read_info(reader) {
            Ok(mut decoder) => {
                let width = decoder.width() as u32;
                let height = decoder.height() as u32;
                let mut frames = Vec::new();

                // Persistent canvas for proper frame compositing
                let mut canvas = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0]));
                let mut previous_disposal = gif::DisposalMethod::Keep;
                let mut previous_rect = (0, 0, 0, 0);
                let mut restore_previous: Option<RgbaImage> = None;

                while let Ok(Some(frame)) = decoder.read_next_frame() {
                    // Disposal applies immediately before the following frame.
                    match previous_disposal {
                        gif::DisposalMethod::Background => {
                            Self::clear_gif_rect(&mut canvas, previous_rect);
                        }
                        gif::DisposalMethod::Previous => {
                            if let Some(previous) = restore_previous.take() {
                                canvas = previous;
                            }
                        }
                        gif::DisposalMethod::Any | gif::DisposalMethod::Keep => {}
                    }

                    let restore_for_this_frame =
                        (frame.dispose == gif::DisposalMethod::Previous).then(|| canvas.clone());

                    // Composite this frame onto the persistent canvas
                    Self::composite_gif_frame(&mut canvas, frame, width, height);

                    // Clone the current canvas state as this frame
                    let delay_ms = (frame.delay as u32) * 10;
                    frames.push(GifFrame {
                        image: image::DynamicImage::ImageRgba8(canvas.clone()),
                        delay_ms: delay_ms.max(20), // Min 20ms (50fps cap)
                    });

                    previous_disposal = frame.dispose;
                    previous_rect = (
                        frame.left.into(),
                        frame.top.into(),
                        frame.width.into(),
                        frame.height.into(),
                    );
                    restore_previous = restore_for_this_frame;
                }

                if frames.is_empty() {
                    Self::load_static_image(path)
                } else {
                    Ok(frames)
                }
            }
            Err(_) => Self::load_static_image(path),
        }
    }

    /// Load a static (non-GIF) image as a single frame
    fn load_static_image(path: &Path) -> Result<Vec<GifFrame>, ImageError> {
        image::ImageReader::open(path)
            .ok()
            .and_then(|r| r.with_guessed_format().ok())
            .and_then(|r| r.decode().ok())
            .map(|img| {
                vec![GifFrame {
                    image: img,
                    delay_ms: 0,
                }]
            })
            .ok_or_else(|| ImageError::InvalidFormat("Unsupported image format".to_string()))
    }

    /// Extract the first frame from an image file, properly handling GIFs.
    ///
    /// For regular images, returns the image as-is.
    /// For GIFs, extracts and composites the first frame with proper transparency.
    pub fn extract_first_frame(path: &Path) -> Result<image::DynamicImage, ImageError> {
        use std::fs::File;

        let file = File::open(path).map_err(|_| ImageError::NotFound)?;
        let reader = BufReader::new(file);

        let mut options = gif::DecodeOptions::new();
        options.set_color_output(gif::ColorOutput::RGBA);

        match options.read_info(reader) {
            Ok(mut decoder) => {
                let width = decoder.width() as u32;
                let height = decoder.height() as u32;

                if let Ok(Some(frame)) = decoder.read_next_frame() {
                    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0]));
                    Self::composite_gif_frame(&mut canvas, frame, width, height);
                    Ok(image::DynamicImage::ImageRgba8(canvas))
                } else {
                    image::ImageReader::open(path)
                        .ok()
                        .and_then(|r| r.with_guessed_format().ok())
                        .and_then(|r| r.decode().ok())
                        .ok_or_else(|| {
                            ImageError::InvalidFormat("Failed to decode image".to_string())
                        })
                }
            }
            Err(_) => image::ImageReader::open(path)
                .ok()
                .and_then(|r| r.with_guessed_format().ok())
                .and_then(|r| r.decode().ok())
                .ok_or_else(|| ImageError::InvalidFormat("Unsupported format".to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gif_frame_struct() {
        // GifFrame should store image and delay information
        let img = image::DynamicImage::new_rgba8(10, 10);
        let frame = GifFrame {
            image: img,
            delay_ms: 100,
        };
        assert_eq!(frame.delay_ms, 100);
    }

    #[test]
    fn clear_gif_rect_only_clears_disposal_region() {
        let opaque = Rgba([10, 20, 30, 255]);
        let mut canvas = RgbaImage::from_pixel(4, 4, opaque);

        ImageCache::clear_gif_rect(&mut canvas, (1, 1, 2, 2));

        assert_eq!(*canvas.get_pixel(0, 0), opaque);
        assert_eq!(*canvas.get_pixel(1, 1), Rgba([0, 0, 0, 0]));
        assert_eq!(*canvas.get_pixel(2, 2), Rgba([0, 0, 0, 0]));
        assert_eq!(*canvas.get_pixel(3, 3), opaque);
    }

    #[test]
    fn async_protocol_encodes_off_thread_and_reuses_completed_size() {
        let worker = ImageWorker::new();
        let picker = ratatui_image::picker::Picker::halfblocks();
        let image = image::DynamicImage::new_rgba8(8, 8);
        let mut protocol = worker.wrap(picker.new_resize_protocol(image));
        let resize = Resize::Scale(None);
        let size = Size::new(4, 3);

        let requested = protocol
            .needs_resize(&resize, size)
            .expect("new protocol needs encoding");
        protocol.resize_encode(&resize, requested);
        assert!(worker.has_pending());

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
        let result = loop {
            if let Some(result) = worker.drain().into_iter().next() {
                break result;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "image worker timed out"
            );
            std::thread::sleep(std::time::Duration::from_millis(1));
        };

        assert!(protocol.matches(&result));
        assert_eq!(protocol.update(result), None);
        assert!(!worker.has_pending());
        assert!(protocol.has_completed_frame());
        assert!(protocol.needs_resize(&resize, size).is_none());

        protocol.replace_protocol(picker.new_resize_protocol(image::DynamicImage::new_rgba8(8, 8)));
        assert!(
            protocol.fallback.is_some(),
            "the completed frame should remain available during replacement"
        );
        let requested = protocol
            .needs_resize(&resize, size)
            .expect("replacement needs encoding");
        protocol.resize_encode(&resize, requested);
        assert!(protocol.inner.is_none());
        assert!(protocol.fallback.is_some());
        assert!(protocol.has_in_flight_work());
    }

    #[test]
    fn streaming_gif_advances_and_loops_without_retaining_all_frames() {
        use std::borrow::Cow;

        let mut file = tempfile::NamedTempFile::new().expect("temporary gif");
        {
            let palette = [255, 0, 0, 0, 255, 0];
            let mut encoder =
                gif::Encoder::new(file.as_file_mut(), 2, 1, &palette).expect("gif encoder");
            encoder
                .set_repeat(gif::Repeat::Infinite)
                .expect("set repeat");

            let first = gif::Frame {
                width: 2,
                height: 1,
                delay: 2,
                buffer: Cow::Owned(vec![0, 0]),
                ..gif::Frame::default()
            };
            encoder.write_frame(&first).expect("first frame");

            let second = gif::Frame {
                width: 2,
                height: 1,
                delay: 2,
                buffer: Cow::Owned(vec![1, 1]),
                ..gif::Frame::default()
            };
            encoder.write_frame(&second).expect("second frame");
        }

        let (mut animation, first) = StreamingGif::open(file.path()).expect("streaming decoder");
        assert_eq!(first.to_rgba8().get_pixel(0, 0), &Rgba([255, 0, 0, 255]));

        animation.last_frame_update = Instant::now() - Duration::from_millis(21);
        assert!(animation.time_until_next_frame().is_none());
        assert!(matches!(animation.advance(), GifAdvance::Waiting));

        animation.set_active(true);
        animation.last_frame_update = Instant::now() - Duration::from_millis(21);
        let GifAdvance::Frame(second) = animation.advance() else {
            panic!("second frame should be due");
        };
        assert_eq!(second.to_rgba8().get_pixel(0, 0), &Rgba([0, 255, 0, 255]));

        animation.last_frame_update = Instant::now() - Duration::from_millis(21);
        let GifAdvance::Frame(looped) = animation.advance() else {
            panic!("infinite GIF should loop to its first frame");
        };
        assert_eq!(looped.to_rgba8().get_pixel(0, 0), &Rgba([255, 0, 0, 255]));

        animation.set_active(false);
        animation.last_frame_update = Instant::now() - Duration::from_millis(21);
        assert!(animation.time_until_next_frame().is_none());
        assert!(matches!(animation.advance(), GifAdvance::Waiting));
    }

    #[test]
    fn gif_metadata_and_random_frame_decode_are_memory_bounded() {
        use std::borrow::Cow;

        let mut file = tempfile::NamedTempFile::new().expect("temporary gif");
        {
            let palette = [255, 0, 0, 0, 255, 0];
            let mut encoder =
                gif::Encoder::new(file.as_file_mut(), 2, 1, &palette).expect("gif encoder");
            for (color, delay) in [(0, 2), (1, 7)] {
                let frame = gif::Frame {
                    width: 2,
                    height: 1,
                    delay,
                    buffer: Cow::Owned(vec![color, color]),
                    ..gif::Frame::default()
                };
                encoder.write_frame(&frame).expect("frame");
            }
        }

        assert_eq!(
            ImageCache::extract_gif_frame_delays(file.path()).unwrap(),
            vec![20, 70]
        );
        let second = ImageCache::extract_gif_frame(file.path(), 1).unwrap();
        assert_eq!(second.to_rgba8().get_pixel(0, 0), &Rgba([0, 255, 0, 255]));
    }
}