any-dialog 1.0.0

Simple dialogs via kdialog, zenity, osascript, or PowerShell. Zero dependencies.
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
//! Simple desktop dialogs via whatever dialog helper the system
//! already has: `kdialog` or `zenity` on Linux, `osascript` on
//! macOS, or PowerShell on Windows. The crate links no GUI
//! toolkit, has zero dependencies, and uses only the standard
//! library.
//!
//! [`Dialogs::new`] probes `PATH` for a helper, preferring the
//! operating system's own bundled tool on macOS and Windows, and
//! every method on the handle renders through the helper it
//! found. If no helper exists, calls fail with
//! [`Error::NoBackend`]; check [`Dialogs::available`] first if
//! that matters.
//!
//! Prompt methods return `Ok(None)` when the user cancels, so a
//! cancel is a value to handle, not an error:
//!
//! ```no_run
//! use any_dialog::Dialogs;
//!
//! fn main() -> Result<(), any_dialog::Error> {
//!     let dialogs = Dialogs::new();
//!     if let Some(name) = dialogs.prompt_text("Example", "Your name:", None)? {
//!         println!("hello, {name}");
//!     }
//!     Ok(())
//! }
//! ```
//!
//! Every call blocks until the user answers, so callers should
//! run them on a worker thread rather than on a UI or event-loop
//! thread.

mod backends;
mod error;
mod outcome;
mod request;

pub use backends::Backend;
pub use error::Error;
pub use request::{FileFilter, FileFilterBuilder};

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use backends::{argv, classify, decode_choices, env};
use outcome::Outcome;
use request::{Level, Request};

/// A handle to the best dialog backend found on this machine.
#[derive(Clone, Debug)]
pub struct Dialogs {
    backend: Option<(Backend, PathBuf)>,
}

impl Dialogs {
    /// Probe `PATH` for a backend, in the backends module's probe
    /// order.
    pub fn new() -> Dialogs {
        Dialogs {
            backend: backends::probe(),
        }
    }

    /// Build a handle from explicit executable paths, bypassing `PATH`.
    /// Primarily useful for tests. The first path present wins, in the
    /// order kdialog, zenity, osascript, powershell.
    pub fn with_paths(
        kdialog: Option<PathBuf>,
        zenity: Option<PathBuf>,
        osascript: Option<PathBuf>,
        powershell: Option<PathBuf>,
    ) -> Dialogs {
        let backend = kdialog
            .map(|path| (Backend::Kdialog, path))
            .or_else(|| zenity.map(|path| (Backend::Zenity, path)))
            .or_else(|| osascript.map(|path| (Backend::Osascript, path)))
            .or_else(|| powershell.map(|path| (Backend::Powershell, path)));
        Dialogs { backend }
    }

    /// Is there a backend to drive?
    pub fn available(&self) -> bool {
        self.backend.is_some()
    }

    /// Which backend this handle drives, if any. Mostly useful
    /// for logging and diagnostics: the dialogs themselves do
    /// not depend on which helper renders them.
    pub fn backend(&self) -> Option<Backend> {
        self.backend.as_ref().map(|(backend, _)| *backend)
    }

    /// Ask for a line of text. `Ok(None)` means the user cancelled.
    pub fn prompt_text(
        &self,
        title: &str,
        label: &str,
        initial: Option<&str>,
    ) -> Result<Option<String>, Error> {
        self.run(Request::Text {
            title,
            label,
            initial,
        })
    }

    /// Ask for a password or other secret. The text is hidden while
    /// typed. `Ok(None)` means the user cancelled.
    pub fn prompt_password(&self, title: &str, label: &str) -> Result<Option<String>, Error> {
        self.run(Request::Password { title, label })
    }

    /// Ask the user to pick one of `choices`. `Ok(None)` means they cancelled.
    #[allow(dead_code)] // part of the liftable adapter API; the tray has no picker yet
    pub fn prompt_choice(
        &self,
        title: &str,
        label: &str,
        choices: &[&str],
        current: Option<&str>,
    ) -> Result<Option<String>, Error> {
        self.run(Request::Choice {
            title,
            label,
            choices,
            current,
        })
    }

    /// Ask the user to pick any number of `choices`, starting with
    /// `current` checked. `Ok(None)` means they cancelled;
    /// `Ok(Some(vec![]))` means they confirmed with nothing picked.
    pub fn prompt_choices(
        &self,
        title: &str,
        label: &str,
        choices: &[&str],
        current: &[&str],
    ) -> Result<Option<Vec<String>>, Error> {
        let backend = self.backend.as_ref().map(|(backend, _)| *backend);
        let request = Request::Choices {
            title,
            label,
            choices,
            current,
        };
        match self.run_completed(request)? {
            // A run that answered implies a backend was there to
            // answer, so the decode always has its backend.
            Completed::Answered(Some(text)) => Ok(Some(decode_choices(
                backend.expect("an answered run has a backend"),
                &text,
                choices,
            ))),
            Completed::Answered(None) => Ok(Some(Vec::new())),
            Completed::Cancelled => Ok(None),
        }
    }

    /// Ask the user to pick a color, starting from `initial` (a
    /// `#rrggbb` string) where the backend supports one. The
    /// answer is normalized to lowercase `#rrggbb`. `Ok(None)`
    /// means the user cancelled.
    pub fn prompt_color(
        &self,
        title: &str,
        initial: Option<&str>,
    ) -> Result<Option<String>, Error> {
        match self.run(Request::Color { title, initial })? {
            Some(raw) => Ok(Some(normalize_color(&raw))),
            None => Ok(None),
        }
    }

    /// Ask the user to pick a file to open. `start` is where the
    /// dialog opens: a directory, or a file whose folder it opens
    /// on. `Ok(None)` means they cancelled.
    pub fn prompt_open_file(
        &self,
        title: &str,
        start: Option<&Path>,
        filters: &[FileFilter],
    ) -> Result<Option<PathBuf>, Error> {
        self.run(Request::OpenFile {
            title,
            start,
            filters,
            multiple: false,
        })
        .map(|answer| answer.map(PathBuf::from))
    }

    /// Ask the user to pick any number of files to open, starting
    /// at `start`. `Ok(None)` means they cancelled.
    pub fn prompt_open_files(
        &self,
        title: &str,
        start: Option<&Path>,
        filters: &[FileFilter],
    ) -> Result<Option<Vec<PathBuf>>, Error> {
        let request = Request::OpenFile {
            title,
            start,
            filters,
            multiple: true,
        };
        match self.run_completed(request)? {
            Completed::Answered(Some(text)) => Ok(Some(text.lines().map(PathBuf::from).collect())),
            Completed::Answered(None) => Ok(Some(Vec::new())),
            Completed::Cancelled => Ok(None),
        }
    }

    /// Ask the user to pick a file to save to. `start` may name a
    /// suggested file, whose name pre-fills the dialog where the
    /// backend supports it. Native overwrite confirmation is left
    /// to the dialog itself. `Ok(None)` means they cancelled.
    pub fn prompt_save_file(
        &self,
        title: &str,
        start: Option<&Path>,
        filters: &[FileFilter],
    ) -> Result<Option<PathBuf>, Error> {
        self.run(Request::SaveFile {
            title,
            start,
            filters,
        })
        .map(|answer| answer.map(PathBuf::from))
    }

    /// Ask the user to pick a folder, starting at `start`.
    /// `Ok(None)` means they cancelled.
    pub fn prompt_folder(
        &self,
        title: &str,
        start: Option<&Path>,
    ) -> Result<Option<PathBuf>, Error> {
        self.run(Request::Folder { title, start })
            .map(|answer| answer.map(PathBuf::from))
    }

    /// Show an informational message with a single dismiss button.
    pub fn show_info(&self, title: &str, message: &str) -> Result<(), Error> {
        self.run(Request::Message {
            title,
            message,
            level: Level::Info,
        })
        .map(|_| ())
    }

    /// Show a warning message with a single dismiss button.
    pub fn show_warning(&self, title: &str, message: &str) -> Result<(), Error> {
        self.run(Request::Message {
            title,
            message,
            level: Level::Warning,
        })
        .map(|_| ())
    }

    /// Show an error message with a single dismiss button.
    pub fn show_error(&self, title: &str, message: &str) -> Result<(), Error> {
        self.run(Request::Message {
            title,
            message,
            level: Level::Error,
        })
        .map(|_| ())
    }

    /// Ask a yes/no question. `Ok(true)` is yes; `Ok(false)` is no,
    /// and also covers the dialog being dismissed without answering,
    /// which most backends cannot tell apart from no.
    pub fn confirm(&self, title: &str, message: &str) -> Result<bool, Error> {
        match self.run_completed(Request::Confirm { title, message })? {
            Completed::Answered(Some(text)) => Ok(text == "yes"),
            Completed::Answered(None) => Ok(true),
            Completed::Cancelled => Ok(false),
        }
    }

    fn run(&self, request: Request<'_>) -> Result<Option<String>, Error> {
        match self.run_completed(request)? {
            Completed::Answered(text) => Ok(text),
            Completed::Cancelled => Ok(None),
        }
    }

    fn run_completed(&self, request: Request<'_>) -> Result<Completed, Error> {
        let Some((backend, program)) = &self.backend else {
            return Err(Error::NoBackend);
        };

        let mut command = Command::new(program);
        command.args(argv(*backend, &request)).stdin(Stdio::null());
        for (name, value) in env(*backend, &request) {
            command.env(name, value);
        }
        // powershell.exe is a console application. Spawned from
        // a GUI process (one with no console of its own, such as
        // an Explorer-launched exe), Windows would give it a
        // console window of its own, visible next to the dialog.
        // CREATE_NO_WINDOW suppresses that; the child's stdio is
        // piped, so it loses nothing it uses. Console parents
        // (terminals, the probe) are unaffected in practice: the
        // child simply does not share their console either, and
        // it never writes to one.
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            command.creation_flags(CREATE_NO_WINDOW);
        }

        let output = command.output().map_err(|source| Error::Spawn {
            program: program.clone(),
            source,
        })?;

        match classify(
            *backend,
            output.status.code(),
            &String::from_utf8_lossy(&output.stdout),
            &String::from_utf8_lossy(&output.stderr),
        ) {
            Outcome::Answered(text) => Ok(Completed::Answered(text)),
            Outcome::Cancelled => Ok(Completed::Cancelled),
            Outcome::Failed => Err(Error::Exit {
                program: program.clone(),
                status: output.status,
            }),
        }
    }
}

/// A dialog run that finished: either it was answered (with whatever
/// text the backend produced, if any) or it was cancelled. Failures
/// travel as `Err` instead, so this never carries [`Outcome::Failed`].
enum Completed {
    Answered(Option<String>),
    Cancelled,
}

/// Normalize a helper's color answer to lowercase `#rrggbb`.
/// kdialog, osascript, and PowerShell already answer in hex;
/// zenity answers in CSS `rgb()` / `rgba()` form. Anything
/// unrecognized passes through trimmed and lowercased, so a
/// helper changing its answer format degrades visibly instead of
/// silently corrupting the value.
fn normalize_color(raw: &str) -> String {
    let raw = raw.trim().to_lowercase();
    let hex = raw.strip_prefix('#');
    if hex.is_some_and(|hex| hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())) {
        return raw;
    }
    let inner = raw
        .strip_prefix("rgba(")
        .or_else(|| raw.strip_prefix("rgb("))
        .and_then(|rest| rest.strip_suffix(')'));
    if let Some(inner) = inner {
        let parts: Vec<&str> = inner.split(',').collect();
        let channel = |index: usize| {
            parts
                .get(index)
                .and_then(|part| part.trim().parse::<u32>().ok())
                .map(|value| value.min(255))
        };
        if let (Some(r), Some(g), Some(b)) = (channel(0), channel(1), channel(2)) {
            return format!("#{r:02x}{g:02x}{b:02x}");
        }
    }
    raw
}

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

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

    #[test]
    fn color_answers_normalize_to_lowercase_hex() {
        assert_eq!(normalize_color("#FF0080\n"), "#ff0080");
        assert_eq!(normalize_color("rgb(255, 0, 128)"), "#ff0080");
        assert_eq!(normalize_color("rgba(0, 128, 255, 0.5)"), "#0080ff");
        // Unrecognized formats pass through, visibly degraded
        // rather than silently rewritten.
        assert_eq!(normalize_color("surprise"), "surprise");
    }

    #[test]
    fn explicit_paths_choose_the_backend() {
        assert!(!Dialogs::with_paths(None, None, None, None).available());
        assert!(
            Dialogs::with_paths(Some(PathBuf::from("/bin/kdialog")), None, None, None).available()
        );
        assert!(
            Dialogs::with_paths(None, Some(PathBuf::from("/bin/zenity")), None, None).available()
        );
        assert!(
            Dialogs::with_paths(None, None, Some(PathBuf::from("/usr/bin/osascript")), None)
                .available()
        );
        assert!(
            Dialogs::with_paths(
                None,
                None,
                None,
                Some(PathBuf::from("/windows/system32/powershell.exe"))
            )
            .available()
        );
        assert_eq!(
            Dialogs::with_paths(None, Some(PathBuf::from("/bin/zenity")), None, None).backend(),
            Some(Backend::Zenity)
        );
        assert_eq!(Dialogs::with_paths(None, None, None, None).backend(), None);
    }
}