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
|
/*
* Copyright (c) 2021, Spencer Dixon <spencercdixon@gmail.com>
* Copyright (c) 2022-2023, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "Providers.h"
#include <AK/Array.h>
#include <AK/DeprecatedString.h>
#include <AK/Error.h>
#include <AK/LexicalPath.h>
#include <AK/QuickSort.h>
#include <AK/Try.h>
#include <LibCore/Debounce.h>
#include <LibCore/LockFile.h>
#include <LibCore/System.h>
#include <LibDesktop/Launcher.h>
#include <LibGUI/Action.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/Menu.h>
#include <LibGUI/Painter.h>
#include <LibGUI/TextBox.h>
#include <LibGfx/Palette.h>
#include <LibMain/Main.h>
#include <LibThreading/Mutex.h>
#include <string.h>
#include <unistd.h>
namespace Assistant {
struct AppState {
Optional<size_t> selected_index;
NonnullRefPtrVector<Result> results;
size_t visible_result_count { 0 };
Threading::Mutex lock;
DeprecatedString last_query;
};
class ResultRow final : public GUI::Button {
C_OBJECT(ResultRow)
ResultRow()
{
set_greedy_for_hits(true);
set_fixed_height(36);
set_text_alignment(Gfx::TextAlignment::CenterLeft);
set_button_style(Gfx::ButtonStyle::Coolbar);
set_focus_policy(GUI::FocusPolicy::NoFocus);
on_context_menu_request = [this](auto& event) {
if (!m_context_menu) {
m_context_menu = GUI::Menu::construct();
if (LexicalPath path { text() }; path.is_absolute()) {
m_context_menu->add_action(GUI::Action::create("&Show in File Manager", MUST(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-file-manager.png"sv)), [=](auto&) {
Desktop::Launcher::open(URL::create_with_file_scheme(path.dirname(), path.basename()));
}));
m_context_menu->add_separator();
}
m_context_menu->add_action(GUI::Action::create("&Copy as Text", MUST(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/edit-copy.png"sv)), [&](auto&) {
GUI::Clipboard::the().set_plain_text(text());
}));
}
m_context_menu->popup(event.screen_position());
};
}
RefPtr<GUI::Menu> m_context_menu;
};
template<size_t ProviderCount>
class Database {
public:
explicit Database(AppState& state, Array<NonnullRefPtr<Provider>, ProviderCount>& providers)
: m_state(state)
, m_providers(providers)
{
}
Function<void(NonnullRefPtrVector<Result>)> on_new_results;
void search(DeprecatedString const& query)
{
auto should_display_precached_results = false;
for (size_t i = 0; i < ProviderCount; ++i) {
auto& result_array = m_result_cache.ensure(query);
if (result_array.at(i) == nullptr) {
m_providers[i]->query(query, [this, query, i](auto results) {
{
Threading::MutexLocker db_locker(m_mutex);
auto& result_array = m_result_cache.ensure(query);
if (result_array.at(i) != nullptr)
return;
result_array[i] = make<NonnullRefPtrVector<Result>>(results);
}
on_result_cache_updated();
});
} else {
should_display_precached_results = true;
}
}
if (should_display_precached_results)
on_result_cache_updated();
}
private:
void on_result_cache_updated()
{
Threading::MutexLocker 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.
Vector<NonnullRefPtr<Result>> all_results;
for (auto const& results_for_provider : new_results->value) {
if (results_for_provider == nullptr)
continue;
for (auto const& result : *results_for_provider) {
all_results.append(result);
}
}
dual_pivot_quick_sort(all_results, 0, static_cast<int>(all_results.size() - 1), [](auto& a, auto& b) {
return a->score() > b->score();
});
on_new_results(all_results);
}
AppState& m_state;
Array<NonnullRefPtr<Provider>, ProviderCount> m_providers;
Threading::Mutex m_mutex;
HashMap<DeprecatedString, Array<OwnPtr<NonnullRefPtrVector<Result>>, ProviderCount>> m_result_cache;
};
}
static constexpr size_t MAX_SEARCH_RESULTS = 6;
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
TRY(Core::System::pledge("stdio recvfd sendfd rpath cpath unix proc exec thread"));
Core::LockFile lockfile("/tmp/lock/assistant.lock");
if (!lockfile.is_held()) {
if (lockfile.error_code()) {
warnln("Core::LockFile: {}", strerror(lockfile.error_code()));
return 1;
}
// Another assistant is open, so exit silently.
return 0;
}
auto app = TRY(GUI::Application::try_create(arguments));
auto window = GUI::Window::construct();
window->set_minimizable(false);
Assistant::AppState app_state;
Array<NonnullRefPtr<Assistant::Provider>, 5> providers = {
make_ref_counted<Assistant::AppProvider>(),
make_ref_counted<Assistant::CalculatorProvider>(),
make_ref_counted<Assistant::TerminalProvider>(),
make_ref_counted<Assistant::URLProvider>(),
make_ref_counted<Assistant::FileProvider>()
};
Assistant::Database db { app_state, providers };
auto container = TRY(window->set_main_widget<GUI::Frame>());
container->set_fill_with_background_color(true);
container->set_frame_shape(Gfx::FrameShape::Window);
auto& layout = container->set_layout<GUI::VerticalBoxLayout>();
layout.set_margins({ 8 });
auto& text_box = container->add<GUI::TextBox>();
auto& results_container = container->add<GUI::Widget>();
auto& results_layout = results_container.set_layout<GUI::VerticalBoxLayout>();
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_font_weight(i == app_state.selected_index ? 700 : 400);
}
};
text_box.on_change = Core::debounce([&]() {
{
Threading::MutexLocker 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());
},
5);
text_box.on_return_pressed = [&]() {
if (!app_state.selected_index.has_value())
return;
lockfile.release();
app_state.results[app_state.selected_index.value()].activate();
GUI::Application::the()->quit();
};
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 = []() {
GUI::Application::the()->quit();
};
window->on_active_window_change = [](bool is_active_window) {
if (!is_active_window)
GUI::Application::the()->quit();
};
auto update_ui_timer = TRY(Core::Timer::create_single_shot(10, [&] {
results_container.remove_all_children();
results_layout.set_margins(app_state.visible_result_count ? GUI::Margins { 4, 0, 0, 0 } : GUI::Margins { 0 });
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_icon(result.bitmap());
match.set_text(move(result.title()));
match.set_tooltip(move(result.tooltip()));
match.on_click = [&result](auto) {
result.activate();
GUI::Application::the()->quit();
};
}
mark_selected_item();
Core::deferred_invoke([&] { window->resize(GUI::Desktop::the().rect().width() / 3, {}); });
}));
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);
update_ui_timer->restart();
};
window->set_window_type(GUI::WindowType::Popup);
window->set_forced_shadow(true);
window->resize(GUI::Desktop::the().rect().width() / 3, {});
window->center_on_screen();
window->move_to(window->x(), window->y() - (GUI::Desktop::the().rect().height() * 0.33));
window->show();
return app->exec();
}
|