1
//! File input button, same as `Button`, but triggers a
2
//! user-supplied path-change callback when clicked
3

            
4
use azul_core::{
5
    callbacks::{CoreCallbackData, Update},
6
    dom::Dom,
7
    refany::RefAny,
8
    resources::OptionImageRef,
9
};
10
#[allow(clippy::wildcard_imports)]
11
// widget/render module pulls in the css property/value types it builds with
12
use azul_css::{
13
    dynamic_selector::{CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec},
14
    props::{
15
        basic::*,
16
        layout::*,
17
        property::{CssProperty, *},
18
        style::*,
19
    },
20
    *,
21
};
22

            
23
use crate::{
24
    callbacks::{Callback, CallbackInfo},
25
    widgets::button::{Button, ButtonOnClick, ButtonOnClickCallback},
26
};
27

            
28
#[derive(Debug, Clone, PartialEq, Eq)]
29
#[repr(C)]
30
pub struct FileInput {
31
    /// State of the file input
32
    pub file_input_state: FileInputStateWrapper,
33
    /// Default text to display when no file has been selected
34
    /// (default = "Select File...")
35
    pub default_text: AzString,
36

            
37
    /// Optional image that is displayed next to the label
38
    pub image: OptionImageRef,
39
    /// Style for this button container, or `None` for "no opinion".
40
    ///
41
    /// A `FileInput` renders AS a [`Button`] and forwards these three fields to it,
42
    /// so
43
    /// `None` here means the Button resolves them. `Some(empty)` still means "no
44
    /// properties at all", as everywhere else.
45
    pub container_style: OptionCssPropertyWithConditionsVec,
46
    /// Style of the label, or `None` to let the Button decide.
47
    pub label_style: OptionCssPropertyWithConditionsVec,
48
    /// Style of the image, or `None` to let the Button decide.
49
    pub image_style: OptionCssPropertyWithConditionsVec,
50
}
51

            
52
impl Default for FileInput {
53
208
    fn default() -> Self {
54
208
        let default_button = Button::create(AzString::from_const_str(""));
55
208
        Self {
56
208
            file_input_state: FileInputStateWrapper::default(),
57
208
            default_text: "Select File...".into(),
58
208
            image: None.into(),
59
208
            // Still copied from a default Button rather than written as
60
208
            // `None`: it keeps the two in step by construction, and a Button
61
208
            // with no opinion hands over no opinion.
62
208
            container_style: default_button.container_style,
63
208
            label_style: default_button.label_style,
64
208
            image_style: default_button.image_style,
65
208
        }
66
208
    }
67
}
68

            
69
impl FileInput {
70
    /// The container CSS the Button this input renders as will use.
71
    ///
72
    /// A `FileInput` has no styling of its own: it builds a [`Button`] and forwards
73
    /// these three fields to it. Each resolver therefore answers with the
74
    /// Button's default, which is what the widget actually paints.
75
    #[must_use]
76
6
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
77
6
        self.container_style
78
6
            .clone()
79
6
            .into_option()
80
6
            .unwrap_or_else(|| Self::style_donor().resolved_container_style())
81
6
    }
82

            
83
    /// The label CSS the Button this input renders as will use.
84
    #[must_use]
85
3
    pub fn resolved_label_style(&self) -> CssPropertyWithConditionsVec {
86
3
        self.label_style
87
3
            .clone()
88
3
            .into_option()
89
3
            .unwrap_or_else(|| Self::style_donor().resolved_label_style())
90
3
    }
91

            
92
    /// The image CSS the Button this input renders as will use.
93
    #[must_use]
94
3
    pub fn resolved_image_style(&self) -> CssPropertyWithConditionsVec {
95
3
        self.image_style
96
3
            .clone()
97
3
            .into_option()
98
3
            .unwrap_or_else(|| Self::style_donor().resolved_image_style())
99
3
    }
100

            
101
    /// The unstyled Button the three resolvers above defer to.
102
12
    fn style_donor() -> Button {
103
12
        Button::create(AzString::from_const_str(""))
104
12
    }
105
}
106

            
107
#[derive(Debug, Clone, PartialEq, Eq)]
108
#[repr(C)]
109
pub struct FileInputStateWrapper {
110
    pub inner: FileInputState,
111
    pub on_path_change: OptionFileInputOnPathChange,
112
    /// Title displayed in the file selection dialog
113
    pub file_dialog_title: AzString,
114
    /// Default directory of file input
115
    pub default_dir: OptionString,
116
}
117

            
118
impl Default for FileInputStateWrapper {
119
391
    fn default() -> Self {
120
391
        Self {
121
391
            inner: FileInputState::default(),
122
391
            on_path_change: None.into(),
123
391
            file_dialog_title: "Select File".into(),
124
391
            default_dir: None.into(),
125
391
        }
126
391
    }
127
}
128

            
129
/// Current state of the file input (selected path)
130
#[derive(Debug, Clone, PartialEq, Eq)]
131
#[repr(C)]
132
pub struct FileInputState {
133
    pub path: OptionString,
134
}
135

            
136
impl Default for FileInputState {
137
394
    fn default() -> Self {
138
394
        Self { path: None.into() }
139
394
    }
140
}
141

            
142
/// Callback type invoked when the file input path changes
143
pub type FileInputOnPathChangeCallbackType =
144
    extern "C" fn(RefAny, CallbackInfo, FileInputState) -> Update;
145

            
146
impl_widget_callback!(
147
    FileInputOnPathChange,
148
    OptionFileInputOnPathChange,
149
    FileInputOnPathChangeCallback,
150
    FileInputOnPathChangeCallbackType
151
);
152

            
153
azul_core::impl_managed_callback! {
154
    wrapper:        FileInputOnPathChangeCallback,
155
    info_ty:        CallbackInfo,
156
    return_ty:      Update,
157
    default_ret:    Update::DoNothing,
158
    invoker_static: FILE_INPUT_ON_PATH_CHANGE_INVOKER,
159
    invoker_ty:     AzFileInputOnPathChangeCallbackInvoker,
160
    thunk_fn:       az_file_input_on_path_change_callback_thunk,
161
    setter_fn:      AzApp_setFileInputOnPathChangeCallbackInvoker,
162
    from_handle_fn: AzFileInputOnPathChangeCallback_createFromHostHandle,
163
    extra_args:     [ state: FileInputState ],
164
}
165

            
166
impl FileInput {
167
    #[must_use]
168
183
    pub fn create(path: OptionString) -> Self {
169
183
        Self {
170
183
            file_input_state: FileInputStateWrapper {
171
183
                inner: FileInputState { path },
172
183
                ..Default::default()
173
183
            },
174
183
            ..Default::default()
175
183
        }
176
183
    }
177

            
178
    #[inline]
179
    #[must_use]
180
6
    pub fn swap_with_default(&mut self) -> Self {
181
6
        let mut s = Self::create(None.into());
182
6
        core::mem::swap(&mut s, self);
183
6
        s
184
6
    }
185

            
186
    #[inline]
187
80
    pub fn set_default_text(&mut self, default_text: AzString) {
188
80
        self.default_text = default_text;
189
80
    }
190

            
191
    #[inline]
192
    #[must_use]
193
41
    pub fn with_default_text(mut self, default_text: AzString) -> Self {
194
41
        self.set_default_text(default_text);
195
41
        self
196
41
    }
197

            
198
    #[inline]
199
13
    pub fn set_on_path_change<I: Into<FileInputOnPathChangeCallback>>(
200
13
        &mut self,
201
13
        refany: RefAny,
202
13
        callback: I,
203
13
    ) {
204
13
        self.file_input_state.on_path_change = Some(FileInputOnPathChange {
205
13
            callback: callback.into(),
206
13
            refany,
207
13
        })
208
13
        .into();
209
13
    }
210

            
211
    #[inline]
212
    #[must_use]
213
7
    pub fn with_on_path_change<I: Into<FileInputOnPathChangeCallback>>(
214
7
        mut self,
215
7
        refany: RefAny,
216
7
        callback: I,
217
7
    ) -> Self {
218
7
        self.set_on_path_change(refany, callback);
219
7
        self
220
7
    }
221

            
222
    #[inline]
223
    #[must_use]
224
89
    pub fn dom(self) -> Dom {
225
        // either show the default text or the file name
226
        // including the extension as the button label
227
89
        let button_label = match self.file_input_state.inner.path.as_ref() {
228
67
            Some(path) => std::path::Path::new(path.as_str())
229
67
                .file_name()
230
67
                .map_or_else(
231
29
                    || self.default_text.as_str().to_string(),
232
38
                    |s| s.to_string_lossy().to_string(),
233
                )
234
67
                .into(),
235
22
            None => self.default_text.clone(),
236
        };
237

            
238
89
        Button {
239
89
            label: button_label,
240
89
            theme: None.into(),
241
89
            image: self.image,
242
89
            icon: AzString::from_const_str(""),
243
89
            icon_dom: None.into(),
244
89
            trailing_icon: AzString::from_const_str(""),
245
89
            button_type: crate::widgets::button::ButtonType::Default,
246
89
            container_style: self.container_style,
247
89
            label_style: self.label_style,
248
89
            image_style: self.image_style,
249
89
            // No opinion, not an explicit empty. The Button below is built with
250
89
            // `icon: ""`, `icon_dom: None` and `trailing_icon: ""`, so neither
251
89
            // icon node is ever created and neither style is ever read — the two
252
89
            // spellings are identical today, and `None` is the one that does not
253
89
            // claim the caller asked for something.
254
89
            icon_style: OptionCssPropertyWithConditionsVec::None,
255
89
            trailing_icon_style: OptionCssPropertyWithConditionsVec::None,
256
89
            on_click: Some(ButtonOnClick {
257
89
                refany: RefAny::new(self.file_input_state),
258
89
                callback: ButtonOnClickCallback {
259
89
                    cb: fileinput_on_click,
260
89
                    ctx: azul_core::refany::OptionRefAny::None,
261
89
                },
262
89
            })
263
89
            .into(),
264
89
        }
265
89
        .dom()
266
89
    }
267
}
268

            
269
3
extern "C" fn fileinput_on_click(mut refany: RefAny, mut info: CallbackInfo) -> Update {
270
    // The click only ISSUES the request. The dialog answer arrives in
271
    // `fileinput_on_file_picked` as a fresh activation - the same shape on
272
    // desktop (modal dialog, resumed right after this callback returns),
273
    // mobile (OS picker delegate) and web (async picker). The widget's public
274
    // API does not change: `on_path_change` still fires once with the new
275
    // path, and `Update::RefreshDom` is still returned for the relabel.
276
    #[cfg(feature = "extra")]
277
    {
278
        use crate::desktop::dialogs::{FileDialog, OptionFileTypeList};
279

            
280
        let (title, default_dir) = {
281
3
            let Some(state) = refany.downcast_ref::<FileInputStateWrapper>() else {
282
3
                return Update::DoNothing;
283
            };
284
            (state.file_dialog_title.clone(), state.default_dir.clone())
285
        };
286
        let _ = info;
287
        let _request = FileDialog::open_file(
288
            title,
289
            default_dir,
290
            OptionFileTypeList::None,
291
            refany.clone(),
292
            crate::callbacks::ResumeCallback::create(fileinput_on_file_picked),
293
        );
294
        Update::DoNothing
295
    }
296
    // Without the `extra` feature there is no dialog to show; the widget
297
    // reports its (unchanged) state so an app can still react to the click.
298
    #[cfg(not(feature = "extra"))]
299
    {
300
        let Some(mut fileinputstatewrapper) = refany.downcast_mut::<FileInputStateWrapper>() else {
301
            return Update::DoNothing;
302
        };
303
        let fileinputstatewrapper = &mut *fileinputstatewrapper;
304
        let inner = fileinputstatewrapper.inner.clone();
305
        let mut result = match fileinputstatewrapper.on_path_change.as_mut() {
306
            Some(FileInputOnPathChange { refany, callback }) => {
307
                (callback.cb)(refany.clone(), info, inner)
308
            }
309
            None => Update::RefreshDom,
310
        };
311
        result.max_self(Update::RefreshDom);
312
        result
313
    }
314
3
}
315

            
316
/// Resume half of [`fileinput_on_click`]: stores the picked path and fires
317
/// the app's `on_path_change`. A cancelled dialog changes nothing.
318
#[cfg(feature = "extra")]
319
extern "C" fn fileinput_on_file_picked(
320
    mut refany: RefAny,
321
    mut info: CallbackInfo,
322
    result: RefAny,
323
) -> Update {
324
    use crate::desktop::dialogs::FileOpenResult;
325

            
326
    let Some(picked) = FileOpenResult::downcast(result).into_option() else {
327
        return Update::DoNothing;
328
    };
329
    let Some(path) = picked.path.into_option() else {
330
        return Update::DoNothing;
331
    };
332
    let Some(mut fileinputstatewrapper) = refany.downcast_mut::<FileInputStateWrapper>() else {
333
        return Update::DoNothing;
334
    };
335
    let fileinputstatewrapper = &mut *fileinputstatewrapper;
336
    fileinputstatewrapper.inner.path = OptionString::Some(path.inner);
337

            
338
    let inner = fileinputstatewrapper.inner.clone();
339
    let mut result = match fileinputstatewrapper.on_path_change.as_mut() {
340
        Some(FileInputOnPathChange { refany, callback }) => {
341
            (callback.cb)(refany.clone(), info, inner)
342
        }
343
        None => Update::RefreshDom,
344
    };
345
    result.max_self(Update::RefreshDom);
346
    result
347
}
348

            
349
#[cfg(all(test, feature = "std"))]
350
#[allow(clippy::too_many_lines)] // table-driven cases; splitting them hides the case list
351
mod autotest_generated {
352
    use std::{
353
        collections::{BTreeMap, HashMap},
354
        sync::{Arc, Mutex},
355
    };
356

            
357
    use azul_core::{
358
        dom::{
359
            DomId, DomNodeId, EventFilter, HoverEventFilter, IdOrClass, NodeId, NodeType, TabIndex,
360
        },
361
        geom::{LogicalRect, OptionLogicalPosition},
362
        gl::OptionGlContextPtr,
363
        hit_test::ScrollPosition,
364
        refany::OptionRefAny,
365
        resources::{ImageRef, RawImageFormat, RendererResources},
366
        styled_dom::{NodeHierarchyItemId, StyledDom},
367
        window::{MonitorVec, RawWindowHandle},
368
    };
369
    use rust_fontconfig::FcFontCache;
370

            
371
    use super::*;
372
    #[cfg(feature = "icu")]
373
    use crate::icu::IcuLocalizerHandle;
374
    use crate::{
375
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
376
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
377
        widgets::button::ButtonType,
378
        window::{DomLayoutResult, LayoutWindow},
379
        window_state::FullWindowState,
380
    };
381

            
382
    // ------------------------------------------------------------------
383
    // Fixtures
384
    // ------------------------------------------------------------------
385

            
386
    /// The label a path-less file input renders, per the doc comment on
387
    /// `FileInput::default_text`.
388
    const DEFAULT_TEXT: &str = "Select File...";
389

            
390
    /// The title `FileInputStateWrapper::default` puts on the native dialog. Note it is
391
    /// *not* the same string as `DEFAULT_TEXT` (no ellipsis) — a "cleanup" that unified
392
    /// the two would silently retitle every file dialog.
393
    const DEFAULT_DIALOG_TITLE: &str = "Select File";
394

            
395
    /// Paths whose *last* component is a real file name, paired with the label
396
    /// `dom()` must render for them. Only shapes that mean the same thing on every
397
    /// platform live here (`/` is a separator on Windows too); the backslash- and
398
    /// double-slash-specific shapes are tested per-platform below.
399
    fn file_name_cases() -> Vec<(String, String)> {
400
        [
401
            ("/tmp/report.pdf", "report.pdf"),
402
            ("report.pdf", "report.pdf"),
403
            ("/tmp/dir/", "dir"),   // a trailing separator is not a component
404
            ("/tmp/dir///", "dir"), // ...and neither are three of them
405
            ("a/.", "a"),           // a trailing `.` normalizes away
406
            ("/a/b/c/d/e/f/g.txt", "g.txt"),
407
            (".hidden", ".hidden"), // a leading dot is part of the name
408
            ("...", "..."),         // only `.` and `..` are special
409
            ("..a", "..a"),
410
            ("/tmp/archive.tar.gz", "archive.tar.gz"),
411
            ("  ", "  "), // whitespace is a legal file name
412
            ("/tmp/a b.txt", "a b.txt"),
413
            ("/tmp/a\nb.txt", "a\nb.txt"), // control chars survive verbatim
414
            ("/tmp/a\tb.txt", "a\tb.txt"),
415
            ("a\0b", "a\0b"), // OsStr allows interior NULs; must not truncate
416
            ("/tmp/a\0b.txt", "a\0b.txt"),
417
            ("/tmp/日本語.txt", "日本語.txt"),
418
            ("/tmp/e\u{0301}.txt", "e\u{0301}.txt"), // decomposed é: no normalization
419
            (
420
                "/tmp/\u{1F469}\u{200D}\u{1F467}.png", // ZWJ emoji sequence
421
                "\u{1F469}\u{200D}\u{1F467}.png",
422
            ),
423
            ("/tmp/\u{202E}gpj.exe", "\u{202E}gpj.exe"), // RTL-override spoof, kept as-is
424
            ("/tmp/\u{FFFD}.bin", "\u{FFFD}.bin"),
425
            ("/Select File.../x", "x"), // a directory named like the default text
426
        ]
427
        .iter()
428
        .map(|(p, l)| ((*p).to_string(), (*l).to_string()))
429
        .collect()
430
    }
431

            
432
    /// Paths with *no* file-name component: `Path::file_name` returns `None` for each,
433
    /// so `dom()` must fall back to `default_text` rather than render an empty button.
434
    fn no_file_name_cases() -> Vec<String> {
435
        [
436
            "", "/", ".", "..", "./", "/.", "/..", "a/..", "a/b/../", "../..",
437
        ]
438
        .iter()
439
        .map(|s| (*s).to_string())
440
        .collect()
441
    }
442

            
443
    /// Adversarial strings for the free-form text fields (`default_text`,
444
    /// `file_dialog_title`, `default_dir`): empty, whitespace-only, combining marks,
445
    /// ZWJ emoji, RTL, embedded NULs (`AzString` is length-based, so a NUL must not
446
    /// truncate), bidi overrides — plus one string far longer than any real label.
447
    fn adversarial_strings() -> Vec<String> {
448
        let mut v: Vec<String> = [
449
            "",
450
            " ",
451
            "Pick a file",
452
            "e\u{0301}",
453
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}",
454
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",
455
            "\0",
456
            "a\0b",
457
            "\u{FFFD}\u{202E}\u{200B}",
458
            "…\t\r\n",
459
            DEFAULT_TEXT,
460
        ]
461
        .iter()
462
        .map(|s| (*s).to_string())
463
        .collect();
464
        v.push("x".repeat(100_000));
465
        v
466
    }
467

            
468
    fn opt(s: &str) -> OptionString {
469
        Some(AzString::from(s)).into()
470
    }
471

            
472
    /// A file input with every field set to something distinguishable, so that a
473
    /// mutator touching a field it should not is visible.
474
    ///
475
    /// Deliberately image-*less*: `ImageRef` equality is identity-based (a fresh `id`
476
    /// per constructor call), so two independently-built images never compare equal and
477
    /// an image here would break every `assert_eq!` between two fixtures.
478
    fn populated() -> FileInput {
479
        let mut fi = FileInput::create(opt("/tmp/original.txt"));
480
        fi.default_text = "custom default".into();
481
        fi.file_input_state.file_dialog_title = "custom title".into();
482
        fi.file_input_state.default_dir = opt("/tmp/custom-dir");
483
        fi
484
    }
485

            
486
    /// [`populated`] plus an image. Only for tests that compare a widget against its own
487
    /// `clone()` (clones share the image identity) or do not compare widgets at all.
488
    fn populated_with_image() -> FileInput {
489
        let mut fi = populated();
490
        fi.image = Some(ImageRef::null_image(
491
            3,
492
            5,
493
            RawImageFormat::RGBA8,
494
            b"file-input-probe".to_vec(),
495
        ))
496
        .into();
497
        fi
498
    }
499

            
500
    // ------------------------------------------------------------------
501
    // DOM probes
502
    // ------------------------------------------------------------------
503

            
504
    fn text_of(dom: &Dom) -> Option<&str> {
505
        match dom.root.get_node_type() {
506
            NodeType::Text(s) => Some(s.as_ref().as_str()),
507
            _ => None,
508
        }
509
    }
510

            
511
    /// The rendered button label. `Button::dom` always appends the label *last*
512
    /// (an optional image is pushed as the first child), block-formatted as
513
    /// `<p>` wrapping the text node.
514
    fn rendered_label(dom: &Dom) -> String {
515
        let children = dom.children.as_ref();
516
        let last = children.last().expect("the button has no label child");
517
        assert!(
518
            matches!(last.root.get_node_type(), NodeType::P),
519
            "the button label is not block-formatted (<p>)"
520
        );
521
        let inner = last.children.as_ref();
522
        assert_eq!(inner.len(), 1, "the label <p> wraps exactly one text node");
523
        text_of(&inner[0])
524
            .expect("the button label is not a text node")
525
            .to_string()
526
    }
527

            
528
    fn classes(dom: &Dom) -> Vec<String> {
529
        dom.root
530
            .get_ids_and_classes()
531
            .as_ref()
532
            .iter()
533
            .filter_map(|c| match c {
534
                IdOrClass::Class(s) => Some(s.as_str().to_string()),
535
                IdOrClass::Id(_) => None,
536
            })
537
            .collect()
538
    }
539

            
540
    /// The recursive descendant count — `Dom::estimated_total_children` is a *cached*
541
    /// value that, if too small, makes `convert_dom_into_compact_dom` under-allocate
542
    /// its arenas and panic on out-of-bounds writes.
543
    fn count_descendants(dom: &Dom) -> usize {
544
        dom.children
545
            .as_ref()
546
            .iter()
547
            .map(|c| 1 + count_descendants(c))
548
            .sum()
549
    }
550

            
551
    /// The state wrapper the rendered DOM handed to its own click handler.
552
    fn registered_state(dom: &Dom) -> RefAny {
553
        let callbacks = dom.root.callbacks.as_ref();
554
        assert_eq!(
555
            callbacks.len(),
556
            1,
557
            "a file input must register exactly one callback",
558
        );
559
        callbacks[0].refany.clone()
560
    }
561

            
562
    fn state_of(refany: &RefAny) -> FileInputStateWrapper {
563
        let mut refany = refany.clone();
564
        let wrapper = refany
565
            .downcast_ref::<FileInputStateWrapper>()
566
            .expect("the widget state changed type");
567
        wrapper.clone()
568
    }
569

            
570
    // ------------------------------------------------------------------
571
    // Callback fixtures
572
    // ------------------------------------------------------------------
573

            
574
    /// A payload the path-change callback writes into. It arrives as the `refany`
575
    /// argument — a *shared* clone of what the test still holds — so the test reads
576
    /// back exactly what the widget passed, with no global state.
577
    #[derive(Debug, Clone, PartialEq, Eq)]
578
    struct PathLog {
579
        seen: Vec<Option<String>>,
580
        payload: u32,
581
    }
582

            
583
    fn log_refany() -> RefAny {
584
        RefAny::new(PathLog {
585
            seen: Vec::new(),
586
            payload: 0xDEAD_BEEF,
587
        })
588
    }
589

            
590
    fn read_log(probe: &RefAny) -> PathLog {
591
        let mut probe = probe.clone();
592
        let log = probe
593
            .downcast_ref::<PathLog>()
594
            .expect("the user payload changed type");
595
        log.clone()
596
    }
597

            
598
    extern "C" fn record_path(
599
        mut refany: RefAny,
600
        _info: CallbackInfo,
601
        state: FileInputState,
602
    ) -> Update {
603
        if let Some(mut log) = refany.downcast_mut::<PathLog>() {
604
            log.seen
605
                .push(state.path.as_ref().map(|p| p.as_str().to_string()));
606
        }
607
        Update::DoNothing
608
    }
609

            
610
    // Only reachable from `without_the_native_dialog`, which is compiled out on a
611
    // default (`extra`) desktop build.
612
    #[allow(dead_code)]
613
    extern "C" fn path_do_nothing(
614
        _refany: RefAny,
615
        _info: CallbackInfo,
616
        _state: FileInputState,
617
    ) -> Update {
618
        Update::DoNothing
619
    }
620

            
621
    extern "C" fn path_refresh_all(
622
        _refany: RefAny,
623
        _info: CallbackInfo,
624
        _state: FileInputState,
625
    ) -> Update {
626
        Update::RefreshDomAllWindows
627
    }
628

            
629
    /// A `Callback`-shaped (2-arg) function — the shape FFI bindings hand in, which the
630
    /// `From<Callback>` arm *transmutes* into the 3-arg file-input slot. Never called.
631
    extern "C" fn generic_shaped(_refany: RefAny, _info: CallbackInfo) -> Update {
632
        Update::DoNothing
633
    }
634

            
635
    fn cb_addr(cb: &FileInputOnPathChangeCallback) -> usize {
636
        cb.cb as *const () as usize
637
    }
638

            
639
    // ------------------------------------------------------------------
640
    // CallbackInfo harness
641
    // ------------------------------------------------------------------
642

            
643
    /// A `DomNodeId` in the root DOM pointing at flattened node `idx`.
644
    fn node(idx: usize) -> DomNodeId {
645
        DomNodeId {
646
            dom: DomId::ROOT_ID,
647
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
648
        }
649
    }
650

            
651
    /// A `DomNodeId` whose node component is `None` — the "no concrete node was hit"
652
    /// case. `fileinput_on_click` never queries the hit node, so it must survive it.
653
    fn node_none() -> DomNodeId {
654
        DomNodeId {
655
            dom: DomId::ROOT_ID,
656
            node: NodeHierarchyItemId::NONE,
657
        }
658
    }
659

            
660
    /// A `DomLayoutResult` carrying only a `styled_dom`: `fileinput_on_click` never
661
    /// queries the layout, so no real layout (and no font) is needed.
662
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
663
        DomLayoutResult {
664
            styled_dom,
665
            layout_tree: LayoutTree {
666
                nodes: Vec::new(),
667
                warm: Vec::new(),
668
                cold: Vec::new(),
669
                root: 0,
670
                dom_to_layout: BTreeMap::new(),
671
                children_arena: Vec::new(),
672
                children_offsets: Vec::new(),
673
                subtree_needs_intrinsic: Vec::new(),
674
            },
675
            calculated_positions: Vec::new(),
676
            viewport: LogicalRect::zero(),
677
            display_list: Arc::new(DisplayList::default()),
678
            scroll_ids: HashMap::new(),
679
            scroll_id_to_node_id: HashMap::new(),
680
        }
681
    }
682

            
683
    /// Runs `f` with a `CallbackInfo` whose window holds `styled_dom` as the root DOM
684
    /// and whose hit node is `hit`. Returns `f`'s value plus every change the callback
685
    /// pushed onto the transaction log.
686
    fn with_info<R>(
687
        styled_dom: StyledDom,
688
        hit: DomNodeId,
689
        f: impl FnOnce(&mut CallbackInfo) -> R,
690
    ) -> (R, Vec<CallbackChange>) {
691
        let mut layout_window =
692
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
693
        layout_window
694
            .layout_results
695
            .insert(DomId::ROOT_ID, layout_result(styled_dom));
696

            
697
        let renderer_resources = RendererResources::default();
698
        let previous_window_state: Option<FullWindowState> = None;
699
        let current_window_state = FullWindowState::default();
700
        let gl_context = OptionGlContextPtr::None;
701
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
702
            BTreeMap::new();
703
        let window_handle = RawWindowHandle::Unsupported;
704
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
705

            
706
        let ref_data = CallbackInfoRefData {
707
            layout_window: &layout_window,
708
            renderer_resources: &renderer_resources,
709
            previous_window_state: &previous_window_state,
710
            current_window_state: &current_window_state,
711
            gl_context: &gl_context,
712
            current_scroll_manager: &scroll_states,
713
            current_window_handle: &window_handle,
714
            system_callbacks: &system_callbacks,
715
            system_style: Arc::new(system::SystemStyle::default()),
716
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
717
            #[cfg(feature = "icu")]
718
            icu_localizer: IcuLocalizerHandle::default(),
719
            ctx: OptionRefAny::None,
720
        };
721

            
722
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
723

            
724
        let mut info = CallbackInfo::new(
725
            &ref_data,
726
            &changes,
727
            hit,
728
            OptionLogicalPosition::None,
729
            OptionLogicalPosition::None,
730
        );
731

            
732
        let r = f(&mut info);
733
        let pushed = info.take_changes();
734
        (r, pushed)
735
    }
736

            
737
    /// Renders `file_input`, then hands back both the laid-out DOM *and* the very
738
    /// `RefAny` the widget registered on its own mouse-up callback. Driving the handler
739
    /// with these two is the real wiring — nothing is re-created by hand, so a mismatch
740
    /// between what `dom()` stores and what the handler expects cannot hide behind the
741
    /// fixture.
742
    #[allow(dead_code)] // only used by `without_the_native_dialog` (see its doc comment)
743
    fn laid_out(file_input: FileInput) -> (StyledDom, RefAny) {
744
        let dom = file_input.dom();
745
        let state = registered_state(&dom);
746
        (StyledDom::create_from_dom(dom), state)
747
    }
748

            
749
    /// One "mouse-up on `hit`" delivered to the widget's own registered handler.
750
    fn click(
751
        styled_dom: StyledDom,
752
        state: &RefAny,
753
        hit: DomNodeId,
754
    ) -> (Update, Vec<CallbackChange>) {
755
        with_info(styled_dom, hit, |info| {
756
            fileinput_on_click(state.clone(), *info)
757
        })
758
    }
759

            
760
    // ==================================================================
761
    // FileInput::create
762
    // ==================================================================
763

            
764
    #[test]
765
    fn create_stores_the_path_verbatim() {
766
        // Byte-for-byte: a NUL must not truncate (AzString is length-based), a 100k
767
        // path must not be capped, and no normalization may happen at construction.
768
        let mut paths: Vec<String> = file_name_cases().into_iter().map(|(p, _)| p).collect();
769
        paths.extend(no_file_name_cases());
770
        paths.extend(adversarial_strings());
771
        paths.push(format!("/tmp/{}", "x".repeat(100_000)));
772

            
773
        for p in paths {
774
            let fi = FileInput::create(opt(&p));
775
            let stored = fi
776
                .file_input_state
777
                .inner
778
                .path
779
                .as_ref()
780
                .expect("create(Some(..)) dropped the path");
781
            assert_eq!(stored.as_str(), p, "create({p:?}) altered the path");
782
            assert_eq!(
783
                stored.as_str().len(),
784
                p.len(),
785
                "create({p:?}) changed the byte length of the path",
786
            );
787
        }
788
    }
789

            
790
    #[test]
791
    fn create_with_no_path_equals_the_default_widget() {
792
        let created = FileInput::create(None.into());
793
        assert!(
794
            created.file_input_state.inner.path.is_none(),
795
            "create(None) invented a path",
796
        );
797
        assert_eq!(
798
            created,
799
            FileInput::default(),
800
            "create(None) and Default disagree — the two constructors have drifted",
801
        );
802
    }
803

            
804
    #[test]
805
    fn create_uses_the_documented_defaults_for_every_other_field() {
806
        for p in [None.into(), opt(""), opt("/tmp/x.txt")] {
807
            let fi = FileInput::create(p);
808
            assert_eq!(fi.default_text.as_str(), DEFAULT_TEXT);
809
            assert_eq!(
810
                fi.file_input_state.file_dialog_title.as_str(),
811
                DEFAULT_DIALOG_TITLE,
812
            );
813
            assert!(fi.file_input_state.default_dir.is_none());
814
            assert!(
815
                fi.file_input_state.on_path_change.as_ref().is_none(),
816
                "create() invented a path-change callback out of nowhere",
817
            );
818
            assert!(fi.image.as_ref().is_none());
819
        }
820
    }
821

            
822
    #[test]
823
    fn create_inherits_the_button_styling_verbatim() {
824
        // The widget is documented as "same as `Button`" — it must not fork the
825
        // button's style vecs, or a restyle of Button would silently skip it.
826
        // Asked through the resolvers: both carry `None` now, so comparing the
827
        // fields would agree no matter what either widget actually renders.
828
        let button = Button::create(AzString::from_const_str(""));
829
        let fi = FileInput::create(opt("/tmp/x.txt"));
830
        assert_eq!(
831
            fi.resolved_container_style(),
832
            button.resolved_container_style()
833
        );
834
        assert_eq!(fi.resolved_label_style(), button.resolved_label_style());
835
        assert_eq!(fi.resolved_image_style(), button.resolved_image_style());
836
        assert!(
837
            !fi.resolved_container_style().as_ref().is_empty(),
838
            "a vacuous comparison of two empty vecs would prove nothing"
839
        );
840
    }
841

            
842
    #[test]
843
    fn create_is_pure_and_repeatable() {
844
        // Same argument, same widget — no hidden counter, clock or global state.
845
        for p in ["", "/tmp/a.txt", "\0"] {
846
            assert_eq!(FileInput::create(opt(p)), FileInput::create(opt(p)));
847
        }
848
    }
849

            
850
    // ==================================================================
851
    // FileInput::swap_with_default
852
    // ==================================================================
853

            
854
    #[test]
855
    fn swap_with_default_returns_the_original_and_resets_self() {
856
        let mut fi = populated_with_image().with_on_path_change(
857
            log_refany(),
858
            record_path as FileInputOnPathChangeCallbackType,
859
        );
860
        let before = fi.clone();
861

            
862
        let taken = fi.swap_with_default();
863

            
864
        assert_eq!(
865
            taken, before,
866
            "swap_with_default did not return the original"
867
        );
868
        assert_eq!(
869
            fi,
870
            FileInput::default(),
871
            "swap_with_default left the widget in a non-default state",
872
        );
873
        assert!(
874
            fi.file_input_state.on_path_change.as_ref().is_none(),
875
            "the callback survived the reset — a stale RefAny would keep firing",
876
        );
877
        assert!(fi.image.as_ref().is_none(), "the image survived the reset");
878
    }
879

            
880
    #[test]
881
    fn swap_with_default_moves_the_callback_out_intact() {
882
        let probe = log_refany();
883
        let mut fi = FileInput::create(opt("/tmp/x"))
884
            .with_on_path_change(probe, record_path as FileInputOnPathChangeCallbackType);
885

            
886
        let taken = fi.swap_with_default();
887

            
888
        let moved = taken
889
            .file_input_state
890
            .on_path_change
891
            .as_ref()
892
            .expect("the callback was lost in the swap");
893
        assert_eq!(
894
            cb_addr(&moved.callback),
895
            record_path as *const () as usize,
896
            "the moved-out callback points somewhere else",
897
        );
898
        assert_eq!(read_log(&moved.refany).payload, 0xDEAD_BEEF);
899
    }
900

            
901
    #[test]
902
    fn swap_with_default_twice_yields_the_default_the_second_time() {
903
        let mut fi = populated_with_image();
904
        let first = fi.swap_with_default();
905
        let second = fi.swap_with_default();
906

            
907
        assert_ne!(
908
            first, second,
909
            "the first swap did not actually take anything"
910
        );
911
        assert_eq!(second, FileInput::default());
912
        assert_eq!(
913
            fi,
914
            FileInput::default(),
915
            "the second swap dirtied the widget"
916
        );
917
    }
918

            
919
    #[test]
920
    fn swap_with_default_on_a_default_widget_is_a_no_op() {
921
        let mut fi = FileInput::default();
922
        let taken = fi.swap_with_default();
923
        assert_eq!(taken, FileInput::default());
924
        assert_eq!(fi, FileInput::default());
925
    }
926

            
927
    #[test]
928
    fn swap_with_default_preserves_extreme_field_values() {
929
        // A 100k default text and a NUL-bearing path must move across the swap
930
        // untouched — `mem::swap` is byte-wise, so any change means a rebuild.
931
        let huge = "x".repeat(100_000);
932
        let mut fi = FileInput::create(opt("a\0b"));
933
        fi.set_default_text(huge.as_str().into());
934

            
935
        let taken = fi.swap_with_default();
936

            
937
        assert_eq!(taken.default_text.as_str().len(), huge.len());
938
        assert_eq!(
939
            taken
940
                .file_input_state
941
                .inner
942
                .path
943
                .as_ref()
944
                .map(|p| p.as_str().to_string()),
945
            Some("a\0b".to_string()),
946
        );
947
    }
948

            
949
    // ==================================================================
950
    // FileInput::set_default_text / with_default_text
951
    // ==================================================================
952

            
953
    #[test]
954
    fn set_default_text_stores_the_text_verbatim() {
955
        for s in adversarial_strings() {
956
            let mut fi = FileInput::default();
957
            fi.set_default_text(s.as_str().into());
958
            assert_eq!(
959
                fi.default_text.as_str(),
960
                s,
961
                "set_default_text({s:?}) altered the text"
962
            );
963
            assert_eq!(
964
                fi.default_text.as_str().len(),
965
                s.len(),
966
                "set_default_text({s:?}) changed the byte length (NUL truncation?)",
967
            );
968
        }
969
    }
970

            
971
    #[test]
972
    fn set_default_text_is_last_write_wins() {
973
        let mut fi = FileInput::default();
974
        for s in adversarial_strings() {
975
            fi.set_default_text(s.as_str().into());
976
            assert_eq!(fi.default_text.as_str(), s);
977
        }
978
        fi.set_default_text("final".into());
979
        assert_eq!(fi.default_text.as_str(), "final");
980
    }
981

            
982
    #[test]
983
    fn set_default_text_touches_nothing_else() {
984
        let mut fi = populated_with_image();
985
        let before = fi.clone();
986
        fi.set_default_text("something else entirely".into());
987

            
988
        assert_eq!(fi.file_input_state.inner, before.file_input_state.inner);
989
        assert_eq!(
990
            fi.file_input_state.file_dialog_title,
991
            before.file_input_state.file_dialog_title,
992
        );
993
        assert_eq!(
994
            fi.file_input_state.default_dir,
995
            before.file_input_state.default_dir,
996
        );
997
        assert_eq!(
998
            fi.resolved_container_style(),
999
            before.resolved_container_style()
        );
        assert_eq!(fi.resolved_label_style(), before.resolved_label_style());
        assert_eq!(fi.resolved_image_style(), before.resolved_image_style());
        assert_eq!(fi.image, before.image);
    }
    #[test]
    fn with_default_text_matches_the_setter() {
        for s in adversarial_strings() {
            let mut by_setter = populated();
            by_setter.set_default_text(s.as_str().into());
            let by_builder = populated().with_default_text(s.as_str().into());
            assert_eq!(
                by_builder, by_setter,
                "with_default_text({s:?}) and set_default_text disagree",
            );
        }
    }
    #[test]
    fn with_default_text_chains_last_wins() {
        let fi = FileInput::default()
            .with_default_text("first".into())
            .with_default_text("second".into())
            .with_default_text("".into());
        assert_eq!(fi.default_text.as_str(), "");
    }
    // ==================================================================
    // FileInput::set_on_path_change / with_on_path_change
    // ==================================================================
    #[test]
    fn set_on_path_change_stores_the_function_pointer_and_the_data() {
        let probe = log_refany();
        let mut fi = FileInput::default();
        fi.set_on_path_change(
            probe.clone(),
            record_path as FileInputOnPathChangeCallbackType,
        );
        let stored = fi
            .file_input_state
            .on_path_change
            .as_ref()
            .expect("the callback was not stored");
        assert_eq!(cb_addr(&stored.callback), record_path as *const () as usize);
        assert_eq!(
            stored.refany, probe,
            "the widget stored a different RefAny than the one it was handed",
        );
        assert_eq!(read_log(&stored.refany).payload, 0xDEAD_BEEF);
    }
    #[test]
    fn set_on_path_change_overwrites_a_previous_callback() {
        // Two live callbacks would fire twice per click; the setter must replace.
        let mut fi = FileInput::default();
        fi.set_on_path_change(
            log_refany(),
            record_path as FileInputOnPathChangeCallbackType,
        );
        fi.set_on_path_change(
            RefAny::new(7_u32),
            path_refresh_all as FileInputOnPathChangeCallbackType,
        );
        let stored = fi
            .file_input_state
            .on_path_change
            .as_ref()
            .expect("no callback");
        assert_eq!(
            cb_addr(&stored.callback),
            path_refresh_all as *const () as usize,
            "the first callback survived the overwrite",
        );
        let mut data = stored.refany.clone();
        assert!(
            data.downcast_ref::<PathLog>().is_none(),
            "the first callback's data survived the overwrite",
        );
    }
    #[test]
    fn set_on_path_change_touches_nothing_else() {
        let mut fi = populated_with_image();
        let before = fi.clone();
        fi.set_on_path_change(
            log_refany(),
            record_path as FileInputOnPathChangeCallbackType,
        );
        assert_eq!(fi.default_text, before.default_text);
        assert_eq!(fi.file_input_state.inner, before.file_input_state.inner);
        assert_eq!(
            fi.file_input_state.file_dialog_title,
            before.file_input_state.file_dialog_title,
        );
        assert_eq!(
            fi.file_input_state.default_dir,
            before.file_input_state.default_dir,
        );
        assert_eq!(fi.image, before.image);
        assert_eq!(
            fi.resolved_container_style(),
            before.resolved_container_style()
        );
    }
    #[test]
    fn with_on_path_change_matches_the_setter() {
        let probe = log_refany();
        let mut by_setter = populated();
        by_setter.set_on_path_change(
            probe.clone(),
            record_path as FileInputOnPathChangeCallbackType,
        );
        let by_builder = populated()
            .with_on_path_change(probe, record_path as FileInputOnPathChangeCallbackType);
        assert_eq!(by_builder, by_setter);
    }
    #[test]
    fn a_generic_callback_keeps_its_address_and_context_through_the_transmute() {
        // FFI bindings hand in a 2-arg `Callback`; the `From<Callback>` arm transmutes
        // it into the 3-arg slot. The transmute must preserve the code address (calling
        // the wrong function) and the `ctx` payload (losing the Python/Lua callable).
        let ctx = RefAny::new(0xABCD_u32);
        let generic = Callback {
            cb: generic_shaped,
            ctx: OptionRefAny::Some(ctx.clone()),
        };
        let fi = FileInput::default().with_on_path_change(log_refany(), generic);
        let stored = fi
            .file_input_state
            .on_path_change
            .as_ref()
            .expect("no callback");
        assert_eq!(
            cb_addr(&stored.callback),
            generic_shaped as *const () as usize,
            "the transmute moved the function pointer",
        );
        assert_eq!(
            stored.callback.ctx,
            OptionRefAny::Some(ctx),
            "the FFI context was dropped by the transmute",
        );
    }
    #[test]
    fn a_raw_function_pointer_gets_no_ffi_context() {
        let fi = FileInput::default().with_on_path_change(
            log_refany(),
            record_path as FileInputOnPathChangeCallbackType,
        );
        let stored = fi
            .file_input_state
            .on_path_change
            .as_ref()
            .expect("no callback");
        assert_eq!(
            stored.callback.ctx,
            OptionRefAny::None,
            "a native Rust callback must not carry an FFI context",
        );
    }
    // ==================================================================
    // FileInput::dom
    // ==================================================================
    #[test]
    fn dom_labels_the_button_with_the_file_name() {
        for (path, expected) in file_name_cases() {
            let dom = FileInput::create(opt(&path)).dom();
            assert_eq!(
                rendered_label(&dom),
                expected,
                "dom() mislabelled the button for path {path:?}",
            );
        }
    }
    #[test]
    fn dom_falls_back_to_the_default_text_when_the_path_has_no_file_name() {
        // `/`, `.`, `..` and friends have no final `Normal` component. Rendering an
        // *empty* button there would leave the user with an unlabelled control.
        for path in no_file_name_cases() {
            let dom = FileInput::create(opt(&path)).dom();
            assert_eq!(
                rendered_label(&dom),
                DEFAULT_TEXT,
                "dom() did not fall back to the default text for path {path:?}",
            );
        }
    }
    #[test]
    fn dom_falls_back_to_the_default_text_when_no_path_is_set() {
        let dom = FileInput::create(None.into()).dom();
        assert_eq!(rendered_label(&dom), DEFAULT_TEXT);
    }
    #[test]
    fn dom_renders_a_custom_default_text_verbatim_when_there_is_no_file_name() {
        for s in adversarial_strings() {
            let fi = FileInput::create(None.into()).with_default_text(s.as_str().into());
            assert_eq!(
                rendered_label(&fi.dom()),
                s,
                "custom default text {s:?} was altered"
            );
            // ...and the same for a path that has no file-name component.
            let fi = FileInput::create(opt("/")).with_default_text(s.as_str().into());
            assert_eq!(rendered_label(&fi.dom()), s);
        }
    }
    #[test]
    fn dom_survives_a_100k_byte_file_name() {
        let huge = "x".repeat(100_000);
        let dom = FileInput::create(opt(&format!("/tmp/{huge}"))).dom();
        let label = rendered_label(&dom);
        assert_eq!(label.len(), huge.len(), "the 100k file name was truncated");
        assert_eq!(label, huge);
    }
    #[test]
    fn dom_prefers_the_file_name_over_the_default_text() {
        // A non-empty default text must not shadow a real selection.
        let fi = FileInput::create(opt("/tmp/chosen.txt")).with_default_text("NOT THIS".into());
        assert_eq!(rendered_label(&fi.dom()), "chosen.txt");
    }
    #[test]
    fn dom_renders_an_empty_label_when_both_the_path_and_the_default_text_are_empty() {
        let fi = FileInput::create(opt("")).with_default_text("".into());
        assert_eq!(rendered_label(&fi.dom()), "");
    }
    #[test]
    fn dom_ignores_the_dialog_title_and_default_dir_when_labelling() {
        // Only `path`/`default_text` may reach the label; leaking the dialog title or
        // the default directory into the button would be visible to the user.
        let mut fi = FileInput::create(None.into());
        fi.file_input_state.file_dialog_title = "TITLE-LEAK".into();
        fi.file_input_state.default_dir = opt("/DIR-LEAK");
        let label = rendered_label(&fi.dom());
        assert_eq!(label, DEFAULT_TEXT);
        assert!(!label.contains("LEAK"));
    }
    #[test]
    fn dom_renders_a_native_button_node() {
        let dom = FileInput::create(opt("/tmp/x.txt")).dom();
        assert!(
            matches!(dom.root.get_node_type(), NodeType::Button),
            "the file input no longer renders a <button>",
        );
        assert_eq!(
            classes(&dom),
            vec![
                "__azul-native-button".to_string(),
                ButtonType::Default.class_name().to_string(),
                // The theme marker the render path adds — `Button::dom` renders through
                // `flat::button` / `flora::button`, which tag the node with their theme.
                "__azul-theme-flat".to_string(),
            ],
            "the file input must be styleable as a default-type native button",
        );
        assert!(
            matches!(dom.root.get_tab_index(), Some(TabIndex::Auto)),
            "the file input dropped the button's keyboard focusability",
        );
    }
    #[test]
    fn dom_registers_exactly_one_mouseup_callback_into_fileinput_on_click() {
        let dom = FileInput::create(opt("/tmp/x.txt")).dom();
        let callbacks = dom.root.callbacks.as_ref();
        assert_eq!(callbacks.len(), 1, "a click must fire exactly one handler");
        assert_eq!(
            callbacks[0].event,
            EventFilter::Hover(HoverEventFilter::Click)
        );
        assert_eq!(
            callbacks[0].callback.cb, fileinput_on_click as *const () as usize,
            "the DOM is wired to a different handler than fileinput_on_click",
        );
        assert_eq!(
            callbacks[0].callback.ctx,
            OptionRefAny::None,
            "the internal handler must not carry an FFI context",
        );
    }
    #[test]
    fn dom_hands_the_whole_state_wrapper_to_the_handler() {
        // The click handler reads the dialog title, the default dir *and* the user
        // callback out of this RefAny — dropping any of them silently disables them.
        let probe = log_refany();
        let mut fi = FileInput::create(opt("/tmp/original.txt"));
        fi.file_input_state.file_dialog_title = "custom title".into();
        fi.file_input_state.default_dir = opt("/tmp/custom-dir");
        fi.set_on_path_change(probe, record_path as FileInputOnPathChangeCallbackType);
        let expected = fi.file_input_state.clone();
        let state = state_of(&registered_state(&fi.dom()));
        assert_eq!(state.inner, expected.inner);
        assert_eq!(state.file_dialog_title, expected.file_dialog_title);
        assert_eq!(state.default_dir, expected.default_dir);
        let stored = state
            .on_path_change
            .as_ref()
            .expect("the user callback was dropped");
        assert_eq!(cb_addr(&stored.callback), record_path as *const () as usize);
    }
    #[test]
    fn dom_child_count_matches_the_cached_descendant_count() {
        // A too-small `estimated_total_children` makes `convert_dom_into_compact_dom`
        // under-allocate its arenas and panic on out-of-bounds writes.
        for fi in [
            FileInput::create(None.into()),
            FileInput::create(opt("/tmp/x.txt")),
            populated_with_image(),
        ] {
            let has_image = fi.image.as_ref().is_some();
            let dom = fi.dom();
            assert_eq!(
                dom.estimated_total_children,
                count_descendants(&dom),
                "estimated_total_children is out of sync with the real subtree",
            );
            assert_eq!(
                dom.children.as_ref().len(),
                usize::from(has_image) + 1,
                "unexpected child count",
            );
        }
    }
    #[test]
    fn dom_renders_the_image_before_the_label() {
        let fi = populated_with_image();
        let dom = fi.dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2);
        assert!(
            matches!(children[0].root.get_node_type(), NodeType::Image(_)),
            "the image is not the first child",
        );
        assert_eq!(rendered_label(&dom), "original.txt");
    }
    #[test]
    fn dom_is_deterministic_for_identical_widgets() {
        for path in ["/tmp/a.txt", "/", ""] {
            let a = FileInput::create(opt(path)).dom();
            let b = FileInput::create(opt(path)).dom();
            assert_eq!(a.root.get_node_type(), b.root.get_node_type());
            assert_eq!(classes(&a), classes(&b));
            assert_eq!(rendered_label(&a), rendered_label(&b));
            assert_eq!(a.children.as_ref().len(), b.children.as_ref().len());
        }
    }
    #[cfg(unix)]
    #[test]
    fn dom_does_not_treat_a_backslash_as_a_separator_on_unix() {
        // A backslash is a perfectly legal *character* in a POSIX file name; splitting
        // on it would mislabel (and, worse, misreport) the selected file.
        let dom = FileInput::create(opt("C:\\dir\\file.txt")).dom();
        assert_eq!(rendered_label(&dom), "C:\\dir\\file.txt");
        let dom = FileInput::create(opt("/tmp/a\\b.txt")).dom();
        assert_eq!(rendered_label(&dom), "a\\b.txt");
    }
    #[cfg(unix)]
    #[test]
    fn dom_handles_multiple_leading_slashes_on_unix() {
        assert_eq!(
            rendered_label(&FileInput::create(opt("//")).dom()),
            DEFAULT_TEXT
        );
        assert_eq!(
            rendered_label(&FileInput::create(opt("///")).dom()),
            DEFAULT_TEXT
        );
        assert_eq!(
            rendered_label(&FileInput::create(opt("//a.txt")).dom()),
            "a.txt"
        );
    }
    #[cfg(windows)]
    #[test]
    fn dom_treats_a_backslash_as_a_separator_on_windows() {
        let dom = FileInput::create(opt("C:\\dir\\file.txt")).dom();
        assert_eq!(rendered_label(&dom), "file.txt");
    }
    // ==================================================================
    // fileinput_on_click
    // ==================================================================
    #[test]
    fn click_with_a_foreign_refany_does_nothing() {
        // The handler is reached through an FFI-visible `usize` function pointer, so a
        // mismatched payload is reachable in practice; it must be rejected by the
        // type check rather than reinterpreted.
        let styled = StyledDom::create_from_dom(FileInput::create(opt("/tmp/x.txt")).dom());
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes) = click(styled, &foreign, node(0));
        assert_eq!(
            update,
            Update::DoNothing,
            "a foreign payload must not trigger a relayout",
        );
        assert!(
            changes.is_empty(),
            "a foreign payload pushed changes: {changes:?}"
        );
        let mut foreign = foreign;
        assert_eq!(
            *foreign
                .downcast_ref::<u32>()
                .expect("the payload was overwritten"),
            0xDEAD_BEEF,
        );
    }
    #[test]
    fn click_rejects_the_inner_state_mistaken_for_the_wrapper() {
        // `FileInputState` is the *inner* half of `FileInputStateWrapper` and is what
        // the user callback receives — passing it back in is the most likely confusion,
        // and reinterpreting it would read an `OptionString` as a callback pointer.
        let styled = StyledDom::create_from_dom(FileInput::create(opt("/tmp/x.txt")).dom());
        let inner = RefAny::new(FileInputState {
            path: opt("/tmp/x.txt"),
        });
        let (update, changes) = click(styled, &inner, node(0));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_a_foreign_refany_ignores_the_hit_node() {
        // `node_none()` is the "nothing concrete was hit" id that panics several
        // `CallbackInfo` queries — the handler must never reach them.
        let styled = StyledDom::create_from_dom(FileInput::create(None.into()).dom());
        let foreign = RefAny::new(0_u8);
        let (update, changes) = click(styled, &foreign, node_none());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    /// `fileinput_on_click` opens a **modal native file dialog** before it ever reaches
    /// the user callback whenever the `extra` feature is on (which it is by default, on
    /// desktop). Driving the handler with a well-typed payload would block the test run
    /// on a GUI prompt, so everything past the downcast is only exercised in builds
    /// where that block is compiled out. The type-rejection path above runs everywhere.
    #[cfg(any(not(feature = "extra"), target_os = "android", target_os = "ios"))]
    mod without_the_native_dialog {
        use super::*;
        #[test]
        fn click_without_a_user_callback_refreshes_the_dom() {
            let (styled, state) = laid_out(FileInput::create(opt("/tmp/x.txt")));
            let (update, changes) = click(styled, &state, node(0));
            assert_eq!(
                update,
                Update::RefreshDom,
                "a click must relayout so the new label is drawn",
            );
            assert!(
                changes.is_empty(),
                "the handler pushed unexpected changes: {changes:?}"
            );
            assert_eq!(
                state_of(&state)
                    .inner
                    .path
                    .as_ref()
                    .map(|p| p.as_str().to_string()),
                Some("/tmp/x.txt".to_string()),
                "the handler mutated the path without a dialog",
            );
        }
        #[test]
        fn click_upgrades_a_do_nothing_user_callback_to_a_refresh() {
            // `result.max_self(Update::RefreshDom)` deliberately swallows the user's
            // `DoNothing` — the label may have changed, so the DOM must be rebuilt.
            let fi = FileInput::create(opt("/tmp/x.txt")).with_on_path_change(
                RefAny::new(0_u8),
                path_do_nothing as FileInputOnPathChangeCallbackType,
            );
            let (styled, state) = laid_out(fi);
            let (update, _) = click(styled, &state, node(0));
            assert_eq!(update, Update::RefreshDom);
        }
        #[test]
        fn click_preserves_a_stronger_user_update() {
            // `max_self` must not *downgrade* RefreshDomAllWindows to RefreshDom.
            let fi = FileInput::create(opt("/tmp/x.txt")).with_on_path_change(
                RefAny::new(0_u8),
                path_refresh_all as FileInputOnPathChangeCallbackType,
            );
            let (styled, state) = laid_out(fi);
            let (update, _) = click(styled, &state, node(0));
            assert_eq!(update, Update::RefreshDomAllWindows);
        }
        #[test]
        fn click_hands_the_current_path_to_the_user_callback() {
            for path in ["/tmp/a.txt", "", "a\0b", "/tmp/日本語.txt"] {
                let probe = log_refany();
                let fi = FileInput::create(opt(path)).with_on_path_change(
                    probe.clone(),
                    record_path as FileInputOnPathChangeCallbackType,
                );
                let (styled, state) = laid_out(fi);
                let (_, _) = click(styled, &state, node(0));
                assert_eq!(
                    read_log(&probe).seen,
                    vec![Some(path.to_string())],
                    "the callback saw the wrong path for {path:?}",
                );
            }
        }
        #[test]
        fn click_hands_a_missing_path_through_as_none() {
            let probe = log_refany();
            let fi = FileInput::create(None.into()).with_on_path_change(
                probe.clone(),
                record_path as FileInputOnPathChangeCallbackType,
            );
            let (styled, state) = laid_out(fi);
            let (_, _) = click(styled, &state, node(0));
            assert_eq!(read_log(&probe).seen, vec![None]);
        }
        #[test]
        fn repeated_clicks_fire_once_each_and_leave_the_state_alone() {
            let probe = log_refany();
            let fi = FileInput::create(opt("/tmp/a.txt")).with_on_path_change(
                probe.clone(),
                record_path as FileInputOnPathChangeCallbackType,
            );
            let (styled, state) = laid_out(fi);
            for _ in 0..3 {
                let (update, _) = click(styled.clone(), &state, node(0));
                assert_eq!(update, Update::RefreshDom);
            }
            assert_eq!(
                read_log(&probe).seen.len(),
                3,
                "clicks were dropped or doubled"
            );
            assert_eq!(
                state_of(&state)
                    .inner
                    .path
                    .as_ref()
                    .map(|p| p.as_str().to_string()),
                Some("/tmp/a.txt".to_string()),
            );
        }
        /// Records whether a *re-entrant* borrow of the widget state succeeded while the
        /// click handler still holds its own `downcast_mut` guard.
        struct ReentryProbe {
            state: RefAny,
            saw_mut: Option<bool>,
            saw_ref: Option<bool>,
        }
        extern "C" fn probe_reentry(
            mut refany: RefAny,
            _info: CallbackInfo,
            _state: FileInputState,
        ) -> Update {
            let Some(mut probe) = refany.downcast_mut::<ReentryProbe>() else {
                return Update::DoNothing;
            };
            let probe = &mut *probe;
            let saw_mut = probe
                .state
                .downcast_mut::<FileInputStateWrapper>()
                .is_some();
            let saw_ref = probe
                .state
                .downcast_ref::<FileInputStateWrapper>()
                .is_some();
            probe.saw_mut = Some(saw_mut);
            probe.saw_ref = Some(saw_ref);
            Update::DoNothing
        }
        #[test]
        fn a_reentrant_borrow_of_the_state_is_refused_rather_than_aliased() {
            // The handler holds a `RefMut` on the state for its whole body, including
            // the user callback. A user callback that grabs the same state must be told
            // "no" (None) — handing out a second `&mut` to the same bytes would be UB,
            // and panicking/deadlocking would take the app down on a mere double-borrow.
            let probe = RefAny::new(ReentryProbe {
                state: RefAny::new(0_u8),
                saw_mut: None,
                saw_ref: None,
            });
            let fi = FileInput::create(opt("/tmp/a.txt")).with_on_path_change(
                probe.clone(),
                probe_reentry as FileInputOnPathChangeCallbackType,
            );
            let (styled, state) = laid_out(fi);
            {
                let mut handle = probe.clone();
                let mut guard = handle
                    .downcast_mut::<ReentryProbe>()
                    .expect("the probe changed type");
                guard.state = state.clone();
            }
            let (update, _) = click(styled, &state, node(0));
            let mut handle = probe.clone();
            let guard = handle
                .downcast_mut::<ReentryProbe>()
                .expect("the probe changed type");
            assert_eq!(
                guard.saw_mut,
                Some(false),
                "a second &mut to the state was handed out"
            );
            assert_eq!(
                guard.saw_ref,
                Some(false),
                "a & alongside the live &mut was handed out"
            );
            drop(guard);
            assert_eq!(update, Update::RefreshDom);
            assert_eq!(
                state_of(&state)
                    .inner
                    .path
                    .as_ref()
                    .map(|p| p.as_str().to_string()),
                Some("/tmp/a.txt".to_string()),
                "the state was corrupted by the re-entrant attempt",
            );
        }
    }
}