embedded-gui-studio 0.2.3

Cross-platform interactive GUI studio for embedded-gui KDL live preview & code generation
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
//! Embedded GUI Studio
//! Cross-platform interactive designer, live animation previewer, and Rust code generator for embedded-gui.

use core::f32::consts::PI;
use eframe::egui::{self, Color32, CornerRadius, FontId, Pos2, Rect, Stroke, StrokeKind, Vec2};
use embedded_gui_codegen::{
    GridTrackDef, ScreenDef, WidgetDef, generate_rust_code, parse_kdl_screen,
};

const SAMPLE_THERMOSTAT: &str = r#"screen id="Thermostat" width=320 height=240 theme="dark" {
    grid cols="1fr 1fr" rows="36px 1fr 48px" gap=6 padding=8 {
        status_bar id="status" time="14:32" col=0 row=0 col_span=2
        scale id="temp_gauge" mode="radial" min=15.0 max=35.0 value=22.5 major_ticks=4 col=0 row=1
        slider id="target_slider" min=10 max=40 value=23 col=1 row=1
        button id="btn_heat" text="Heat Mode" style="accent" col=0 row=2
        toggle id="power_switch" label="Power" checked=true col=1 row=2
    }
}
"#;

const SAMPLE_DASHBOARD: &str = r#"screen id="SensorDashboard" width=320 height=240 theme="dark" {
    grid cols="1fr 1fr" rows="32px 1fr 1fr" gap=4 padding=6 {
        label id="header" text="ENVIRONMENTAL TELEMETRY" style="bold" col=0 row=0 col_span=2
        panel id="pnl_temp" style="card" col=0 row=1
        panel id="pnl_hum" style="card" col=1 row=1
        progress id="battery" value=0.85 col=0 row=2
        button id="btn_sync" text="Sync Telemetry" col=1 row=2
    }
}
"#;

const SAMPLE_WAVEFORM: &str = r#"screen id="ScopeScreen" width=320 height=240 theme="dark" {
    grid cols="1fr 80px" rows="30px 1fr 40px" gap=4 padding=4 {
        label id="title" text="DSO-X 2-CHANNEL OSCILLOSCOPE" col=0 row=0 col_span=2
        plotter id="wave_view" mode="sine" col=0 row=1
        roller id="v_div" selected=1 col=1 row=1 {
            option "100mV"
            option "500mV"
            option "1V"
            option "5V"
        }
        button id="btn_run" text="RUN/STOP" style="accent" col=0 row=2
        button id="btn_single" text="SINGLE" col=1 row=2
    }
}
"#;

const SAMPLE_MOTION_KITCHEN_SINK: &str = r#"screen id="MotionShowcase" width=320 height=240 theme="dark" {
    grid cols="1fr 1fr" rows="32px 1fr 1fr" gap=6 padding=6 {
        status_bar id="clock" time="12:00" col=0 row=0 col_span=2
        plotter id="live_scope" mode="sine" col=0 row=1
        busy_wheel id="spinner" active=true col=1 row=1
        progress id="pulse_bar" value=0.5 col=0 row=2
        scale id="dyn_gauge" mode="radial" min=0.0 max=100.0 value=50.0 major_ticks=5 col=1 row=2
    }
}
"#;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StudioTab {
    VisualPreview,
    RustCodegen,
    AstHierarchy,
}

struct EmbeddedGuiStudio {
    kdl_source: String,
    parsed_screen: Result<ScreenDef, String>,
    generated_rust: String,
    active_tab: StudioTab,
    preview_zoom: f32,
    copied_toast_timer: f32,

    // Animation playback state
    is_playing: bool,
    timeline_time: f32,
    playback_speed: f32,
    loop_duration: f32,
}

impl Default for EmbeddedGuiStudio {
    fn default() -> Self {
        let mut app = Self {
            kdl_source: SAMPLE_WAVEFORM.to_string(),
            parsed_screen: Err("Not parsed".to_string()),
            generated_rust: String::new(),
            active_tab: StudioTab::VisualPreview,
            preview_zoom: 1.5,
            copied_toast_timer: 0.0,
            is_playing: true,
            timeline_time: 0.0,
            playback_speed: 1.0,
            loop_duration: 4.0,
        };
        app.recompile();
        app
    }
}

impl EmbeddedGuiStudio {
    fn recompile(&mut self) {
        match parse_kdl_screen(&self.kdl_source) {
            Ok(screen) => {
                self.generated_rust = generate_rust_code(&screen);
                self.parsed_screen = Ok(screen);
            }
            Err(err) => {
                self.parsed_screen = Err(err.to_string());
            }
        }
    }

    fn render_visual_preview(&mut self, ui: &mut egui::Ui, screen: &ScreenDef) {
        // Toolbar: Zoom & Playback Controls
        ui.horizontal(|ui| {
            ui.label(format!(
                "Screen: {} ({}×{} px)",
                screen.id, screen.width, screen.height
            ));
            ui.separator();

            // Zoom controls
            ui.label("Zoom:");
            ui.selectable_value(&mut self.preview_zoom, 1.0, "1x");
            ui.selectable_value(&mut self.preview_zoom, 1.5, "1.5x");
            ui.selectable_value(&mut self.preview_zoom, 2.0, "2x");

            ui.separator();

            // Animation Play/Pause
            let play_label = if self.is_playing {
                "⏸ Pause"
            } else {
                "▶ Play"
            };
            if ui.button(play_label).clicked() {
                self.is_playing = !self.is_playing;
            }

            if ui.button("↺ Reset").clicked() {
                self.timeline_time = 0.0;
            }

            // Time Scrubber
            ui.label("Time:");
            ui.add(
                egui::Slider::new(&mut self.timeline_time, 0.0..=self.loop_duration)
                    .show_value(true)
                    .custom_formatter(|n, _| format!("{:.2}s", n)),
            );

            // Speed dropdown/buttons
            ui.label("Speed:");
            ui.selectable_value(&mut self.playback_speed, 0.5, "0.5x");
            ui.selectable_value(&mut self.playback_speed, 1.0, "1.0x");
            ui.selectable_value(&mut self.playback_speed, 2.0, "2.0x");
        });
        ui.separator();

        let screen_w = screen.width as f32 * self.preview_zoom;
        let screen_h = screen.height as f32 * self.preview_zoom;

        egui::ScrollArea::both().show(ui, |ui| {
            let (response, painter) = ui.allocate_painter(
                Vec2::new(screen_w + 32.0, screen_h + 32.0),
                egui::Sense::hover(),
            );
            let origin = response.rect.min + Vec2::new(16.0, 16.0);
            let display_rect = Rect::from_min_size(origin, Vec2::new(screen_w, screen_h));

            // Bezel / Hardware Chassis
            let bezel_rect = display_rect.expand(6.0);
            painter.rect_filled(
                bezel_rect,
                CornerRadius::same(8),
                Color32::from_rgb(30, 32, 38),
            );
            painter.rect_stroke(
                bezel_rect,
                CornerRadius::same(8),
                Stroke::new(2.0f32, Color32::from_rgb(70, 75, 85)),
                StrokeKind::Outside,
            );

            // Display LCD background
            painter.rect_filled(
                display_rect,
                CornerRadius::same(2),
                Color32::from_rgb(18, 20, 24),
            );

            // Compute grid layout pixel bounds
            let pad = (screen.grid.padding as f32) * self.preview_zoom;
            let gap = (screen.grid.gap as f32) * self.preview_zoom;
            let inner_rect = display_rect.shrink(pad);

            let cols = &screen.grid.cols;
            let rows = &screen.grid.rows;
            let col_widths = compute_track_sizes(cols, inner_rect.width(), gap);
            let row_heights = compute_track_sizes(rows, inner_rect.height(), gap);

            // Calculate track starting offsets
            let mut col_xs = Vec::with_capacity(col_widths.len());
            let mut cur_x = inner_rect.min.x;
            for w in &col_widths {
                col_xs.push(cur_x);
                cur_x += *w + gap;
            }

            let mut row_ys = Vec::with_capacity(row_heights.len());
            let mut cur_y = inner_rect.min.y;
            for h in &row_heights {
                row_ys.push(cur_y);
                cur_y += *h + gap;
            }

            let t = self.timeline_time;

            // Draw each widget with live animation time passed in
            for (placement, widget) in &screen.grid.children {
                let c = placement.col.min(col_xs.len().saturating_sub(1));
                let r = placement.row.min(row_ys.len().saturating_sub(1));
                let c_span = placement.col_span.max(1);
                let r_span = placement.row_span.max(1);

                let x0 = col_xs.get(c).copied().unwrap_or(inner_rect.min.x);
                let y0 = row_ys.get(r).copied().unwrap_or(inner_rect.min.y);

                let mut w = 0.0;
                for i in 0..c_span {
                    if let Some(cw) = col_widths.get(c + i) {
                        w += *cw;
                        if i + 1 < c_span {
                            w += gap;
                        }
                    }
                }

                let mut h = 0.0;
                for i in 0..r_span {
                    if let Some(rh) = row_heights.get(r + i) {
                        h += *rh;
                        if i + 1 < r_span {
                            h += gap;
                        }
                    }
                }

                let widget_rect = Rect::from_min_size(Pos2::new(x0, y0), Vec2::new(w, h));
                draw_animated_widget(&painter, widget_rect, widget, t);
            }
        });
    }
}

fn compute_track_sizes(tracks: &[GridTrackDef], available_size: f32, gap: f32) -> Vec<f32> {
    let n = tracks.len();
    if n == 0 {
        return vec![available_size];
    }
    let total_gap = gap * (n.saturating_sub(1) as f32);
    let net_space = (available_size - total_gap).max(0.0);

    let mut fixed_sum = 0.0;
    let mut total_fr = 0u32;

    for t in tracks {
        match t {
            GridTrackDef::Px(px) => fixed_sum += *px as f32,
            GridTrackDef::Fr(fr) => total_fr += *fr as u32,
            GridTrackDef::Auto => fixed_sum += 32.0,
        }
    }

    let remaining = (net_space - fixed_sum).max(0.0);
    let fr_unit = if total_fr > 0 {
        remaining / (total_fr as f32)
    } else {
        0.0
    };

    tracks
        .iter()
        .map(|t| match t {
            GridTrackDef::Px(px) => *px as f32,
            GridTrackDef::Fr(fr) => (*fr as f32) * fr_unit,
            GridTrackDef::Auto => 32.0,
        })
        .collect()
}

fn draw_animated_widget(painter: &egui::Painter, rect: Rect, widget: &WidgetDef, time: f32) {
    match widget {
        WidgetDef::Label { text, .. } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(26, 28, 34));
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                text,
                FontId::proportional(12.0),
                Color32::from_rgb(220, 225, 235),
            );
        }
        WidgetDef::Button { text, style, .. } => {
            let bg = if style.as_deref() == Some("accent") {
                Color32::from_rgb(45, 110, 220)
            } else {
                Color32::from_rgb(50, 56, 68)
            };
            painter.rect_filled(rect, CornerRadius::same(4), bg);
            painter.rect_stroke(
                rect,
                CornerRadius::same(4),
                Stroke::new(1.0f32, Color32::from_rgb(90, 100, 120)),
                StrokeKind::Inside,
            );
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                format!("🔘 {}", text),
                FontId::proportional(12.0),
                Color32::WHITE,
            );
        }
        WidgetDef::Toggle { label, checked, .. } => {
            painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgb(32, 35, 42));
            let check_icon = if *checked { " [ON]" } else { " [OFF]" };
            let text_color = if *checked {
                Color32::from_rgb(80, 220, 120)
            } else {
                Color32::from_rgb(160, 165, 175)
            };
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                format!("⏻ {}{}", label, check_icon),
                FontId::proportional(11.0),
                text_color,
            );
        }
        WidgetDef::Checkbox { label, checked, .. } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(30, 33, 40));
            let mark = if *checked { "☑" } else { "☐" };
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                format!("{} {}", mark, label),
                FontId::proportional(11.0),
                Color32::from_rgb(200, 205, 215),
            );
        }
        WidgetDef::Slider {
            min, max, value, ..
        } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(28, 30, 36));
            let pct = if max > min {
                ((*value - *min) as f32 / (*max - *min) as f32).clamp(0.0, 1.0)
            } else {
                0.5
            };
            let track_h = 6.0;
            let track_y = rect.center().y - track_h / 2.0;
            let track_rect = Rect::from_min_size(
                Pos2::new(rect.min.x + 8.0, track_y),
                Vec2::new(rect.width() - 16.0, track_h),
            );
            painter.rect_filled(
                track_rect,
                CornerRadius::same(3),
                Color32::from_rgb(50, 55, 65),
            );

            let fill_w = track_rect.width() * pct;
            let fill_rect = Rect::from_min_size(track_rect.min, Vec2::new(fill_w, track_h));
            painter.rect_filled(
                fill_rect,
                CornerRadius::same(3),
                Color32::from_rgb(60, 140, 240),
            );

            painter.text(
                Pos2::new(rect.center().x, rect.min.y + 7.0),
                egui::Align2::CENTER_CENTER,
                format!("Slider: {}", value),
                FontId::proportional(10.0),
                Color32::from_rgb(180, 185, 195),
            );
        }
        WidgetDef::ProgressBar { value, .. } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(24, 26, 32));
            let track_rect = rect.shrink2(Vec2::new(6.0, 6.0));
            painter.rect_filled(
                track_rect,
                CornerRadius::same(3),
                Color32::from_rgb(45, 50, 60),
            );

            // Dynamic oscillating progress pulse if animated
            let animated_val = if *value > 0.0 {
                *value
            } else {
                0.5 + 0.45 * (time * 2.0).sin()
            };
            let fill_w = track_rect.width() * animated_val.clamp(0.0, 1.0);
            let fill_rect =
                Rect::from_min_size(track_rect.min, Vec2::new(fill_w, track_rect.height()));
            painter.rect_filled(
                fill_rect,
                CornerRadius::same(3),
                Color32::from_rgb(40, 180, 120),
            );
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                format!("{:.0}%", animated_val * 100.0),
                FontId::proportional(11.0),
                Color32::WHITE,
            );
        }
        WidgetDef::Scale {
            mode,
            min,
            max,
            value,
            ..
        } => {
            painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgb(26, 30, 38));
            painter.rect_stroke(
                rect,
                CornerRadius::same(4),
                Stroke::new(1.0f32, Color32::from_rgb(60, 70, 85)),
                StrokeKind::Inside,
            );

            // Dynamic oscillating gauge needle
            let dynamic_val = *value + ((*max - *min) * 0.2 * (time * 1.8).sin());
            let clamped_val = dynamic_val.clamp(*min, *max);

            painter.text(
                Pos2::new(rect.center().x, rect.center().y - 8.0),
                egui::Align2::CENTER_CENTER,
                format!("⏱ Scale ({})", mode),
                FontId::proportional(11.0),
                Color32::from_rgb(140, 180, 240),
            );
            painter.text(
                Pos2::new(rect.center().x, rect.center().y + 8.0),
                egui::Align2::CENTER_CENTER,
                format!("{:.1} [{:.0}..{:.0}]", clamped_val, min, max),
                FontId::proportional(12.0),
                Color32::from_rgb(230, 235, 245),
            );
        }
        WidgetDef::BusyWheel { active, .. } => {
            painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgb(20, 24, 32));
            painter.rect_stroke(
                rect,
                CornerRadius::same(4),
                Stroke::new(1.0f32, Color32::from_rgb(45, 52, 68)),
                StrokeKind::Inside,
            );

            let center = rect.center();
            let radius = (rect.width().min(rect.height()) / 2.0 - 8.0).max(6.0);
            let num_dots = 8;
            let rotation_offset = if *active { time * 5.0 } else { 0.0 };

            for i in 0..num_dots {
                let angle = rotation_offset + (i as f32 * 2.0 * PI / num_dots as f32);
                let dot_pos = center + Vec2::new(angle.cos() * radius, angle.sin() * radius);
                let alpha = (i as f32 + 1.0) / (num_dots as f32);
                let dot_radius = 2.0 + alpha * 2.0;
                let color = Color32::from_rgba_unmultiplied(60, 160, 255, (alpha * 255.0) as u8);
                painter.circle_filled(dot_pos, dot_radius, color);
            }

            painter.text(
                Pos2::new(center.x, rect.max.y - 8.0),
                egui::Align2::CENTER_CENTER,
                "Busy Spinner",
                FontId::proportional(9.0),
                Color32::from_rgb(140, 150, 165),
            );
        }
        WidgetDef::SweepingArc {
            start_angle,
            end_angle,
            ..
        } => {
            painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgb(20, 24, 32));
            let center = rect.center();
            let radius = (rect.width().min(rect.height()) / 2.0 - 10.0).max(8.0);

            // Dynamic sweep pulse
            let pulse = (time * 2.5).sin() * 0.5 + 0.5;
            let sweep_end = *start_angle as f32 + (*end_angle - *start_angle) as f32 * pulse;

            painter.circle_stroke(
                center,
                radius,
                Stroke::new(2.0f32, Color32::from_rgb(50, 60, 75)),
            );

            // Draw arc sample dots
            let mut a = *start_angle as f32;
            while a <= sweep_end {
                let rad = a.to_radians();
                let p = center + Vec2::new(rad.cos() * radius, rad.sin() * radius);
                painter.circle_filled(p, 2.5, Color32::from_rgb(80, 200, 255));
                a += 15.0;
            }

            painter.text(
                Pos2::new(center.x, center.y),
                egui::Align2::CENTER_CENTER,
                format!("{:.0}°", sweep_end),
                FontId::proportional(11.0),
                Color32::WHITE,
            );
        }
        WidgetDef::Plotter { mode, .. } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(10, 14, 20));
            painter.rect_stroke(
                rect,
                CornerRadius::same(3),
                Stroke::new(1.0f32, Color32::from_rgb(35, 45, 60)),
                StrokeKind::Inside,
            );

            // Draw oscilloscope grid lines
            let grid_color = Color32::from_rgb(25, 35, 45);
            let num_v = 6;
            for i in 1..num_v {
                let x = rect.min.x + (rect.width() * i as f32 / num_v as f32);
                painter.line_segment(
                    [Pos2::new(x, rect.min.y), Pos2::new(x, rect.max.y)],
                    Stroke::new(0.8f32, grid_color),
                );
            }
            let num_h = 4;
            for i in 1..num_h {
                let y = rect.min.y + (rect.height() * i as f32 / num_h as f32);
                painter.line_segment(
                    [Pos2::new(rect.min.x, y), Pos2::new(rect.max.x, y)],
                    Stroke::new(0.8f32, grid_color),
                );
            }

            // Real-time animated waveform signal
            let center_y = rect.center().y;
            let amp = rect.height() * 0.35;
            let steps = (rect.width() as usize).max(20);
            let mut points = Vec::with_capacity(steps);

            for i in 0..steps {
                let x = rect.min.x + i as f32;
                let phase = (i as f32 * 0.08) - (time * 6.0);
                let y = if mode == "square" {
                    if phase.sin() >= 0.0 {
                        center_y - amp
                    } else {
                        center_y + amp
                    }
                } else {
                    // Sine with slight 2nd harmonic
                    center_y - (phase.sin() * amp * 0.8 + (phase * 2.0).sin() * amp * 0.2)
                };
                points.push(Pos2::new(x, y));
            }

            for win in points.windows(2) {
                painter.line_segment(
                    [win[0], win[1]],
                    Stroke::new(1.8f32, Color32::from_rgb(60, 230, 180)),
                );
            }

            painter.text(
                Pos2::new(rect.min.x + 6.0, rect.min.y + 6.0),
                egui::Align2::LEFT_TOP,
                "CH1: 1.00kHz (Live Scope)",
                FontId::proportional(9.0),
                Color32::from_rgb(60, 230, 180),
            );
        }
        WidgetDef::StatusBar { time: time_str, .. } => {
            painter.rect_filled(rect, CornerRadius::ZERO, Color32::from_rgb(35, 38, 48));
            painter.text(
                Pos2::new(rect.min.x + 8.0, rect.center().y),
                egui::Align2::LEFT_CENTER,
                "📶  🔋 98%",
                FontId::proportional(10.0),
                Color32::from_rgb(180, 190, 200),
            );

            // Blinking colon indicator with animation clock
            let colon = if (time * 2.0).fract() > 0.5 { ":" } else { " " };
            let live_time = format!("12{}34", colon);
            let display_time = if time_str.is_empty() {
                &live_time
            } else {
                time_str
            };

            painter.text(
                Pos2::new(rect.max.x - 8.0, rect.center().y),
                egui::Align2::RIGHT_CENTER,
                display_time,
                FontId::proportional(11.0),
                Color32::from_rgb(220, 225, 235),
            );
        }
        WidgetDef::Panel { style, .. } => {
            let bg = if style.as_deref() == Some("card") {
                Color32::from_rgb(32, 36, 44)
            } else {
                Color32::from_rgb(25, 28, 35)
            };
            painter.rect_filled(rect, CornerRadius::same(4), bg);
            painter.rect_stroke(
                rect,
                CornerRadius::same(4),
                Stroke::new(1.0f32, Color32::from_rgb(55, 60, 72)),
                StrokeKind::Inside,
            );
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                "Card Panel",
                FontId::proportional(11.0),
                Color32::from_rgb(120, 130, 145),
            );
        }
        WidgetDef::Dropdown {
            options, selected, ..
        } => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(38, 42, 52));
            painter.rect_stroke(
                rect,
                CornerRadius::same(3),
                Stroke::new(1.0f32, Color32::from_rgb(70, 80, 95)),
                StrokeKind::Inside,
            );
            let item = options
                .get(*selected)
                .map(|s| s.as_str())
                .unwrap_or("(none)");
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                format!("▼ {}", item),
                FontId::proportional(11.0),
                Color32::from_rgb(210, 215, 225),
            );
        }
        WidgetDef::Roller {
            options, selected, ..
        } => {
            painter.rect_filled(rect, CornerRadius::same(4), Color32::from_rgb(25, 28, 35));
            painter.rect_stroke(
                rect,
                CornerRadius::same(4),
                Stroke::new(1.0f32, Color32::from_rgb(60, 68, 82)),
                StrokeKind::Inside,
            );

            if !options.is_empty() {
                let len = options.len();
                let sel = (*selected).min(len.saturating_sub(1));
                let prev_idx = (sel + len - 1) % len;
                let next_idx = (sel + 1) % len;

                let row_h = rect.height() / 3.0;

                // Previous option (faded top row)
                let prev_rect = Rect::from_min_size(rect.min, Vec2::new(rect.width(), row_h));
                painter.text(
                    prev_rect.center(),
                    egui::Align2::CENTER_CENTER,
                    &options[prev_idx],
                    FontId::proportional(9.5),
                    Color32::from_rgb(110, 118, 130),
                );

                // Active / selected option (highlighted center row)
                let cur_rect = Rect::from_min_size(
                    Pos2::new(rect.min.x + 2.0, rect.min.y + row_h),
                    Vec2::new(rect.width() - 4.0, row_h),
                );
                painter.rect_filled(
                    cur_rect,
                    CornerRadius::same(2),
                    Color32::from_rgb(45, 105, 205),
                );
                painter.text(
                    cur_rect.center(),
                    egui::Align2::CENTER_CENTER,
                    &options[sel],
                    FontId::proportional(11.0),
                    Color32::WHITE,
                );

                // Next option (faded bottom row)
                let next_rect = Rect::from_min_size(
                    Pos2::new(rect.min.x, rect.min.y + 2.0 * row_h),
                    Vec2::new(rect.width(), row_h),
                );
                painter.text(
                    next_rect.center(),
                    egui::Align2::CENTER_CENTER,
                    &options[next_idx],
                    FontId::proportional(9.5),
                    Color32::from_rgb(110, 118, 130),
                );
            }
        }
        WidgetDef::Spacer => {}
        _ => {
            painter.rect_filled(rect, CornerRadius::same(3), Color32::from_rgb(28, 30, 36));
            painter.text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                widget.id().unwrap_or("widget"),
                FontId::proportional(10.0),
                Color32::from_rgb(160, 170, 180),
            );
        }
    }
}

impl eframe::App for EmbeddedGuiStudio {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // Handle Toast Timer
        if self.copied_toast_timer > 0.0 {
            self.copied_toast_timer -= ctx.input(|i| i.stable_dt);
        }

        // Advance animation timeline clock and request next frame repaint
        if self.is_playing {
            let dt = ctx.input(|i| i.stable_dt);
            self.timeline_time += dt * self.playback_speed;
            if self.timeline_time > self.loop_duration {
                self.timeline_time %= self.loop_duration;
            }
            ctx.request_repaint();
        }

        // Top Menu Bar
        egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
            egui::menu::bar(ui, |ui| {
                ui.label(egui::RichText::new("⚡ Embedded GUI Studio").strong());
                ui.separator();

                ui.menu_button("📄 Presets", |ui| {
                    if ui.button("📈 Live Oscilloscope").clicked() {
                        self.kdl_source = SAMPLE_WAVEFORM.to_string();
                        self.recompile();
                        ui.close_menu();
                    }
                    if ui.button("✨ Motion Kitchen Sink").clicked() {
                        self.kdl_source = SAMPLE_MOTION_KITCHEN_SINK.to_string();
                        self.recompile();
                        ui.close_menu();
                    }
                    if ui.button("🌡 Smart Thermostat").clicked() {
                        self.kdl_source = SAMPLE_THERMOSTAT.to_string();
                        self.recompile();
                        ui.close_menu();
                    }
                    if ui.button("📊 Sensor Dashboard").clicked() {
                        self.kdl_source = SAMPLE_DASHBOARD.to_string();
                        self.recompile();
                        ui.close_menu();
                    }
                });

                if ui.button("📋 Copy Rust Code").clicked() {
                    ctx.copy_text(self.generated_rust.clone());
                    self.copied_toast_timer = 2.0;
                }

                if self.copied_toast_timer > 0.0 {
                    ui.colored_label(Color32::from_rgb(80, 220, 120), "✓ Copied to clipboard!");
                }

                ui.with_layout(
                    egui::Layout::right_to_left(egui::Align::Center),
                    |ui| match &self.parsed_screen {
                        Ok(screen) => {
                            ui.colored_label(
                                Color32::from_rgb(80, 220, 120),
                                format!("✓ Valid ({} nodes)", screen.grid.children.len()),
                            );
                        }
                        Err(_) => {
                            ui.colored_label(Color32::from_rgb(255, 100, 100), "✗ Syntax Error");
                        }
                    },
                );
            });
        });

        // Left Panel: KDL Code Editor
        egui::SidePanel::left("editor_panel")
            .min_width(380.0)
            .default_width(440.0)
            .show(ctx, |ui| {
                ui.horizontal(|ui| {
                    ui.heading("KDL Screen Definition");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ui.small_button("Clear").clicked() {
                            self.kdl_source.clear();
                            self.recompile();
                        }
                    });
                });
                ui.separator();

                egui::ScrollArea::vertical()
                    .max_height(ui.available_height() - 70.0)
                    .show(ui, |ui| {
                        let response = ui.add(
                            egui::TextEdit::multiline(&mut self.kdl_source)
                                .font(egui::TextStyle::Monospace)
                                .desired_rows(24)
                                .desired_width(f32::INFINITY)
                                .lock_focus(true),
                        );
                        if response.changed() {
                            self.recompile();
                        }
                    });

                if let Err(err) = &self.parsed_screen {
                    ui.separator();
                    ui.colored_label(Color32::from_rgb(255, 90, 90), format!("⚠️ {}", err));
                }
            });

        // Right / Central Panel: Tabs
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.horizontal(|ui| {
                ui.selectable_value(
                    &mut self.active_tab,
                    StudioTab::VisualPreview,
                    "🖥 Visual Preview",
                );
                ui.selectable_value(
                    &mut self.active_tab,
                    StudioTab::RustCodegen,
                    "🦀 Generated Rust",
                );
                ui.selectable_value(
                    &mut self.active_tab,
                    StudioTab::AstHierarchy,
                    "🌲 AST Inspector",
                );
            });
            ui.separator();

            match self.active_tab {
                StudioTab::VisualPreview => {
                    if let Ok(screen) = self.parsed_screen.clone() {
                        self.render_visual_preview(ui, &screen);
                    } else {
                        ui.label("Fix KDL syntax errors to display preview.");
                    }
                }
                StudioTab::RustCodegen => {
                    egui::ScrollArea::both().show(ui, |ui| {
                        ui.add(
                            egui::TextEdit::multiline(&mut self.generated_rust.as_str())
                                .font(egui::TextStyle::Monospace)
                                .desired_width(f32::INFINITY),
                        );
                    });
                }
                StudioTab::AstHierarchy => {
                    if let Ok(screen) = &self.parsed_screen {
                        egui::ScrollArea::vertical().show(ui, |ui| {
                            ui.heading(format!("Screen: {}", screen.id));
                            ui.label(format!("Dimensions: {}x{}", screen.width, screen.height));
                            ui.label(format!("Cols: {:?}", screen.grid.cols));
                            ui.label(format!("Rows: {:?}", screen.grid.rows));
                            ui.label(format!(
                                "Gap: {}, Padding: {}",
                                screen.grid.gap, screen.grid.padding
                            ));
                            ui.separator();
                            ui.heading("Widget Placements:");
                            for (p, w) in &screen.grid.children {
                                ui.label(format!(
                                    "• [c:{}, r:{}, span:{}x{}] {:?}",
                                    p.col, p.row, p.col_span, p.row_span, w
                                ));
                            }
                        });
                    } else {
                        ui.label("No AST available.");
                    }
                }
            }
        });
    }
}

fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([1150.0, 750.0])
            .with_min_inner_size([700.0, 480.0])
            .with_title("Embedded GUI Studio - KDL Live Preview & Codegen"),
        ..Default::default()
    };

    eframe::run_native(
        "Embedded GUI Studio",
        options,
        Box::new(|_cc| Ok(Box::new(EmbeddedGuiStudio::default()))),
    )
}