summaryrefslogtreecommitdiff
path: root/Userland/Applications/Assistant/main.cpp
blob: 743dc7518807274f3c2b1050aef3d08e9769f359 (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
/*
 * Copyright (c) 2021, Spencer Dixon <spencercdixon@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Providers.h"
#include <AK/QuickSort.h>
#include <AK/String.h>
#include <LibGUI/Application.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Event.h>
#include <LibGUI/Icon.h>
#include <LibGUI/ImageWidget.h>
#include <LibGUI/Label.h>
#include <LibGUI/Painter.h>
#include <LibGUI/TextBox.h>
#include <LibGfx/Palette.h>
#include <LibThreading/Lock.h>

namespace Assistant {

struct AppState {
    Optional<size_t> selected_index;
    NonnullRefPtrVector<Result> results;
    size_t visible_result_count { 0 };

    Threading::Lock lock;
    String last_query;
};

class ResultRow final : public GUI::Widget {
    C_OBJECT(ResultRow)
public:
    ResultRow()
    {
        auto& layout = set_layout<GUI::HorizontalBoxLayout>();
        layout.set_spacing(12);
        layout.set_margins({ 4, 4, 4, 4 });

        m_image = add<GUI::ImageWidget>();

        m_label_container = add<GUI::Widget>();
        m_label_container->set_layout<GUI::VerticalBoxLayout>();
        m_label_container->set_fixed_height(30);

        m_title = m_label_container->add<GUI::Label>();
        m_title->set_text_alignment(Gfx::TextAlignment::CenterLeft);

        set_shrink_to_fit(true);
        set_fill_with_background_color(true);
        set_global_cursor_tracking(true);
        set_greedy_for_hits(true);
    }

    void set_image(RefPtr<Gfx::Bitmap> bitmap)
    {
        m_image->set_bitmap(bitmap);
    }
    void set_title(String text)
    {
        m_title->set_text(move(text));
    }
    void set_subtitle(String text)
    {
        if (text.is_empty()) {
            if (m_subtitle)
                m_subtitle->remove_from_parent();
            m_subtitle = nullptr;
            return;
        }
        if (!m_subtitle) {
            m_subtitle = m_label_container->add<GUI::Label>();
            m_subtitle->set_text_alignment(Gfx::TextAlignment::CenterLeft);
        }
        m_subtitle->set_text(move(text));
    }
    void set_is_highlighted(bool value)
    {
        if (m_is_highlighted == value)
            return;

        m_is_highlighted = value;
        m_title->set_font_weight(value ? 700 : 400);
    }

    Function<void()> on_selected;

private:
    void mousedown_event(GUI::MouseEvent&) override
    {
        set_background_role(ColorRole::MenuBase);
    }

    void mouseup_event(GUI::MouseEvent&) override
    {
        set_background_role(ColorRole::NoRole);
        on_selected();
    }

    void enter_event(Core::Event&) override
    {
        set_background_role(ColorRole::HoverHighlight);
    }

    void leave_event(Core::Event&) override
    {
        set_background_role(ColorRole::NoRole);
    }

    RefPtr<GUI::ImageWidget> m_image;
    RefPtr<GUI::Widget> m_label_container;
    RefPtr<GUI::Label> m_title;
    RefPtr<GUI::Label> m_subtitle;
    bool m_is_highlighted { false };
};

class Database {
public:
    explicit Database(AppState& state)
        : m_state(state)
    {
        m_providers.append(make<AppProvider>());
        m_providers.append(make<CalculatorProvider>());
        m_providers.append(make<FileProvider>());
        m_providers.append(make<TerminalProvider>());
        m_providers.append(make<URLProvider>());
    }

    Function<void(NonnullRefPtrVector<Result>)> on_new_results;

    void search(String const& query)
    {
        for (auto& provider : m_providers) {
            provider.query(query, [=, this](auto results) {
                did_receive_results(query, results);
            });
        }
    }

private:
    void did_receive_results(String const& query, NonnullRefPtrVector<Result> const& results)
    {
        {
            Threading::Locker db_locker(m_lock);
            auto it = m_result_cache.find(query);
            if (it == m_result_cache.end()) {
                m_result_cache.set(query, {});
            }
            it = m_result_cache.find(query);

            for (auto& result : results) {
                auto found = it->value.find_if([&result](auto& other) {
                    return result.equals(other);
                });

                if (found.is_end())
                    it->value.append(result);
            }
        }

        Threading::Locker state_locker(m_state.lock);
        auto new_results = m_result_cache.find(m_state.last_query);
        if (new_results == m_result_cache.end())
            return;

        // NonnullRefPtrVector will provide dual_pivot_quick_sort references rather than pointers,
        // and dual_pivot_quick_sort requires being able to construct the underlying type on the
        // stack. Assistant::Result is pure virtual, thus cannot be constructed on the stack.
        auto& sortable_results = static_cast<Vector<NonnullRefPtr<Result>>&>(new_results->value);

        dual_pivot_quick_sort(sortable_results, 0, static_cast<int>(sortable_results.size() - 1), [](auto& a, auto& b) {
            return a->score() > b->score();
        });

        on_new_results(new_results->value);
    }

    AppState& m_state;

    NonnullOwnPtrVector<Provider> m_providers;

    Threading::Lock m_lock;
    HashMap<String, NonnullRefPtrVector<Result>> m_result_cache;
};

}

static constexpr size_t MAX_SEARCH_RESULTS = 6;

int main(int argc, char** argv)
{
    if (pledge("stdio recvfd sendfd rpath unix proc exec thread", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    auto app = GUI::Application::construct(argc, argv);
    auto window = GUI::Window::construct();
    window->set_minimizable(false);

    Assistant::AppState app_state;
    Assistant::Database db { app_state };

    auto& container = window->set_main_widget<GUI::Frame>();
    container.set_fill_with_background_color(true);
    container.set_frame_shadow(Gfx::FrameShadow::Raised);
    auto& layout = container.set_layout<GUI::VerticalBoxLayout>();
    layout.set_margins({ 8, 8, 8, 0 });

    auto& text_box = container.add<GUI::TextBox>();
    auto& results_container = container.add<GUI::Widget>();
    auto& results_layout = results_container.set_layout<GUI::VerticalBoxLayout>();
    results_layout.set_margins({ 0, 10, 0, 10 });

    auto mark_selected_item = [&]() {
        for (size_t i = 0; i < app_state.visible_result_count; ++i) {
            auto& row = static_cast<Assistant::ResultRow&>(results_container.child_widgets()[i]);
            row.set_is_highlighted(i == app_state.selected_index);
        }
    };

    text_box.on_change = [&]() {
        {
            Threading::Locker locker(app_state.lock);
            if (app_state.last_query == text_box.text())
                return;

            app_state.last_query = text_box.text();
        }

        db.search(text_box.text());
    };
    text_box.on_return_pressed = [&]() {
        if (!app_state.selected_index.has_value())
            return;
        app_state.results[app_state.selected_index.value()].activate();
        exit(0);
    };
    text_box.on_up_pressed = [&]() {
        if (!app_state.visible_result_count)
            return;
        auto new_selected_index = app_state.selected_index.value_or(0);
        if (new_selected_index == 0)
            new_selected_index = app_state.visible_result_count - 1;
        else if (new_selected_index > 0)
            new_selected_index -= 1;

        app_state.selected_index = new_selected_index;
        mark_selected_item();
    };
    text_box.on_down_pressed = [&]() {
        if (!app_state.visible_result_count)
            return;

        auto new_selected_index = app_state.selected_index.value_or(0);
        if ((app_state.visible_result_count - 1) == new_selected_index)
            new_selected_index = 0;
        else if (app_state.visible_result_count > new_selected_index)
            new_selected_index += 1;

        app_state.selected_index = new_selected_index;
        mark_selected_item();
    };
    text_box.on_escape_pressed = []() {
        exit(0);
    };

    db.on_new_results = [&](auto results) {
        if (results.is_empty())
            app_state.selected_index = {};
        else
            app_state.selected_index = 0;
        app_state.results = results;
        app_state.visible_result_count = min(results.size(), MAX_SEARCH_RESULTS);
        results_container.remove_all_children();

        for (size_t i = 0; i < app_state.visible_result_count; ++i) {
            auto& result = app_state.results[i];
            auto& match = results_container.add<Assistant::ResultRow>();
            match.set_image(result.bitmap());
            match.set_title(result.title());
            match.set_subtitle(result.subtitle());
            match.on_selected = [&result]() {
                result.activate();
                exit(0);
            };
        }

        mark_selected_item();

        auto window_height = app_state.visible_result_count * 40 + text_box.height() + 28;
        window->resize(GUI::Desktop::the().rect().width() / 3, window_height);
    };

    window->set_frameless(true);
    window->set_forced_shadow(true);
    window->resize(GUI::Desktop::the().rect().width() / 3, 46);
    window->center_on_screen();
    window->move_to(window->x(), window->y() - (GUI::Desktop::the().rect().height() * 0.33));
    window->show();

    return app->exec();
}