summaryrefslogtreecommitdiff
path: root/src/modules/launcher.tsx
blob: b588e3ae446de317330253d1e038ab0afb185e4e (plain)
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
import { bind, execAsync, Gio, GLib, register, timeout, Variable } from "astal";
import { App, Astal, Gtk, Widget } from "astal/gtk3";
import fuzzysort from "fuzzysort";
import type AstalApps from "gi://AstalApps";
import AstalHyprland from "gi://AstalHyprland";
import { launcher as config } from "../../config";
import { Apps } from "../services/apps";
import MathService, { type HistoryItem } from "../services/math";
import { getAppCategoryIcon } from "../utils/icons";
import { launch } from "../utils/system";
import type { Client } from "../utils/types";
import { MenuItem, setupCustomTooltip } from "../utils/widgets";
import PopupWindow from "../widgets/popupwindow";

type Mode = "apps" | "files" | "math" | "windows";

interface Subcommand {
    icon: string;
    name: string;
    description: string;
    command: (...args: string[]) => void;
}

const getIconFromMode = (mode: Mode) => {
    switch (mode) {
        case "apps":
            return "apps";
        case "files":
            return "folder";
        case "math":
            return "calculate";
        case "windows":
            return "select_window_2";
    }
};

const getEmptyTextFromMode = (mode: Mode) => {
    switch (mode) {
        case "apps":
            return "No apps found";
        case "files":
            return GLib.find_program_in_path("fd") === null ? "File search requires `fd`" : "No files found";
        case "math":
            return "Type an expression";
        case "windows":
            return "No windows found";
    }
};

const close = (self: JSX.Element) => {
    const toplevel = self.get_toplevel();
    if (toplevel instanceof Widget.Window) toplevel.hide();
};

const launchAndClose = (self: JSX.Element, astalApp: AstalApps.Application) => {
    close(self);
    launch(astalApp);
};

const openFileAndClose = (self: JSX.Element, path: string) => {
    close(self);
    execAsync([
        "bash",
        "-c",
        `dbus-send --session --dest=org.freedesktop.FileManager1 --type=method_call /org/freedesktop/FileManager1 org.freedesktop.FileManager1.ShowItems array:string:"file://${path}" string:"" || xdg-open "${path}"`,
    ]).catch(console.error);
};

const PinnedApp = (names: string[]) => {
    let app: Gio.DesktopAppInfo | null = null;
    let astalApp: AstalApps.Application | undefined;
    for (const name of names) {
        app = Gio.DesktopAppInfo.new(`${name}.desktop`);
        if (app) {
            astalApp = Apps.get_list().find(a => a.entry === `${name}.desktop`);
            if (app.get_icon() && astalApp) break;
            else app = null; // Set app to null if no icon or matching AstalApps#Application
        }
    }

    if (!app) {
        console.error(`Launcher - Unable to find app for "${names.join(", ")}"`);
        return null;
    }

    const menu = new Gtk.Menu();
    menu.append(new MenuItem({ label: "Launch", onActivate: () => launchAndClose(widget, astalApp!) }));

    if (app.list_actions().length > 0) menu.append(new Gtk.SeparatorMenuItem({ visible: true }));
    app.list_actions().forEach(action => {
        menu.append(
            new MenuItem({
                label: app.get_action_name(action),
                onActivate: () => {
                    close(widget); // Pass result cause menu is its own toplevel
                    app.launch_action(action, null);
                },
            })
        );
    });

    const widget = (
        <button
            className="pinned-app result"
            cursor="pointer"
            onClicked={self => launchAndClose(self, astalApp!)}
            onClick={(_, event) => event.button === Astal.MouseButton.SECONDARY && menu.popup_at_pointer(null)}
            setup={self => setupCustomTooltip(self, app.get_display_name())}
            onDestroy={() => menu.destroy()}
        >
            <icon gicon={app.get_icon()!} />
        </button>
    );
    return widget;
};

const PinnedApps = () => <box homogeneous>{config.pins.map(PinnedApp)}</box>;

const SearchEntry = ({ entry }: { entry: Widget.Entry }) => (
    <stack
        hexpand
        transitionType={Gtk.StackTransitionType.CROSSFADE}
        transitionDuration={150}
        setup={self =>
            self.hook(entry, "notify::text-length", () =>
                // Timeout to avoid flickering when replacing entire text (cause it'll set len to 0 then back to > 0)
                timeout(1, () => (self.shown = entry.textLength > 0 ? "entry" : "placeholder"))
            )
        }
    >
        <label name="placeholder" className="placeholder" xalign={0} label='Type ">" for subcommands' />
        {entry}
    </stack>
);

const Result = ({
    icon,
    materialIcon,
    label,
    sublabel,
    tooltip,
    onClicked,
    onSecondaryClick,
    onDestroy,
}: {
    icon?: string | Gio.Icon | null;
    materialIcon?: string;
    label: string;
    sublabel?: string;
    tooltip?: string;
    onClicked: (self: Widget.Button) => void;
    onSecondaryClick?: (self: Widget.Button) => void;
    onDestroy?: () => void;
}) => (
    <button
        className="result"
        cursor="pointer"
        tooltipText={tooltip}
        onClicked={onClicked}
        onClick={(self, event) => event.button === Astal.MouseButton.SECONDARY && onSecondaryClick?.(self)}
        onDestroy={onDestroy}
    >
        <box>
            {icon &&
                (typeof icon === "string" ? (
                    Astal.Icon.lookup_icon(icon) && <icon valign={Gtk.Align.START} className="icon" icon={icon} />
                ) : (
                    <icon valign={Gtk.Align.START} className="icon" gicon={icon} />
                ))}
            {!icon && materialIcon && <label valign={Gtk.Align.START} className="icon" label={materialIcon} />}
            {sublabel ? (
                <box vertical valign={Gtk.Align.CENTER} className="has-sublabel">
                    <label hexpand truncate maxWidthChars={1} xalign={0} label={label} />
                    <label hexpand truncate maxWidthChars={1} className="sublabel" xalign={0} label={sublabel} />
                </box>
            ) : (
                <label xalign={0} label={label} />
            )}
        </box>
    </button>
);

const SubcommandResult = ({
    entry,
    subcommand,
    args,
}: {
    entry: Widget.Entry;
    subcommand: Subcommand;
    args: string[];
}) => (
    <Result
        materialIcon={subcommand.icon}
        label={subcommand.name}
        sublabel={subcommand.description}
        onClicked={() => {
            subcommand.command(...args);
            entry.set_text("");
        }}
    />
);

const AppResult = ({ app }: { app: AstalApps.Application }) => {
    const menu = new Gtk.Menu();
    menu.append(new MenuItem({ label: "Launch", onActivate: () => launchAndClose(result, app) }));

    const appInfo = app.app as Gio.DesktopAppInfo;
    if (appInfo.list_actions().length > 0) menu.append(new Gtk.SeparatorMenuItem({ visible: true }));
    appInfo.list_actions().forEach(action => {
        menu.append(
            new MenuItem({
                label: appInfo.get_action_name(action),
                onActivate: () => {
                    close(result); // Pass result cause menu is its own toplevel
                    appInfo.launch_action(action, null);
                },
            })
        );
    });

    const result = (
        <Result
            icon={app.iconName}
            materialIcon={getAppCategoryIcon(app)}
            label={app.name}
            sublabel={app.description}
            onClicked={self => launchAndClose(self, app)}
            onSecondaryClick={() => menu.popup_at_pointer(null)}
            onDestroy={() => menu.destroy()}
        />
    );
    return result;
};

const MathResult = ({ math, isHistory, entry }: { math: HistoryItem; isHistory?: boolean; entry: Widget.Entry }) => (
    <Result
        materialIcon={math.icon}
        label={math.equation}
        sublabel={math.result}
        onClicked={() => {
            if (isHistory) {
                MathService.get_default().select(math);
                entry.set_text(math.equation);
                entry.grab_focus();
                entry.set_position(-1);
            } else {
                execAsync(`wl-copy -- ${math.result}`).catch(console.error);
                entry.set_text("");
            }
        }}
    />
);

const FileResult = ({ path }: { path: string }) => (
    <Result
        icon={Gio.File.new_for_path(path)
            .query_info(Gio.FILE_ATTRIBUTE_STANDARD_ICON, Gio.FileQueryInfoFlags.NONE, null)
            .get_icon()}
        label={path.split("/").pop()!}
        sublabel={path.startsWith(HOME) ? "~" + path.slice(HOME.length) : path}
        onClicked={self => openFileAndClose(self, path)}
    />
);

const WindowResult = ({ client, reload }: { client: Client; reload: () => void }) => {
    const hyprland = AstalHyprland.get_default();
    const app = Apps.fuzzy_query(client.class)[0];
    const astalClient = hyprland.get_client(client.address);

    const menu = new Gtk.Menu();
    menu.append(
        new MenuItem({
            label: "Focus",
            onActivate: () => {
                close(result);
                astalClient?.focus();
            },
        })
    );
    menu.append(new Gtk.SeparatorMenuItem({ visible: true }));

    const addSubmenus = (silent: boolean) => {
        menu.append(
            new MenuItem({
                label: `Move to workspace${silent ? " (silent)" : ""}`,
                setup: self => {
                    const submenu = new Gtk.Menu();
                    const start = Math.floor((hyprland.focusedWorkspace.id - 1) / 10) * 10;
                    for (let i = 1; i <= 10; i++)
                        submenu.append(
                            new MenuItem({
                                label: `Workspace ${start + i}`,
                                onActivate: () => {
                                    if (!silent) close(result);
                                    hyprland.dispatch(
                                        `movetoworkspace${silent ? "silent" : ""}`,
                                        `${start + i},address:${client.address}`
                                    );
                                },
                            })
                        );
                    self.set_submenu(submenu);
                },
            })
        );
        menu.append(
            new MenuItem({
                label: `Move to special workspace${silent ? " (silent)" : ""}`,
                setup: self => {
                    const submenu = new Gtk.Menu();
                    submenu.append(
                        new MenuItem({
                            label: "special",
                            onActivate: () => {
                                if (!silent) close(result);
                                hyprland.dispatch(
                                    `movetoworkspace${silent ? "silent" : ""}`,
                                    `special,address:${client.address}`
                                );
                            },
                        })
                    );
                    hyprland.message_async("j/workspaces", (_, res) => {
                        const workspaces = JSON.parse(hyprland.message_finish(res));
                        for (const workspace of workspaces)
                            if (workspace.name.startsWith("special:"))
                                submenu.append(
                                    new MenuItem({
                                        label: workspace.name.slice(8),
                                        onActivate: () => {
                                            if (!silent) close(result);
                                            hyprland.dispatch(
                                                `movetoworkspace${silent ? "silent" : ""}`,
                                                `${workspace.name},address:${client.address}`
                                            );
                                        },
                                    })
                                );
                    });
                    self.set_submenu(submenu);
                },
            })
        );
    };
    addSubmenus(false);
    addSubmenus(true);

    menu.append(
        new MenuItem({
            label: "Copy property",
            setup: self => {
                const addSubmenu = (self: MenuItem, obj: object) => {
                    const submenu = new Gtk.Menu();

                    for (const [key, value] of Object.entries(obj))
                        if (typeof value === "object") submenu.append(addSubmenu(new MenuItem({ label: key }), value));
                        else
                            submenu.append(
                                new MenuItem({
                                    label: key,
                                    onActivate: () => {
                                        close(result);
                                        execAsync(`wl-copy -- ${value}`).catch(console.error);
                                    },
                                    tooltipText: String(value),
                                })
                            );

                    self.set_submenu(submenu);
                    return self;
                };
                addSubmenu(self, client);
            },
        })
    );

    menu.append(new Gtk.SeparatorMenuItem({ visible: true }));
    menu.append(
        new MenuItem({
            label: "Kill",
            onActivate: () => {
                astalClient?.kill();
                const id = hyprland.connect("client-removed", () => {
                    hyprland.disconnect(id);
                    reload();
                });
            },
        })
    );

    const result = (
        <Result
            icon={app.iconName}
            materialIcon={getAppCategoryIcon(app)}
            label={client.title || (client.initialTitle ? `${client.initialTitle} (initial)` : "No title")}
            sublabel={client.class || (client.initialClass ? `${client.initialClass} (initial)` : "No class")}
            tooltip={`Address: ${client.address}\nWorkspace: ${client.workspace.name} (${client.workspace.id})\nProcess ID: ${client.pid}\nFloating: ${client.floating}\nInhibiting idle: ${client.inhibitingIdle}`}
            onClicked={self => {
                close(self);
                astalClient?.focus();
            }}
            onSecondaryClick={() => menu.popup_at_pointer(null)}
            onDestroy={() => menu.destroy()}
        />
    );
    return result;
};

const Results = ({ entry, mode }: { entry: Widget.Entry; mode: Variable<Mode> }) => {
    const empty = Variable(true);

    return (
        <stack
            className="results"
            transitionType={Gtk.StackTransitionType.CROSSFADE}
            transitionDuration={150}
            shown={bind(empty).as(t => (t ? "empty" : "list"))}
        >
            <box name="empty" className="empty" halign={Gtk.Align.CENTER} valign={Gtk.Align.CENTER}>
                <label className="icon" label="bug_report" />
                <label
                    label={bind(entry, "text").as(t =>
                        t.startsWith(">") ? "No matching subcommands" : getEmptyTextFromMode(mode.get())
                    )}
                />
            </box>
            <box
                vertical
                name="list"
                setup={self => {
                    const subcommands: Record<string, Subcommand> = {
                        apps: {
                            icon: "apps",
                            name: "Apps",
                            description: "Search for apps",
                            command: () => mode.set("apps"),
                        },
                        files: {
                            icon: "folder",
                            name: "Files",
                            description: "Search for files",
                            command: () => mode.set("files"),
                        },
                        math: {
                            icon: "calculate",
                            name: "Math",
                            description: "Do math calculations",
                            command: () => mode.set("math"),
                        },
                        windows: {
                            icon: "select_window_2",
                            name: "Windows",
                            description: "Manage open windows",
                            command: () => mode.set("windows"),
                        },
                        todo: {
                            icon: "checklist",
                            name: "Todo",
                            description: "Create a todo in <INSERT_TODO_APP>",
                            command: (...args) => {
                                // TODO: todo service or maybe use external app
                            },
                        },
                        reload: {
                            icon: "refresh",
                            name: "Reload",
                            description: "Reload app list",
                            command: () => Apps.reload(),
                        },
                    };
                    const subcommandList = Object.keys(subcommands);

                    const updateEmpty = () => empty.set(self.get_children().length === 0);

                    const appSearch = () => {
                        const apps = Apps.fuzzy_query(entry.text);
                        if (apps.length > config.maxResults) apps.length = config.maxResults;
                        for (const app of apps) self.add(<AppResult app={app} />);
                    };

                    const calculate = () => {
                        if (entry.text) {
                            self.add(
                                <MathResult math={MathService.get_default().evaluate(entry.text)} entry={entry} />
                            );
                            self.add(<box className="separator" />);
                        }
                        for (const item of MathService.get_default().history)
                            self.add(<MathResult isHistory math={item} entry={entry} />);
                    };

                    const fileSearch = () =>
                        execAsync(["fd", ...config.fdOpts, entry.text, HOME])
                            .then(out => {
                                const paths = out.split("\n").filter(path => path);
                                if (paths.length > config.maxResults) paths.length = config.maxResults;
                                self.foreach(ch => ch.destroy());
                                for (const path of paths) self.add(<FileResult path={path} />);
                            })
                            .catch(e => {
                                // Ignore execAsync error
                                if (!(e instanceof Gio.IOErrorEnum || e instanceof GLib.SpawnError)) console.error(e);
                            })
                            .finally(updateEmpty);

                    const listWindows = () => {
                        const hyprland = AstalHyprland.get_default();
                        // Use message cause AstalHyprland is buggy (inconsistent prop updating)
                        hyprland.message_async("j/clients", (_, res) => {
                            try {
                                const unsortedClients: Client[] = JSON.parse(hyprland.message_finish(res));
                                if (entry.text) {
                                    const clients = fuzzysort.go(entry.text, unsortedClients, {
                                        all: true,
                                        limit: config.maxResults,
                                        keys: ["title", "class", "initialTitle", "initialClass"],
                                        scoreFn: r =>
                                            r[0].score * config.windows.title +
                                            r[1].score * config.windows.class +
                                            r[2].score * config.windows.initialTitle +
                                            r[3].score * config.windows.initialClass,
                                    });
                                    self.foreach(ch => ch.destroy());
                                    for (const { obj } of clients)
                                        self.add(<WindowResult reload={listWindows} client={obj} />);
                                } else {
                                    const clients = unsortedClients.sort((a, b) => a.focusHistoryID - b.focusHistoryID);
                                    self.foreach(ch => ch.destroy());
                                    for (const client of clients)
                                        self.add(<WindowResult reload={listWindows} client={client} />);
                                }
                            } catch (e) {
                                console.error(e);
                            } finally {
                                updateEmpty();
                            }
                        });
                    };

                    // Update windows on open
                    self.hook(App, "window-toggled", (_, window) => {
                        if (window.name === "launcher" && window.visible && mode.get() === "windows") listWindows();
                    });

                    self.hook(entry, "activate", () => {
                        if (mode.get() === "math") {
                            if (entry.text.startsWith("clear")) MathService.get_default().clear();
                            else MathService.get_default().commit();
                        }
                        self.get_children()[0]?.activate();
                    });
                    self.hook(entry, "changed", () => {
                        if (!entry.text && mode.get() === "apps") return;

                        // Files and windows have delay cause async so they do some stuff by themselves
                        const ignoreFileAsync =
                            entry.text.startsWith(">") || (mode.get() !== "files" && mode.get() !== "windows");
                        if (ignoreFileAsync) self.foreach(ch => ch.destroy());

                        if (entry.text.startsWith(">")) {
                            const args = entry.text.split(" ");
                            for (const { target } of fuzzysort.go(args[0].slice(1), subcommandList, { all: true }))
                                self.add(
                                    <SubcommandResult
                                        entry={entry}
                                        subcommand={subcommands[target]}
                                        args={args.slice(1)}
                                    />
                                );
                        } else if (mode.get() === "apps") appSearch();
                        else if (mode.get() === "math") calculate();
                        else if (mode.get() === "files") fileSearch();
                        else if (mode.get() === "windows") listWindows();

                        if (ignoreFileAsync) updateEmpty();
                    });
                }}
            />
        </stack>
    );
};

const LauncherContent = ({
    mode,
    showResults,
    entry,
}: {
    mode: Variable<Mode>;
    showResults: Variable<boolean>;
    entry: Widget.Entry;
}) => (
    <box vertical className={bind(mode).as(m => `launcher ${m}`)}>
        <box className="search-bar">
            <label className="icon" label="search" />
            <SearchEntry entry={entry} />
            <label className="icon" label={bind(mode).as(getIconFromMode)} />
        </box>
        <revealer
            revealChild={bind(showResults).as(s => !s)}
            transitionType={Gtk.RevealerTransitionType.SLIDE_DOWN}
            transitionDuration={150}
        >
            <PinnedApps />
        </revealer>
        <revealer
            revealChild={bind(showResults)}
            transitionType={Gtk.RevealerTransitionType.SLIDE_UP}
            transitionDuration={150}
        >
            <Results entry={entry} mode={mode} />
        </revealer>
    </box>
);

@register()
export default class Launcher extends PopupWindow {
    readonly mode: Variable<Mode>;

    constructor() {
        const entry = (<entry name="entry" />) as Widget.Entry;
        const mode = Variable<Mode>("apps");
        const showResults = Variable.derive([bind(entry, "textLength"), mode], (t, m) => t > 0 || m !== "apps");

        super({
            name: "launcher",
            anchor: Astal.WindowAnchor.TOP,
            keymode: Astal.Keymode.EXCLUSIVE,
            onKeyPressEvent(_, event) {
                const keyval = event.get_keyval()[1];
                // Focus entry on typing
                if (!entry.isFocus && keyval >= 32 && keyval <= 126) {
                    entry.text += String.fromCharCode(keyval);
                    entry.grab_focus();
                    entry.set_position(-1);

                    // Consume event, if not consumed it will duplicate character in entry
                    return true;
                }
            },
            child: <LauncherContent mode={mode} showResults={showResults} entry={entry} />,
        });

        this.mode = mode;

        this.connect("show", () => (this.marginTop = AstalHyprland.get_default().focusedMonitor.height / 4));

        // Clear search on hide if not in math mode
        this.connect("hide", () => mode.get() !== "math" && entry.set_text(""));

        this.connect("destroy", () => showResults.drop());
    }

    open(mode: Mode) {
        this.mode.set(mode);
        this.show();
    }
}