sk-desktop 0.4.0

Skathi's desktop integration: argv, shell, single instance, custom protocols and the tray
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! File dialogs: `<input type=file>`, the File System Access pickers and `<a download>`'s Save As.
//!
//! Each dialog runs on its own short-lived `sk-dialog` thread (an STA on Windows), so an open Save As
//! holds up neither the shell thread nor the frame thread.
//!
//! A dialog belongs to the window it was asked from, one at a time (a second picker is refused, a
//! download waits). When that window starts to close, [`owner_closing`] marks it: a dialog not yet in the
//! OS never will be, and the open one is closed by a check on its own thread. sk-app destroys the window
//! only once [`is_idle`], since destroying an owner under another thread's modal dialog hangs or crashes.
//!
//! `SK_DIALOGS=scripted`: nothing reaches the OS; requests wait for the devtools `dialog` command.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::SystemTime;

use serde_json::{json, Value as Json};

use crate::fs::writable::Data;
use crate::fs::{self, fail_io, Access};
use crate::{Done, Fail};

pub mod ask;
pub mod color;
pub mod scripted;

pub use ask::{ask, ask_with, Ask, Present, Reply};

#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")]
use win as imp;

#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "macos")]
use mac as imp;
#[cfg(target_os = "macos")]
pub use mac::ns_window_of_view;
#[cfg(target_os = "macos")]
pub(crate) use mac::window_of;
#[cfg(any(target_os = "macos", test))]
mod mac_plan;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
use linux as imp;

#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
mod imp {
    use super::*;
    pub(super) fn pick(
        _: &Native,
        _: isize,
        _: &Cancellation,
    ) -> Result<Option<Vec<PathBuf>>, Fail> {
        Err(Fail::new(
            "NotSupportedError",
            "file dialogs are not implemented on this platform yet",
        ))
    }
    pub(super) fn ask(_: &Ask, _: isize, _: &Cancellation) -> Result<Option<usize>, Fail> {
        Err(Fail::new(
            "NotSupportedError",
            "native questions are not implemented on this platform yet",
        ))
    }
    pub(super) fn color(_: &str, _: isize, _: &Cancellation) -> Result<Option<String>, Fail> {
        Err(Fail::new(
            "NotSupportedError",
            "color pickers are not implemented on this platform yet",
        ))
    }
    pub(super) fn known_folder(_: Known) -> Option<PathBuf> {
        None
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Open,
    Save,
    Folder,
}

impl Kind {
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Open => "open",
            Kind::Save => "save",
            Kind::Folder => "folder",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Filter {
    pub name: String,
    pub exts: Vec<String>,
}

impl Filter {
    pub fn spec(&self) -> String {
        self.exts
            .iter()
            .map(|e| format!("*.{e}"))
            .collect::<Vec<_>>()
            .join(";")
    }
}

pub const ALL_FILES: &str = "All Files (*.*)";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Known {
    Desktop,
    Documents,
    Downloads,
    Music,
    Pictures,
    Videos,
}

impl Known {
    pub fn parse(s: &str) -> Option<Known> {
        Some(match s {
            "desktop" => Known::Desktop,
            "documents" => Known::Documents,
            "downloads" => Known::Downloads,
            "music" => Known::Music,
            "pictures" => Known::Pictures,
            "videos" => Known::Videos,
            _ => return None,
        })
    }
    pub fn as_str(self) -> &'static str {
        match self {
            Known::Desktop => "desktop",
            Known::Documents => "documents",
            Known::Downloads => "downloads",
            Known::Music => "music",
            Known::Pictures => "pictures",
            Known::Videos => "videos",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Start {
    Known(Known),
    Path(PathBuf),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Native {
    pub kind: Kind,
    pub multiple: bool,
    pub filters: Vec<Filter>,
    pub allow_all: bool,
    pub client: u128,
    pub start: Option<Start>,
    /// `true`: `SetFolder` (startIn is an instruction). `false`: `SetDefaultFolder` (the remembered folder wins).
    pub force_start: bool,
    pub suggested_name: Option<String>,
    pub default_ext: Option<String>,
}

pub enum Then {
    /// `<input type=file>`; `walk` is `webkitdirectory`; `prev` is the current selection, so re-picking it is a `cancel`.
    Files {
        walk: bool,
        prev: Vec<PathBuf>,
    },
    Handles,
    SaveHandle,
    Download(Data),
}

fn ext_of(token: &str) -> Option<String> {
    let e = token.strip_prefix('.')?;
    (!e.is_empty() && !e.contains(['*', '?', ';', '/', '\\', '\0'])).then(|| e.to_ascii_lowercase())
}

fn push_unique(out: &mut Vec<String>, e: String) {
    if !out.contains(&e) {
        out.push(e);
    }
}

/// `<input accept>` → the dialog's type list, as Chromium builds it: one combined "Image/Audio/Video
/// Files" entry for that wildcard, "Custom Files" otherwise.
pub fn filters_for_accept(tokens: &[String]) -> Vec<Filter> {
    let mut exts = Vec::new();
    let mut valid = 0;
    for t in tokens {
        let before = exts.len();
        if let Some(e) = ext_of(t) {
            push_unique(&mut exts, e);
        } else {
            for e in sk_runtime::redjs::webapi::mime::exts_for(t) {
                push_unique(&mut exts, e);
            }
        }
        if exts.len() > before {
            valid += 1;
        }
    }
    if exts.is_empty() {
        return Vec::new();
    }
    let name = match (valid, tokens.first().map(String::as_str)) {
        (1, Some("image/*")) => "Image Files",
        (1, Some("audio/*")) => "Audio Files",
        (1, Some("video/*")) => "Video Files",
        _ => "Custom Files",
    };
    vec![Filter {
        name: name.to_string(),
        exts,
    }]
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptType {
    pub description: String,
    pub accept: Vec<(String, Vec<String>)>,
}

/// FSA `types` → one dialog entry per type; a type with no extension cannot filter and is left out.
pub fn filters_for_types(types: &[AcceptType]) -> Vec<Filter> {
    let mut out = Vec::new();
    for t in types {
        let mut exts = Vec::new();
        for (mime, listed) in &t.accept {
            for e in listed.iter().filter_map(|e| ext_of(e)) {
                push_unique(&mut exts, e);
            }
            for e in sk_runtime::redjs::webapi::mime::exts_for(mime) {
                push_unique(&mut exts, e);
            }
        }
        if exts.is_empty() {
            continue;
        }
        let name = if t.description.trim().is_empty() {
            "Custom Files".to_string()
        } else {
            t.description.clone()
        };
        out.push(Filter { name, exts });
    }
    out
}

/// FNV-1a, 128-bit. Must stay deterministic: the GUID names a folder remembered across sessions.
pub fn fnv128(bytes: &[u8]) -> u128 {
    const OFFSET: u128 = 0x6c62272e07bb014262b821756295c58d;
    const PRIME: u128 = 0x0000000001000000000000000000013B;
    let mut h = OFFSET;
    for &b in bytes {
        h ^= u128::from(b);
        h = h.wrapping_mul(PRIME);
    }
    h
}

/// `SetClientGuid` for a picker: `fnv128(app id ‖ "\0" ‖ id)`; the app id is included because the dev host runs many apps.
pub fn client_guid(app_id: &str, id: Option<&str>) -> u128 {
    match id {
        Some(id) => fnv128(format!("{app_id}\0{id}").as_bytes()),
        None => fnv128(app_id.as_bytes()),
    }
}

/// Downloads remember their own folder. `<` cannot appear in an FSA `id`, so no collision.
const DOWNLOAD_ID: &str = "<download>";

fn app_id() -> String {
    crate::launch::identity()
        .map(|i| i.id.clone())
        .unwrap_or_else(|| "vue-native-app".to_string())
}

pub fn valid_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 32
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

fn bad(msg: impl Into<String>) -> Fail {
    Fail::type_error(msg)
}

fn strings(v: Option<&Json>) -> Vec<String> {
    v.and_then(Json::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|s| s.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

pub fn parse(req: &str, prev: Vec<PathBuf>) -> Result<(Native, Then), Fail> {
    let v: Json =
        serde_json::from_str(req).map_err(|e| bad(format!("dialog request is not JSON: {e}")))?;
    let kind = match v.get("kind").and_then(Json::as_str) {
        Some("open") => Kind::Open,
        Some("save") => Kind::Save,
        Some("folder") => Kind::Folder,
        other => {
            return Err(bad(format!(
                "dialog kind {other:?} is not open, save or folder"
            )))
        }
    };
    let flag = |k: &str| v.get(k).and_then(Json::as_bool).unwrap_or(false);
    let files = v.get("result").and_then(Json::as_str) == Some("files");
    let (filters, allow_all) = match v.get("types").and_then(Json::as_array) {
        Some(types) => {
            let types: Vec<AcceptType> = types
                .iter()
                .map(|t| AcceptType {
                    description: t
                        .get("description")
                        .and_then(Json::as_str)
                        .unwrap_or("")
                        .to_string(),
                    accept: t
                        .get("accept")
                        .and_then(Json::as_object)
                        .map(|o| {
                            o.iter()
                                .map(|(m, exts)| (m.clone(), strings(Some(exts))))
                                .collect()
                        })
                        .unwrap_or_default(),
                })
                .collect();
            let filters = filters_for_types(&types);
            // Without a usable type, "All Files" stays so the dialog is not empty.
            let allow_all = !flag("excludeAcceptAllOption") || filters.is_empty();
            (filters, allow_all)
        }
        None => (filters_for_accept(&strings(v.get("accept"))), true),
    };
    let id = v.get("id").and_then(Json::as_str).filter(|id| valid_id(id));
    let start = match v.get("startIn") {
        Some(Json::String(s)) => {
            Some(Start::Known(Known::parse(s).ok_or_else(|| {
                bad(format!("{s:?} is not a WellKnownDirectory"))
            })?))
        }
        Some(Json::Object(o)) => {
            let h = o.get("h").and_then(Json::as_u64).unwrap_or(0);
            let (path, k) =
                fs::path_of(h).ok_or_else(|| Fail::new("InvalidStateError", fs::INVALID_STATE))?;
            let dir = match k {
                fs::Kind::Directory => path,
                fs::Kind::File => path.parent().map(Path::to_path_buf).unwrap_or(path),
            };
            Some(Start::Path(dir))
        }
        _ => None,
    };
    let suggested_name = v
        .get("suggestedName")
        .and_then(Json::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    let default_ext = match kind {
        Kind::Save => filters.first().and_then(|f| f.exts.first()).cloned(),
        _ => None,
    };
    let native = Native {
        kind,
        multiple: kind == Kind::Open && flag("multiple"),
        filters,
        allow_all,
        client: client_guid(&app_id(), id),
        force_start: start.is_some(),
        start,
        suggested_name,
        default_ext,
    };
    let then = match (kind, files) {
        (Kind::Save, _) => Then::SaveHandle,
        (_, true) => Then::Files {
            walk: kind == Kind::Folder,
            prev,
        },
        (_, false) => Then::Handles,
    };
    Ok((native, then))
}

const RESERVED_NAMES: &[&str] = &[
    "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
    "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
];

/// A download's file name, as Chromium's `net::GenerateFileName` makes it.
pub fn download_name(attr: &str, url: &str, mime: &str) -> String {
    fn clean(s: &str) -> String {
        let s: String = s
            .chars()
            .map(|c| {
                if (c as u32) < 0x20
                    || matches!(
                        c,
                        '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' | '\u{7f}'
                    )
                {
                    '_'
                } else {
                    c
                }
            })
            .collect();
        s.trim_matches(|c: char| c == '.' || c.is_whitespace())
            .to_string()
    }
    let leaf = attr.rsplit(['/', '\\']).next().unwrap_or(attr);
    let mut name = clean(leaf);
    if name.is_empty() {
        name = if url.starts_with("data:") {
            "download".to_string()
        } else {
            clean(url.rsplit('/').next().unwrap_or(""))
        };
    }
    if name.is_empty() {
        name = "download".to_string();
    }
    let stem = name.split('.').next().unwrap_or("").to_ascii_lowercase();
    if RESERVED_NAMES.contains(&stem.trim()) {
        name = format!("_{name}");
    }
    if !name.contains('.') {
        if let Some(ext) = sk_runtime::redjs::webapi::mime::exts_for(mime).first() {
            name = format!("{name}.{ext}");
        }
    }
    name
}

/// A resolved `blob:` URL as the bytes a download writes; a picked file changed since the pick fails with `NotReadableError`.
pub fn data_of_blob_target(t: sk_runtime::redjs::webapi::url::BlobTarget) -> Data {
    use sk_runtime::redjs::webapi::blob::{DiskFile, Range, Source};
    use sk_runtime::redjs::webapi::url::BlobTarget;
    match t {
        BlobTarget::Bytes {
            bytes, offset, len, ..
        } => Data::Blob(Range {
            source: Source::Memory(bytes),
            offset: offset as u64,
            len: len as u64,
        }),
        BlobTarget::Path {
            path,
            range,
            size,
            mtime,
            ..
        } => {
            let (offset, len) = range.unwrap_or((0, size));
            Data::Blob(Range {
                source: Source::Disk(Arc::new(DiskFile { path, size, mtime })),
                offset,
                len,
            })
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Owner {
    pub key: u64,
    pub hwnd: isize,
}

static RESOLVER: OnceLock<fn() -> Option<Owner>> = OnceLock::new();

/// sk-app names the published window at the moment of a call; without a resolver a dialog has no owner.
pub fn set_owner_resolver(f: fn() -> Option<Owner>) {
    let _ = RESOLVER.set(f);
}

pub(crate) fn current_owner() -> Option<Owner> {
    RESOLVER.get().and_then(|f| f())
}

#[derive(Default)]
struct OwnerState {
    closed: AtomicBool,
    active: AtomicBool,
    ticket: std::sync::atomic::AtomicU64,
    queue: Mutex<std::collections::VecDeque<u64>>,
}

impl OwnerState {
    fn leave_queue(&self, ticket: u64) {
        self.queue
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .retain(|&t| t != ticket);
    }
}

fn owners() -> &'static Mutex<std::collections::HashMap<u64, Arc<OwnerState>>> {
    static O: OnceLock<Mutex<std::collections::HashMap<u64, Arc<OwnerState>>>> = OnceLock::new();
    O.get_or_init(Default::default)
}

fn owner_state(key: u64) -> Arc<OwnerState> {
    owners()
        .lock()
        .unwrap_or_else(|p| p.into_inner())
        .entry(key)
        .or_default()
        .clone()
}

/// Window `key` is about to be destroyed: its open dialog is told to close. `true` while one is still running on it.
pub fn owner_closing(key: u64) -> bool {
    let mut map = owners().lock().unwrap_or_else(|p| p.into_inner());
    let Some(st) = map.get(&key).cloned() else {
        return false;
    };
    st.closed.store(true, Ordering::Release);
    let active = st.active.load(Ordering::Acquire);
    if !active {
        map.remove(&key);
    }
    active
}

pub fn is_idle(key: u64) -> bool {
    let mut map = owners().lock().unwrap_or_else(|p| p.into_inner());
    let Some(st) = map.get(&key) else { return true };
    let idle = !st.active.load(Ordering::Acquire);
    if idle && st.closed.load(Ordering::Acquire) {
        map.remove(&key);
    }
    idle
}

#[derive(Clone)]
pub struct Cancellation(Arc<OwnerState>);

impl Cancellation {
    pub fn is_requested(&self) -> bool {
        self.0.closed.load(Ordering::Acquire)
    }
}

/// `SK_DIALOGS=scripted`. Unit tests are always scripted, so none opens a window on the host.
pub fn scripted_mode() -> bool {
    static S: OnceLock<bool> = OnceLock::new();
    cfg!(test)
        || *S.get_or_init(|| {
            std::env::var("SK_DIALOGS").is_ok_and(|v| v.eq_ignore_ascii_case("scripted"))
        })
}

pub const ALREADY_ACTIVE: &str = "File picker already active.";

/// A picker is refused if its owner already has a dialog open; a download waits for it.
pub fn start(native: Native, then: Then, label: &'static str) -> Result<u32, Fail> {
    start_owned(RESOLVER.get().and_then(|f| f()), native, then, label)
}

const QUEUE_POLL: std::time::Duration = std::time::Duration::from_millis(25);

/// On a dialog thread: waits for `ticket`'s turn, then claims the owner. `false` when the owner closed meanwhile.
fn wait_turn(st: &OwnerState, ticket: u64, cancel: &Cancellation) -> bool {
    loop {
        if cancel.is_requested() {
            st.leave_queue(ticket);
            return false;
        }
        let front = st.queue.lock().unwrap_or_else(|p| p.into_inner()).front() == Some(&ticket);
        if front && !st.active.swap(true, Ordering::AcqRel) {
            break;
        }
        std::thread::sleep(QUEUE_POLL);
    }
    st.leave_queue(ticket);
    if cancel.is_requested() {
        st.active.store(false, Ordering::Release);
        return false;
    }
    true
}

fn start_owned(
    owner: Option<Owner>,
    native: Native,
    then: Then,
    label: &'static str,
) -> Result<u32, Fail> {
    let key = owner.map(|o| o.key).unwrap_or(0);
    let hwnd = owner.map(|o| o.hwnd).unwrap_or(0);
    let st = owner_state(key);
    let token = crate::next_token();
    if st.closed.load(Ordering::Acquire) {
        crate::settle(token, Ok(cancelled()));
        return Ok(token);
    }
    let queued = matches!(then, Then::Download(_));
    if !queued && st.active.swap(true, Ordering::AcqRel) {
        return Err(Fail::new("NotAllowedError", ALREADY_ACTIVE).code("EBUSY"));
    }
    let ticket = st.ticket.fetch_add(1, Ordering::AcqRel);
    if queued {
        st.queue
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .push_back(ticket);
    }
    let cancel = Cancellation(st.clone());
    let spawned = std::thread::Builder::new()
        .name("sk-dialog".into())
        .spawn(move || {
            if queued && !wait_turn(&st, ticket, &cancel) {
                crate::settle(token, Ok(cancelled()));
                return;
            }
            let picked = if scripted_mode() {
                scripted::pick(&native, key, label, &cancel)
            } else {
                imp::pick(&native, hwnd, &cancel)
            };
            st.active.store(false, Ordering::Release);
            let result = match picked {
                Ok(Some(paths)) if !paths.is_empty() && !cancel.is_requested() => {
                    finish(paths, then)
                }
                Ok(_) => Ok(Done::json(&cancelled())),
                Err(f) => Err(f),
            };
            crate::settle_done(token, result);
        });
    if spawned.is_err() {
        // The closure went down with the failed spawn; a queued download claimed only its queue slot.
        let st = owner_state(key);
        if queued {
            st.leave_queue(ticket);
        } else {
            st.active.store(false, Ordering::Release);
        }
        return Err(
            Fail::new("InvalidStateError", "could not start the dialog thread").code("EIO"),
        );
    }
    Ok(token)
}

fn cancelled() -> String {
    "{\"cancelled\":true}".to_string()
}

pub fn start_open(req: &str, prev: Vec<PathBuf>) -> Result<u32, Fail> {
    if let Ok(request) = serde_json::from_str::<Json>(req) {
        if request["kind"] == "color" {
            return color::start(request["value"].as_str().unwrap_or("#000000"));
        }
    }
    match parse(req, prev) {
        Ok((native, then)) => start(native, then, "picker"),
        Err(f) => Err(f),
    }
}

pub fn start_download(data: Data, name: String) -> Result<u32, Fail> {
    let native = Native {
        kind: Kind::Save,
        multiple: false,
        filters: Vec::new(),
        allow_all: true,
        client: client_guid(&app_id(), Some(DOWNLOAD_ID)),
        start: Some(Start::Known(Known::Downloads)),
        force_start: false,
        default_ext: name
            .rsplit_once('.')
            .map(|(_, e)| e.to_ascii_lowercase())
            .filter(|e| !e.is_empty()),
        suggested_name: Some(name),
    };
    start(native, Then::Download(data), "download")
}

struct Picked {
    path: PathBuf,
    name: String,
    size: u64,
    mtime: Option<SystemTime>,
    rel: String,
}

fn stat_picked(path: PathBuf, rel: String) -> Result<Picked, Fail> {
    let (size, mtime) = fs::op_stat_file(&path)?;
    let name = fs::name_of(&path);
    Ok(Picked {
        path,
        name,
        size,
        mtime,
        rel,
    })
}

/// `webkitdirectory`: every file under `root`, sorted by relative path. Directory links are not followed.
pub fn walk(root: &Path) -> Result<Vec<(PathBuf, String)>, Fail> {
    let base = fs::name_of(root);
    let mut out = Vec::new();
    let mut stack = vec![(root.to_path_buf(), base)];
    while let Some((dir, rel)) = stack.pop() {
        let entries = std::fs::read_dir(&dir)
            .map_err(|e| fail_io(&e, Access::Read))?
            .filter_map(Result::ok);
        let mut subdirs = Vec::new();
        for e in entries {
            let Ok(ft) = e.file_type() else { continue };
            let name = e.file_name().to_string_lossy().into_owned();
            let child_rel = format!("{rel}/{name}");
            if ft.is_dir() {
                subdirs.push((e.path(), child_rel));
            } else if ft.is_file() {
                out.push((e.path(), child_rel));
            } else if ft.is_symlink() && std::fs::metadata(e.path()).is_ok_and(|m| m.is_file()) {
                out.push((e.path(), child_rel));
            }
        }
        stack.extend(subdirs);
    }
    out.sort_by(|a, b| a.1.cmp(&b.1));
    Ok(out)
}

fn finish(paths: Vec<PathBuf>, then: Then) -> Result<Done, Fail> {
    match then {
        Then::Files { walk: walked, prev } => {
            let picked: Vec<Picked> = if walked {
                let root = paths
                    .into_iter()
                    .next()
                    .ok_or_else(|| Fail::new("AbortError", "nothing was picked"))?;
                walk(&root)?
                    .into_iter()
                    .map(|(p, rel)| stat_picked(p, rel))
                    .collect::<Result<_, _>>()?
            } else {
                paths
                    .into_iter()
                    .map(|p| stat_picked(p, String::new()))
                    .collect::<Result<_, _>>()?
            };
            let same =
                picked.len() == prev.len() && picked.iter().zip(&prev).all(|(a, b)| &a.path == b);
            if same {
                return Ok(Done::json(&cancelled()));
            }
            let payload = json!({ "files": picked.len() }).to_string();
            Ok(Done::with_value(payload, move |g| unsafe {
                make_file_list(g, &picked)
            }))
        }
        Then::Handles => {
            let mut handles = Vec::new();
            for p in paths {
                let meta = std::fs::metadata(&p).map_err(|e| fail_io(&e, Access::Read))?;
                let kind = if meta.is_dir() {
                    fs::Kind::Directory
                } else {
                    fs::Kind::File
                };
                handles.push(fs::granted_handle_json(p, kind));
            }
            Ok(Done {
                payload: json!({ "handles": handles }).to_string(),
                make: None,
            })
        }
        Then::SaveHandle => {
            let p = paths
                .into_iter()
                .next()
                .ok_or_else(|| Fail::new("AbortError", "nothing was picked"))?;
            std::fs::OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&p)
                .map_err(|e| fail_io(&e, Access::Write))?;
            Ok(Done {
                payload: json!({ "handles": [fs::granted_handle_json(p, fs::Kind::File)] })
                    .to_string(),
                make: None,
            })
        }
        Then::Download(data) => {
            let p = paths
                .into_iter()
                .next()
                .ok_or_else(|| Fail::new("AbortError", "nothing was picked"))?;
            crate::fs::writable::write_whole(&p, &data)?;
            let name = fs::name_of(&p);
            crate::log_later("dialog", format!("[download] saved {name}"));
            Ok(Done::json(&json!({ "saved": name }).to_string()))
        }
    }
}

/// The picked Files and their FileList, on the JS thread; each File is protected until the list holds it.
unsafe fn make_file_list(g: *mut std::ffi::c_void, picked: &[Picked]) -> u64 {
    use sk_runtime::redjs::ffi::{redjs_protect, redjs_unprotect};
    use sk_runtime::redjs::webapi::file;
    let mut files = Vec::with_capacity(picked.len());
    for p in picked {
        let f = file::create_file(g, &p.path, &p.name, None, p.size, p.mtime, &p.rel);
        redjs_protect(g, f);
        files.push(f);
    }
    let list = file::create_file_list(g, &files);
    for f in files {
        redjs_unprotect(g, f);
    }
    list
}

pub fn describe(n: &Native) -> Json {
    let start = match &n.start {
        Some(Start::Known(k)) => Json::String(k.as_str().to_string()),
        Some(Start::Path(p)) => Json::String(p.to_string_lossy().into_owned()),
        None => Json::Null,
    };
    json!({
        "kind": n.kind.as_str(),
        "multiple": n.multiple,
        "filters": n.filters.iter().map(|f| json!({ "name": f.name, "spec": f.spec() })).collect::<Vec<_>>(),
        "allowAll": n.allow_all,
        "startIn": start,
        "suggestedName": n.suggested_name,
        "defaultExtension": n.default_ext,
        "clientGuid": format!("{:032x}", n.client),
    })
}

pub fn known_folder(k: Known) -> Option<PathBuf> {
    imp::known_folder(k)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::tests::Scratch;
    use crate::tests::{token_of, wait_for_settles};
    use std::sync::atomic::AtomicU64;

    fn toks(s: &[&str]) -> Vec<String> {
        s.iter().map(|t| t.to_string()).collect()
    }

    #[test]
    fn accept_becomes_one_combined_filter_named_as_chromium_names_it() {
        let image = filters_for_accept(&toks(&["image/*"]));
        assert_eq!(image.len(), 1);
        assert_eq!(image[0].name, "Image Files");
        assert!(
            image[0].exts.contains(&"png".to_string())
                && image[0].exts.contains(&"jpg".to_string())
        );
        assert_eq!(
            filters_for_accept(&toks(&["audio/*"]))[0].name,
            "Audio Files"
        );
        assert_eq!(
            filters_for_accept(&toks(&["video/*"]))[0].name,
            "Video Files"
        );
        let one = filters_for_accept(&toks(&[".csv"]));
        assert_eq!(
            one,
            vec![Filter {
                name: "Custom Files".into(),
                exts: vec!["csv".into()]
            }]
        );
        let mixed = filters_for_accept(&toks(&[".png", "image/*", "application/pdf"]));
        assert_eq!(mixed[0].name, "Custom Files");
        assert_eq!(mixed[0].exts[0], "png");
        assert_eq!(mixed[0].exts.iter().filter(|e| *e == "png").count(), 1);
        assert!(mixed[0].exts.contains(&"pdf".to_string()));
        assert!(mixed[0].spec().starts_with("*.png;"));
        assert!(filters_for_accept(&toks(&["x-unknown/nothing"])).is_empty());
        assert!(filters_for_accept(&[]).is_empty());
    }

    #[test]
    fn fsa_types_become_one_filter_each_with_their_mime_extensions() {
        let types = vec![
            AcceptType {
                description: "Text".into(),
                accept: vec![("text/plain".into(), vec![".txt".into(), ".LOG".into()])],
            },
            AcceptType {
                description: "".into(),
                accept: vec![("image/png".into(), vec![])],
            },
            AcceptType {
                description: "Nothing".into(),
                accept: vec![("x-unknown/nothing".into(), vec![])],
            },
        ];
        let f = filters_for_types(&types);
        assert_eq!(f.len(), 2, "a type with no extension is left out: {f:?}");
        assert_eq!(f[0].name, "Text");
        assert_eq!(&f[0].exts[..2], &["txt".to_string(), "log".to_string()]);
        assert_eq!(f[1].name, "Custom Files");
        assert!(f[1].exts.contains(&"png".to_string()));
    }

    #[test]
    fn the_client_guid_is_fnv1a_128_and_scoped_to_the_app() {
        assert_eq!(fnv128(b""), 0x6c62272e07bb014262b821756295c58d);
        assert_eq!(fnv128(b"a"), 0xd228cb696f1a8caf78912b704e4a8964);
        assert_eq!(client_guid("app", Some("x")), fnv128(b"app\0x"));
        assert_eq!(client_guid("app", None), fnv128(b"app"));
        assert_ne!(
            client_guid("app", Some("x")),
            client_guid("other", Some("x"))
        );
        assert_ne!(client_guid("app", Some("x")), client_guid("app", Some("y")));
        assert!(valid_id("Recent_files-2"));
        for bad in ["", "has space", "a/b", &"x".repeat(33)] {
            assert!(!valid_id(bad), "{bad:?}");
        }
    }

    #[test]
    fn a_request_parses_into_the_dialog_and_what_follows_it() {
        let (n, then) = parse(
            r#"{"kind":"open","multiple":true,"accept":[".txt"],"result":"files"}"#,
            vec![],
        )
        .unwrap();
        assert_eq!((n.kind, n.multiple, n.allow_all), (Kind::Open, true, true));
        assert!(matches!(then, Then::Files { walk: false, .. }));
        let (n, then) = parse(
            r#"{"kind":"folder","multiple":true,"result":"files"}"#,
            vec![],
        )
        .unwrap();
        assert!(!n.multiple, "only an Open picks several");
        assert!(matches!(then, Then::Files { walk: true, .. }));
        let (n, then) = parse(
            r#"{"kind":"save","types":[{"description":"CSV","accept":{"text/csv":[".csv"]}}],
                "excludeAcceptAllOption":true,"suggestedName":"out.csv","id":"export","startIn":"documents"}"#,
            vec![],
        )
        .unwrap();
        assert!(matches!(then, Then::SaveHandle));
        assert_eq!(n.default_ext.as_deref(), Some("csv"));
        assert!(!n.allow_all);
        assert_eq!(n.start, Some(Start::Known(Known::Documents)));
        assert!(n.force_start);
        assert_eq!(n.client, client_guid(&app_id(), Some("export")));
        let s = Scratch::new("dialog-start");
        std::fs::write(s.0.join("f.txt"), b"x").unwrap();
        let h = fs::register(s.0.join("f.txt"), fs::Kind::File);
        let (n, _) = parse(
            &format!(r#"{{"kind":"open","startIn":{{"h":{h}}}}}"#),
            vec![],
        )
        .unwrap();
        assert_eq!(n.start, Some(Start::Path(s.0.clone())));
        fs::release(h);
        assert_eq!(
            parse(
                &format!(r#"{{"kind":"open","startIn":{{"h":{h}}}}}"#),
                vec![]
            )
            .err()
            .map(|f| f.name),
            Some("InvalidStateError")
        );
        assert_eq!(
            parse(r#"{"kind":"open","startIn":"home"}"#, vec![])
                .err()
                .map(|f| f.name),
            Some("TypeError")
        );
        assert_eq!(
            parse(r#"{"kind":"run"}"#, vec![]).err().map(|f| f.name),
            Some("TypeError")
        );
        let (n, _) = parse(
            r#"{"kind":"open","types":[],"excludeAcceptAllOption":true}"#,
            vec![],
        )
        .unwrap();
        assert!(n.allow_all);
    }

    #[test]
    fn download_names_follow_chromium() {
        assert_eq!(
            download_name("report.csv", "blob:x/1", "text/csv"),
            "report.csv"
        );
        assert_eq!(download_name("dir/sub\\a:b.txt", "blob:x/1", ""), "a_b.txt");
        assert_eq!(
            download_name("", "data:text/plain,hi", "text/plain"),
            "download.txt"
        );
        assert_eq!(
            download_name("", "blob:http://localhost/5b1f-77aa", "application/pdf"),
            "5b1f-77aa.pdf"
        );
        assert_eq!(download_name(" ..x.. ", "blob:x/1", ""), "x");
        assert_eq!(download_name("con.txt", "blob:x/1", ""), "_con.txt");
        assert_eq!(
            download_name("a?b", "data:,x", "application/x-unknown"),
            "a_b"
        );
    }

    static KEY: AtomicU64 = AtomicU64::new(1 << 40);

    fn owner() -> Option<Owner> {
        Some(Owner {
            key: KEY.fetch_add(1, Ordering::Relaxed),
            hwnd: 0,
        })
    }

    fn pending_of(window: u64) -> u64 {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
        loop {
            if let Some(v) = scripted::list()
                .as_array()
                .unwrap()
                .iter()
                .find(|v| v["window"] == window)
            {
                return v["id"].as_u64().unwrap();
            }
            assert!(
                std::time::Instant::now() < deadline,
                "no scripted dialog appeared for window {window}"
            );
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
    }

    fn open(owner: Option<Owner>, req: &str, prev: Vec<PathBuf>) -> Result<u32, Fail> {
        let (n, then) = parse(req, prev).unwrap();
        start_owned(owner, n, then, "picker")
    }

    #[test]
    fn a_scripted_open_answers_cancels_and_refuses_a_second_dialog() {
        let s = Scratch::new("dialog-open");
        let (a, b) = (s.0.join("a.txt"), s.0.join("b.txt"));
        std::fs::write(&a, b"alpha").unwrap();
        std::fs::write(&b, b"beta").unwrap();
        let o = owner();
        let key = o.unwrap().key;
        let req = r#"{"kind":"open","multiple":true,"result":"files"}"#;
        let t = token_of(open(o, req, vec![]));
        let id = pending_of(key);
        let second = open(o, req, vec![]).unwrap_err();
        assert_eq!(
            (second.name, second.message.as_str()),
            ("NotAllowedError", ALREADY_ACTIVE)
        );
        assert!(scripted::answer(id, vec![s.0.join("missing.txt")]).is_err());
        assert!(scripted::answer(id, vec![PathBuf::from("relative.txt")]).is_err());
        scripted::answer(id, vec![a.clone(), b.clone()]).unwrap();
        let got = wait_for_settles(&[t]);
        assert_eq!(got[&t], (true, r#"{"files":2}"#.to_string()));
        assert!(is_idle(key));
        let t = token_of(open(o, req, vec![a.clone(), b.clone()]));
        scripted::answer(pending_of(key), vec![a.clone(), b.clone()]).unwrap();
        assert_eq!(wait_for_settles(&[t])[&t], (true, cancelled()));
        let t = token_of(open(o, req, vec![]));
        scripted::cancel(pending_of(key)).unwrap();
        assert_eq!(wait_for_settles(&[t])[&t], (true, cancelled()));
        let t = token_of(open(o, r#"{"kind":"open","result":"handles"}"#, vec![]));
        let id = pending_of(key);
        assert!(scripted::answer(id, vec![a.clone(), b.clone()]).is_err());
        scripted::answer(id, vec![a.clone()]).unwrap();
        let (ok, payload) = wait_for_settles(&[t]).remove(&t).unwrap();
        assert!(ok);
        let v: Json = serde_json::from_str(&payload).unwrap();
        assert_eq!(
            (
                v["handles"][0]["name"].as_str(),
                v["handles"][0]["kind"].as_str()
            ),
            (Some("a.txt"), Some("file"))
        );
        assert!(
            !payload.contains(&*s.0.to_string_lossy()),
            "no path in what JS sees: {payload}"
        );
        fs::release(v["handles"][0]["h"].as_u64().unwrap());
    }

    #[test]
    fn a_closing_owner_cancels_its_dialog_and_refuses_new_ones() {
        let o = owner();
        let key = o.unwrap().key;
        let t = token_of(open(o, r#"{"kind":"open","result":"handles"}"#, vec![]));
        let _ = pending_of(key);
        assert!(!is_idle(key));
        assert!(owner_closing(key), "a dialog is still running on it");
        assert_eq!(wait_for_settles(&[t])[&t], (true, cancelled()));
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
        while !is_idle(key) {
            assert!(std::time::Instant::now() < deadline);
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        assert!(!owner_closing(KEY.fetch_add(1, Ordering::Relaxed)));
        let o2 = owner();
        let k2 = o2.unwrap().key;
        owner_state(k2).closed.store(true, Ordering::Release);
        let t = token_of(open(o2, r#"{"kind":"open","result":"handles"}"#, vec![]));
        assert_eq!(wait_for_settles(&[t])[&t], (true, cancelled()));
    }

    #[test]
    fn a_folder_pick_walks_without_following_links_and_names_relative_paths() {
        let s = Scratch::new("dialog-walk");
        let root = s.0.join("proj");
        std::fs::create_dir_all(root.join("a/y")).unwrap();
        std::fs::write(root.join("c.txt"), b"c").unwrap();
        std::fs::write(root.join("b.txt"), b"b").unwrap();
        std::fs::write(root.join("a/x.txt"), b"x").unwrap();
        std::fs::write(root.join("a/y/z.txt"), b"z").unwrap();
        let rel: Vec<String> = walk(&root).unwrap().into_iter().map(|(_, r)| r).collect();
        assert_eq!(
            rel,
            ["proj/a/x.txt", "proj/a/y/z.txt", "proj/b.txt", "proj/c.txt"]
        );
        let o = owner();
        let t = token_of(open(o, r#"{"kind":"folder","result":"files"}"#, vec![]));
        let id = pending_of(o.unwrap().key);
        assert!(
            scripted::answer(id, vec![root.join("b.txt")]).is_err(),
            "a folder pick takes a folder"
        );
        scripted::answer(id, vec![root.clone()]).unwrap();
        assert_eq!(
            wait_for_settles(&[t])[&t],
            (true, r#"{"files":4}"#.to_string())
        );
    }

    #[test]
    fn a_save_pick_truncates_and_a_download_writes_through_a_swap() {
        let s = Scratch::new("dialog-save");
        let target = s.0.join("out.txt");
        std::fs::write(&target, b"old contents").unwrap();
        let o = owner();
        let key = o.unwrap().key;
        let t = token_of(open(
            o,
            r#"{"kind":"save","suggestedName":"out.txt"}"#,
            vec![],
        ));
        let id = pending_of(key);
        assert!(scripted::answer(id, vec![s.0.join("no-such-dir").join("x.txt")]).is_err());
        scripted::answer(id, vec![target.clone()]).unwrap();
        let (ok, payload) = wait_for_settles(&[t]).remove(&t).unwrap();
        assert!(ok, "{payload}");
        assert_eq!(
            std::fs::read(&target).unwrap(),
            b"",
            "FSA step 7.7: the picked file starts empty"
        );
        let v: Json = serde_json::from_str(&payload).unwrap();
        fs::release(v["handles"][0]["h"].as_u64().unwrap());

        let saved = s.0.join("report.csv");
        let n = Native {
            kind: Kind::Save,
            multiple: false,
            filters: vec![],
            allow_all: true,
            client: 0,
            start: Some(Start::Known(Known::Downloads)),
            force_start: false,
            suggested_name: Some("report.csv".into()),
            default_ext: Some("csv".into()),
        };
        let t = token_of(start_owned(
            o,
            n,
            Then::Download(Data::Bytes(b"a,b\n1,2\n".to_vec())),
            "download",
        ));
        let id = pending_of(key);
        let listed = scripted::list();
        let v = listed
            .as_array()
            .unwrap()
            .iter()
            .find(|v| v["id"] == id)
            .unwrap();
        assert_eq!(
            (v["what"].as_str(), v["startIn"].as_str()),
            (Some("download"), Some("downloads"))
        );
        assert_eq!(v["suggestedName"], "report.csv");
        scripted::answer(id, vec![saved.clone()]).unwrap();
        assert_eq!(
            wait_for_settles(&[t])[&t],
            (true, r#"{"saved":"report.csv"}"#.to_string())
        );
        assert_eq!(std::fs::read(&saved).unwrap(), b"a,b\n1,2\n");
        let names: Vec<String> = std::fs::read_dir(&s.0)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert!(
            !names.iter().any(|n| n.contains(".vnswap")),
            "no swap left: {names:?}"
        );
    }

    fn download(o: Option<Owner>, name: &str, bytes: &[u8]) -> Result<u32, Fail> {
        let n = Native {
            kind: Kind::Save,
            multiple: false,
            filters: vec![],
            allow_all: true,
            client: 0,
            start: None,
            force_start: false,
            suggested_name: Some(name.into()),
            default_ext: None,
        };
        start_owned(
            o,
            n,
            Then::Download(Data::Bytes(bytes.to_vec())),
            "download",
        )
    }

    fn pending_count(window: u64) -> usize {
        scripted::list()
            .as_array()
            .unwrap()
            .iter()
            .filter(|v| v["window"] == window)
            .count()
    }

    #[test]
    fn a_download_waits_for_the_open_dialog_instead_of_being_refused() {
        let s = Scratch::new("dialog-queue");
        let o = owner();
        let key = o.unwrap().key;
        let picker = token_of(open(o, r#"{"kind":"open","result":"handles"}"#, vec![]));
        let first = pending_of(key);
        let d1 = token_of(download(o, "one.txt", b"1"));
        let d2 = token_of(download(o, "two.txt", b"2"));
        std::thread::sleep(QUEUE_POLL * 3);
        assert_eq!(
            pending_count(key),
            1,
            "only the picker is in front of the user"
        );
        scripted::cancel(first).unwrap();
        assert_eq!(wait_for_settles(&[picker])[&picker], (true, cancelled()));
        for name in ["one.txt", "two.txt"] {
            let id = pending_of(key);
            assert_eq!(pending_count(key), 1);
            let listed = scripted::list();
            let v = listed
                .as_array()
                .unwrap()
                .iter()
                .find(|v| v["id"] == id)
                .unwrap();
            assert_eq!(v["suggestedName"], name);
            scripted::answer(id, vec![s.0.join(name)]).unwrap();
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            while scripted::list()
                .as_array()
                .unwrap()
                .iter()
                .any(|v| v["id"] == id)
                || !s.0.join(name).exists()
            {
                assert!(std::time::Instant::now() < deadline);
                std::thread::sleep(std::time::Duration::from_millis(2));
            }
        }
        let got = wait_for_settles(&[d1, d2]);
        assert_eq!(got[&d1], (true, r#"{"saved":"one.txt"}"#.to_string()));
        assert_eq!(got[&d2], (true, r#"{"saved":"two.txt"}"#.to_string()));
        assert_eq!(std::fs::read(s.0.join("two.txt")).unwrap(), b"2");
        let o = owner();
        let key = o.unwrap().key;
        let picker = token_of(open(o, r#"{"kind":"open","result":"handles"}"#, vec![]));
        let _ = pending_of(key);
        let queued = token_of(download(o, "never.txt", b"x"));
        assert!(owner_closing(key));
        let got = wait_for_settles(&[picker, queued]);
        assert_eq!(
            (got[&picker].1.as_str(), got[&queued].1.as_str()),
            (cancelled().as_str(), cancelled().as_str())
        );
        assert!(!s.0.join("never.txt").exists());
    }
}