summaryrefslogtreecommitdiff
path: root/src/modules/launcher.tsx
blob: 2fc6eefb1308fabfacd16c5f17e757c8dc88e0c1 (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
import { bind, execAsync, Gio, GLib, register, timeout, Variable } from "astal";
import { 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 Math, { type HistoryItem } from "../services/math";
import { getAppCategoryIcon } from "../utils/icons";
import { launch } from "../utils/system";
import { setupCustomTooltip } from "../utils/widgets";
import PopupWindow from "../widgets/popupwindow";

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

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";
    }
};

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";
    }
};

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 app ? (
        <button
            className="pinned-app result"
            cursor="pointer"
            onClicked={self => launchAndClose(self, astalApp!)}
            setup={self => setupCustomTooltip(self, app.get_display_name())}
        >
            <icon gicon={app.get_icon()!} />
        </button>
    ) : null;
};

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,
    onClicked,
}: {
    icon?: string;
    materialIcon?: string;
    label: string;
    sublabel?: string;
    onClicked: (self: Widget.Button) => void;
}) => (
    <button className="result" cursor="pointer" onClicked={onClicked}>
        <box>
            {icon && Astal.Icon.lookup_icon(icon) ? (
                <icon valign={Gtk.Align.START} className="icon" icon={icon} />
            ) : (
                <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 }) => (
    <Result
        icon={app.iconName}
        materialIcon={getAppCategoryIcon(app)}
        label={app.name}
        sublabel={app.description}
        onClicked={self => launchAndClose(self, app)}
    />
);

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) {
                Math.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
        label={path.split("/").pop()!}
        sublabel={path.startsWith(HOME) ? "~" + path.slice(HOME.length) : path}
        onClicked={self => openFileAndClose(self, path)}
    />
);

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"),
                        },
                        todo: {
                            icon: "checklist",
                            name: "Todo",
                            description: "Create a todo in <INSERT_TODO_APP>",
                            command: (...args) => {
                                // TODO: todo service or maybe use external app
                            },
                        },
                    };
                    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={Math.get_default().evaluate(entry.text)} entry={entry} />);
                            self.add(<box className="separator" />);
                        }
                        for (const item of Math.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);

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

                        // Files has delay cause async so it does some stuff by itself
                        const ignoreFileAsync = entry.text.startsWith(">") || mode.get() !== "files";
                        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();

                        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();
    }
}