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
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
//! The osascript backend: how macOS's bundled script runner wants
//! each dialog said.
//!
//! Unlike the other helpers, osascript runs a script rather than
//! taking flags, so the scripts here are fixed text. User text is
//! never interpolated into a script: it travels as arguments to the
//! script's `run` handler instead (the arguments after the `-e`
//! lines), so no AppleScript escaping is needed anywhere. Each script
//! returns only the extracted value, never the raw result record, so
//! stdout stays a plain answer.
//!
//! Cancellation needs care. `display dialog` raises the "User
//! canceled" error (-128) itself, which osascript reports on stderr
//! with a nonzero exit. `choose from list` instead returns `false`,
//! so its script re-raises -128, giving every dialog the same cancel
//! signature. That signature is why this backend classifies results
//! itself instead of using [`crate::outcome`]: osascript also exits 1
//! for genuine script errors, so an exit code alone cannot tell a
//! cancel from a failure; the -128 marker on stderr can.

use crate::outcome::Outcome;
use crate::request::{Level, Request};

/// The helper program's name, as probed for on `PATH`.
pub(crate) const PROGRAM: &str = "osascript";

const TEXT_SCRIPT: &[&str] = &[
    "on run argv",
    "set answer to display dialog (item 2 of argv) default answer (item 3 of argv) with title (item 1 of argv)",
    "return text returned of answer",
    "end run",
];

const CHOICE_SCRIPT: &[&str] = &[
    "on run argv",
    "set choices to {}",
    "if (count of argv) > 3 then set choices to items 4 thru -1 of argv",
    "set picks to choose from list choices with title (item 1 of argv) with prompt (item 2 of argv) default items {(item 3 of argv)}",
    "if picks is false then error number -128",
    "return item 1 of picks",
    "end run",
];

const ERROR_SCRIPT: &[&str] = &[
    "on run argv",
    "display alert (item 1 of argv) message (item 2 of argv)",
    "return \"\"",
    "end run",
];

const PASSWORD_SCRIPT: &[&str] = &[
    "on run argv",
    "set answer to display dialog (item 2 of argv) default answer \"\" with title (item 1 of argv) hidden answer",
    "return text returned of answer",
    "end run",
];

/// Info and warning messages. Errors keep the sharper `display
/// alert` form above; these use `display dialog` because it is the
/// form that takes an icon: 1 is the application (note) icon, 2 is
/// caution. The icon number travels as a script argument like any
/// other value and is coerced to an integer inside the script.
const MESSAGE_SCRIPT: &[&str] = &[
    "on run argv",
    "display dialog (item 2 of argv) buttons {\"OK\"} default button \"OK\" with title (item 1 of argv) with icon (item 3 of argv as integer)",
    "return \"\"",
    "end run",
];

/// The buttons are named No and Yes rather than Cancel and OK on
/// purpose: a button named Cancel would raise -128 like a cancel,
/// making "no" indistinguishable from dismissing the dialog. As
/// written, no answers normally and only dismissal cancels.
const CONFIRM_SCRIPT: &[&str] = &[
    "on run argv",
    "set answer to display dialog (item 2 of argv) buttons {\"No\", \"Yes\"} default button \"Yes\" with title (item 1 of argv)",
    "if button returned of answer is \"Yes\" then return \"yes\"",
    "return \"no\"",
    "end run",
];

/// The argument layout differs from the single-choice script:
/// preselected items are variable in number here, so the data is
/// title, prompt, a count, that many preselected items, then the
/// choices themselves. The picks come back joined by linefeeds,
/// one per line like the other backends' multi answers.
const CHOICES_SCRIPT: &[&str] = &[
    "on run argv",
    "set n to (item 3 of argv) as integer",
    "set defaults to {}",
    "if n > 0 then set defaults to items 4 thru (3 + n) of argv",
    "set choices to {}",
    "if (count of argv) > (3 + n) then set choices to items (4 + n) thru -1 of argv",
    "set picks to choose from list choices with title (item 1 of argv) with prompt (item 2 of argv) default items defaults with multiple selections allowed",
    "if picks is false then error number -128",
    "set AppleScript's text item delimiters to linefeed",
    "return picks as string",
    "end run",
];

/// `choose color` takes no title, so the request's title is
/// dropped by this backend. It speaks in 16-bit RGB components:
/// the arguments are the initial color's components (converted
/// from `#rrggbb` in [`color_components`]), and the answer's
/// components are converted back to hex by the script's helper
/// handler. Cancelling raises -128, like the other choosers.
const COLOR_SCRIPT: &[&str] = &[
    "on hexpair(n)",
    "set digits to \"0123456789abcdef\"",
    "return (character ((n div 16) + 1) of digits) & (character ((n mod 16) + 1) of digits)",
    "end hexpair",
    "on run argv",
    "set rgb to choose color default color {(item 1 of argv) as integer, (item 2 of argv) as integer, (item 3 of argv) as integer}",
    "return \"#\" & hexpair((item 1 of rgb) div 257) & hexpair((item 2 of rgb) div 257) & hexpair((item 3 of rgb) div 257)",
    "end run",
];

/// The file choosers take a prompt, not a title, so the request's
/// title is the prompt text here. The argument layout is prompt,
/// start path (empty for none), an extension count, then that
/// many extensions: every named filter's extensions merged into
/// one flat list, because `choose file`'s `of type` is the only
/// filtering the chooser has. AppleScript cannot leave a clause
/// out conditionally, so each combination gets its own line and
/// exactly one of them runs. Cancelling raises -128.
const OPEN_FILE_SCRIPT: &[&str] = &[
    "on run argv",
    "set n to (item 3 of argv) as integer",
    "set types to {}",
    "if n > 0 then set types to items 4 thru (3 + n) of argv",
    "if (item 2 of argv) is \"\" and n = 0 then set pick to choose file with prompt (item 1 of argv)",
    "if (item 2 of argv) is \"\" and n > 0 then set pick to choose file with prompt (item 1 of argv) of type types",
    "if (item 2 of argv) is not \"\" and n = 0 then set pick to choose file with prompt (item 1 of argv) default location (POSIX file (item 2 of argv))",
    "if (item 2 of argv) is not \"\" and n > 0 then set pick to choose file with prompt (item 1 of argv) default location (POSIX file (item 2 of argv)) of type types",
    "return POSIX path of pick",
    "end run",
];

const OPEN_FILES_SCRIPT: &[&str] = &[
    "on run argv",
    "set n to (item 3 of argv) as integer",
    "set types to {}",
    "if n > 0 then set types to items 4 thru (3 + n) of argv",
    "if (item 2 of argv) is \"\" and n = 0 then set picks to choose file with prompt (item 1 of argv) with multiple selections allowed",
    "if (item 2 of argv) is \"\" and n > 0 then set picks to choose file with prompt (item 1 of argv) of type types with multiple selections allowed",
    "if (item 2 of argv) is not \"\" and n = 0 then set picks to choose file with prompt (item 1 of argv) default location (POSIX file (item 2 of argv)) with multiple selections allowed",
    "if (item 2 of argv) is not \"\" and n > 0 then set picks to choose file with prompt (item 1 of argv) default location (POSIX file (item 2 of argv)) of type types with multiple selections allowed",
    "set out to {}",
    "repeat with p in picks",
    "set end of out to POSIX path of p",
    "end repeat",
    "set AppleScript's text item delimiters to linefeed",
    "return out as string",
    "end run",
];

/// The arguments are prompt, folder, and file name: the crate
/// splits the suggested path in two (see `split_start`) because
/// splitting it in AppleScript would be miserable. `choose file
/// name` has no type filter, so save filters do not reach this
/// backend.
const SAVE_FILE_SCRIPT: &[&str] = &[
    "on run argv",
    "if (item 3 of argv) is \"\" then set pick to choose file name with prompt (item 1 of argv)",
    "if (item 3 of argv) is not \"\" and (item 2 of argv) is \"\" then set pick to choose file name with prompt (item 1 of argv) default name (item 3 of argv)",
    "if (item 3 of argv) is not \"\" and (item 2 of argv) is not \"\" then set pick to choose file name with prompt (item 1 of argv) default name (item 3 of argv) default location (POSIX file (item 2 of argv))",
    "return POSIX path of pick",
    "end run",
];

const FOLDER_SCRIPT: &[&str] = &[
    "on run argv",
    "if (item 2 of argv) is \"\" then set pick to choose folder with prompt (item 1 of argv)",
    "if (item 2 of argv) is not \"\" then set pick to choose folder with prompt (item 1 of argv) default location (POSIX file (item 2 of argv))",
    "return POSIX path of pick",
    "end run",
];

/// Split a save dialog's start path into the (folder, file name)
/// text pair SAVE_FILE_SCRIPT takes. Neither piece exists when
/// there is no start; a bare file name leaves the folder empty.
fn split_start(start: Option<&std::path::Path>) -> (String, String) {
    let Some(start) = start else {
        return (String::new(), String::new());
    };
    let dir = start.parent().map(super::path_text).unwrap_or_default();
    let name = start
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    (dir, name)
}

/// A `#rrggbb` initial color as the three 16-bit component
/// strings `choose color` wants. Missing or unparsable input
/// falls back to white.
fn color_components(initial: Option<&str>) -> [String; 3] {
    let rgb = initial
        .and_then(|text| text.strip_prefix('#'))
        .and_then(|hex| u32::from_str_radix(hex, 16).ok())
        .unwrap_or(0xff_ffff);
    [
        (((rgb >> 16) & 0xff) * 257).to_string(),
        (((rgb >> 8) & 0xff) * 257).to_string(),
        ((rgb & 0xff) * 257).to_string(),
    ]
}

/// Build the argument list for one request, excluding argv[0]: one
/// `-e` per script line, then the values the script reads from argv.
pub(crate) fn argv(request: &Request<'_>) -> Vec<String> {
    let (script, mut data): (&[&str], Vec<String>) = match *request {
        Request::Text {
            title,
            label,
            initial,
        } => (
            TEXT_SCRIPT,
            vec![
                title.to_string(),
                label.to_string(),
                initial.unwrap_or("").to_string(),
            ],
        ),
        Request::Choice {
            title,
            label,
            choices,
            current,
        } => {
            let mut data = vec![
                title.to_string(),
                label.to_string(),
                super::selected(choices, current).unwrap_or("").to_string(),
            ];
            data.extend(choices.iter().map(|choice| (*choice).to_string()));
            (CHOICE_SCRIPT, data)
        }
        Request::Password { title, label } => {
            (PASSWORD_SCRIPT, vec![title.to_string(), label.to_string()])
        }
        Request::Message {
            title,
            message,
            level,
        } => match level {
            Level::Error => (ERROR_SCRIPT, vec![title.to_string(), message.to_string()]),
            Level::Info => (
                MESSAGE_SCRIPT,
                vec![title.to_string(), message.to_string(), "1".to_string()],
            ),
            Level::Warning => (
                MESSAGE_SCRIPT,
                vec![title.to_string(), message.to_string(), "2".to_string()],
            ),
        },
        Request::Confirm { title, message } => {
            (CONFIRM_SCRIPT, vec![title.to_string(), message.to_string()])
        }
        Request::Choices {
            title,
            label,
            choices,
            current,
        } => {
            let defaults = super::selected_many(choices, current);
            let mut data = vec![
                title.to_string(),
                label.to_string(),
                defaults.len().to_string(),
            ];
            data.extend(defaults.iter().map(|choice| (*choice).to_string()));
            data.extend(choices.iter().map(|choice| (*choice).to_string()));
            (CHOICES_SCRIPT, data)
        }
        Request::Color { title: _, initial } => (
            COLOR_SCRIPT,
            color_components(initial).into_iter().collect(),
        ),
        Request::OpenFile {
            title,
            start,
            filters,
            multiple,
        } => {
            let extensions: Vec<&str> = filters
                .iter()
                .flat_map(|filter| filter.extensions.iter().copied())
                .collect();
            let mut data = vec![
                title.to_string(),
                start.map(super::path_text).unwrap_or_default(),
                extensions.len().to_string(),
            ];
            data.extend(extensions.iter().map(|extension| (*extension).to_string()));
            if multiple {
                (OPEN_FILES_SCRIPT, data)
            } else {
                (OPEN_FILE_SCRIPT, data)
            }
        }
        Request::SaveFile {
            title,
            start,
            filters: _,
        } => {
            let (dir, name) = split_start(start);
            (SAVE_FILE_SCRIPT, vec![title.to_string(), dir, name])
        }
        Request::Folder { title, start } => (
            FOLDER_SCRIPT,
            vec![
                title.to_string(),
                start.map(super::path_text).unwrap_or_default(),
            ],
        ),
    };

    let mut args = Vec::new();
    for line in script {
        args.push("-e".to_string());
        args.push((*line).to_string());
    }
    args.append(&mut data);
    args
}

/// Interpret an osascript run. Success reuses the shared reading of
/// stdout; a failure counts as a cancel only when stderr carries the
/// -128 "User canceled" marker.
pub(crate) fn classify(exit_code: Option<i32>, stdout: &str, stderr: &str) -> Outcome {
    match exit_code {
        Some(0) => crate::outcome::classify(Some(0), stdout),
        Some(1) if stderr.contains("(-128)") => Outcome::Cancelled,
        _ => Outcome::Failed,
    }
}

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

    fn args(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| (*item).to_string()).collect()
    }

    #[test]
    fn osascript_text_argv_passes_values_as_script_arguments() {
        let request = Request::Text {
            title: "Title",
            label: "Label",
            initial: Some("1.00"),
        };
        assert_eq!(
            argv(&request),
            args(&[
                "-e",
                "on run argv",
                "-e",
                "set answer to display dialog (item 2 of argv) default answer (item 3 of argv) with title (item 1 of argv)",
                "-e",
                "return text returned of answer",
                "-e",
                "end run",
                "Title",
                "Label",
                "1.00",
            ])
        );

        let without_initial = Request::Text {
            title: "Title",
            label: "Label",
            initial: None,
        };
        assert_eq!(argv(&without_initial).last().map(String::as_str), Some(""));
    }

    #[test]
    fn osascript_choice_argv_appends_choices_after_the_selection() {
        let request = Request::Choice {
            title: "Title",
            label: "Label",
            choices: &["a", "b"],
            current: Some("b"),
        };
        let argv = argv(&request);
        assert_eq!(
            &argv[argv.len() - 5..],
            args(&["Title", "Label", "b", "a", "b"]).as_slice()
        );
    }

    #[test]
    fn osascript_password_argv_passes_values_as_script_arguments() {
        let request = Request::Password {
            title: "Title",
            label: "Label",
        };
        assert_eq!(
            argv(&request),
            args(&[
                "-e",
                "on run argv",
                "-e",
                "set answer to display dialog (item 2 of argv) default answer \"\" with title (item 1 of argv) hidden answer",
                "-e",
                "return text returned of answer",
                "-e",
                "end run",
                "Title",
                "Label",
            ])
        );
    }

    #[test]
    fn osascript_error_message_argv_uses_the_alert_script() {
        let request = Request::Message {
            title: "Title",
            message: "Message",
            level: Level::Error,
        };
        let argv = argv(&request);
        assert_eq!(
            &argv[argv.len() - 2..],
            args(&["Title", "Message"]).as_slice()
        );
        assert!(
            argv.iter().any(|arg| arg.contains("display alert")),
            "error messages render with display alert"
        );
    }

    #[test]
    fn osascript_info_and_warning_argv_carry_their_icon_numbers() {
        for (level, icon) in [(Level::Info, "1"), (Level::Warning, "2")] {
            let request = Request::Message {
                title: "Title",
                message: "Message",
                level,
            };
            let argv = argv(&request);
            assert_eq!(
                &argv[argv.len() - 3..],
                args(&["Title", "Message", icon]).as_slice()
            );
        }
    }

    #[test]
    fn osascript_confirm_argv_passes_values_as_script_arguments() {
        let request = Request::Confirm {
            title: "Title",
            message: "Message",
        };
        assert_eq!(
            argv(&request),
            args(&[
                "-e",
                "on run argv",
                "-e",
                "set answer to display dialog (item 2 of argv) buttons {\"No\", \"Yes\"} default button \"Yes\" with title (item 1 of argv)",
                "-e",
                "if button returned of answer is \"Yes\" then return \"yes\"",
                "-e",
                "return \"no\"",
                "-e",
                "end run",
                "Title",
                "Message",
            ])
        );
    }

    #[test]
    fn osascript_choices_argv_counts_the_preselected_items() {
        let request = Request::Choices {
            title: "Title",
            label: "Label",
            choices: &["a", "b", "c"],
            current: &["c", "missing"],
        };
        let with_current = argv(&request);
        assert_eq!(
            &with_current[with_current.len() - 7..],
            args(&["Title", "Label", "1", "c", "a", "b", "c"]).as_slice()
        );

        let none_current = Request::Choices {
            title: "Title",
            label: "Label",
            choices: &["a"],
            current: &[],
        };
        let argv = argv(&none_current);
        assert_eq!(
            &argv[argv.len() - 4..],
            args(&["Title", "Label", "0", "a"]).as_slice()
        );
    }

    #[test]
    fn osascript_color_argv_converts_the_initial_color() {
        let request = Request::Color {
            title: "Title",
            initial: Some("#ff0080"),
        };
        let with_initial = argv(&request);
        assert_eq!(
            &with_initial[with_initial.len() - 3..],
            args(&["65535", "0", "32896"]).as_slice()
        );

        let no_initial = Request::Color {
            title: "Title",
            initial: None,
        };
        let argv = argv(&no_initial);
        assert_eq!(
            &argv[argv.len() - 3..],
            args(&["65535", "65535", "65535"]).as_slice()
        );
    }

    #[test]
    fn osascript_open_file_argv_merges_filter_extensions() {
        let filters = [
            crate::request::FileFilter {
                name: "Images",
                extensions: &["png", "jpg"],
            },
            crate::request::FileFilter {
                name: "Text",
                extensions: &["txt"],
            },
        ];
        let request = Request::OpenFile {
            title: "Title",
            start: Some(std::path::Path::new("/home/user")),
            filters: &filters,
            multiple: false,
        };
        let single = argv(&request);
        assert_eq!(
            &single[single.len() - 6..],
            args(&["Title", "/home/user", "3", "png", "jpg", "txt"]).as_slice()
        );

        let multiple = Request::OpenFile {
            title: "Title",
            start: None,
            filters: &[],
            multiple: true,
        };
        let multi = argv(&multiple);
        assert_eq!(
            &multi[multi.len() - 3..],
            args(&["Title", "", "0"]).as_slice()
        );
        assert_ne!(single, multi);
    }

    #[test]
    fn osascript_save_file_argv_splits_the_start() {
        let request = Request::SaveFile {
            title: "Title",
            start: Some(std::path::Path::new("/home/user/out.txt")),
            filters: &[],
        };
        let save = argv(&request);
        assert_eq!(
            &save[save.len() - 3..],
            args(&["Title", "/home/user", "out.txt"]).as_slice()
        );

        let bare = Request::SaveFile {
            title: "Title",
            start: Some(std::path::Path::new("out.txt")),
            filters: &[],
        };
        let bare_argv = argv(&bare);
        assert_eq!(
            &bare_argv[bare_argv.len() - 3..],
            args(&["Title", "", "out.txt"]).as_slice()
        );
    }

    #[test]
    fn osascript_folder_argv() {
        let request = Request::Folder {
            title: "Title",
            start: None,
        };
        let folder = argv(&request);
        assert_eq!(&folder[folder.len() - 2..], args(&["Title", ""]).as_slice());
    }

    #[test]
    fn osascript_classifier_needs_the_cancel_marker() {
        assert_eq!(
            classify(Some(0), "hello\n", ""),
            Outcome::Answered(Some("hello".to_string()))
        );
        assert_eq!(
            classify(Some(1), "", "36:40: execution error: User canceled. (-128)"),
            Outcome::Cancelled
        );
        // Same exit code and empty stdout as a cancel, but no marker:
        // a real error, where the shared classifier would say cancel.
        assert_eq!(classify(Some(1), "", ""), Outcome::Failed);
        assert_eq!(
            classify(Some(1), "", "0:10: syntax error: Expected end of line"),
            Outcome::Failed
        );
        assert_eq!(classify(None, "", ""), Outcome::Failed);
    }
}