hyprshell-launcher-lib 4.10.3

A modern GTK4-based window switcher and application launcher for Hyprland
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
use crate::plugins;
use crate::plugins::{
    SortedLaunchOption, StaticLaunchOption, get_sorted_launch_options, get_static_launch_options,
    get_static_options_chars,
};
use crate::plugins_boxes::{LauncherPlugins, LauncherPluginsInit, LauncherPluginsOutput};
use crate::result::{LauncherResults, LauncherResultsInit, LauncherResultsOutput};
use config_lib::{Launcher, Modifier};
use core_lib::transfer::Identifier;
use core_lib::{Direction, LAUNCHER_NAMESPACE, WarnWithDetails};
use gtk4_layer_shell::{Edge, KeyboardMode, Layer, LayerShell};
use relm4::adw::gdk::ModifierType;
use relm4::adw::prelude::*;
use relm4::adw::{gdk, glib, gtk};
use relm4::factory::FactoryVecDeque;
use relm4::gtk::{
    EventController, EventControllerKey, Orientation, PropagationPhase, SelectionMode,
};
use relm4::{ComponentParts, ComponentSender, SimpleComponent};
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use tracing::{trace, warn};

#[derive(Debug)]
pub struct LauncherRoot {
    launcher: Launcher,
    window: gtk::ApplicationWindow,
    entry: gtk::Entry,
    results: FactoryVecDeque<LauncherResults>,
    plugins: FactoryVecDeque<LauncherPlugins>,
    controller: Option<EventController>,

    data: LauncherData,
    switching: bool,
    data_dir: Rc<PathBuf>,
}

#[derive(Debug)]
pub enum LauncherRootInput {
    SetLauncher(Launcher),
    OpenLauncher,
    CloseLauncher,
    Launch(char),
    Return,
    Switch(Direction, bool),
    Type,
}

#[derive(Debug)]
pub struct LauncherRootInit {
    pub launcher: Launcher,
    pub data_dir: Rc<PathBuf>,
}

#[derive(Debug)]
pub enum LauncherRootOutput {
    Switch(Direction, bool),
    Close(bool),
}

#[relm4::component(pub)]
impl SimpleComponent for LauncherRoot {
    type Init = LauncherRootInit;
    type Input = LauncherRootInput;
    type Output = LauncherRootOutput;

    view! {
        #[root]
        gtk::ApplicationWindow {
            set_css_classes: &["window"],
            set_default_size: (20, 20),
            gtk::Box {
                set_css_classes: &["launcher"],
                set_orientation: Orientation::Vertical,
                set_spacing: 4,
                #[watch]
                set_width_request: i32::from(model.launcher.width),
                #[local_ref]
                entrye -> gtk::Entry {
                    set_css_classes: &["launcher-input"],
                    connect_changed => LauncherRootInput::Type,
                },
                #[local_ref]
                resultse -> gtk::Box {
                    set_orientation: Orientation::Vertical,
                    set_css_classes: &["launcher-results"],
                    set_spacing: 3,
                },
                #[local_ref]
                pluginse -> gtk::Box {
                    set_orientation: Orientation::Horizontal,
                    set_css_classes: &["launcher-plugins"],
                    set_spacing: 4,
                }
            }
        }
    }

    fn init(
        init: Self::Init,
        root: Self::Root,
        sender: ComponentSender<Self>,
    ) -> ComponentParts<Self> {
        let entry = gtk::Entry::new();
        let results: FactoryVecDeque<LauncherResults> = FactoryVecDeque::builder()
            .launch(gtk::Box::default())
            .forward(sender.input_sender(), |r| match r {
                LauncherResultsOutput::Clicked(idx) => LauncherRootInput::Launch(
                    idx.current_index()
                        .to_string()
                        .chars()
                        .next()
                        .expect("No char"),
                ),
            });
        let plugins: FactoryVecDeque<LauncherPlugins> = FactoryVecDeque::builder()
            .launch(gtk::Box::default())
            .forward(sender.input_sender(), |r| match r {
                LauncherPluginsOutput::Clicked(ch) => LauncherRootInput::Launch(ch),
            });

        let model = Self {
            launcher: init.launcher,
            data_dir: init.data_dir,
            window: root.clone(),
            entry,
            results,
            plugins,
            controller: None,
            data: LauncherData::default(),
            switching: false, // enter when nothing was done launches program
        };

        let entrye = &model.entry;
        let resultse = &model.results.widget().clone();
        let pluginse = &model.plugins.widget().clone();
        let widgets = view_output!();

        // ensure that the entry is always focused
        let entry_2 = model.entry.clone();
        let window_2 = root.clone();
        glib::timeout_add_local(std::time::Duration::from_millis(200), move || {
            if window_2.is_visible() {
                entry_2.grab_focus_without_selecting();
            }
            glib::ControlFlow::Continue
        });

        // TODO someday move to generic init fn
        plugins::init_calc_context();

        let window = &root;
        window.init_layer_shell();
        window.set_namespace(Some(LAUNCHER_NAMESPACE));
        window.set_layer(Layer::Overlay);
        window.set_anchor(Edge::Top, true);
        window.set_margin(Edge::Top, 0);
        window.set_exclusive_zone(-1);
        window.set_keyboard_mode(KeyboardMode::Exclusive);
        ComponentParts { model, widgets }
    }

    fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>) {
        match message {
            LauncherRootInput::SetLauncher(launcher) => {
                self.launcher = launcher;
                self.setup_keyboard_controller(&sender);
            }
            LauncherRootInput::OpenLauncher => {
                self.open_launcher();
                self.handle_type();
            }
            LauncherRootInput::CloseLauncher => self.close_launcher(),
            LauncherRootInput::Launch(char) => {
                trace!("Closing launcher with char: {}", char);
                if let Some(iden) = match char {
                    '0'..='9' => char
                        .to_digit(10)
                        .and_then(|a| self.data.sorted_matches.get(a as usize)),
                    _ => self.data.static_matches.get(&char),
                } {
                    plugins::launch(
                        iden,
                        &self.entry.text(),
                        self.launcher.default_terminal.as_deref(),
                        &self.data_dir,
                    );
                } else {
                    warn!("No match found for char: {}", char);
                }

                sender
                    .output_sender()
                    .emit(LauncherRootOutput::Close(false));
            }
            LauncherRootInput::Type => {
                self.switching = false;
                self.handle_type()
            }
            LauncherRootInput::Switch(dir, ws) => {
                self.switching = true;
                sender
                    .output_sender()
                    .emit(LauncherRootOutput::Switch(dir, ws));
            }
            LauncherRootInput::Return => {
                if !self.switching {
                    sender.input_sender().emit(LauncherRootInput::Launch('0'));
                } else {
                    sender.output_sender().emit(LauncherRootOutput::Close(true));
                }
            }
        }
    }
}

impl LauncherRoot {
    fn setup_keyboard_controller(&mut self, sender: &ComponentSender<Self>) {
        let event_controller = EventControllerKey::new();
        let plugin_keys = get_static_options_chars(&self.launcher.plugins);
        let sender_2 = sender.clone();
        let launcher = self.launcher.clone();
        let entry = self.entry.clone();
        event_controller.set_propagation_phase(PropagationPhase::Capture);
        event_controller.connect_key_pressed(move |_, key, _, modt| {
            trace!("input: {key:?}");
            let text_empty = entry.text().is_empty();
            handle_key(
                &launcher,
                text_empty,
                key,
                modt,
                &plugin_keys,
                sender_2.clone(),
            )
        });
        if let Some(controller) = self.controller.take() {
            self.entry.remove_controller(&controller);
        }
        self.entry.add_controller(event_controller);
    }
    fn open_launcher(&mut self) {
        trace!("Showing window {:?}", self.window.id());
        self.window.set_visible(true);
        self.entry.grab_focus();
        self.entry.set_text("");
        exec_lib::set_no_follow_mouse().warn_details("Failed to set follow mouse");
    }
    fn close_launcher(&mut self) {
        trace!("Hiding window {:?}", self.window.id());
        self.window.set_visible(false);
        exec_lib::reset_no_follow_mouse().warn_details("Failed to reset follow mouse");
    }

    fn handle_type(&mut self) {
        self.data.sorted_matches.clear();
        self.data.static_matches.clear();
        let text: &str = &self.entry.text();

        let mut results_lock = self.results.guard();
        results_lock.clear();
        let mut plugins_lock = self.plugins.guard();
        plugins_lock.clear();

        if !self.launcher.show_when_empty && text.is_empty() {
            return;
        }
        let items = self.launcher.max_items.min(9) as usize;
        for (index, (_, opt)) in
            get_sorted_launch_options(&self.launcher.plugins, text, &self.data_dir)
                .into_iter()
                .take(items)
                .enumerate()
        {
            self.data.sorted_matches.push(opt.iden.clone());
            results_lock.push_back(LauncherResultsInit {
                opt,
                key: match index {
                    0 => "Return".to_string(),
                    i => format!("{}+{i}", self.launcher.launch_modifier),
                },
            });
        }

        for (opt) in get_static_launch_options(
            &self.launcher.plugins,
            self.launcher.default_terminal.as_deref(),
            text,
        ) {
            self.data
                .static_matches
                .entry(opt.key)
                .or_insert(opt.iden.clone());
            plugins_lock.push_back(LauncherPluginsInit {
                opt,
                launch_modifier: self.launcher.launch_modifier,
            });
        }
    }
}

fn handle_key(
    launcher: &Launcher,
    text_empty: bool,
    key: gdk::Key,
    modt: ModifierType,
    plugin_keys: &[gdk::Key],
    sender: ComponentSender<LauncherRoot>,
) -> glib::Propagation {
    let launch_mod = match launcher.launch_modifier {
        Modifier::Ctrl => modt == ModifierType::CONTROL_MASK,
        Modifier::Alt => modt == ModifierType::ALT_MASK,
        Modifier::Super => modt == ModifierType::SUPER_MASK,
        Modifier::None => false,
    };
    trace!(
        "key: {}{:?}, mods: {:?}, launch_mod: {}, launch_modifier: {}",
        key, key, modt, launch_mod, launcher.launch_modifier
    );
    if launch_mod && plugin_keys.contains(&key) {
        if let Some(ch) = key.name().unwrap_or_default().to_string().pop() {
            sender.input_sender().emit(LauncherRootInput::Launch(ch));
        }
        return glib::Propagation::Stop;
    }

    match (launch_mod, key) {
        (_, gdk::Key::Escape) => {
            sender
                .output_sender()
                .emit(LauncherRootOutput::Close(false));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Tab) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Right, false));
            glib::Propagation::Stop
        }
        (_, gdk::Key::ISO_Left_Tab | gdk::Key::grave | gdk::Key::dead_grave) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Left, false));
            glib::Propagation::Stop
        }
        (true, gdk::Key::h) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Left, true));
            glib::Propagation::Stop
        }
        (true, gdk::Key::l) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Right, true));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Left) => {
            if !text_empty {
                // allow using with text in launcher
                return glib::Propagation::Proceed;
            }
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Left, true));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Right) => {
            if !text_empty {
                // allow using with text in launcher
                return glib::Propagation::Proceed;
            }
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Right, true));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Up) | (true, gdk::Key::k) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Up, true));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Down) | (true, gdk::Key::j) => {
            sender
                .input_sender()
                .emit(LauncherRootInput::Switch(Direction::Down, true));
            glib::Propagation::Stop
        }
        (_, gdk::Key::Return) => {
            sender.input_sender().emit(LauncherRootInput::Return);
            glib::Propagation::Stop
        }
        (true, gdk::Key::_1) => {
            sender.input_sender().emit(LauncherRootInput::Launch('1'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_2) => {
            sender.input_sender().emit(LauncherRootInput::Launch('2'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_3) => {
            sender.input_sender().emit(LauncherRootInput::Launch('3'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_4) => {
            sender.input_sender().emit(LauncherRootInput::Launch('4'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_5) => {
            sender.input_sender().emit(LauncherRootInput::Launch('5'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_6) => {
            sender.input_sender().emit(LauncherRootInput::Launch('6'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_7) => {
            sender.input_sender().emit(LauncherRootInput::Launch('7'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_8) => {
            sender.input_sender().emit(LauncherRootInput::Launch('8'));
            glib::Propagation::Stop
        }
        (true, gdk::Key::_9) => {
            sender.input_sender().emit(LauncherRootInput::Launch('9'));
            glib::Propagation::Stop
        }
        _ => glib::Propagation::Proceed,
    }
}

#[derive(Debug, Default)]
pub struct LauncherData {
    pub sorted_matches: Vec<Identifier>,
    pub static_matches: HashMap<char, Identifier>,
}