installrs 0.1.0-rc13

Build self-contained software installers in plain Rust, with an optional native wizard GUI (Win32 / GTK3), component selection, progress, cancellation, and compression.
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
use gtk::prelude::*;

const PAD: i32 = 20;
const SPACING: i32 = 10;

fn set_page_margins(w: &gtk::Box) {
    w.set_margin_top(PAD);
    w.set_margin_bottom(PAD);
    w.set_margin_start(PAD);
    w.set_margin_end(PAD);
}

fn bold_heading(text: &str, size: &str) -> gtk::Label {
    let label = gtk::Label::new(None);
    label.set_markup(&format!(
        "<span weight='bold' size='{size}'>{}</span>",
        glib::markup_escape_text(text)
    ));
    label.set_xalign(0.0);
    label.set_halign(gtk::Align::Start);
    label
}

#[allow(dead_code)]
pub enum PageKind {
    Welcome(WelcomePage),
    License(LicensePage),
    Components(ComponentsPage),
    DirectoryPicker(DirectoryPickerPage),
    Install(InstallPage),
    Finish(FinishPage),
    Error(ErrorPage),
    Custom(CustomPage),
}

// ── Welcome Page ────────────────────────────────────────────────────────────

pub struct WelcomePage {
    widget: gtk::Box,
    controls: Vec<(String, CustomControl)>,
}

impl WelcomePage {
    pub fn new(
        title: &str,
        message: &str,
        widgets: &[crate::gui::CustomWidget],
        initial: &std::collections::HashMap<String, crate::OptionValue>,
    ) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(title, "x-large"), false, false, 0);

        let msg = gtk::Label::new(Some(message));
        msg.set_xalign(0.0);
        msg.set_yalign(0.0);
        msg.set_halign(gtk::Align::Start);
        msg.set_valign(gtk::Align::Start);
        msg.set_line_wrap(true);
        vbox.pack_start(&msg, widgets.is_empty(), widgets.is_empty(), 0);

        let controls = if widgets.is_empty() {
            Vec::new()
        } else {
            let inner = gtk::Box::new(gtk::Orientation::Vertical, 6);
            inner.set_margin_top(12);
            inner.set_valign(gtk::Align::Start);
            let c = pack_widget_column(&inner, widgets, initial);
            vbox.pack_start(&inner, true, true, 0);
            c
        };

        Self {
            widget: vbox,
            controls,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn collect_values(&self) -> Vec<(String, crate::OptionValue)> {
        collect_widget_values(&self.controls)
    }
}

// ── License Page ────────────────────────────────────────────────────────────

pub struct LicensePage {
    widget: gtk::Box,
    accept_check: gtk::CheckButton,
}

impl LicensePage {
    pub fn new(heading: &str, text: &str, accept_label: &str) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(heading, "large"), false, false, 0);

        let scrolled = gtk::ScrolledWindow::builder()
            .vexpand(true)
            .hexpand(true)
            .shadow_type(gtk::ShadowType::In)
            .build();
        let text_view = gtk::TextView::new();
        text_view.set_editable(false);
        text_view.set_cursor_visible(false);
        text_view.set_wrap_mode(gtk::WrapMode::Word);
        text_view
            .buffer()
            .expect("TextView has no buffer")
            .set_text(text);
        scrolled.add(&text_view);
        vbox.pack_start(&scrolled, true, true, 0);

        let accept_check = gtk::CheckButton::with_label(accept_label);
        vbox.pack_start(&accept_check, false, false, 0);

        Self {
            widget: vbox,
            accept_check,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn is_accepted(&self) -> bool {
        self.accept_check.is_active()
    }

    pub fn on_accept_changed<F>(&self, f: F)
    where
        F: Fn() + 'static,
    {
        self.accept_check.connect_toggled(move |_| f());
    }

    /// Place keyboard focus on the accept checkbox so the user can toggle
    /// it with Space without first clicking. Used as the License page's
    /// default focus instead of the wizard's Next button.
    pub fn focus_accept(&self) {
        self.accept_check.grab_focus();
    }
}

// ── Directory Picker Page ───────────────────────────────────────────────────

pub struct DirectoryPickerPage {
    widget: gtk::Box,
    entry: gtk::Entry,
    key: String,
}

impl DirectoryPickerPage {
    pub fn new(heading: &str, label_text: &str, key: &str, initial: &str) -> Self {
        let default = initial;
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(heading, "large"), false, false, 0);

        let label = gtk::Label::new(Some(label_text));
        label.set_xalign(0.0);
        label.set_halign(gtk::Align::Start);
        vbox.pack_start(&label, false, false, 0);

        let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 6);
        let entry = gtk::Entry::new();
        entry.set_text(default);
        entry.set_hexpand(true);
        hbox.pack_start(&entry, true, true, 0);

        let browse_btn = gtk::Button::with_label("Browse...");
        hbox.pack_start(&browse_btn, false, false, 0);
        vbox.pack_start(&hbox, false, false, 0);

        {
            let entry_c = entry.clone();
            browse_btn.connect_clicked(move |btn| {
                let parent = btn
                    .toplevel()
                    .and_then(|w| w.downcast::<gtk::Window>().ok());
                let dialog = gtk::FileChooserDialog::with_buttons(
                    Some("Select Folder"),
                    parent.as_ref(),
                    gtk::FileChooserAction::SelectFolder,
                    &[
                        ("Cancel", gtk::ResponseType::Cancel),
                        ("Select", gtk::ResponseType::Accept),
                    ],
                );
                let current = entry_c.text().to_string();
                if !current.is_empty() {
                    let _ = dialog.set_current_folder(&current);
                }
                let response = dialog.run();
                if response == gtk::ResponseType::Accept {
                    if let Some(path) = dialog.filename() {
                        entry_c.set_text(&path.to_string_lossy());
                    }
                }
                unsafe {
                    dialog.destroy();
                }
            });
        }

        Self {
            widget: vbox,
            entry,
            key: key.to_string(),
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn get_directory(&self) -> String {
        self.entry.text().to_string()
    }

    pub fn key(&self) -> &str {
        &self.key
    }
}

// ── Components Page ─────────────────────────────────────────────────────────

pub struct ComponentsPage {
    widget: gtk::Box,
    checks: Vec<(String, gtk::CheckButton)>,
    _desc_label: gtk::Label,
}

impl ComponentsPage {
    pub fn new(heading: &str, label_text: &str, components: &[crate::Component]) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(heading, "large"), false, false, 0);

        let label = gtk::Label::new(Some(label_text));
        label.set_xalign(0.0);
        label.set_halign(gtk::Align::Start);
        vbox.pack_start(&label, false, false, 0);

        let scrolled = gtk::ScrolledWindow::builder()
            .vexpand(true)
            .hexpand(true)
            .shadow_type(gtk::ShadowType::In)
            .hscrollbar_policy(gtk::PolicyType::Never)
            .vscrollbar_policy(gtk::PolicyType::Automatic)
            .min_content_height(120)
            .build();
        let list_box = gtk::Box::new(gtk::Orientation::Vertical, 4);
        list_box.set_margin_top(6);
        list_box.set_margin_bottom(6);
        list_box.set_margin_start(6);
        list_box.set_margin_end(6);
        list_box.set_valign(gtk::Align::Start);

        let desc_label = gtk::Label::new(None);
        desc_label.set_xalign(0.0);
        desc_label.set_yalign(0.0);
        desc_label.set_halign(gtk::Align::Start);
        desc_label.set_valign(gtk::Align::Start);
        desc_label.set_line_wrap(true);
        desc_label.set_size_request(-1, 40);

        let mut checks: Vec<(String, gtk::CheckButton)> = Vec::new();
        for c in components {
            let display = if c.required {
                format!("{} (required)", c.label)
            } else {
                c.label.clone()
            };
            let cb = gtk::CheckButton::with_label(&display);
            cb.set_active(c.selected);
            if c.required {
                // Keep the widget sensitive so it still receives hover events —
                // setting sensitive = false silently swallows enter-notify.
                // Instead, fade it via opacity and revert toggle attempts.
                cb.set_opacity(0.5);
                cb.connect_toggled(|btn| {
                    if !btn.is_active() {
                        btn.set_active(true);
                    }
                });
            }
            cb.add_events(
                gtk::gdk::EventMask::ENTER_NOTIFY_MASK | gtk::gdk::EventMask::LEAVE_NOTIFY_MASK,
            );
            let desc_enter = desc_label.clone();
            let description = if c.description.is_empty() {
                c.label.clone()
            } else {
                c.description.clone()
            };
            cb.connect_enter_notify_event(move |_, _| {
                desc_enter.set_text(&description);
                glib::Propagation::Proceed
            });
            let desc_leave_cb = desc_label.clone();
            cb.connect_leave_notify_event(move |_, _| {
                desc_leave_cb.set_text("");
                glib::Propagation::Proceed
            });
            list_box.pack_start(&cb, false, false, 0);
            checks.push((c.id.clone(), cb));
        }

        scrolled.add(&list_box);
        vbox.pack_start(&scrolled, true, true, 0);
        vbox.pack_start(&desc_label, false, false, 0);

        // Clear the description when the cursor leaves the list.
        scrolled.add_events(gtk::gdk::EventMask::LEAVE_NOTIFY_MASK);
        let desc_leave = desc_label.clone();
        scrolled.connect_leave_notify_event(move |_, _| {
            desc_leave.set_text("");
            glib::Propagation::Proceed
        });

        Self {
            widget: vbox,
            checks,
            _desc_label: desc_label,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn selections(&self) -> Vec<(String, bool)> {
        self.checks
            .iter()
            .map(|(id, cb)| (id.clone(), cb.is_active()))
            .collect()
    }
}

// ── Install Page ────────────────────────────────────────────────────────────

pub struct InstallPage {
    widget: gtk::Box,
    status_label: gtk::Label,
    progress_bar: gtk::ProgressBar,
    log: Option<(gtk::TextBuffer, gtk::TextView)>,
}

impl InstallPage {
    pub fn new(show_log: bool) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        let status_label = gtk::Label::new(Some("Waiting to start..."));
        status_label.set_xalign(0.0);
        status_label.set_halign(gtk::Align::Start);
        vbox.pack_start(&status_label, false, false, 0);

        let progress_bar = gtk::ProgressBar::new();
        vbox.pack_start(&progress_bar, false, false, 0);

        let log = if show_log {
            let scrolled = gtk::ScrolledWindow::builder()
                .vexpand(true)
                .hexpand(true)
                .shadow_type(gtk::ShadowType::In)
                .build();
            let log_view = gtk::TextView::new();
            log_view.set_editable(false);
            log_view.set_cursor_visible(false);
            log_view.set_wrap_mode(gtk::WrapMode::WordChar);
            let log_buffer = log_view.buffer().expect("TextView has no buffer");
            scrolled.add(&log_view);
            vbox.pack_start(&scrolled, true, true, 0);
            Some((log_buffer, log_view))
        } else {
            None
        };

        Self {
            widget: vbox,
            status_label,
            progress_bar,
            log,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn set_status(&self, status: &str) {
        self.status_label.set_text(status);
    }

    pub fn set_progress(&self, progress: f64) {
        self.progress_bar.set_fraction(progress.clamp(0.0, 1.0));
    }

    pub fn append_log(&self, message: &str) {
        let Some((log_buffer, log_view)) = self.log.as_ref() else {
            return;
        };
        let mut end = log_buffer.end_iter();
        let text = if log_buffer.char_count() == 0 {
            message.to_string()
        } else {
            format!("\n{message}")
        };
        log_buffer.insert(&mut end, &text);
        if let Some(end_mark) = log_buffer.create_mark(None, &log_buffer.end_iter(), false) {
            log_view.scroll_to_mark(&end_mark, 0.0, true, 0.0, 1.0);
            log_buffer.delete_mark(&end_mark);
        }
    }
}

// ── Custom Page ─────────────────────────────────────────────────────────────

enum CustomControl {
    Text(gtk::Entry),
    Number(gtk::Entry),
    Multiline(gtk::TextBuffer),
    Checkbox(gtk::CheckButton),
    Dropdown {
        combo: gtk::ComboBoxText,
        values: Vec<String>,
    },
    Radio {
        buttons: Vec<gtk::RadioButton>,
        values: Vec<String>,
    },
    PathPicker(gtk::Entry),
}

pub struct CustomPage {
    widget: gtk::Box,
    controls: Vec<(String, CustomControl)>,
}

impl CustomPage {
    pub fn new(
        heading: &str,
        label_text: &str,
        widgets: &[crate::gui::CustomWidget],
        initial: &std::collections::HashMap<String, crate::OptionValue>,
    ) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(heading, "large"), false, false, 0);

        let label = gtk::Label::new(Some(label_text));
        label.set_xalign(0.0);
        label.set_halign(gtk::Align::Start);
        vbox.pack_start(&label, false, false, 0);

        let inner = gtk::Box::new(gtk::Orientation::Vertical, 6);
        inner.set_margin_top(6);
        inner.set_margin_bottom(6);
        inner.set_valign(gtk::Align::Start);

        let controls = pack_widget_column(&inner, widgets, initial);

        vbox.pack_start(&inner, true, true, 0);

        Self {
            widget: vbox,
            controls,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    /// Read the current value of every widget, keyed by option name.
    pub fn collect_values(&self) -> Vec<(String, crate::OptionValue)> {
        collect_widget_values(&self.controls)
    }
}

fn collect_widget_values(
    controls: &[(String, CustomControl)],
) -> Vec<(String, crate::OptionValue)> {
    let mut out = Vec::new();
    for (key, ctl) in controls {
        let val = match ctl {
            CustomControl::Text(entry) => crate::OptionValue::String(entry.text().to_string()),
            CustomControl::Number(entry) => {
                let t = entry.text().to_string();
                crate::OptionValue::Int(t.trim().parse::<i64>().unwrap_or(0))
            }
            CustomControl::Multiline(buffer) => {
                let (start, end) = (buffer.start_iter(), buffer.end_iter());
                let text = buffer.text(&start, &end, false);
                crate::OptionValue::String(text.map(|s| s.to_string()).unwrap_or_default())
            }
            CustomControl::Checkbox(check) => crate::OptionValue::Bool(check.is_active()),
            CustomControl::Dropdown { combo, values } => {
                let idx = combo.active().unwrap_or(0) as usize;
                let v = values.get(idx).cloned().unwrap_or_default();
                crate::OptionValue::String(v)
            }
            CustomControl::Radio { buttons, values } => {
                let idx = buttons.iter().position(|b| b.is_active()).unwrap_or(0);
                let v = values.get(idx).cloned().unwrap_or_default();
                crate::OptionValue::String(v)
            }
            CustomControl::PathPicker(entry) => {
                crate::OptionValue::String(entry.text().to_string())
            }
        };
        out.push((key.clone(), val));
    }
    out
}

fn pack_widget_column(
    inner: &gtk::Box,
    widgets: &[crate::gui::CustomWidget],
    initial: &std::collections::HashMap<String, crate::OptionValue>,
) -> Vec<(String, CustomControl)> {
    let mut controls: Vec<(String, CustomControl)> = Vec::new();
    {
        for w in widgets {
            use crate::gui::CustomWidget;
            match w {
                CustomWidget::Text {
                    key,
                    label: lbl,
                    default,
                    password,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let entry = gtk::Entry::new();
                    let initial_text = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    entry.set_text(&initial_text);
                    if *password {
                        entry.set_visibility(false);
                        entry.set_invisible_char(Some('\u{2022}'));
                    }
                    inner.pack_start(&entry, false, false, 0);
                    controls.push((key.clone(), CustomControl::Text(entry)));
                }
                CustomWidget::Checkbox {
                    key,
                    label: lbl,
                    default,
                } => {
                    let check = gtk::CheckButton::with_label(lbl);
                    let initial_val = match initial.get(key) {
                        Some(crate::OptionValue::Flag(b)) | Some(crate::OptionValue::Bool(b)) => *b,
                        _ => *default,
                    };
                    check.set_active(initial_val);
                    inner.pack_start(&check, false, false, 0);
                    controls.push((key.clone(), CustomControl::Checkbox(check)));
                }
                CustomWidget::Dropdown {
                    key,
                    label: lbl,
                    choices,
                    default,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let combo = gtk::ComboBoxText::new();
                    let values: Vec<String> = choices.iter().map(|(v, _)| v.clone()).collect();
                    for (_, display) in choices {
                        combo.append_text(display);
                    }
                    let current = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    let idx = values.iter().position(|v| v == &current).unwrap_or(0);
                    combo.set_active(Some(idx as u32));
                    inner.pack_start(&combo, false, false, 0);
                    controls.push((key.clone(), CustomControl::Dropdown { combo, values }));
                }
                CustomWidget::Radio {
                    key,
                    label: lbl,
                    choices,
                    default,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let current = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    let values: Vec<String> = choices.iter().map(|(v, _)| v.clone()).collect();
                    let mut buttons: Vec<gtk::RadioButton> = Vec::new();
                    let rb_box = gtk::Box::new(gtk::Orientation::Vertical, 2);
                    rb_box.set_margin_start(8);
                    for (idx, (val, disp)) in choices.iter().enumerate() {
                        let rb = if idx == 0 {
                            gtk::RadioButton::with_label(disp)
                        } else {
                            gtk::RadioButton::with_label_from_widget(&buttons[0], disp)
                        };
                        if *val == current {
                            rb.set_active(true);
                        }
                        rb_box.pack_start(&rb, false, false, 0);
                        buttons.push(rb);
                    }
                    inner.pack_start(&rb_box, false, false, 0);
                    controls.push((key.clone(), CustomControl::Radio { buttons, values }));
                }
                CustomWidget::Number {
                    key,
                    label: lbl,
                    default,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let entry = gtk::Entry::new();
                    // Restrict to optional sign + digits.
                    entry.connect_insert_text(|entry, text, position| {
                        if !text.chars().all(|c| c.is_ascii_digit() || c == '-') {
                            gtk::glib::signal::signal_stop_emission_by_name(entry, "insert-text");
                            let _ = position;
                        }
                    });
                    let initial_text = match initial.get(key) {
                        Some(crate::OptionValue::Int(n)) => n.to_string(),
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.to_string(),
                    };
                    entry.set_text(&initial_text);
                    inner.pack_start(&entry, false, false, 0);
                    controls.push((key.clone(), CustomControl::Number(entry)));
                }
                CustomWidget::Multiline {
                    key,
                    label: lbl,
                    default,
                    rows,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let sw = gtk::ScrolledWindow::builder()
                        .hexpand(true)
                        .shadow_type(gtk::ShadowType::In)
                        .min_content_height((*rows as i32).max(2) * 22)
                        .build();
                    let tv = gtk::TextView::new();
                    tv.set_wrap_mode(gtk::WrapMode::WordChar);
                    tv.set_left_margin(6);
                    tv.set_right_margin(6);
                    tv.set_top_margin(4);
                    tv.set_bottom_margin(4);
                    let buffer = tv.buffer().expect("TextView has no buffer");
                    let initial_text = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    buffer.set_text(&initial_text);
                    sw.add(&tv);
                    inner.pack_start(&sw, false, false, 0);
                    controls.push((key.clone(), CustomControl::Multiline(buffer)));
                }
                CustomWidget::FilePicker {
                    key,
                    label: lbl,
                    default,
                    filters,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 6);
                    let entry = gtk::Entry::new();
                    entry.set_hexpand(true);
                    let initial_text = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    entry.set_text(&initial_text);
                    hbox.pack_start(&entry, true, true, 0);
                    let browse_btn = gtk::Button::with_label("Browse...");
                    hbox.pack_start(&browse_btn, false, false, 0);
                    inner.pack_start(&hbox, false, false, 0);

                    let entry_c = entry.clone();
                    let filters_owned: Vec<(String, String)> = filters.clone();
                    browse_btn.connect_clicked(move |btn| {
                        let parent = btn
                            .toplevel()
                            .and_then(|w| w.downcast::<gtk::Window>().ok());
                        let dialog = gtk::FileChooserDialog::with_buttons(
                            Some("Select File"),
                            parent.as_ref(),
                            gtk::FileChooserAction::Open,
                            &[
                                ("Cancel", gtk::ResponseType::Cancel),
                                ("Select", gtk::ResponseType::Accept),
                            ],
                        );
                        for (name, glob) in &filters_owned {
                            let f = gtk::FileFilter::new();
                            f.set_name(Some(name));
                            for pat in glob.split(';') {
                                let pat = pat.trim();
                                if !pat.is_empty() {
                                    f.add_pattern(pat);
                                }
                            }
                            dialog.add_filter(f);
                        }
                        if dialog.run() == gtk::ResponseType::Accept {
                            if let Some(path) = dialog.filename() {
                                entry_c.set_text(&path.to_string_lossy());
                            }
                        }
                        unsafe {
                            dialog.destroy();
                        }
                    });
                    controls.push((key.clone(), CustomControl::PathPicker(entry)));
                }
                CustomWidget::DirPicker {
                    key,
                    label: lbl,
                    default,
                } => {
                    let lbl_ctl = gtk::Label::new(Some(lbl));
                    lbl_ctl.set_xalign(0.0);
                    lbl_ctl.set_halign(gtk::Align::Start);
                    inner.pack_start(&lbl_ctl, false, false, 0);

                    let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 6);
                    let entry = gtk::Entry::new();
                    entry.set_hexpand(true);
                    let initial_text = match initial.get(key) {
                        Some(crate::OptionValue::String(s)) => s.clone(),
                        _ => default.clone(),
                    };
                    entry.set_text(&initial_text);
                    hbox.pack_start(&entry, true, true, 0);
                    let browse_btn = gtk::Button::with_label("Browse...");
                    hbox.pack_start(&browse_btn, false, false, 0);
                    inner.pack_start(&hbox, false, false, 0);

                    let entry_c = entry.clone();
                    browse_btn.connect_clicked(move |btn| {
                        let parent = btn
                            .toplevel()
                            .and_then(|w| w.downcast::<gtk::Window>().ok());
                        let dialog = gtk::FileChooserDialog::with_buttons(
                            Some("Select Folder"),
                            parent.as_ref(),
                            gtk::FileChooserAction::SelectFolder,
                            &[
                                ("Cancel", gtk::ResponseType::Cancel),
                                ("Select", gtk::ResponseType::Accept),
                            ],
                        );
                        let current = entry_c.text().to_string();
                        if !current.is_empty() {
                            let _ = dialog.set_current_folder(&current);
                        }
                        if dialog.run() == gtk::ResponseType::Accept {
                            if let Some(path) = dialog.filename() {
                                entry_c.set_text(&path.to_string_lossy());
                            }
                        }
                        unsafe {
                            dialog.destroy();
                        }
                    });
                    controls.push((key.clone(), CustomControl::PathPicker(entry)));
                }
            }
        }
    }
    controls
}

// ── Error Page ──────────────────────────────────────────────────────────────

pub struct ErrorPage {
    widget: gtk::Box,
    error_buffer: gtk::TextBuffer,
}

impl ErrorPage {
    pub fn new(title: &str, message: &str) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(title, "x-large"), false, false, 0);

        let msg = gtk::Label::new(Some(message));
        msg.set_xalign(0.0);
        msg.set_halign(gtk::Align::Start);
        msg.set_line_wrap(true);
        vbox.pack_start(&msg, false, false, 0);

        let scrolled = gtk::ScrolledWindow::builder()
            .vexpand(true)
            .hexpand(true)
            .shadow_type(gtk::ShadowType::In)
            .build();
        let text_view = gtk::TextView::new();
        text_view.set_editable(false);
        text_view.set_cursor_visible(false);
        text_view.set_wrap_mode(gtk::WrapMode::WordChar);
        text_view.set_monospace(true);
        text_view.set_left_margin(8);
        text_view.set_right_margin(8);
        text_view.set_top_margin(6);
        text_view.set_bottom_margin(6);
        let error_buffer = text_view.buffer().expect("TextView has no buffer");
        scrolled.add(&text_view);
        vbox.pack_start(&scrolled, true, true, 0);

        Self {
            widget: vbox,
            error_buffer,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn set_error_text(&self, text: &str) {
        self.error_buffer.set_text(text);
    }
}

// ── Finish Page ─────────────────────────────────────────────────────────────

pub struct FinishPage {
    widget: gtk::Box,
    controls: Vec<(String, CustomControl)>,
}

impl FinishPage {
    pub fn new(
        title: &str,
        message: &str,
        widgets: &[crate::gui::CustomWidget],
        initial: &std::collections::HashMap<String, crate::OptionValue>,
    ) -> Self {
        let vbox = gtk::Box::new(gtk::Orientation::Vertical, SPACING);
        set_page_margins(&vbox);

        vbox.pack_start(&bold_heading(title, "x-large"), false, false, 0);

        let msg = gtk::Label::new(Some(message));
        msg.set_xalign(0.0);
        msg.set_yalign(0.0);
        msg.set_halign(gtk::Align::Start);
        msg.set_valign(gtk::Align::Start);
        msg.set_line_wrap(true);
        vbox.pack_start(&msg, widgets.is_empty(), widgets.is_empty(), 0);

        let controls = if widgets.is_empty() {
            Vec::new()
        } else {
            let inner = gtk::Box::new(gtk::Orientation::Vertical, 6);
            inner.set_margin_top(12);
            inner.set_valign(gtk::Align::Start);
            let c = pack_widget_column(&inner, widgets, initial);
            vbox.pack_start(&inner, true, true, 0);
            c
        };

        Self {
            widget: vbox,
            controls,
        }
    }

    pub fn widget(&self) -> &gtk::Box {
        &self.widget
    }

    pub fn collect_values(&self) -> Vec<(String, crate::OptionValue)> {
        collect_widget_values(&self.controls)
    }
}