installrs 0.1.0-rc10

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
//! Optional native wizard GUI and dialog helpers.
//!
//! Gated behind the `gui` feature. The backend is picked at compile time
//! via `gui-win32` (Win32 on Windows, using `winsafe`) or `gui-gtk`
//! (GTK3 on Linux, using `gtk-rs`). Both backends present the same
//! high-level API via [`InstallerGui`] and its page builders.
//!
//! Typical usage:
//!
//! ```rust,ignore
//! use installrs::gui::*;
//!
//! let mut w = InstallerGui::wizard("My App Installer");
//! w.welcome("Welcome!", "Click Next to continue.");
//! w.license("License", include_str!("../LICENSE"), "I accept");
//! w.components_page("Components", "Choose features:");
//! w.directory_picker("Install Location", "Install to:", "install-dir");
//! w.install_page(|i| {
//!     i.file(installrs::source!("app.exe"), "app.exe").install()?;
//!     i.uninstaller("uninstall.exe").install()?;
//!     Ok(())
//! });
//! w.finish_page("Done!", "Click Finish to exit.");
//! w.run(i)?;
//! ```
//!
//! The same wizard definition runs headless (no window) when the user
//! passes `--headless` — [`InstallerGui::run`] checks `installer.headless`
//! and dispatches accordingly.
//!
//! See the repository's [GUI Wizard guide] for the full walkthrough —
//! custom pages, error page, native dialogs, pre-wizard language
//! selector, and headless mode.
//!
//! [GUI Wizard guide]: https://github.com/merlinz01/InstallRS/blob/main/docs/gui-wizard.md

pub mod dialog;
mod types;

#[cfg(feature = "gui-win32")]
mod win32;

#[cfg(all(feature = "gui-gtk", not(feature = "gui-win32")))]
mod gtk;

pub use dialog::{choose_language, confirm, error, info, warn};

/// Install a PNG byte-slice as the default window icon for every GTK
/// window and dialog the wizard creates. No-op on Windows (icons come
/// from the embedded `.ico` resource) and on builds without a GTK
/// backend. InstallRS's build tool emits a call to this at the top of
/// the generated Linux `main.rs` when `[package.metadata.installrs].icon`
/// points at a PNG — user code shouldn't need to call it directly.
#[doc(hidden)]
pub fn __set_window_icon_png(bytes: &'static [u8]) {
    #[cfg(all(feature = "gui-gtk", not(feature = "gui-win32")))]
    {
        gtk::set_icon_bytes(bytes);
    }
    #[cfg(not(all(feature = "gui-gtk", not(feature = "gui-win32"))))]
    {
        let _ = bytes;
    }
}
pub use types::{
    ButtonLabels, ConfiguredPage, CustomPageBuilder, CustomWidget, ExitCallback, GuiMessage,
    InstallCallback, OnBeforeLeaveCallback, OnEnterCallback, StartCallback, WizardConfig,
    WizardPage,
};

use anyhow::Result;

use crate::Installer;

/// Builder for a wizard-style installer GUI.
///
/// Wizard configuration is statement-style — every method takes
/// `&mut self` and you call them on their own line. Page-adding methods
/// ([`welcome`](Self::welcome), [`license`](Self::license),
/// [`custom_page`](Self::custom_page), etc.) return a [`PageHandle`]
/// scoped to the page just added, so you can chain
/// [`on_enter`](PageHandle::on_enter),
/// [`on_before_leave`](PageHandle::on_before_leave), and
/// [`skip_if`](PageHandle::skip_if) on that handle.
///
/// # Example
///
/// ```rust,ignore
/// use installrs::gui::*;
///
/// let mut w = InstallerGui::wizard("My App Installer");
/// w.on_start(|i| { /* ... */ Ok(()) });
/// w.on_exit(|i| { /* ... */ Ok(()) });
/// w.welcome("Welcome!", "Click Next to continue.");
/// w.license("License", include_str!("../LICENSE"), "I accept")
///     .skip_if(|i| i.get_option::<bool>("accept-license").unwrap_or(false));
/// w.directory_picker("Install Location", "Install to:", "install-dir");
/// w.install_page(|i| {
///     i.set_status("Installing...");
///     // ... install files ...
///     i.set_progress(1.0);
///     i.set_status("Done!");
///     Ok(())
/// });
/// w.finish_page("Complete!", "Click Finish to exit.");
/// w.run(i)?;
/// ```
pub struct InstallerGui {
    config: WizardConfig,
}

impl InstallerGui {
    /// Create a new wizard builder. `title` is the window title shown by
    /// the OS — typically your app name plus "Installer".
    pub fn wizard(title: impl AsRef<str>) -> Self {
        Self {
            config: WizardConfig {
                title: title.as_ref().to_string(),
                pages: Vec::new(),
                buttons: ButtonLabels::default(),
                on_start: None,
                on_exit: None,
            },
        }
    }

    /// Set a callback that runs at wizard startup, before the window is
    /// shown (or before the install callback fires in headless mode).
    ///
    /// Inspect `installer.headless` inside the callback to branch on mode.
    /// Useful for work that must happen regardless of UI — environment
    /// setup, argument validation, prerequisite checks.
    pub fn on_start(&mut self, f: impl FnOnce(&mut Installer) -> Result<()> + 'static) {
        self.config.on_start = Some(Box::new(f));
    }

    /// Set a callback that runs at wizard exit, after the window closes (or
    /// after the install callback completes in headless mode). Runs even
    /// when the install flow fails.
    pub fn on_exit(&mut self, f: impl FnOnce(&mut Installer) -> Result<()> + 'static) {
        self.config.on_exit = Some(Box::new(f));
    }

    /// Override the navigation button labels (e.g. for translation).
    ///
    /// Use struct update syntax to override only specific labels:
    ///
    /// ```rust,ignore
    /// .buttons(ButtonLabels {
    ///     next: "Weiter".into(),
    ///     back: "Zurück".into(),
    ///     ..Default::default()
    /// })
    /// ```
    pub fn buttons(&mut self, labels: ButtonLabels) {
        self.config.buttons = labels;
    }

    /// Add a welcome page with a title and description message.
    pub fn welcome(&mut self, title: impl AsRef<str>, message: impl AsRef<str>) -> PageHandle<'_> {
        self.push_page(WizardPage::Welcome {
            title: title.as_ref().to_string(),
            message: message.as_ref().to_string(),
            widgets: Vec::new(),
        })
    }

    /// Add a license agreement page.
    ///
    /// `heading` is the title displayed above the license text, and `accept_label`
    /// is the label on the acceptance checkbox (both translatable by the caller).
    pub fn license(
        &mut self,
        heading: impl AsRef<str>,
        text: impl AsRef<str>,
        accept_label: impl AsRef<str>,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::License {
            heading: heading.as_ref().to_string(),
            text: text.as_ref().to_string(),
            accept_label: accept_label.as_ref().to_string(),
        })
    }

    /// Add a components page (list of checkboxes for optional features).
    ///
    /// Components must be registered on the `Installer` via
    /// [`Installer::component`](crate::Installer::component) before calling
    /// [`run`](Self::run). The page renders one checkbox per registered
    /// component; required components render greyed-out.
    ///
    /// `heading` is the bold title at the top; `label` is the intro sentence
    /// above the checkbox list (e.g. "Select the features to install:").
    pub fn components_page(
        &mut self,
        heading: impl AsRef<str>,
        label: impl AsRef<str>,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::Components {
            heading: heading.as_ref().to_string(),
            label: label.as_ref().to_string(),
        })
    }

    /// Add a directory picker page bound to a named installer option.
    ///
    /// `heading` is the bold title at the top of the page, `label` is the
    /// prompt next to the path input (e.g. "Install to:"), and `key` is the
    /// name of the [`crate::OptionValue::String`] option the picker reads
    /// and writes. Initial display value is the option's current value (or
    /// empty if unset) — seed it via `installer.set_option(key, ...)` (or
    /// the helper `set_option_default`) before [`run`](Self::run) for a
    /// sensible first-run default. The option is auto-registered as
    /// [`crate::OptionKind::String`] at `run()` if the user hasn't already
    /// registered it; register it explicitly before
    /// [`Installer::process_commandline`] if you want a `--<key>` CLI flag.
    ///
    /// User code is responsible for lifting the picked value into
    /// `installer.set_out_dir(...)` if relative-path resolution should
    /// honour it — typically inside the install callback:
    ///
    /// ```rust,ignore
    /// w.install_page(|i| {
    ///     i.set_out_dir(i.get_option::<String>("install-dir").unwrap_or_default());
    ///     // ...
    /// });
    /// ```
    pub fn directory_picker(
        &mut self,
        heading: impl AsRef<str>,
        label: impl AsRef<str>,
        key: impl AsRef<str>,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::DirectoryPicker {
            heading: heading.as_ref().to_string(),
            label: label.as_ref().to_string(),
            key: key.as_ref().to_string(),
        })
    }

    /// Add the install page with a callback that performs the actual installation.
    ///
    /// The callback receives `&mut Installer` directly. A progress sink
    /// that forwards to the install page is attached for the duration of
    /// the callback. The wizard does not implicitly call
    /// [`Installer::set_out_dir`] from a directory_picker page — lift the
    /// option value yourself if you want relative-path resolution.
    pub fn install_page(
        &mut self,
        callback: impl FnOnce(&mut Installer) -> Result<()> + Send + 'static,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::Install {
            callback: Box::new(callback),
            is_uninstall: false,
        })
    }

    /// Add an uninstall page — identical to [`install_page`](Self::install_page)
    /// except the Next button preceding it (and visible while the page is
    /// showing) uses `ButtonLabels::uninstall` ("Uninstall" by default) in
    /// place of `ButtonLabels::install`.
    pub fn uninstall_page(
        &mut self,
        callback: impl FnOnce(&mut Installer) -> Result<()> + Send + 'static,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::Install {
            callback: Box::new(callback),
            is_uninstall: true,
        })
    }

    /// Add a finish page shown after installation completes.
    pub fn finish_page(
        &mut self,
        title: impl AsRef<str>,
        message: impl AsRef<str>,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::Finish {
            title: title.as_ref().to_string(),
            message: message.as_ref().to_string(),
            widgets: Vec::new(),
        })
    }

    /// Add a custom page — a labeled column of text inputs, checkboxes,
    /// and dropdowns. Each widget is tied to an installer option by key:
    /// values are pre-filled from `installer.option_value(key)` (useful
    /// for CLI overrides), and written back to the options store on
    /// forward navigation. Validate via `.on_before_leave(...)` on the
    /// returned page handle:
    ///
    /// ```rust,ignore
    /// w.custom_page("Settings", "Configure your install:", |p| {
    ///     p.text("username", "Username:", "admin");
    ///     p.password("password", "Password:");
    ///     p.checkbox("desktop_shortcut", "Create a desktop shortcut", true);
    ///     p.dropdown(
    ///         "db_backend",
    ///         "Database:",
    ///         &[("sqlite", "SQLite"), ("postgres", "PostgreSQL")],
    ///         "sqlite",
    ///     );
    /// })
    /// .on_before_leave(|i| {
    ///     let u: String = i.get_option("username").unwrap_or_default();
    ///     if u.is_empty() {
    ///         installrs::gui::error("Required", "Enter a username.");
    ///         return Ok(false);
    ///     }
    ///     Ok(true)
    /// });
    /// ```
    pub fn custom_page(
        &mut self,
        heading: impl AsRef<str>,
        label: impl AsRef<str>,
        build: impl FnOnce(&mut CustomPageBuilder),
    ) -> PageHandle<'_> {
        let mut b = CustomPageBuilder::new();
        build(&mut b);
        self.push_page(WizardPage::Custom {
            heading: heading.as_ref().to_string(),
            label: label.as_ref().to_string(),
            widgets: b.widgets,
        })
    }

    /// Add an error page shown after the install page if the install
    /// callback returns an error or the user cancels mid-install. `title`
    /// is the bold heading; `message` is a user-facing description shown
    /// above the actual error text (which is filled in at runtime).
    ///
    /// If no error page is registered, install failures surface as a
    /// native error dialog instead.
    pub fn error_page(
        &mut self,
        title: impl AsRef<str>,
        message: impl AsRef<str>,
    ) -> PageHandle<'_> {
        self.push_page(WizardPage::Error {
            title: title.as_ref().to_string(),
            message: message.as_ref().to_string(),
        })
    }

    fn push_page(&mut self, page: WizardPage) -> PageHandle<'_> {
        self.config.pages.push(ConfiguredPage::new(page));
        PageHandle {
            page: self.config.pages.last_mut().unwrap(),
        }
    }

    /// Run the wizard GUI. This blocks until the user closes the window.
    ///
    /// On Windows with the `gui-win32` feature, this creates a native Win32 wizard.
    /// Falls back to an error on unsupported platforms.
    pub fn run(mut self, installer: &mut Installer) -> Result<()> {
        let on_start = self.config.on_start.take();
        let on_exit = self.config.on_exit.take();

        // Auto-register any directory_picker option keys not already
        // registered, so the picker's read/write via set_option works
        // without forcing the user to call `i.option(key, ...)`. Users
        // who want a `--<key>` CLI flag should still register the option
        // explicitly before `process_commandline()`.
        for configured in &self.config.pages {
            if let WizardPage::DirectoryPicker { key, .. } = &configured.page {
                if !installer.is_option_registered(key) {
                    installer.option(key.clone(), crate::OptionKind::String, "");
                }
            }
        }

        if let Some(cb) = on_start {
            cb(installer)?;
        }

        let result = if installer.headless {
            self.run_headless(installer)
        } else {
            self.run_platform(installer)
        };

        if let Some(cb) = on_exit {
            if let Err(e) = cb(installer) {
                eprintln!("on_exit error: {e:#}");
            }
        }

        result
    }

    /// Headless runner: pulls the install callback out of the pages and
    /// invokes it on the current thread. A default [`crate::StderrProgressSink`]
    /// is attached if the caller didn't already set one, so status / log /
    /// progress events surface readably on stderr.
    fn run_headless(self, installer: &mut Installer) -> Result<()> {
        // Extract install callback. Directory_picker pages are no-ops in
        // headless mode — user code reads / seeds the relevant option
        // directly and lifts it into out_dir as needed.
        let mut install_callback: Option<InstallCallback> = None;
        for configured in self.config.pages {
            if let WizardPage::Install { callback, .. } = configured.page {
                install_callback = Some(callback);
            }
        }

        // Attach a default stderr sink if none is already set, so headless
        // installs get readable feedback without extra setup.
        if !installer.has_progress_sink() {
            installer.set_progress_sink(Box::new(crate::StderrProgressSink::new()));
        }
        installer.reset_progress();

        let result = if let Some(cb) = install_callback {
            cb(installer)
        } else {
            Ok(())
        };

        if let Err(ref e) = result {
            installer.log_error(e);
        }

        // Detach the progress sink so its Drop runs now (the StderrProgressSink
        // finalizes its in-place progress line with a trailing newline) before
        // any subsequent `on_exit` stderr output prints.
        installer.clear_progress_sink();

        result
    }

    #[cfg(feature = "gui-win32")]
    fn run_platform(self, installer: &mut Installer) -> Result<()> {
        win32::run_wizard(self.config, installer)
    }

    #[cfg(all(feature = "gui-gtk", not(feature = "gui-win32")))]
    fn run_platform(self, installer: &mut Installer) -> Result<()> {
        gtk::run_wizard(self.config, installer)
    }

    #[cfg(all(feature = "gui", not(any(feature = "gui-win32", feature = "gui-gtk"))))]
    fn run_platform(self, _installer: &mut Installer) -> Result<()> {
        Err(anyhow::anyhow!(
            "No GUI backend available for this platform. Enable `gui-win32` on Windows or `gui-gtk` on Linux."
        ))
    }
}

/// Handle to the most recently added wizard page, returned by every
/// page-adding method on [`InstallerGui`]. Scope for attaching
/// page-specific callbacks — `on_enter`, `on_before_leave`, `skip_if`.
///
/// The handle borrows the wizard mutably, so it must be consumed (or
/// dropped) before the next page-adding call. In practice that means
/// one page per statement — which reads better than a 30-line chain
/// anyway.
pub struct PageHandle<'a> {
    page: &'a mut ConfiguredPage,
}

impl<'a> PageHandle<'a> {
    /// Attach an `on_enter` callback. Runs on the GUI thread after the
    /// page becomes visible, on forward navigation only.
    pub fn on_enter<F>(self, f: F) -> Self
    where
        F: Fn(&mut Installer) -> Result<()> + 'static,
    {
        self.page.on_enter = Some(Box::new(f));
        self
    }

    /// Attach an `on_before_leave` callback. Returning `Ok(false)`
    /// cancels navigation and keeps the page visible; `Err(_)` also
    /// cancels. Runs on forward navigation only.
    pub fn on_before_leave<F>(self, f: F) -> Self
    where
        F: Fn(&mut Installer) -> Result<bool> + 'static,
    {
        self.page.on_before_leave = Some(Box::new(f));
        self
    }

    /// Attach a `skip_if` predicate. Evaluated every time the wizard
    /// navigates past the page; returning `true` hides it. Must be pure
    /// — side effects belong in `on_enter`. Both Next and Back respect
    /// the skip, so a hidden page is also skipped on backward nav.
    ///
    /// ```rust,ignore
    /// w.license("License", include_str!("../LICENSE"), "I accept")
    ///     .skip_if(|i| i.get_option::<bool>("accept-license").unwrap_or(false));
    ///
    /// w.directory_picker("Install Location", "Install to:", default_dir)
    ///     .skip_if(|i| i.get_option::<String>("install-dir").is_some());
    /// ```
    pub fn skip_if<F>(self, f: F) -> Self
    where
        F: Fn(&Installer) -> bool + 'static,
    {
        self.page.skip_if = Some(Box::new(f));
        self
    }

    /// Append a column of input widgets below the page's main content.
    /// Supported on welcome and finish pages; calling on any other page
    /// kind panics. Widget keys bind to installer options exactly like
    /// [`custom_page`](InstallerGui::custom_page) — values pre-fill from
    /// the options store on entry and write back on forward navigation.
    ///
    /// ```rust,ignore
    /// w.finish_page("All done!", "Click Finish to exit.")
    ///     .with_widgets(|p| {
    ///         p.checkbox("launch_app", "Launch My App now", true);
    ///         p.checkbox("show_readme", "Show the README", false);
    ///     });
    /// ```
    pub fn with_widgets(self, build: impl FnOnce(&mut CustomPageBuilder)) -> Self {
        let mut b = CustomPageBuilder::new();
        build(&mut b);
        match &mut self.page.page {
            WizardPage::Welcome { widgets, .. } | WizardPage::Finish { widgets, .. } => {
                widgets.extend(b.widgets);
            }
            _ => panic!(
                "with_widgets is only supported on welcome and finish pages; \
                 use custom_page for other widget layouts"
            ),
        }
        self
    }
}