summaryrefslogtreecommitdiff
path: root/src/modules/launcher/modes.tsx
blob: 0db7cd5784ab0d3aa65e561e0ee4c7e6884e8869 (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
import { Apps as AppsService } from "@/services/apps";
import MathService, { type HistoryItem } from "@/services/math";
import { getAppCategoryIcon } from "@/utils/icons";
import { launch } from "@/utils/system";
import { type FlowBox, setupCustomTooltip } from "@/utils/widgets";
import { bind, execAsync, Gio, register, Variable } from "astal";
import { Astal, Gtk, Widget } from "astal/gtk3";
import { launcher as config } from "config";
import type AstalApps from "gi://AstalApps";
import { close, ContentBox, type LauncherContent, limitLength } from "./util";

const AppResult = ({ app }: { app: AstalApps.Application }) => (
    <Gtk.FlowBoxChild visible canFocus={false}>
        <button
            className="result"
            cursor="pointer"
            onClicked={() => {
                launch(app);
                close();
            }}
            setup={self => setupCustomTooltip(self, app.description ? `${app.name}: ${app.description}` : app.name)}
        >
            <box>
                {app.iconName && Astal.Icon.lookup_icon(app.iconName) ? (
                    <icon className="icon" icon={app.iconName} />
                ) : (
                    <label className="icon" label={getAppCategoryIcon(app)} />
                )}
                <label truncate label={app.name} />
            </box>
        </button>
    </Gtk.FlowBoxChild>
);

const FileResult = ({ path }: { path: string }) => (
    <Gtk.FlowBoxChild visible canFocus={false}>
        <button
            className="result"
            cursor="pointer"
            onClicked={() => {
                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);
                close();
            }}
        >
            <box setup={self => setupCustomTooltip(self, path.replace(HOME, "~"))}>
                <icon
                    className="icon"
                    gicon={
                        Gio.File.new_for_path(path)
                            .query_info(Gio.FILE_ATTRIBUTE_STANDARD_ICON, Gio.FileQueryInfoFlags.NONE, null)
                            .get_icon()!
                    }
                />
                <label
                    truncate
                    label={
                        path.replace(HOME, "~").length > config.files.shortenThreshold.get()
                            ? path
                                  .replace(HOME, "~")
                                  .split("/")
                                  .map((n, i, arr) => (i === 0 || i === arr.length - 1 ? n : n.slice(0, 1)))
                                  .join("/")
                            : path.replace(HOME, "~")
                    }
                />
            </box>
        </button>
    </Gtk.FlowBoxChild>
);

const MathResult = ({ icon, equation, result }: HistoryItem) => (
    <Gtk.FlowBoxChild visible canFocus={false}>
        <button
            className="result"
            cursor="pointer"
            onClicked={() => {
                execAsync(["wl-copy", "--", result]).catch(console.error);
                close();
            }}
            setup={self => setupCustomTooltip(self, `${equation} -> ${result}`)}
        >
            <box>
                <label className="icon" label={icon} />
                <box vertical className="has-sublabel">
                    <label truncate xalign={0} label={equation} />
                    <label truncate xalign={0} label={result} className="sublabel" />
                </box>
            </box>
        </button>
    </Gtk.FlowBoxChild>
);

@register()
class Apps extends Widget.Box implements LauncherContent {
    #content: FlowBox;

    constructor() {
        super({ name: "apps", className: "apps" });

        this.#content = (<ContentBox />) as FlowBox;

        this.add(
            <scrollable expand hscroll={Gtk.PolicyType.NEVER}>
                {this.#content}
            </scrollable>
        );
    }

    updateContent(search: string): void {
        this.#content.foreach(c => c.destroy());
        for (const app of limitLength(AppsService.fuzzy_query(search), config.apps))
            this.#content.add(<AppResult app={app} />);
    }

    handleActivate(): void {
        this.#content.get_child_at_index(0)?.get_child()?.grab_focus();
        this.#content.get_child_at_index(0)?.get_child()?.activate();
    }
}

@register()
class Files extends Widget.Box implements LauncherContent {
    #content: FlowBox;

    constructor() {
        super({ name: "files", className: "files" });

        this.#content = (<ContentBox />) as FlowBox;

        this.add(
            <scrollable expand hscroll={Gtk.PolicyType.NEVER}>
                {this.#content}
            </scrollable>
        );
    }

    updateContent(search: string): void {
        execAsync(["fd", ...config.files.fdOpts.get(), search, HOME])
            .then(out => {
                this.#content.foreach(c => c.destroy());
                const paths = out.split("\n").filter(path => path);
                for (const path of limitLength(paths, config.files)) this.#content.add(<FileResult path={path} />);
            })
            .catch(() => {}); // Ignore errors
    }

    handleActivate(): void {
        this.#content.get_child_at_index(0)?.get_child()?.grab_focus();
        this.#content.get_child_at_index(0)?.get_child()?.activate();
    }
}

@register()
class Math extends Widget.Box implements LauncherContent {
    #showResult: Variable<boolean>;
    #result: Variable<HistoryItem>;
    #content: FlowBox;

    constructor() {
        super({ name: "math", className: "math", vertical: true });

        this.#showResult = Variable(false);
        this.#result = Variable({ equation: "", result: "", icon: "" });
        this.#content = (<ContentBox />) as FlowBox;

        this.add(
            <revealer
                transitionType={Gtk.RevealerTransitionType.SLIDE_DOWN}
                transitionDuration={150}
                revealChild={bind(this.#showResult)}
            >
                <box vertical className="preview">
                    <box className="result">
                        <label className="icon" label={bind(this.#result).as(r => r.icon)} />
                        <box vertical>
                            <label xalign={0} label="Result" />
                            <label
                                truncate
                                xalign={0}
                                className="sublabel"
                                label={bind(this.#result).as(r => r.result)}
                            />
                        </box>
                    </box>
                    <box className="separator" />
                </box>
            </revealer>
        );
        this.add(
            <scrollable expand hscroll={Gtk.PolicyType.NEVER}>
                {this.#content}
            </scrollable>
        );
    }

    updateContent(search: string): void {
        this.#showResult.set(search.length > 0);
        this.#result.set(MathService.get_default().evaluate(search));

        this.#content.foreach(c => c.destroy());
        for (const item of limitLength(MathService.get_default().history, config.math))
            this.#content.add(<MathResult {...item} />);
    }

    handleActivate(search: string): void {
        if (!search) return;
        MathService.get_default().commit();
        const res = this.#result.get();
        // Copy and close if not assignment, help or error
        if (!["equal", "help", "error"].includes(res.icon)) {
            execAsync(["wl-copy", "--", res.result]).catch(console.error);
            close();
        }
    }
}

export default () => ({
    apps: new Apps(),
    files: new Files(),
    math: new Math(),
});