elbey 0.6.1

A desktop app launcher for Linux
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
//! Functions and other types for `iced` UI to view, filter, and launch apps
use std::cmp::{max, min};
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::exit;

use freedesktop_desktop_entry::DesktopEntry;
use freedesktop_icons::lookup;
use iced::keyboard::key::Named;
use iced::keyboard::Key;
use iced::widget::button::{primary, text as text_style};
use iced::widget::image::Handle as ImageHandle;
use iced::widget::operation::focus;
use iced::widget::svg::Handle as SvgHandle;
use iced::widget::{button, column, image, row, scrollable, svg, text, text_input, Column};
use iced::{event, window, Alignment, Element, Event, Length, Pixels, Task, Theme};
use iced_layershell::to_layer_message;
use serde::{Deserialize, Serialize};

use crate::values::*;
use crate::CACHE;
use crate::PROGRAM_NAME;

#[cfg(test)]
use iced_runtime::{task::into_stream, Action, Task as RuntimeTask};

fn persist_cache_snapshot(apps: &[AppDescriptor]) {
    if let Ok(mut cache) = CACHE.lock() {
        if let Err(e) = cache.store_snapshot(apps) {
            eprintln!("Failed to persist cache snapshot: {e}");
        }
    }
}

fn not_loaded_icon() -> IconHandle {
    IconHandle::NotLoaded
}

fn icon_handle_from_path(p: PathBuf) -> IconHandle {
    if p.extension().and_then(|s| s.to_str()) == Some("svg") {
        IconHandle::Vector(SvgHandle::from_path(p))
    } else {
        IconHandle::Raster(ImageHandle::from_path(p))
    }
}

fn default_icon_handle() -> IconHandle {
    FALLBACK_ICON_HANDLE.clone()
}

fn set_icon(app: &mut AppDescriptor, handle: IconHandle, path: Option<PathBuf>) {
    app.icon_handle = handle;
    app.icon_path = path;
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppDescriptor {
    pub appid: String,
    pub title: String,
    #[serde(default)]
    pub lower_title: String,
    pub exec: String,
    pub exec_count: usize,
    pub icon_name: Option<String>,
    #[serde(default)]
    pub icon_path: Option<PathBuf>,
    #[serde(skip, default = "not_loaded_icon")]
    pub icon_handle: IconHandle,
}

impl From<DesktopEntry> for AppDescriptor {
    fn from(value: DesktopEntry) -> Self {
        AppDescriptor {
            appid: value.appid.clone(),
            title: value.desktop_entry("Name").expect("get name").to_string(),
            lower_title: value
                .desktop_entry("Name")
                .expect("get name")
                .to_lowercase(),
            exec: value.exec().expect("has exec").to_string(),
            exec_count: 0,
            icon_name: value.icon().map(str::to_string),
            icon_path: None,
            icon_handle: IconHandle::NotLoaded,
        }
    }
}

/// The application model type.  See [the iced book](https://book.iced.rs/) for details.
#[derive(Debug)]
pub struct State {
    /// A text entry box where a user can enter list filter criteria
    entry: String,
    /// Lowercased entry text to avoid repeated allocations during filtering
    entry_lower: String,
    /// The complete list of DesktopEntry, as retrieved by lib
    apps: Vec<AppDescriptor>,
    /// Indices of apps that match the current filter, to avoid re-filtering
    filtered_indices: Vec<usize>,
    /// The index of the item visibly selected in the UI
    selected_index: usize,
    /// A flag to indicate app window has received focus. Work around to some windowing environments passing `unfocused` unexpectedly.
    received_focus: bool,
    /// Cache of icon handles keyed by icon name to avoid repeated theme lookups
    icon_cache: HashMap<String, IconHandle>,
}

/// Root struct of application
#[derive(Debug)]
pub struct Elbey {
    state: State,
    flags: ElbeyFlags,
}

/// Number of icons to prefetch beyond the current viewport to avoid UI jank when scrolling.
const PREFETCH_ICON_COUNT: usize = VIEWABLE_LIST_ITEM_COUNT;

/// Messages are how your logic mutates the app state and GUI
#[to_layer_message]
#[derive(Debug, Clone)]
pub enum ElbeyMessage {
    /// Signals that the `DesktopEntries` have been fully loaded into the vec
    ModelLoaded(Vec<AppDescriptor>),
    /// Signals that an icon path has been found for an app
    IconLoaded(usize, Option<PathBuf>),
    /// Signals that the primary text edit box on the UI has been changed by the user, including the new text.
    EntryUpdate(String),
    /// Signals that the user has taken primary action on a selection.  In the case of a desktop app launcher, the app is launched.
    ExecuteSelected(),
    /// Signals that the user has pressed a key
    KeyEvent(Key),
    /// Signals that the window has gained focus
    GainedFocus,
    /// Signals that the window has lost focus
    LostFocus,
}

/// Provide some initial configuration to app to facilitate testing
#[derive(Debug, Clone)]
pub struct ElbeyFlags {
    /**
     * A function that returns a list of `DesktopEntry`s
     */
    pub apps_loader: fn() -> Vec<AppDescriptor>,
    /**
     * A function that launches a process from a `DesktopEntry`
     */
    pub app_launcher: fn(&AppDescriptor) -> anyhow::Result<()>, //TODO ~ return a task that exits app

    pub theme: Theme,

    pub icon_size: u16,

    /// Placeholder text for the entry field.
    pub hint: String,

    /// Font size for the filter input.
    pub filter_font_size: u16,

    /// Font size for the entry list items.
    pub entries_font_size: u16,
}

impl Elbey {
    /// Initialize the app.  Only notable item here is probably the return type Task<ElbeyMessage> and what we pass
    /// back.  Here, within the async execution, we directly call the library to retrieve `DesktopEntry`'s which
    /// are the primary model of the [XDG Desktop Specification](https://www.freedesktop.org/wiki/Specifications/desktop-entry-spec/).
    /// Then we create and pass a layer shell as another task.
    pub fn new(flags: ElbeyFlags) -> (Self, Task<ElbeyMessage>) {
        // A task to load the app model
        let apps_loader = flags.apps_loader;
        let load_task = Task::perform(async move { (apps_loader)() }, ElbeyMessage::ModelLoaded);

        (
            Self {
                state: State {
                    entry: String::new(),
                    entry_lower: String::new(),
                    apps: vec![],
                    filtered_indices: vec![],
                    selected_index: 0,
                    received_focus: false,
                    icon_cache: HashMap::new(),
                },
                flags,
            },
            load_task,
        )
    }

    pub fn namespace() -> String {
        PROGRAM_NAME.to_string()
    }

    /// Entry-point from `iced`` into app to construct UI
    pub fn view(&self) -> Element<'_, ElbeyMessage> {
        // Create the list UI elements based on the `DesktopEntry` model
        let app_elements: Vec<Element<ElbeyMessage>> = self
            .state
            .filtered_indices
            .iter()
            .enumerate()
            .filter_map(|(filtered_index, original_index)| {
                self.state
                    .apps
                    .get(*original_index)
                    .map(|entry| (filtered_index, entry))
            })
            .filter(|(filtered_index, _)| {
                (self.state.selected_index..self.state.selected_index + VIEWABLE_LIST_ITEM_COUNT)
                    .contains(filtered_index)
            }) // Only show entries in selection range
            .map(|(filtered_index, entry)| {
                let name = entry.title.as_str();
                let selected = self.state.selected_index == filtered_index;
                let icon_handle_to_render = match &entry.icon_handle {
                    IconHandle::NotLoaded => default_icon_handle(),
                    IconHandle::Loading => default_icon_handle(),
                    other => other.clone(),
                };
                let icon: Element<'_, ElbeyMessage> = match icon_handle_to_render {
                    IconHandle::Raster(handle) => image(handle)
                        .width(Length::Fixed(self.flags.icon_size.into()))
                        .height(Length::Fixed(self.flags.icon_size.into()))
                        .into(),
                    IconHandle::Vector(handle) => svg(handle)
                        .width(Length::Fixed(self.flags.icon_size.into()))
                        .height(Length::Fixed(self.flags.icon_size.into()))
                        .into(),
                    IconHandle::Loading => unreachable!(),
                    IconHandle::NotLoaded => unreachable!(),
                };
                let content = row![
                    icon,
                    text(name).size(Pixels::from(u32::from(self.flags.entries_font_size)))
                ]
                .spacing(10)
                .align_y(Alignment::Center);

                button(content)
                    .style(if selected { primary } else { text_style })
                    .width(Length::Fill)
                    .on_press(ElbeyMessage::ExecuteSelected())
                    .into()
            })
            .collect();

        // Bare bones!
        // TODO: Fancier layout?
        column![
            text_input(&self.flags.hint, &self.state.entry)
                .id(ENTRY_WIDGET_ID.clone())
                .on_input(ElbeyMessage::EntryUpdate)
                .size(Pixels::from(u32::from(self.flags.filter_font_size)))
                .width(Length::Fill),
            scrollable(Column::with_children(app_elements))
                .width(Length::Fill)
                .id(ITEMS_WIDGET_ID.clone()),
        ]
        .into()
    }

    /// Entry-point from `iced` to handle user and system events
    pub fn update(&mut self, message: ElbeyMessage) -> Task<ElbeyMessage> {
        match message {
            // The model has been loaded, initialize the UI
            ElbeyMessage::ModelLoaded(items) => {
                self.state.apps = items;
                self.state.entry_lower = self.state.entry.to_lowercase();
                self.state.icon_cache.reserve(
                    self.state
                        .apps
                        .len()
                        .saturating_sub(self.state.icon_cache.len()),
                );
                self.refresh_filtered_indices();
                let focus_task = focus(ENTRY_WIDGET_ID.clone());
                let load_icons_task = self.load_visible_icons();
                Task::batch(vec![focus_task, load_icons_task])
            }
            // Rebuild the select list based on the updated text entry
            ElbeyMessage::EntryUpdate(entry_text) => {
                self.state.entry = entry_text;
                self.state.entry_lower = self.state.entry.to_lowercase();
                self.state.selected_index = 0;
                self.refresh_filtered_indices();
                self.load_visible_icons()
            }
            // Launch an application selected by the user
            ElbeyMessage::ExecuteSelected() => {
                if let Some(entry) = self.selected_entry() {
                    (self.flags.app_launcher)(entry).expect("Failed to launch app");
                }
                Task::none()
            }
            ElbeyMessage::IconLoaded(index, path) => {
                if let Some(app) = self.state.apps.get_mut(index) {
                    if let Some(p) = path {
                        let handle = icon_handle_from_path(p.clone());
                        if let Some(icon_name) = app.icon_name.clone() {
                            self.state.icon_cache.insert(icon_name, handle.clone());
                        }
                        set_icon(app, handle, Some(p));
                    } else {
                        let fallback = default_icon_handle();
                        if let Some(icon_name) = app.icon_name.clone() {
                            self.state.icon_cache.insert(icon_name, fallback.clone());
                        }
                        set_icon(app, fallback, Some(PathBuf::new()));
                    }
                    persist_cache_snapshot(&self.state.apps);
                }
                Task::none()
            }
            // Handle keyboard entries
            ElbeyMessage::KeyEvent(key) => match key {
                Key::Named(Named::Escape) => {
                    persist_cache_snapshot(&self.state.apps);
                    exit(0)
                }
                Key::Named(Named::ArrowUp) => {
                    self.navigate_items(-1);
                    self.load_visible_icons()
                }
                Key::Named(Named::ArrowDown) => {
                    self.navigate_items(1);
                    self.load_visible_icons()
                }
                Key::Named(Named::PageUp) => {
                    self.navigate_items(-(VIEWABLE_LIST_ITEM_COUNT as i32));
                    self.load_visible_icons()
                }
                Key::Named(Named::PageDown) => {
                    self.navigate_items(VIEWABLE_LIST_ITEM_COUNT as i32);
                    self.load_visible_icons()
                }
                Key::Named(Named::Enter) => {
                    if let Some(entry) = self.selected_entry() {
                        (self.flags.app_launcher)(entry).expect("Failed to launch app");
                    }
                    Task::none()
                }
                _ => Task::none(),
            },
            // Handle window events
            ElbeyMessage::GainedFocus => {
                self.state.received_focus = true;
                focus(ENTRY_WIDGET_ID.clone())
            }
            ElbeyMessage::LostFocus => {
                if self.state.received_focus {
                    persist_cache_snapshot(&self.state.apps);
                    exit(0);
                }
                Task::none()
            }
            ElbeyMessage::AnchorChange(anchor) => {
                dbg!(anchor);
                Task::none()
            }
            ElbeyMessage::SetInputRegion(_action_callback) => Task::none(),
            ElbeyMessage::AnchorSizeChange(anchor, _) => {
                dbg!(anchor);
                Task::none()
            }
            ElbeyMessage::ExclusiveZoneChange(exclusive_zone) => {
                dbg!(exclusive_zone);
                Task::none()
            }
            ElbeyMessage::LayerChange(layer) => {
                dbg!(layer);
                Task::none()
            }
            ElbeyMessage::MarginChange(mc) => {
                dbg!(mc);
                Task::none()
            }
            ElbeyMessage::SizeChange(sc) => {
                dbg!(sc);
                Task::none()
            }
            ElbeyMessage::VirtualKeyboardPressed { time, key } => {
                dbg!(time, key);
                Task::none()
            }
        }
    }

    /// The `iced` entry-point to setup event listeners
    pub fn subscription(&self) -> iced::Subscription<ElbeyMessage> {
        // Framework code to integrate with underlying user interface devices; keyboard, mouse.
        event::listen_with(|event, _status, _| match event {
            Event::Window(window::Event::Focused) => Some(ElbeyMessage::GainedFocus),
            Event::Window(window::Event::Unfocused) => Some(ElbeyMessage::LostFocus),
            Event::Keyboard(iced::keyboard::Event::KeyPressed {
                modifiers: _,
                text: _,
                key,
                location: _,
                modified_key: _,
                physical_key: _,
                repeat: _,
            }) => Some(ElbeyMessage::KeyEvent(key)),
            _ => None,
        })
    }

    pub fn theme(&self) -> Theme {
        self.flags.theme.clone()
    }
}

impl Elbey {
    // Return ref to the selected item from the app list after applying filter
    fn selected_entry(&self) -> Option<&AppDescriptor> {
        self.state
            .filtered_indices
            .get(self.state.selected_index)
            .and_then(|original_index| self.state.apps.get(*original_index))
    }

    fn navigate_items(&mut self, delta: i32) {
        let filtered_len = self.state.filtered_indices.len();
        if filtered_len == 0 {
            self.state.selected_index = 0;
            return;
        }

        if delta < 0 {
            self.state.selected_index = max(0, self.state.selected_index as i32 + delta) as usize;
        } else {
            self.state.selected_index = min(
                filtered_len as i32 - 1,
                self.state.selected_index as i32 + delta,
            ) as usize;
        }
    }

    // Compute the items in the list to display based on the model
    fn text_entry_filter(entry: &AppDescriptor, model: &State) -> bool {
        entry.lower_title.contains(&model.entry_lower)
    }

    fn queue_icon_load(
        &mut self,
        original_index: usize,
        icon_size: u16,
        tasks: &mut Vec<Task<ElbeyMessage>>,
    ) {
        if let Some(app) = self.state.apps.get_mut(original_index) {
            if let Some(icon_name) = app.icon_name.clone() {
                if let Some(icon_path) = app.icon_path.clone() {
                    if icon_path.as_os_str().is_empty() {
                        set_icon(app, default_icon_handle(), Some(icon_path));
                        return;
                    }
                    if matches!(app.icon_handle, IconHandle::NotLoaded) {
                        let handle = icon_handle_from_path(icon_path);
                        self.state
                            .icon_cache
                            .insert(icon_name.clone(), handle.clone());
                        set_icon(app, handle, app.icon_path.clone());
                        return;
                    }
                }
                if let Some(cached) = self.state.icon_cache.get(&icon_name) {
                    app.icon_handle = cached.clone();
                    return;
                }
                if app.icon_handle == IconHandle::Loading {
                    return;
                }
                if matches!(app.icon_handle, IconHandle::NotLoaded) {
                    app.icon_handle = IconHandle::Loading;
                    tasks.push(Task::perform(
                        async move { lookup(&icon_name).with_size(icon_size).with_cache().find() },
                        move |path| ElbeyMessage::IconLoaded(original_index, path),
                    ));
                }
            }
        }
    }

    fn load_visible_icons(&mut self) -> Task<ElbeyMessage> {
        let filtered_app_indices = self.state.filtered_indices.clone();

        let view_start = self.state.selected_index;
        let view_end =
            (self.state.selected_index + VIEWABLE_LIST_ITEM_COUNT).min(filtered_app_indices.len());

        let icon_size = self.flags.icon_size;

        let mut tasks = vec![];

        if let Some(visible_indices) = filtered_app_indices.get(view_start..view_end) {
            for &original_index in visible_indices {
                self.queue_icon_load(original_index, icon_size, &mut tasks);
            }
        }

        let prefetch_end = (view_end + PREFETCH_ICON_COUNT).min(filtered_app_indices.len());
        if let Some(prefetch_indices) = filtered_app_indices.get(view_end..prefetch_end) {
            for &original_index in prefetch_indices {
                self.queue_icon_load(original_index, icon_size, &mut tasks);
            }
        }
        Task::batch(tasks)
    }

    #[cfg(test)]
    fn load_all_icons(&mut self) -> Task<ElbeyMessage> {
        let icon_size = self.flags.icon_size;
        let mut tasks = vec![];
        for idx in 0..self.state.apps.len() {
            self.queue_icon_load(idx, icon_size, &mut tasks);
        }
        Task::batch(tasks)
    }

    fn refresh_filtered_indices(&mut self) {
        self.state.filtered_indices = self
            .state
            .apps
            .iter()
            .enumerate()
            .filter(|(_, e)| Self::text_entry_filter(e, &self.state))
            .map(|(i, _)| i)
            .collect();

        if self.state.selected_index >= self.state.filtered_indices.len() {
            self.state.selected_index = self.state.filtered_indices.len().saturating_sub(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iced::futures::stream::StreamExt;
    use std::sync::{LazyLock, OnceLock};
    use std::time::Instant;

    fn set_test_cache_home() {
        static CACHE_HOME: OnceLock<PathBuf> = OnceLock::new();
        let cache_dir = CACHE_HOME.get_or_init(|| {
            let mut dir = std::env::temp_dir();
            dir.push(format!("elbey-test-cache-{}", std::process::id()));
            let _ = std::fs::create_dir_all(&dir);
            dir
        });
        std::env::set_var("XDG_CACHE_HOME", cache_dir);
    }

    static EMPTY_LOADER: fn() -> Vec<AppDescriptor> = || vec![];

    static TEST_DESKTOP_ENTRY_1: LazyLock<AppDescriptor> = LazyLock::new(|| AppDescriptor {
        appid: "test_app_id_1".to_string(),
        title: "t1".to_string(),
        lower_title: "t1".to_string(),
        exec: "".to_string(),
        exec_count: 0,
        icon_name: None,
        icon_path: None,
        icon_handle: IconHandle::NotLoaded,
    });

    static TEST_DESKTOP_ENTRY_2: LazyLock<AppDescriptor> = LazyLock::new(|| AppDescriptor {
        appid: "test_app_id_2".to_string(),
        title: "t2".to_string(),
        lower_title: "t2".to_string(),
        exec: "".to_string(),
        exec_count: 0,
        icon_name: None,
        icon_path: None,
        icon_handle: IconHandle::NotLoaded,
    });

    static TEST_DESKTOP_ENTRY_3: LazyLock<AppDescriptor> = LazyLock::new(|| AppDescriptor {
        appid: "test_app_id_3".to_string(),
        title: "t2".to_string(),
        lower_title: "t2".to_string(),
        exec: "".to_string(),
        exec_count: 0,
        icon_name: None,
        icon_path: None,
        icon_handle: IconHandle::NotLoaded,
    });

    static TEST_ENTRY_LOADER: fn() -> Vec<AppDescriptor> = || {
        vec![
            TEST_DESKTOP_ENTRY_1.clone(),
            TEST_DESKTOP_ENTRY_2.clone(),
            TEST_DESKTOP_ENTRY_3.clone(),
        ]
    };

    #[test]
    fn test_default_app_launch() {
        let test_launcher: fn(&AppDescriptor) -> anyhow::Result<()> = |e| {
            assert!(e.appid == "test_app_id_1");
            Ok(())
        };

        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: test_launcher,
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let _ = unit.update(ElbeyMessage::ModelLoaded(TEST_ENTRY_LOADER()));
        let _ = unit.update(ElbeyMessage::ExecuteSelected());
    }

    #[test]
    fn test_no_apps_try_launch() {
        let test_launcher: fn(&AppDescriptor) -> anyhow::Result<()> = |_e| {
            assert!(false); // should never get here
            Ok(())
        };

        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: test_launcher,
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let _ = unit.update(ElbeyMessage::ModelLoaded(EMPTY_LOADER()));
        let _result = unit.update(ElbeyMessage::ExecuteSelected());
    }

    #[test]
    fn test_app_navigation() {
        let test_launcher: fn(&AppDescriptor) -> anyhow::Result<()> = |e| {
            assert!(e.appid == "test_app_id_2");
            Ok(())
        };

        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: test_launcher,
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let _ = unit.update(ElbeyMessage::ModelLoaded(TEST_ENTRY_LOADER()));
        let _ = unit.update(ElbeyMessage::KeyEvent(Key::Named(Named::ArrowDown)));
        let _ = unit.update(ElbeyMessage::KeyEvent(Key::Named(Named::ArrowDown)));
        let _ = unit.update(ElbeyMessage::KeyEvent(Key::Named(Named::ArrowUp)));
        let _ = unit.update(ElbeyMessage::ExecuteSelected());
    }

    #[test]
    fn test_icon_loaded_png() {
        set_test_cache_home();
        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });
        let _ = unit.update(ElbeyMessage::ModelLoaded(TEST_ENTRY_LOADER()));

        let png_path = PathBuf::from("test.png");
        let _ = unit.update(ElbeyMessage::IconLoaded(0, Some(png_path)));

        assert!(matches!(
            unit.state.apps[0].icon_handle,
            IconHandle::Raster(_)
        ));
    }

    #[test]
    fn test_icon_loaded_svg() {
        set_test_cache_home();
        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });
        let _ = unit.update(ElbeyMessage::ModelLoaded(TEST_ENTRY_LOADER()));

        let svg_path = PathBuf::from("test.svg");
        let _ = unit.update(ElbeyMessage::IconLoaded(0, Some(svg_path)));

        assert!(matches!(
            unit.state.apps[0].icon_handle,
            IconHandle::Vector(_)
        ));
    }

    #[test]
    fn test_icon_loaded_fallback() {
        set_test_cache_home();
        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: TEST_ENTRY_LOADER,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });
        let _ = unit.update(ElbeyMessage::ModelLoaded(TEST_ENTRY_LOADER()));

        let _ = unit.update(ElbeyMessage::IconLoaded(0, None));

        assert!(matches!(
            unit.state.apps[0].icon_handle,
            IconHandle::Vector(_)
        ));
    }

    /// Ignored by default; run with `cargo test measure_load_visible_icons_time -- --ignored --nocapture`
    /// to capture the elapsed time for filtering and preparing icon loads over a large dataset.
    #[test]
    #[ignore]
    fn measure_load_visible_icons_time() {
        let (mut unit, _) = Elbey::new(ElbeyFlags {
            apps_loader: EMPTY_LOADER,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: 48,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let app_count = 50_000;
        unit.state.apps = (0..app_count)
            .map(|i| AppDescriptor {
                appid: format!("test_app_id_{i}"),
                title: format!("App {i}"),
                lower_title: format!("app {i}"),
                exec: "".to_string(),
                exec_count: 0,
                icon_name: None,
                icon_path: None,
                icon_handle: IconHandle::NotLoaded,
            })
            .collect();
        unit.state.entry = "app 4".to_string();
        unit.state.entry_lower = unit.state.entry.to_lowercase();
        unit.state.selected_index = 0;

        let start = Instant::now();
        let _ = unit.load_visible_icons();
        let elapsed = start.elapsed();
        println!(
            "load_visible_icons on {app_count} apps took {:?} (view size {})",
            elapsed, VIEWABLE_LIST_ITEM_COUNT
        );
    }

    /// Drives iced `Task` streams to completion in tests, emulating the runtime loop.
    fn drain_tasks(elbey: &mut Elbey, task: RuntimeTask<ElbeyMessage>) {
        use std::collections::VecDeque;

        let mut queue = VecDeque::new();
        queue.push_back(task);
        let mut runtime = iced::futures::executor::LocalPool::new();

        while let Some(task) = queue.pop_front() {
            if let Some(mut stream) = into_stream(task) {
                let mut outputs = Vec::new();
                runtime.run_until(async {
                    while let Some(action) = stream.next().await {
                        if let Action::Output(msg) = action {
                            outputs.push(msg);
                        }
                    }
                });

                for message in outputs {
                    let follow_up = elbey.update(message);
                    queue.push_back(follow_up);
                }
            }
        }
    }

    /// Ignored by default; measures the elapsed time (in ms) to resolve the Firefox icon.
    #[test]
    #[ignore]
    fn measure_firefox_icon_latency() {
        set_test_cache_home();
        let locales = freedesktop_desktop_entry::get_languages_from_env();
        let locales_ref: Vec<&str> = locales.iter().map(String::as_str).collect();
        let firefox_entry = DesktopEntry::from_path(
            PathBuf::from("/usr/share/applications/firefox.desktop"),
            Some(&locales_ref),
        )
        .expect("firefox desktop entry missing");

        let firefox = AppDescriptor::from(firefox_entry);

        let (mut elbey, _) = Elbey::new(ElbeyFlags {
            apps_loader: EMPTY_LOADER,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: DEFAULT_ICON_SIZE,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let start = Instant::now();
        let initial = elbey.update(ElbeyMessage::ModelLoaded(vec![firefox]));
        drain_tasks(&mut elbey, initial);
        let elapsed = start.elapsed();

        if let Some(app) = elbey.state.apps.first() {
            println!(
                "firefox icon latency: {:?} (icon_name: {:?})",
                elapsed, app.icon_name
            );
            assert!(app.icon_name.is_some(), "icon did not resolve");
        } else {
            panic!("no app loaded");
        }

        assert!(
            elapsed.as_millis() > 0,
            "latency too small; headless timing likely invalid"
        );
    }

    /// Ignored by default; measures total icon resolution time across all discovered apps.
    #[test]
    #[ignore]
    fn measure_all_icons_latency() {
        set_test_cache_home();
        use crate::load_apps;

        // Cold run: resolve icons via filesystem lookups.
        let (mut cold, _) = Elbey::new(ElbeyFlags {
            apps_loader: load_apps,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: DEFAULT_ICON_SIZE,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });

        let start_cold = Instant::now();
        let initial_apps = (cold.flags.apps_loader)();
        let task = cold.update(ElbeyMessage::ModelLoaded(initial_apps));
        drain_tasks(&mut cold, task);
        let all_icons = cold.load_all_icons();
        drain_tasks(&mut cold, all_icons);
        let cold_elapsed = start_cold.elapsed();
        let cold_resolved = cold
            .state
            .apps
            .iter()
            .filter(|app| {
                matches!(
                    app.icon_handle,
                    IconHandle::Vector(_) | IconHandle::Raster(_)
                )
            })
            .count();

        println!(
            "all-apps icon latency (cold): {:?} across {} apps (resolved: {})",
            cold_elapsed,
            cold.state.apps.len(),
            cold_resolved
        );

        // Warm run: uses cached icon paths persisted from the cold run.
        let (mut warm, _) = Elbey::new(ElbeyFlags {
            apps_loader: load_apps,
            app_launcher: |_| Ok(()),
            theme: DEFAULT_THEME,
            icon_size: DEFAULT_ICON_SIZE,
            hint: DEFAULT_HINT.to_string(),
            filter_font_size: DEFAULT_TEXT_SIZE,
            entries_font_size: DEFAULT_TEXT_SIZE,
        });
        let start_warm = Instant::now();
        let warm_apps = (warm.flags.apps_loader)();
        let warm_task = warm.update(ElbeyMessage::ModelLoaded(warm_apps));
        drain_tasks(&mut warm, warm_task);
        let warm_icons = warm.load_all_icons();
        drain_tasks(&mut warm, warm_icons);
        let warm_elapsed = start_warm.elapsed();
        let warm_resolved = warm
            .state
            .apps
            .iter()
            .filter(|app| {
                matches!(
                    app.icon_handle,
                    IconHandle::Vector(_) | IconHandle::Raster(_)
                )
            })
            .count();

        println!(
            "all-apps icon latency (warm): {:?} across {} apps (resolved: {})",
            warm_elapsed,
            warm.state.apps.len(),
            warm_resolved
        );

        assert!(
            warm_elapsed < cold_elapsed,
            "warm run should be faster than cold run"
        );
    }
}