GORBIE 0.13.2

GORBIE! Is a minimalist notebook library for Rust.
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
//! ## Working with mutable/non-cloneable things.
//! Sometimes when working with existing code, libraries or even std things like
//! files, can introduce an impedance mismatch with a dataflow-style model.
//! Often it is enough to wrap the object in question into another layer of `Arc`s
//! and `RWLock`s in addition to what Gorby already does with its shared state
//! store.
//!
//! For heavier work, `ComputedState` can run background tasks and hold the latest
//! value. Use `Option<T>` when a value may be absent while a computation runs.
//!
//! But sometimes that isn't enough, e.g. when you want to display some application
//! global state. This is why `NotebookCtx::state` and `NotebookCtx::view` are carefully
//! designed to stay independent from any dataflow runtime. Instead they can be used,
//! like any other mutable rust type, via the typed `StateId` handle.
//!

#![allow(non_snake_case)]

/// Card context — the `&mut CardCtx` passed to card closures.
pub mod card_ctx;
/// Card trait and built-in card types (stateful, stateless).
pub mod cards;
/// Background computation with [`ComputedState`](dataflow::ComputedState).
pub mod dataflow;
pub(crate) mod floating;
mod headless;
/// Convenient glob import of common types and constants.
pub mod prelude;
/// Thread-safe state management via [`StateId`](state::StateId) handles.
pub mod state;
/// Telemetry dashboard (requires `telemetry` feature).
#[cfg(feature = "telemetry")]
pub mod telemetry;
/// Visual themes, RAL colors, and widget style structs.
pub mod themes;
/// Built-in widgets: buttons, fields, sliders, progress bars, and more.
pub mod widgets;

pub use gorbie_macros::notebook;

use crate::themes::industrial_dark;
use crate::themes::industrial_fonts;
use crate::themes::industrial_light;
use eframe::egui::{self};
use std::any::TypeId;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use dark_light::Mode;


#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct SourceLocation {
    file: String,
    line: u32,
    column: u32,
}

impl SourceLocation {
    fn from_location(location: &'static std::panic::Location<'static>) -> Self {
        Self {
            file: location.file().to_string(),
            line: location.line(),
            column: location.column(),
        }
    }

    fn format_arg(&self, template: &str) -> String {
        let file = &self.file;
        let line = self.line;
        let column = self.column;
        template
            .replace("{file}", file)
            .replace("{line}", &line.to_string())
            .replace("{column}", &column.to_string())
    }

    fn file_line_column(&self) -> String {
        let file = &self.file;
        let line = self.line;
        let column = self.column;
        format!("{file}:{line}:{column}")
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
enum CardIdentityKey {
    Stateless {
        source: Option<SourceLocation>,
        function: TypeId,
    },
    Stateful {
        source: Option<SourceLocation>,
        state: egui::Id,
        function: TypeId,
    },
    Custom,
}

/// Command template for opening source files in an external editor.
///
/// Argument strings may contain `{file}`, `{line}`, and `{column}` placeholders
/// that are expanded when a card's source location is opened.
#[derive(Clone, Debug)]
pub struct EditorCommand {
    program: String,
    args: Vec<String>,
}

impl EditorCommand {
    /// Creates a new editor command with the given program name.
    pub fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
        }
    }

    /// Appends an argument to the command. Supports `{file}`, `{line}`, and
    /// `{column}` placeholders.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    fn open(&self, source: &SourceLocation) -> std::io::Result<()> {
        let mut cmd = Command::new(&self.program);
        if self.args.is_empty() {
            cmd.arg(source.file_line_column());
        } else {
            for arg in &self.args {
                cmd.arg(source.format_arg(arg));
            }
        }
        let _child = cmd.spawn()?;
        Ok(())
    }
}

struct CardEntry {
    card: Box<dyn cards::Card + 'static>,
    source: Option<SourceLocation>,
    identity: egui::Id,
}

#[derive(Clone, Default)]
struct NotebookState {
    card_detached: Vec<bool>,
    card_placeholder_sizes: Vec<egui::Vec2>,
    card_identities: Vec<Option<egui::Id>>,
}

impl NotebookState {
    fn sync_len(&mut self, len: usize) {
        self.card_detached.resize(len, false);
        self.card_placeholder_sizes.resize(len, egui::Vec2::ZERO);
        self.card_identities.resize(len, None);
    }

    fn ensure_card_identity(&mut self, index: usize, identity: egui::Id) {
        let slot = self
            .card_identities
            .get_mut(index)
            .expect("card_identities synced to cards");
        if slot.map_or(true, |prev| prev != identity) {
            *slot = Some(identity);
            *self
                .card_detached
                .get_mut(index)
                .expect("card_detached synced to cards") = false;
            *self
                .card_placeholder_sizes
                .get_mut(index)
                .expect("card_placeholder_sizes synced to cards") = egui::Vec2::ZERO;
        }
    }
}

/// Configuration for a notebook application.
pub struct NotebookConfig {
    title: String,
    editor: Option<EditorCommand>,
    headless_capture: Option<HeadlessCaptureConfig>,
    headless_settle_timeout: Option<Duration>,
}

#[derive(Clone)]
struct HeadlessCaptureConfig {
    output_dir: PathBuf,
    card_width: f32,
    pixels_per_point: f32,
    settle_timeout: Duration,
}

#[derive(Clone)]
struct AppIcons {
    light: Arc<egui::IconData>,
    dark: Arc<egui::IconData>,
}

struct NotebookCore {
    config: NotebookConfig,
    body: Box<dyn FnMut(&mut NotebookCtx)>,
    state_store: Arc<state::StateStore>,
    settled: Arc<AtomicBool>,
}

struct Notebook {
    core: NotebookCore,
    icons: Option<AppIcons>,
    icon_is_dark: Option<bool>,
    #[cfg(feature = "telemetry")]
    #[allow(dead_code)] // kept alive to flush/close the telemetry sink on shutdown
    telemetry: Option<telemetry::Telemetry>,
}

/// Frame-scoped notebook builder used to collect cards in immediate mode.
pub struct NotebookCtx {
    state_id: egui::Id,
    cards: Vec<CardEntry>,
    state_store: Arc<state::StateStore>,
    settled: Arc<AtomicBool>,
}

pub use card_ctx::CardCtx;
pub use card_ctx::Grid;
pub use card_ctx::GRID_COL_WIDTH;
pub use card_ctx::GRID_COLUMNS;
pub use card_ctx::GRID_GUTTER;

pub(crate) const NOTEBOOK_COLUMN_WIDTH: f32 = 768.0;
const NOTEBOOK_MIN_HEIGHT: f32 = 360.0;
const HEADLESS_DEFAULT_PIXELS_PER_POINT: f32 = 2.0;
const HEADLESS_DEFAULT_SETTLE_TIMEOUT: Duration = Duration::from_millis(2000);

impl Default for NotebookConfig {
    fn default() -> Self {
        Self::new(String::new())
    }
}

impl NotebookConfig {
    /// Creates a new configuration with the given application title.
    ///
    /// The editor command is auto-detected from the `GORBIE_EDITOR` environment
    /// variable; use [`with_editor`](Self::with_editor) to override.
    pub fn new(name: impl Into<String>) -> Self {
        let title = name.into();
        Self {
            title,
            editor: editor_from_env(),
            headless_capture: None,
            headless_settle_timeout: None,
        }
    }

    /// Overrides the editor command used for "open in editor" buttons.
    pub fn with_editor(mut self, editor: EditorCommand) -> Self {
        self.editor = Some(editor);
        self
    }

    /// Enables headless capture mode, rendering each card to a PNG in `output_dir`.
    pub fn with_headless_capture(mut self, output_dir: impl Into<PathBuf>) -> Self {
        let settle_timeout = self
            .headless_settle_timeout
            .unwrap_or(HEADLESS_DEFAULT_SETTLE_TIMEOUT);
        self.headless_capture = Some(HeadlessCaptureConfig {
            output_dir: output_dir.into(),
            card_width: NOTEBOOK_COLUMN_WIDTH,
            pixels_per_point: HEADLESS_DEFAULT_PIXELS_PER_POINT,
            settle_timeout,
        });
        self
    }

    /// Like [`with_headless_capture`](Self::with_headless_capture), but with a
    /// custom `pixels_per_point` scaling factor for the rendered output.
    pub fn with_headless_capture_scaled(
        mut self,
        output_dir: impl Into<PathBuf>,
        pixels_per_point: f32,
    ) -> Self {
        let pixels_per_point = if pixels_per_point > 0.0 {
            pixels_per_point
        } else {
            HEADLESS_DEFAULT_PIXELS_PER_POINT
        };
        let settle_timeout = self
            .headless_settle_timeout
            .unwrap_or(HEADLESS_DEFAULT_SETTLE_TIMEOUT);
        self.headless_capture = Some(HeadlessCaptureConfig {
            output_dir: output_dir.into(),
            card_width: NOTEBOOK_COLUMN_WIDTH,
            pixels_per_point,
            settle_timeout,
        });
        self
    }

    /// Sets the settle timeout for headless capture. The renderer waits up to
    /// this duration for the UI to stabilize before capturing.
    pub fn with_headless_settle_timeout(mut self, timeout: Duration) -> Self {
        self.headless_settle_timeout = Some(timeout);
        if let Some(headless) = &mut self.headless_capture {
            headless.settle_timeout = timeout;
        }
        self
    }

    fn state_id(&self) -> egui::Id {
        egui::Id::new(("gorbie_notebook_state", self.title.as_str()))
    }

    /// Launches the notebook application.
    ///
    /// The `body` closure is called once per frame to populate cards. In headless
    /// mode the cards are rendered to PNGs and the process exits; otherwise an
    /// interactive window is opened.
    pub fn run(self, body: impl FnMut(&mut NotebookCtx) + 'static) -> eframe::Result {
        let config = self;
        if let Some(headless) = config.headless_capture.clone() {
            return headless::run_headless(NotebookCore::new(config, Box::new(body)), headless)
                .map_err(eframe::Error::AppCreation);
        }

        let window_title = if config.title.is_empty() {
            "GORBIE".to_owned()
        } else {
            config.title.clone()
        };

        let icons = load_app_icons();
        let mut native_options = eframe::NativeOptions::default();
        native_options.persist_window = true;
        native_options.viewport = native_options
            .viewport
            .with_inner_size(egui::vec2(1200.0, 800.0))
            .with_min_inner_size(egui::vec2(NOTEBOOK_COLUMN_WIDTH, NOTEBOOK_MIN_HEIGHT));

        if let Some(icons) = icons.as_ref() {
            let icon = match dark_light::detect() {
                Ok(Mode::Light) => icons.light.clone(),
                Ok(Mode::Dark) => icons.dark.clone(),
                Ok(Mode::Unspecified) | Err(_) => icons.dark.clone(),
            };
            native_options.viewport = native_options.viewport.with_icon(icon);
        }

        let body = Box::new(body);
        eframe::run_native(
            &window_title,
            native_options,
            Box::new(|cc| {
                let ctx = cc.egui_ctx.clone();
                ctrlc::set_handler(move || ctx.send_viewport_cmd(egui::ViewportCommand::Close))
                    .expect("failed to set exit signal handler");

                cc.egui_ctx.set_fonts(industrial_fonts());

                cc.egui_ctx
                    .set_style_of(egui::Theme::Light, industrial_light());
                cc.egui_ctx
                    .set_style_of(egui::Theme::Dark, industrial_dark());

                #[cfg(feature = "telemetry")]
                let telemetry_title = config.title.clone();
                Ok(Box::new(Notebook {
                    core: NotebookCore::new(config, body),
                    icons,
                    icon_is_dark: None,
                    #[cfg(feature = "telemetry")]
                    telemetry: telemetry::Telemetry::install_global_from_env(&telemetry_title),
                }))
            }),
        )
    }
}

fn load_app_icons() -> Option<AppIcons> {
    let light =
        eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon_light.png")).ok()?;
    let dark = eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon_dark.png")).ok()?;
    Some(AppIcons {
        light: Arc::new(light),
        dark: Arc::new(dark),
    })
}

fn editor_from_env() -> Option<EditorCommand> {
    let gorbie_editor = std::env::var("GORBIE_EDITOR")
        .ok()
        .filter(|value| !value.trim().is_empty());
    if gorbie_editor.is_none() {
        log_missing_editor_hint();
        return None;
    }
    let editor = gorbie_editor?;

    let mut parts = editor.split_whitespace();
    let program = parts.next()?.to_string();
    let args = parts.map(str::to_string);
    let mut command = EditorCommand::new(program);
    for arg in args {
        command = command.arg(arg);
    }
    Some(command)
}

fn log_missing_editor_hint() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        log::info!(
            "GORBIE_EDITOR is not set. Set it to an editor command with placeholders {{file}} {{line}} {{column}} to enable open-in-editor. Example: GORBIE_EDITOR='code -g {{file}}:{{line}}:{{column}}'."
        );
    });
}

impl state::StateAccess for NotebookCtx {
    fn store(&self) -> &state::StateStore {
        &self.state_store
    }
}

impl NotebookCtx {
    fn new(config: &NotebookConfig, state_store: Arc<state::StateStore>, settled: Arc<AtomicBool>) -> Self {
        Self {
            state_id: config.state_id(),
            cards: Vec::new(),
            state_store,
            settled,
        }
    }

    /// Signal that notebook content is fully loaded and ready for capture.
    /// In headless mode this triggers immediate capture instead of waiting
    /// for the settle timeout. In interactive mode this is a no-op.
    pub fn settled(&self) {
        self.settled.store(true, Ordering::Relaxed);
    }

    /// Adds a stateless card whose content is drawn by `function` each frame.
    #[track_caller]
    pub fn view<F>(&mut self, function: F)
    where
        F: for<'a, 'b> FnMut(&'a mut CardCtx<'b>) + 'static,
    {
        let source = SourceLocation::from_location(std::panic::Location::caller());
        let identity = self.card_identity(CardIdentityKey::Stateless {
            source: Some(source.clone()),
            function: TypeId::of::<F>(),
        });
        let card = cards::StatelessCard::new(function);
        self.push_with_source(Box::new(card), Some(source), identity);
    }

    /// Adds a stateful card backed by a value of type `T` in the shared state store.
    ///
    /// The state is initialized with `init` on first use and persists across frames.
    /// Returns a [`StateId`](state::StateId) handle for reading/writing the state
    /// from other cards.
    #[track_caller]
    pub fn state<K, T, F>(&mut self, key: &K, init: T, function: F) -> state::StateId<T>
    where
        K: std::hash::Hash + ?Sized,
        T: Send + Sync + 'static,
        F: for<'a, 'b> FnMut(&'a mut CardCtx<'b>, &mut T) + 'static,
    {
        let source = SourceLocation::from_location(std::panic::Location::caller());
        let state_id = self.state_id_for(key);
        let identity = self.card_identity(CardIdentityKey::Stateful {
            source: Some(source.clone()),
            state: state_id,
            function: TypeId::of::<F>(),
        });
        let state = state::StateId::new(state_id);
        let handle = state;
        self.state_store.get_or_insert(state, init);
        let card = cards::StatefulCard::new(state, function);
        self.push_with_source(Box::new(card), Some(source), identity);
        handle
    }

    /// Adds a pre-built [`Card`](cards::Card) trait object to the notebook.
    pub fn push(&mut self, card: Box<dyn cards::Card>) {
        let identity = self.card_identity(CardIdentityKey::Custom);
        self.push_with_source(card, None, identity);
    }

    pub(crate) fn state_id_for<K: std::hash::Hash + ?Sized>(&self, key: &K) -> egui::Id {
        self.state_id.with(("state", key))
    }

    fn card_identity(&self, key: CardIdentityKey) -> egui::Id {
        self.state_id.with(("card", key))
    }

    fn push_with_source(
        &mut self,
        card: Box<dyn cards::Card>,
        source: Option<SourceLocation>,
        identity: egui::Id,
    ) {
        self.cards.push(CardEntry {
            card,
            source,
            identity,
        });
    }
}

impl NotebookCore {
    fn new(config: NotebookConfig, body: Box<dyn FnMut(&mut NotebookCtx)>) -> Self {
        Self {
            config,
            body,
            state_store: Arc::new(state::StateStore::default()),
            settled: Arc::new(AtomicBool::new(false)),
        }
    }

    fn has_settled(&self) -> bool {
        self.settled.swap(false, Ordering::Relaxed)
    }

    fn build_notebook(&mut self) -> NotebookCtx {
        let mut notebook = NotebookCtx::new(&self.config, self.state_store.clone(), self.settled.clone());
        (self.body)(&mut notebook);
        notebook
    }

    fn draw_card(
        &self,
        ctx: &egui::Context,
        notebook: &mut NotebookCtx,
        index: usize,
        card_width: f32,
    ) -> Option<f32> {
        if index >= notebook.cards.len() {
            return None;
        }

        let store = notebook.state_store.clone();
        let mut measured_height: Option<f32> = None;
        let panel_fill = ctx.global_style().visuals.window_fill;
        egui::CentralPanel::default()
            .frame(egui::Frame::NONE.fill(panel_fill))
            .show(ctx, |ui| {
                ui.set_min_size(egui::vec2(card_width, 0.0));
                if let Some(entry) = notebook.cards.get_mut(index) {
                    let card: &mut dyn cards::Card = entry.card.as_mut();
                    let rect = draw_card_body(ui, card_width, card, store.as_ref(), None);
                    measured_height = Some(rect.height());
                }
            });

        measured_height
    }
}

impl Notebook {
    fn update_app_icon(&mut self, ctx: &egui::Context) {
        let Some(icons) = self.icons.as_ref() else {
            return;
        };
        let is_dark = matches!(ctx.theme(), egui::Theme::Dark);
        if self.icon_is_dark == Some(is_dark) {
            return;
        }

        let icon = if is_dark {
            icons.dark.clone()
        } else {
            icons.light.clone()
        };
        ctx.send_viewport_cmd(egui::ViewportCommand::Icon(Some(icon)));
        self.icon_is_dark = Some(is_dark);
    }
}

impl eframe::App for Notebook {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let ctx = ui.ctx().clone();
        self.update_app_icon(&ctx);
        ctx.global_style_mut(|style| {
            style.visuals.clip_rect_margin = 0.0;
        });

        #[cfg(feature = "telemetry")]
        let _telemetry_frame = tracing::info_span!("frame").entered();

        let mut notebook = {
            #[cfg(feature = "telemetry")]
            let _build_span = tracing::info_span!("build_notebook").entered();
            self.core.build_notebook()
        };
        let config = &self.core.config;

        let state_id = config.state_id();
        let mut runtime = ctx.data_mut(|data| {
            let slot = data.get_temp_mut_or_insert_with(state_id, NotebookState::default);
            std::mem::take(slot)
        });

        // eframe 0.34's `fn ui` receives a bare `&mut Ui` with no margin
        // or background color (see the trait doc). Wrap in a central-panel
        // Frame so the notebook draws on the theme's panel fill instead
        // of transparent/black.
        egui::Frame::central_panel(&ctx.global_style()).show(ui, |ui| {
        egui::ScrollArea::vertical()
            .auto_shrink([false; 2])
            // Disable drag-to-scroll on the main notebook scroller. egui's
            // hit-test panics (`hit_test.rs:365`) when a big drag-sensing
            // ScrollArea coexists with nearby click-sensing widgets —
            // which is every interactive card in a notebook. Users still
            // scroll via scroll bars + mouse wheel; touch-style drag-pan
            // is lost.
            .scroll_source(egui::scroll_area::ScrollSource {
                scroll_bar: true,
                drag: false,
                mouse_wheel: true,
            })
            .show_viewport(ui, |ui, viewport| {
                    let rect = ui.max_rect();
                    let clip_rect = ui.clip_rect();
                        let scroll_y = viewport.min.y;

                    // Publish scroll info so floating cards can do anchor switching.
                    floating::store_scroll_info(
                        ui.ctx(),
                        floating::NotebookScrollInfo {
                            scroll_y,
                            viewport_top: clip_rect.min.y,
                            clip_rect,
                        },
                    );

                    let column_width = NOTEBOOK_COLUMN_WIDTH;
                    let left_margin_width = 0.0;
                    let card_width = column_width;

                    let left_margin_paint = egui::Rect::from_min_max(
                        egui::pos2(rect.min.x, clip_rect.min.y),
                        egui::pos2(rect.min.x + left_margin_width, clip_rect.max.y),
                    );
                    let left_margin = egui::Rect::from_min_max(
                        rect.min,
                        egui::pos2(rect.min.x + left_margin_width, rect.max.y),
                    );
                    let column_rect = egui::Rect::from_min_max(
                        egui::pos2(left_margin.max.x, rect.min.y),
                        egui::pos2(left_margin.max.x + column_width, rect.max.y),
                    );
                    let right_margin_paint = egui::Rect::from_min_max(
                        egui::pos2(column_rect.max.x, clip_rect.min.y),
                        egui::pos2(rect.max.x, clip_rect.max.y),
                    );
                    let right_margin = egui::Rect::from_min_max(
                        egui::pos2(column_rect.max.x, rect.min.y),
                        rect.max,
                    );

                    paint_dot_grid(ui, left_margin_paint, scroll_y);
                    paint_dot_grid(ui, right_margin_paint, scroll_y);

                    ui.scope_builder(egui::UiBuilder::new().max_rect(column_rect), |ui| {
                        // Keep column/background fills from painting into the margins when
                        // a too-wide widget forces a larger layout rect.
                        let restore_clip_rect = ui.clip_rect();
                        let column_clip_rect = egui::Rect::from_min_max(
                            egui::pos2(column_rect.min.x, restore_clip_rect.min.y),
                            egui::pos2(column_rect.max.x, restore_clip_rect.max.y),
                        );
                        ui.set_clip_rect(column_clip_rect);

                        // Min-size in y is bounded by the viewport, not by
                        // `max_rect` — `ui.max_rect()` inside ScrollArea
                        // reflects the previous frame's content size, so
                        // forcing the column to that height plus float
                        // overflow grows the scroll content by `float_overflow`
                        // every frame (linear "infinite scroll" once any
                        // content-anchored float exists).
                        ui.set_min_size(egui::vec2(column_rect.width(), clip_rect.height()));
                        ui.set_max_width(column_rect.width());

                        let fill = ui.visuals().window_fill;

                        let card_gap = ui
                            .visuals()
                            .widgets
                            .noninteractive
                            .bg_stroke
                            .width
                            .max(1.0);
                        let card_gap_i8 = card_gap
                            .round()
                            .clamp(0.0, i8::MAX as f32) as i8;
                        let column_inner_margin = egui::Margin {
                            left: 0,
                            right: 0,
                            top: 12,
                            bottom: card_gap_i8,
                        };
                        let column_frame = egui::Frame::new()
                            .fill(fill)
                            .stroke(egui::Stroke::NONE)
                            .corner_radius(0.0)
                            .inner_margin(column_inner_margin)
                            .show(ui, |ui| {
                                // Theme switch is part of the page header (above the first card).
                                ui.horizontal(|ui| {
                                    ui.add_space(16.0);
                                    if !config.title.is_empty() {
                                        let header_title =
                                            egui::RichText::new(config.title.to_uppercase())
                                                .monospace()
                                                .strong();
                                        ui.add(egui::Label::new(header_title).truncate());
                                    }

                                    ui.with_layout(
                                        egui::Layout::right_to_left(egui::Align::Center),
                                        |ui| {
                                            ui.add_space(16.0);
                                            let mut preference =
                                                ui.ctx().options(|opt| opt.theme_preference);
                                            if ui
                                                .add(
                                                    widgets::ChoiceToggle::new(&mut preference)
                                                        .choice(egui::ThemePreference::System, "")
                                                        .choice(egui::ThemePreference::Dark, "")
                                                        .choice(egui::ThemePreference::Light, ""),
                                                )
                                                .changed()
                                            {
                                                ui.ctx().set_theme(preference);
                                            }
                                        },
                                    );
                                });

                                ui.add_space(12.0);

                                let default_item_spacing = ui.style().spacing.item_spacing;
                                ui.style_mut().spacing.item_spacing.y = 0.0;

                                // Separator between header and first card.
                                {
                                    let (gap_rect, _) = ui.allocate_exact_size(
                                        egui::vec2(card_width, card_gap),
                                        egui::Sense::hover(),
                                    );
                                    let stroke = ui.visuals().widgets.noninteractive.bg_stroke;
                                    ui.painter().rect_filled(gap_rect, 0.0, stroke.color);
                                }

                                runtime.sync_len(notebook.cards.len());
                                let store = notebook.state_store.clone();
                                let cards_len = notebook.cards.len();
                                for (i, entry) in notebook.cards.iter_mut().enumerate() {
                                    let card_identity = entry.identity;
                                    runtime.ensure_card_identity(i, card_identity);
                                    let card_detached = runtime.card_detached
                                        .get_mut(i)
                                        .expect("card_detached synced to cards");
                                    let card_placeholder_size = runtime.card_placeholder_sizes
                                        .get_mut(i)
                                        .expect("card_placeholder_sizes synced to cards");
                                    ui.push_id((i, card_identity), |ui| {
                                        let card_left = column_rect.min.x;
                                        let card: &mut dyn cards::Card = entry.card.as_mut();
                                        let card_rect = if *card_detached {
                                            let placeholder_height =
                                                crate::card_ctx::GRID_ROW_MODULE;
                                            let placeholder_width = card_width;
                                            let (rect, resp) = ui.allocate_exact_size(
                                                egui::vec2(placeholder_width, placeholder_height),
                                                egui::Sense::click(),
                                            );
                                            let fill = ui.visuals().window_fill;
                                            let outline =
                                                ui.visuals().widgets.noninteractive.bg_stroke.color;
                                            ui.painter().rect_filled(rect, 0.0, fill);
                                            paint_hatching(
                                                &ui.painter().with_clip_rect(rect),
                                                rect,
                                                outline,
                                            );
                                            show_postit_tooltip(ui, &resp, "Dock card");
                                            if resp.clicked() {
                                                *card_detached = false;
                                            }

                                            if *card_detached {
                                                let initial_screen_pos = egui::pos2(
                                                    right_margin.min.x + 12.0,
                                                    rect.top(),
                                                );
                                                let detached_id = ui.id().with("detached_card");
                                                let float_resp = floating::show_floating_card(
                                                    ui.ctx(),
                                                    detached_id,
                                                    initial_screen_pos,
                                                    card_width,
                                                    card_placeholder_size.y,
                                                    store.as_ref(),
                                                    "Dock card",
                                                    &mut |ctx| {
                                                        #[cfg(feature = "telemetry")]
                                                        let _detached_span = tracing::info_span!(
                                                            "detached_draw"
                                                        )
                                                        .entered();
                                                        card.draw(ctx);
                                                    },
                                                );
                                                if float_resp.handle_clicked {
                                                    *card_detached = false;
                                                }
                                            }
                                            rect
                                        } else {
                                            let clip_rect = ui.clip_rect();
                                            let card_clip_rect = egui::Rect::from_min_max(
                                                egui::pos2(
                                                    column_rect.min.x,
                                                    clip_rect.min.y,
                                                ),
                                                egui::pos2(
                                                    column_rect.max.x,
                                                    clip_rect.max.y,
                                                ),
                                            );
                                            #[cfg(feature = "telemetry")]
                                            let _card_span = {
                                                let source = entry
                                                    .source
                                                    .as_ref()
                                                    .map(|s| s.file_line_column())
                                                    .unwrap_or_default();
                                                tracing::info_span!(
                                                    "card",
                                                    source = source.as_str()
                                                )
                                                .entered()
                                            };
                                            let inner_rect = draw_card_body(
                                                ui,
                                                card_width,
                                                card,
                                                store.as_ref(),
                                                Some(card_clip_rect),
                                            );
                                            *card_placeholder_size =
                                                egui::vec2(card_width, inner_rect.height());
                                            egui::Rect::from_min_size(
                                                egui::pos2(card_left, inner_rect.min.y),
                                                egui::vec2(card_width, inner_rect.height()),
                                            )
                                        };
                                        if i + 1 < cards_len {
                                            let separator_top = card_rect.bottom().ceil();
                                            let cursor_top = ui.cursor().top();
                                            if separator_top > cursor_top {
                                                ui.add_space(separator_top - cursor_top);
                                            }
                                            let (gap_rect, _) = ui.allocate_exact_size(
                                                egui::vec2(card_width, card_gap),
                                                egui::Sense::hover(),
                                            );
                                            let stroke = ui
                                                .visuals()
                                                .widgets
                                                .noninteractive
                                                .bg_stroke;
                                            ui.painter()
                                                .rect_filled(gap_rect, 0.0, stroke.color);
                                        }

                                        let show_detach_button = !*card_detached;
                                        let show_open_button = show_detach_button
                                            && entry.source.is_some()
                                            && config.editor.is_some();
                                        if show_detach_button {
                                            let tab_size = egui::vec2(20.0, 2.0 * crate::card_ctx::GRID_ROW_MODULE);
                                            let tab_pull = 4.0;
                                            let base_tab_gap = 4.0;
                                            let base_top_offset = 8.0;
                                            let min_top_offset = 0.0;
                                            let min_visible = tab_size.y * 0.4;
                                            let tab_fill = crate::themes::GorbieButtonStyle::from(
                                                ui.style().as_ref(),
                                            )
                                            .fill;

                                            let tab_count = 1 + usize::from(show_open_button);
                                            let available = card_rect.height().max(0.0);
                                            let mut top_offset = base_top_offset;
                                            let mut gap = base_tab_gap;
                                            let required = top_offset
                                                + tab_size.y * tab_count as f32
                                                + gap * (tab_count.saturating_sub(1) as f32);

                                            if required > available {
                                                let extra = required - available;
                                                let max_top_reduce =
                                                    (top_offset - min_top_offset).max(0.0);
                                                let top_reduce = extra.min(max_top_reduce);
                                                top_offset -= top_reduce;
                                                let remaining = extra - top_reduce;

                                                if remaining > 0.0 && tab_count > 1 {
                                                    let min_gap =
                                                        -(tab_size.y - min_visible);
                                                    let max_gap_reduce =
                                                        (gap - min_gap).max(0.0);
                                                    let gap_reduce = remaining.min(max_gap_reduce);
                                                    gap -= gap_reduce;
                                                }
                                            }

                                            let tab_x = card_rect.right().round();
                                            let top_y =
                                                (card_rect.top() + top_offset).round();
                                            let detach_pos = egui::pos2(tab_x, top_y);
                                            let open_pos = show_open_button.then(|| {
                                                egui::pos2(
                                                    tab_x,
                                                    (top_y + tab_size.y + gap).round(),
                                                )
                                            });

                                            ui.push_id((i, card_identity), |ui| {
                                                if let Some(open_pos) = open_pos {
                                                    let open_id =
                                                        ui.id().with("open_button");
                                                    let open_area = egui::Area::new(open_id)
                                                        .order(egui::Order::Middle)
                                                        .fixed_pos(open_pos)
                                                        .movable(false)
                                                        .constrain_to(egui::Rect::EVERYTHING);
                                                    let open_resp =
                                                        open_area.show(ui.ctx(), |ui| {
                                                            let (rect, resp) =
                                                                ui.allocate_exact_size(
                                                                    egui::vec2(
                                                                        tab_size.x + tab_pull,
                                                                        tab_size.y,
                                                                    ),
                                                                    egui::Sense::click(),
                                                                );
                                                            let tab_rect =
                                                                egui::Rect::from_min_size(
                                                                    rect.min,
                                                                    tab_size,
                                                                );
                                                            paint_card_tab_button(
                                                                ui,
                                                                &resp,
                                                                tab_rect,
                                                                "<>",
                                                                tab_fill,
                                                                tab_pull,
                                                            );

                                                            if let Some(source) =
                                                                entry.source.as_ref()
                                                            {
                                                                let file = &source.file;
                                                                let line = source.line;
                                                                let tooltip = format!(
                                                                    "Open in editor\n{file}:{line}"
                                                                );
                                                                show_postit_tooltip(
                                                                    ui,
                                                                    &resp,
                                                                    &tooltip,
                                                                );
                                                            } else {
                                                                show_postit_tooltip(
                                                                    ui,
                                                                    &resp,
                                                                    "Open in editor",
                                                                );
                                                            }
                                                            resp
                                                        });

                                                    if open_resp.inner.clicked() {
                                                        if let (Some(source), Some(editor)) =
                                                            (
                                                                entry.source.as_ref(),
                                                                config.editor.as_ref(),
                                                            )
                                                        {
                                                            if let Err(err) = editor.open(source) {
                                                                log::warn!(
                                                                    "failed to open editor: {err}"
                                                                );
                                                            }
                                                        }
                                                    }
                                                }

                                                let detach_id = ui.id().with("detach_button");
                                                let detach_area = egui::Area::new(detach_id)
                                                    .order(egui::Order::Middle)
                                                    .fixed_pos(detach_pos)
                                                    .movable(false)
                                                    .constrain_to(egui::Rect::EVERYTHING);
                                                let detach_resp =
                                                    detach_area.show(ui.ctx(), |ui| {
                                                        let (rect, resp) =
                                                            ui.allocate_exact_size(
                                                                egui::vec2(
                                                                    tab_size.x + tab_pull,
                                                                    tab_size.y,
                                                                ),
                                                                egui::Sense::click(),
                                                            );
                                                        let tab_rect =
                                                            egui::Rect::from_min_size(
                                                                rect.min,
                                                                tab_size,
                                                            );
                                                        paint_card_tab_button(
                                                            ui,
                                                            &resp,
                                                            tab_rect,
                                                            "[]",
                                                            tab_fill,
                                                            tab_pull,
                                                        );

                                                        let tooltip = if *card_detached {
                                                            "Dock card"
                                                        } else {
                                                            "Detach card"
                                                        };
                                                        show_postit_tooltip(ui, &resp, tooltip);
                                                        resp
                                                    });

                                                if detach_resp.inner.clicked() {
                                                    *card_detached = !*card_detached;
                                                }
                                            });
                                        }

                                    });
                                }

                                ui.style_mut().spacing.item_spacing = default_item_spacing;

                            });
                        ui.set_clip_rect(restore_clip_rect);
                        let frame_rect = column_frame.response.rect;
                        let frame_rect = egui::Rect::from_min_max(
                            egui::pos2(column_rect.min.x, frame_rect.min.y),
                            egui::pos2(column_rect.max.x, frame_rect.max.y),
                        );
                        let stroke = ui.visuals().widgets.noninteractive.bg_stroke;
                        ui.painter()
                            .rect_stroke(frame_rect, 0.0, stroke, egui::StrokeKind::Inside);

                        // Extend scroll content to include content-anchored
                        // floating cards. The comparison is in *heights*,
                        // not absolute positions — `frame_rect.bottom()`
                        // is in screen coords (drifts with scroll), while
                        // `float_bottom` (= fstate.pos.y + card_h) is in
                        // content coords (fixed). Subtracting the two
                        // mixes coord systems and grows linearly with
                        // scroll position → runaway scroll content.
                        // Compare heights instead: the column's inline
                        // content occupies content_y = [0, frame_h]; the
                        // float ends at content_y = float_bottom; we
                        // extend by the gap.
                        let inline_height = frame_rect.height();
                        let float_bottom = floating::max_float_content_bottom(ui.ctx());
                        if float_bottom > inline_height {
                            ui.allocate_space(egui::vec2(0.0, float_bottom - inline_height));
                        }
                    });
                });
        });

        ctx.data_mut(|data| {
            data.insert_temp(state_id, runtime);
        });
    }
}

fn draw_card_body(
    ui: &mut egui::Ui,
    card_width: f32,
    card: &mut dyn cards::Card,
    store: &state::StateStore,
    clip_rect: Option<egui::Rect>,
) -> egui::Rect {
    // Clamp *all* painting (including the frame fill) to the column rect.
    // Without this, a too-wide widget can expand the frame and paint into the
    // notebook margins, covering the dot grid.
    let restore_clip = clip_rect.map(|rect| {
        let restore = ui.clip_rect();
        ui.set_clip_rect(rect);
        restore
    });

    let inner = egui::Frame::group(ui.style())
        .stroke(egui::Stroke::NONE)
        .corner_radius(0.0)
        .inner_margin(egui::Margin::ZERO)
        .show(ui, |ui| {
            ui.reset_style();
            ui.set_width(card_width);
            let mut ctx = CardCtx::new(ui, store);
            card.draw(&mut ctx);
        });

    if let Some(restore) = restore_clip {
        ui.set_clip_rect(restore);
    }
    inner.response.rect
}

fn paint_dot_grid(ui: &egui::Ui, rect: egui::Rect, scroll_y: f32) {
    if rect.width() <= 0.0 || rect.height() <= 0.0 {
        return;
    }

    let painter = ui.painter_at(rect);

    let spacing = 18.0;
    let radius = 1.2;
    let background = ui.visuals().window_fill;
    let outline = ui.visuals().widgets.noninteractive.bg_stroke.color;
    let color = crate::themes::blend(background, outline, 0.35);

    let start_x = (rect.left() / spacing).floor() * spacing + spacing / 2.0;
    let start_y = rect.top() - scroll_y.rem_euclid(spacing) + spacing / 2.0;

    let mut y = start_y;
    while y < rect.bottom() {
        let mut x = start_x;
        while x < rect.right() {
            painter.circle_filled(egui::pos2(x, y), radius, color);
            x += spacing;
        }
        y += spacing;
    }
}

fn paint_hatching(painter: &egui::Painter, rect: egui::Rect, color: egui::Color32) {
    let spacing = 12.0;
    let stroke = egui::Stroke::new(1.0, color);

    let h = rect.height();
    let mut x = rect.left() - h;
    while x < rect.right() + h {
        painter.line_segment(
            [egui::pos2(x, rect.top()), egui::pos2(x + h, rect.bottom())],
            stroke,
        );
        x += spacing;
    }
}

pub(crate) fn show_postit_tooltip(ui: &egui::Ui, response: &egui::Response, text: &str) {
    let outline = ui.visuals().widgets.noninteractive.bg_stroke.color;
    let shadow_color = crate::themes::ral(9004);
    let shadow = egui::epaint::Shadow {
        offset: [4, 4],
        blur: 0,
        spread: 0,
        color: shadow_color,
    };

    let frame = egui::Frame::new()
        .fill(crate::themes::ral(1003))
        .stroke(egui::Stroke::new(1.0, outline))
        .shadow(shadow)
        .corner_radius(0.0)
        .inner_margin(egui::Margin::same(10));

    let mut tooltip = egui::containers::Tooltip::for_enabled(response);
    tooltip.popup = tooltip.popup.frame(frame);
    tooltip.show(|ui| {
        ui.set_max_width(ui.spacing().tooltip_width);
        ui.add(
            egui::Label::new(
                egui::RichText::new(text)
                    .monospace()
                    .color(crate::themes::ral(9011)),
            )
            .wrap_mode(egui::TextWrapMode::Extend),
        );
    });
}

fn paint_card_tab_button(
    ui: &egui::Ui,
    response: &egui::Response,
    rect: egui::Rect,
    label: &str,
    fill: egui::Color32,
    pull_out: f32,
) {
    let outline = ui.visuals().widgets.noninteractive.bg_stroke.color;
    let stroke = egui::Stroke::new(1.0, outline);
    let rounding = egui::CornerRadius {
        nw: 0,
        ne: 4,
        sw: 0,
        se: 4,
    };
    let rect = if response.hovered() || response.has_focus() {
        egui::Rect::from_min_max(rect.min, egui::pos2(rect.max.x + pull_out, rect.max.y))
    } else {
        rect
    };

    ui.painter().rect_filled(rect, rounding, fill);
    ui.painter()
        .rect_stroke(rect, rounding, stroke, egui::StrokeKind::Inside);
    let text_color = if response.enabled() {
        crate::themes::ral(9011)
    } else {
        crate::themes::blend(crate::themes::ral(9011), fill, 0.55)
    };
    ui.painter().text(
        rect.center(),
        egui::Align2::CENTER_CENTER,
        label,
        egui::FontId::monospace(10.0),
        text_color,
    );
}

// notebook initialization is handled by the #[notebook] attribute macro.