scrin-widgets 0.2.2

Scrin-native widgets and Aisling terminal effects for immersive TUIs.
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]

use std::borrow::Cow;

use scrin::{
    Color, Rect,
    core::buffer::{Buffer, Cell},
    style::{Modifier, Style},
    widgets::{
        Widget,
        block::{Block, BorderStyle},
    },
};

pub use scrin;

/// Common imports for apps that want the Scrin widget set plus Scrin.
pub mod prelude {
    pub use crate::{
        Aisling, AislingEffect, AislingExt, AislingPalette, FlickerPanel, GlyphRain, NebulaGauge,
        PulseRing, SignalPanel, WaveType, Waveform, scrin,
    };
    pub use scrin::widgets::Widget;
}

/// The default color system used by Aisling effects and bundled widgets.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AislingPalette {
    pub low: Color,
    pub mid: Color,
    pub high: Color,
    pub pulse: Color,
    pub shadow: Color,
}

impl AislingPalette {
    /// Cyan, violet, and amber tones intended for dark terminals.
    #[must_use]
    pub const fn dream() -> Self {
        Self {
            low: Color::rgb(58, 192, 255),
            mid: Color::rgb(176, 92, 255),
            high: Color::rgb(255, 219, 125),
            pulse: Color::rgb(255, 118, 205),
            shadow: Color::rgb(17, 18, 35),
        }
    }

    /// Green phosphor tones for surveillance or terminal-core screens.
    #[must_use]
    pub const fn phosphor() -> Self {
        Self {
            low: Color::rgb(61, 255, 142),
            mid: Color::rgb(19, 189, 112),
            high: Color::rgb(210, 255, 181),
            pulse: Color::rgb(135, 255, 221),
            shadow: Color::rgb(7, 22, 16),
        }
    }

    /// Hot magenta/orange tones for signal-heavy panels.
    #[must_use]
    pub const fn flare() -> Self {
        Self {
            low: Color::rgb(255, 107, 107),
            mid: Color::rgb(255, 168, 76),
            high: Color::rgb(255, 236, 153),
            pulse: Color::rgb(255, 75, 145),
            shadow: Color::rgb(35, 14, 24),
        }
    }

    fn lane(self, value: u64) -> Color {
        match value % 4 {
            0 => self.low,
            1 => self.mid,
            2 => self.high,
            _ => self.pulse,
        }
    }
}

impl Default for AislingPalette {
    fn default() -> Self {
        Self::dream()
    }
}

/// A composable post-render effect that can be applied to any Scrin buffer area.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AislingEffect {
    tick: u64,
    intensity: u16,
    palette: AislingPalette,
    shimmer: bool,
    scanlines: bool,
    glow: bool,
}

impl AislingEffect {
    /// Creates an animated effect for the given frame or time tick.
    #[must_use]
    pub fn new(tick: u64) -> Self {
        Self {
            tick,
            ..Self::default()
        }
    }

    /// Sets the frame or time tick used to animate the effect.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets the palette used by the effect.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Sets effect strength on a 0..=10 scale.
    #[must_use]
    pub fn intensity(mut self, intensity: u16) -> Self {
        self.intensity = intensity.min(10);
        self
    }

    /// Enables or disables moving foreground highlights.
    #[must_use]
    pub fn shimmer(mut self, enabled: bool) -> Self {
        self.shimmer = enabled;
        self
    }

    /// Enables or disables low-contrast background scanlines.
    #[must_use]
    pub fn scanlines(mut self, enabled: bool) -> Self {
        self.scanlines = enabled;
        self
    }

    /// Enables or disables border/edge pulses.
    #[must_use]
    pub fn glow(mut self, enabled: bool) -> Self {
        self.glow = enabled;
        self
    }

    /// Applies this effect directly to an already-rendered buffer area.
    pub fn apply(self, area: Rect, buf: &mut Buffer) {
        if is_empty(area) || self.intensity == 0 {
            return;
        }

        let right = area.x.saturating_add(area.width);
        let bottom = area.y.saturating_add(area.height);
        let edge_phase = self.tick / 2;
        let shimmer_gate = 11_u64.saturating_sub(u64::from(self.intensity.min(10)));

        for y in area.y..bottom {
            for x in area.x..right {
                if self.scanlines && (u64::from(y) + edge_phase).is_multiple_of(3) {
                    set_cell_bg(buf, x, y, self.palette.shadow);
                }

                if self.shimmer {
                    let phase = u64::from(x) * 3 + u64::from(y) * 5 + self.tick;
                    if phase % 11 >= shimmer_gate {
                        set_cell_style(
                            buf,
                            x,
                            y,
                            Style::default()
                                .fg(self.palette.lane(phase))
                                .add_modifier(Modifier::BOLD),
                        );
                    }
                }

                if self.glow
                    && is_edge(area, x, y)
                    && (u64::from(x) + u64::from(y) + edge_phase) % 5 == 0
                {
                    set_cell_style(
                        buf,
                        x,
                        y,
                        Style::default()
                            .fg(self.palette.pulse)
                            .add_modifier(Modifier::BOLD),
                    );
                }
            }
        }
    }
}

impl Default for AislingEffect {
    fn default() -> Self {
        Self {
            tick: 0,
            intensity: 5,
            palette: AislingPalette::default(),
            shimmer: true,
            scanlines: true,
            glow: true,
        }
    }
}

/// Wraps any Scrin widget with an Aisling post-render effect.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Aisling<W> {
    inner: W,
    effect: AislingEffect,
}

impl<W> Aisling<W> {
    /// Creates an effect wrapper around any Scrin widget.
    #[must_use]
    pub fn new(inner: W) -> Self {
        Self {
            inner,
            effect: AislingEffect::default(),
        }
    }

    /// Replaces the effect used by the wrapper.
    #[must_use]
    pub fn effect(mut self, effect: AislingEffect) -> Self {
        self.effect = effect;
        self
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.effect = self.effect.tick(tick);
        self
    }

    /// Sets the palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.effect = self.effect.palette(palette);
        self
    }

    /// Sets effect strength on a 0..=10 scale.
    #[must_use]
    pub fn intensity(mut self, intensity: u16) -> Self {
        self.effect = self.effect.intensity(intensity);
        self
    }
}

impl<W: Widget> Widget for Aisling<W> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        self.inner.render(buf, area);
        self.effect.apply(area, buf);
    }
}

/// Extension trait for calling `.aisling()` on any Scrin widget.
pub trait AislingExt: Widget + Sized {
    /// Decorates this widget with the default Aisling effect.
    #[must_use]
    fn aisling(self) -> Aisling<Self> {
        Aisling::new(self)
    }
}

impl<W: Widget> AislingExt for W {}

/// A deterministic matrix/rain field for ambient Scrin backgrounds.
#[derive(Clone, Debug)]
pub struct GlyphRain<'a> {
    tick: u64,
    density: u16,
    glyphs: Cow<'a, str>,
    palette: AislingPalette,
    block: Option<Block<'a>>,
}

impl PartialEq for GlyphRain<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.tick == other.tick
            && self.density == other.density
            && self.glyphs == other.glyphs
            && self.palette == other.palette
            && option_block_eq(self.block.as_ref(), other.block.as_ref())
    }
}

impl Eq for GlyphRain<'_> {}

impl<'a> GlyphRain<'a> {
    /// Creates a glyph rain widget for the given animation tick.
    #[must_use]
    pub fn new(tick: u64) -> Self {
        Self {
            tick,
            density: 34,
            glyphs: Cow::Borrowed("01#$*+<>[]{}"),
            palette: AislingPalette::phosphor(),
            block: None,
        }
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets density on a 0..=100 scale.
    #[must_use]
    pub fn density(mut self, density: u16) -> Self {
        self.density = density.min(100);
        self
    }

    /// Sets the glyph alphabet used by the rain field.
    #[must_use]
    pub fn glyphs(mut self, glyphs: impl Into<Cow<'a, str>>) -> Self {
        self.glyphs = glyphs.into();
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Adds a block around the field.
    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }
}

impl Widget for GlyphRain<'_> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        let inner = self
            .block
            .as_ref()
            .map_or(area, |block| block_content_area(block, area));
        if let Some(block) = &self.block {
            block.render(buf, area);
        }
        if is_empty(inner) || self.density == 0 {
            return;
        }

        let glyphs: Vec<char> = self.glyphs.chars().collect();
        if glyphs.is_empty() {
            return;
        }

        let right = inner.x.saturating_add(inner.width);
        let bottom = inner.y.saturating_add(inner.height);
        for y in inner.y..bottom {
            for x in inner.x..right {
                let noise = field_noise(x, y, self.tick);
                if noise % 100 >= u64::from(self.density) {
                    continue;
                }

                let glyph = glyphs[(noise as usize + usize::from(y)) % glyphs.len()];
                let head = (noise + self.tick) % 9 == 0;
                let style = if head {
                    Style::default()
                        .fg(self.palette.high)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(self.palette.lane(noise + self.tick))
                };

                set_styled_char(buf, x, y, glyph, style);
            }
        }
    }
}

/// A compact progress gauge with a flowing nebula fill.
#[derive(Clone, Debug)]
pub struct NebulaGauge<'a> {
    ratio: f64,
    tick: u64,
    label: Option<Cow<'a, str>>,
    palette: AislingPalette,
    block: Option<Block<'a>>,
}

impl PartialEq for NebulaGauge<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.ratio == other.ratio
            && self.tick == other.tick
            && self.label == other.label
            && self.palette == other.palette
            && option_block_eq(self.block.as_ref(), other.block.as_ref())
    }
}

impl<'a> NebulaGauge<'a> {
    /// Creates a gauge with a ratio clamped to 0.0..=1.0.
    #[must_use]
    pub fn new(ratio: f64) -> Self {
        Self {
            ratio: ratio.clamp(0.0, 1.0),
            tick: 0,
            label: None,
            palette: AislingPalette::dream(),
            block: None,
        }
    }

    /// Returns the clamped ratio.
    #[must_use]
    pub fn ratio(&self) -> f64 {
        self.ratio
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets the centered label.
    #[must_use]
    pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Adds a block around the gauge.
    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }
}

impl Widget for NebulaGauge<'_> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        let inner = self
            .block
            .as_ref()
            .map_or(area, |block| block_content_area(block, area));
        if let Some(block) = &self.block {
            block.render(buf, area);
        }
        if is_empty(inner) {
            return;
        }

        let right = inner.x.saturating_add(inner.width);
        let bottom = inner.y.saturating_add(inner.height);
        let filled = (f64::from(inner.width) * self.ratio).round() as u16;

        for y in inner.y..bottom {
            for x in inner.x..right {
                let offset = x.saturating_sub(inner.x);
                let flow = u64::from(offset) + u64::from(y) * 2 + self.tick;
                if offset < filled {
                    set_styled_char(
                        buf,
                        x,
                        y,
                        '',
                        Style::default()
                            .fg(self.palette.lane(flow))
                            .bg(self.palette.shadow)
                            .add_modifier(Modifier::BOLD),
                    );
                } else {
                    set_styled_char(buf, x, y, '', Style::default().fg(self.palette.shadow));
                }
            }
        }

        if let Some(label) = &self.label {
            let row = inner.y + inner.height / 2;
            let label_width = label.chars().count().min(usize::from(inner.width)) as u16;
            let start = inner.x + inner.width.saturating_sub(label_width) / 2;
            paint_text(
                Rect::new(start, row, label_width, 1),
                buf,
                label.as_ref(),
                Style::default()
                    .fg(self.palette.high)
                    .add_modifier(Modifier::BOLD),
            );
        }
    }
}

/// A bordered status panel with animated signal bars.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SignalPanel<'a> {
    title: Cow<'a, str>,
    lines: Vec<Cow<'a, str>>,
    tick: u64,
    palette: AislingPalette,
}

impl<'a> SignalPanel<'a> {
    /// Creates a signal panel with a title.
    #[must_use]
    pub fn new(title: impl Into<Cow<'a, str>>) -> Self {
        Self {
            title: title.into(),
            lines: Vec::new(),
            tick: 0,
            palette: AislingPalette::flare(),
        }
    }

    /// Adds one body line.
    #[must_use]
    pub fn line(mut self, line: impl Into<Cow<'a, str>>) -> Self {
        self.lines.push(line.into());
        self
    }

    /// Replaces all body lines.
    #[must_use]
    pub fn lines<I, S>(mut self, lines: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<Cow<'a, str>>,
    {
        self.lines = lines.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }
}

impl Widget for SignalPanel<'_> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        if is_empty(area) {
            return;
        }

        let block = Block::new(self.title.as_ref())
            .with_borders(BorderStyle::Plain)
            .with_border_color(self.palette.mid)
            .with_inner_margin(Rect::ZERO);
        let inner = block_content_area(&block, area);
        block.render(buf, area);
        if is_empty(inner) {
            return;
        }

        let bars_width = inner.width.min(12);
        let text_width = inner.width.saturating_sub(bars_width.saturating_add(1));
        let max_lines = usize::from(inner.height);

        for (index, line) in self.lines.iter().take(max_lines).enumerate() {
            paint_text(
                Rect::new(inner.x, inner.y + index as u16, text_width, 1),
                buf,
                line.as_ref(),
                Style::default().fg(self.palette.high),
            );
        }

        if bars_width == 0 {
            return;
        }

        let bars_x = inner.x + inner.width.saturating_sub(bars_width);
        for row in 0..inner.height {
            for column in 0..bars_width {
                let x = bars_x + column;
                let y = inner.y + row;
                let noise = field_noise(x, y, self.tick / 2);
                let active = (noise + self.tick + u64::from(column)) % 7 <= 3;
                let symbol = if active { '' } else { '·' };
                let style = if active {
                    Style::default()
                        .fg(self.palette.lane(noise))
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(self.palette.shadow)
                };
                set_styled_char(buf, x, y, symbol, style);
            }
        }
    }
}

/// A text panel with per-character flicker and glitch effects.
#[derive(Clone, Debug)]
pub struct FlickerPanel<'a> {
    text: Cow<'a, str>,
    tick: u64,
    intensity: u16,
    palette: AislingPalette,
    block: Option<Block<'a>>,
}

impl PartialEq for FlickerPanel<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
            && self.tick == other.tick
            && self.intensity == other.intensity
            && self.palette == other.palette
            && option_block_eq(self.block.as_ref(), other.block.as_ref())
    }
}

impl Eq for FlickerPanel<'_> {}

impl<'a> FlickerPanel<'a> {
    /// Creates a flicker panel with the given text.
    #[must_use]
    pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
        Self {
            text: text.into(),
            tick: 0,
            intensity: 5,
            palette: AislingPalette::dream(),
            block: None,
        }
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets glitch intensity on a 0..=10 scale (0 = no glitch).
    #[must_use]
    pub fn intensity(mut self, intensity: u16) -> Self {
        self.intensity = intensity.min(10);
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Adds a block around the panel.
    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }
}

impl Widget for FlickerPanel<'_> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        let inner = self
            .block
            .as_ref()
            .map_or(area, |block| block_content_area(block, area));
        if let Some(block) = &self.block {
            block.render(buf, area);
        }
        if is_empty(inner) || self.intensity == 0 {
            return;
        }

        let glitch_chars: Vec<char> = "░▒▓█▀▄▌▐│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬".chars().collect();
        let text_chars: Vec<char> = self.text.chars().collect();
        if text_chars.is_empty() {
            return;
        }

        let right = inner.x.saturating_add(inner.width);
        let bottom = inner.y.saturating_add(inner.height);
        for y in inner.y..bottom {
            for x in inner.x..right {
                let col = usize::from(x.saturating_sub(inner.x));
                let noise = field_noise(x, y, self.tick);
                let glitch_gate = 11_u64.saturating_sub(u64::from(self.intensity));

                let (ch, style) = if noise % 11 >= glitch_gate {
                    let g = glitch_chars[(noise as usize) % glitch_chars.len()];
                    (g, Style::default().fg(self.palette.pulse).add_modifier(Modifier::BOLD))
                } else if col < text_chars.len() {
                    let c = text_chars[col];
                    let flicker = (noise + self.tick) % 9 == 0;
                    let style = if flicker {
                        Style::default()
                            .fg(self.palette.high)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(self.palette.mid)
                    };
                    (c, style)
                } else {
                    (' ', Style::default())
                };
                set_styled_char(buf, x, y, ch, style);
            }
        }
    }
}

/// An animated oscilloscope / waveform display.
#[derive(Clone, Debug)]
pub struct Waveform<'a> {
    tick: u64,
    frequency: f64,
    amplitude: f64,
    wave_type: WaveType,
    palette: AislingPalette,
    block: Option<Block<'a>>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WaveType {
    Sine,
    Square,
    Sawtooth,
    Triangle,
}

impl PartialEq for Waveform<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.tick == other.tick
            && self.frequency == other.frequency
            && self.amplitude == other.amplitude
            && self.wave_type == other.wave_type
            && self.palette == other.palette
            && option_block_eq(self.block.as_ref(), other.block.as_ref())
    }
}

impl Eq for Waveform<'_> {}

impl<'a> Waveform<'a> {
    /// Creates a waveform with the given frequency and amplitude.
    #[must_use]
    pub fn new(frequency: f64, amplitude: f64) -> Self {
        Self {
            tick: 0,
            frequency,
            amplitude: amplitude.clamp(0.0, 1.0),
            wave_type: WaveType::Sine,
            palette: AislingPalette::phosphor(),
            block: None,
        }
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets the wave type.
    #[must_use]
    pub fn wave_type(mut self, wave_type: WaveType) -> Self {
        self.wave_type = wave_type;
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Adds a block around the waveform.
    #[must_use]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    fn sample(&self, phase: f64) -> f64 {
        let t = phase.fract();
        match self.wave_type {
            WaveType::Sine => (std::f64::consts::TAU * t).sin(),
            WaveType::Square => {
                if t < 0.5 {
                    1.0
                } else {
                    -1.0
                }
            }
            WaveType::Sawtooth => 2.0 * t - 1.0,
            WaveType::Triangle => {
                if t < 0.5 {
                    4.0 * t - 1.0
                } else {
                    3.0 - 4.0 * t
                }
            }
        }
    }
}

impl Widget for Waveform<'_> {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        let inner = self
            .block
            .as_ref()
            .map_or(area, |block| block_content_area(block, area));
        if let Some(block) = &self.block {
            block.render(buf, area);
        }
        if is_empty(inner) || inner.height < 3 {
            return;
        }

        let mid_y = inner.y + inner.height / 2;
        let half = (inner.height / 2) as f64;

        for col in 0..inner.width {
            let phase = f64::from(col) / f64::from(inner.width) * self.frequency
                + f64::from(self.tick as u32) * 0.05;
            let sample = self.sample(phase);
            let offset = (sample * self.amplitude * half).round() as i16;

            let y = mid_y as i16 + offset;
            if y >= inner.y as i16 && y < (inner.y + inner.height) as i16 {
                let noise = field_noise(inner.x + col, y as u16, self.tick);
                set_styled_char(
                    buf,
                    inner.x + col,
                    y as u16,
                    '',
                    Style::default()
                        .fg(self.palette.lane(noise))
                        .add_modifier(Modifier::BOLD),
                );
            }
        }
    }
}

/// An animated expanding concentric ring effect.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PulseRing {
    tick: u64,
    rings: u16,
    palette: AislingPalette,
}

impl PulseRing {
    /// Creates a pulse ring with the given number of concentric rings.
    #[must_use]
    pub fn new(rings: u16) -> Self {
        Self {
            tick: 0,
            rings: rings.max(1),
            palette: AislingPalette::dream(),
        }
    }

    /// Sets the animation tick.
    #[must_use]
    pub fn tick(mut self, tick: u64) -> Self {
        self.tick = tick;
        self
    }

    /// Sets the color palette.
    #[must_use]
    pub fn palette(mut self, palette: AislingPalette) -> Self {
        self.palette = palette;
        self
    }
}

impl Widget for PulseRing {
    fn render(&self, buf: &mut Buffer, area: Rect) {
        if is_empty(area) || self.rings == 0 {
            return;
        }

        let cx = area.x + area.width / 2;
        let cy = area.y + area.height / 2;
        let max_radius = (area.width.min(area.height) / 2) as f64;
        if max_radius < 1.0 {
            return;
        }

        let right = area.x.saturating_add(area.width);
        let bottom = area.y.saturating_add(area.height);

        for y in area.y..bottom {
            for x in area.x..right {
                let dx = x as f64 - cx as f64;
                let dy = y as f64 - cy as f64;
                let dist = (dx * dx + dy * dy).sqrt();

                for ring in 0..self.rings {
                    let ring_phase = (self.tick as f64 * 0.1 + ring as f64 * 3.0) % max_radius;
                    let diff = (dist - ring_phase).abs();
                    if diff < 1.5 {
                        let noise = field_noise(x, y, self.tick + ring as u64);
                        let style = if diff < 0.8 {
                            Style::default()
                                .fg(self.palette.high)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().fg(self.palette.lane(noise))
                        };
                        set_styled_char(buf, x, y, '', style);
                        break;
                    }
                }
            }
        }
    }
}

fn is_empty(area: Rect) -> bool {
    area.width == 0 || area.height == 0
}

fn block_content_area(block: &Block<'_>, area: Rect) -> Rect {
    match block.borders {
        BorderStyle::None => area,
        _ => Rect::new(
            area.x.saturating_add(1),
            area.y.saturating_add(1),
            area.width.saturating_sub(2),
            area.height.saturating_sub(2),
        ),
    }
}

fn option_block_eq(left: Option<&Block<'_>>, right: Option<&Block<'_>>) -> bool {
    match (left, right) {
        (Some(left), Some(right)) => block_eq(left, right),
        (None, None) => true,
        _ => false,
    }
}

fn block_eq(left: &Block<'_>, right: &Block<'_>) -> bool {
    left.title == right.title
        && left.title_right == right.title_right
        && left.borders == right.borders
        && left.border_color == right.border_color
        && left.bg == right.bg
        && left.style == right.style
        && left.inner_margin == right.inner_margin
}

fn is_edge(area: Rect, x: u16, y: u16) -> bool {
    x == area.x
        || y == area.y
        || x + 1 == area.x.saturating_add(area.width)
        || y + 1 == area.y.saturating_add(area.height)
}

fn field_noise(x: u16, y: u16, tick: u64) -> u64 {
    let mut value = u64::from(x).wrapping_mul(0x9e37_79b9_7f4a_7c15)
        ^ u64::from(y).wrapping_mul(0xbf58_476d_1ce4_e5b9)
        ^ tick.wrapping_mul(0x94d0_49bb_1331_11eb);
    value ^= value >> 30;
    value = value.wrapping_mul(0xbf58_476d_1ce4_e5b9);
    value ^= value >> 27;
    value = value.wrapping_mul(0x94d0_49bb_1331_11eb);
    value ^ (value >> 31)
}

fn paint_text(area: Rect, buf: &mut Buffer, text: &str, style: Style) {
    if is_empty(area) {
        return;
    }

    let right = area.x.saturating_add(area.width);
    for (offset, glyph) in text.chars().take(usize::from(area.width)).enumerate() {
        let x = area.x + offset as u16;
        if x >= right {
            break;
        }
        set_styled_char(buf, x, area.y, glyph, style);
    }
}

fn set_cell_bg(buf: &mut Buffer, x: u16, y: u16, bg: Color) {
    let Some(mut cell) = buf.get(usize::from(x), usize::from(y)).copied() else {
        return;
    };
    cell.bg = Some(bg);
    buf.set(usize::from(x), usize::from(y), cell);
}

fn set_cell_style(buf: &mut Buffer, x: u16, y: u16, style: Style) {
    let Some(cell) = buf.get(usize::from(x), usize::from(y)).copied() else {
        return;
    };
    buf.set(usize::from(x), usize::from(y), replace_style(cell, style));
}

fn set_styled_char(buf: &mut Buffer, x: u16, y: u16, ch: char, style: Style) {
    buf.set(
        usize::from(x),
        usize::from(y),
        replace_style(
            Cell::new(ch, style.fg.unwrap_or(Color::WHITE), style.bg),
            style,
        ),
    );
}

fn replace_style(mut cell: Cell, style: Style) -> Cell {
    cell.fg = style.fg.unwrap_or(Color::WHITE);
    cell.bg = style.bg;
    cell.bold = (style.bold || style.add_modifier.contains(Modifier::BOLD))
        && !style.sub_modifier.contains(Modifier::BOLD);
    cell.italic = (style.italic || style.add_modifier.contains(Modifier::ITALIC))
        && !style.sub_modifier.contains(Modifier::ITALIC);
    cell.underlined = (style.underlined || style.add_modifier.contains(Modifier::UNDERLINED))
        && !style.sub_modifier.contains(Modifier::UNDERLINED);
    cell
}

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

    #[test]
    fn gauge_ratio_is_clamped() {
        assert_eq!(NebulaGauge::new(1.5).ratio(), 1.0);
        assert_eq!(NebulaGauge::new(-1.0).ratio(), 0.0);
    }

    #[test]
    fn effect_can_be_applied_to_a_buffer() {
        let area = Rect::new(0, 0, 12, 4);
        let mut buf = Buffer::new(usize::from(area.width), usize::from(area.height));

        AislingEffect::new(8).intensity(7).apply(area, &mut buf);
    }

    #[test]
    fn flicker_panel_renders_without_panic() {
        let area = Rect::new(0, 0, 20, 3);
        let mut buf = Buffer::new(usize::from(area.width), usize::from(area.height));
        FlickerPanel::new("test").tick(5).intensity(3).render(&mut buf, area);
    }

    #[test]
    fn waveform_renders_without_panic() {
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::new(usize::from(area.width), usize::from(area.height));
        Waveform::new(4.0, 0.6).tick(12).render(&mut buf, area);
    }

    #[test]
    fn waveform_short_height_is_noop() {
        let area = Rect::new(0, 0, 20, 2);
        let mut buf = Buffer::new(usize::from(area.width), usize::from(area.height));
        Waveform::new(4.0, 0.6).render(&mut buf, area);
    }

    #[test]
    fn pulse_ring_renders_without_panic() {
        let area = Rect::new(0, 0, 30, 15);
        let mut buf = Buffer::new(usize::from(area.width), usize::from(area.height));
        PulseRing::new(3).tick(7).render(&mut buf, area);
    }

    #[test]
    fn pulse_ring_zero_area_is_noop() {
        let area = Rect::new(0, 0, 0, 0);
        let mut buf = Buffer::new(1, 1);
        PulseRing::new(5).render(&mut buf, area);
    }
}