forked from albertlauncher/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.cpp
More file actions
355 lines (282 loc) · 13.2 KB
/
Copy pathextension.cpp
File metadata and controls
355 lines (282 loc) · 13.2 KB
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
// Copyright (c) 2017-2018 Manuel Schneider
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include "pythonmodulev1.h"
#include <QClipboard>
#include <QDesktopServices>
#include <QDirIterator>
#include <QFileSystemWatcher>
#include <QMessageLogger>
#include <QMutexLocker>
#include <QPointer>
#include <QStandardPaths>
#include <QUrl>
#include <memory>
#include "xdg/iconlookup.h"
#include "albert/query.h"
#include "albert/item.h"
#include "albert/action.h"
#include "albert/util/standardactions.h"
#include "albert/util/standarditem.h"
#include "extension.h"
#include "modulesmodel.h"
#include "configwidget.h"
#include "cast_specialization.h"
using namespace std;
using namespace Core;
namespace py = pybind11;
Q_LOGGING_CATEGORY(qlc_python, "python")
#define DEBUG qCDebug(qlc_python).noquote()
#define INFO qCInfo(qlc_python).noquote()
#define WARNING qCWarning(qlc_python).noquote()
#define CRITICAL qCCritical(qlc_python).noquote()
namespace Python {
const constexpr char* MODULES_DIR = "modules";
const constexpr char* CFG_ENABLEDMODS = "enabled_modules";
/*
* Module definition
*/
#include <pybind11/stl.h>
PYBIND11_EMBEDDED_MODULE(albertv0, m)
{
/*
* 0.1
*/
m.doc() = "pybind11 example module";
py::class_<Core::Query, std::unique_ptr<Query, py::nodelete>>(m, "Query", "The query object to handle for a user input")
.def_property_readonly("string", &Query::string)
.def_property_readonly("rawString", &Query::rawString)
.def_property_readonly("trigger", &Query::trigger)
.def_property_readonly("isTriggered", &Query::isTriggered)
.def_property_readonly("isValid", &Query::isValid)
;
py::class_<Action, shared_ptr<Action>>(m, "ActionBase", "An abstract action")
;
py::class_<Item, shared_ptr<Item>> iitem(m, "ItemBase", "An abstract item")
;
/* This is a bit more evolved. In this case a piece of python code is injected into C++ code and
* has to be handled with care. The GIL has to be locked whenever the code is touched, i.e. on
* execution and deletion. Further exceptions thrown from python have to be catched. */
py::class_<FuncAction, Action, shared_ptr<FuncAction>>(m, "FuncAction", "Executes the callable")
.def(py::init([](QString text, const py::object& callable) {
return shared_ptr<FuncAction>(
new FuncAction(move(text), [callable](){
py::gil_scoped_acquire acquire;
try{
callable();
} catch (exception &e) {
WARNING << e.what();
}
}),
[=](FuncAction *funcAction) {
py::gil_scoped_acquire acquire;
delete funcAction;
}
);
}), py::arg("text"), py::arg("callable"))
;
py::class_<ClipAction, Action, shared_ptr<ClipAction>>(m, "ClipAction", "Copies to clipboard")
.def(py::init<QString, QString>(), py::arg("text"), py::arg("clipboardText"))
;
py::class_<UrlAction, Action, shared_ptr<UrlAction>>(m, "UrlAction", "Opens a URL")
.def(py::init<QString, QString>(), py::arg("text"), py::arg("url"))
;
py::class_<ProcAction, Action, shared_ptr<ProcAction>>(m, "ProcAction", "Runs a process")
.def(py::init([](QString text, list<QString> commandline, QString workdir) {
return std::make_shared<ProcAction>(move(text), QStringList::fromStdList(commandline), move(workdir));
}), py::arg("text"), py::arg("commandline"), py::arg("cwd") = QString())
;
py::class_<TermAction, Action, shared_ptr<TermAction>>pyTermAction(m, "TermAction", "Runs a command in terminal");
py::enum_<TermAction::CloseBehavior>(pyTermAction, "CloseBehavior")
.value("CloseOnSuccess", TermAction::CloseBehavior::CloseOnSuccess)
.value("CloseOnExit", TermAction::CloseBehavior::CloseOnExit)
.value("DoNotClose", TermAction::CloseBehavior::DoNotClose)
.export_values()
;
pyTermAction.def(py::init([](QString text, list<QString> commandline, QString workdir, bool shell, TermAction::CloseBehavior behavior) {
return std::make_shared<TermAction>(move(text), QStringList::fromStdList(commandline), move(workdir), shell, behavior);
}), py::arg("text"), py::arg("commandline"), py::arg("cwd") = QString(), py::arg("shell") = true, py::arg("behavior") = TermAction::CloseBehavior::CloseOnSuccess)
;
py::enum_<Item::Urgency>(iitem, "Urgency")
.value("Alert", Item::Urgency::Alert)
.value("Notification", Item::Urgency::Notification)
.value("Normal", Item::Urgency::Normal)
.export_values()
;
py::class_<StandardItem, Item, shared_ptr<StandardItem>>(m, "Item", "A result item")
.def(py::init<QString,QString,QString,QString,QString,Item::Urgency,vector<shared_ptr<Action>>>(),
py::arg("id") = QString(),
py::arg("icon") = QString(":python_module"),
py::arg("text") = QString(),
py::arg("subtext") = QString(),
py::arg("completion") = QString(),
py::arg("urgency") = Item::Urgency::Normal,
py::arg("actions") = vector<shared_ptr<Action>>())
.def_property("id", &StandardItem::id, &StandardItem::setId)
.def_property("icon", &StandardItem::iconPath, &StandardItem::setIconPath)
.def_property("text", &StandardItem::text, &StandardItem::setText)
.def_property("subtext", &StandardItem::subtext, &StandardItem::setSubtext)
.def_property("completion", &StandardItem::completion, &StandardItem::setCompletion)
.def_property("urgency", &StandardItem::urgency, &StandardItem::setUrgency)
.def("addAction", static_cast<void (StandardItem::*)(const std::shared_ptr<Action> &)>(&StandardItem::addAction))
;
m.def("debug", [](const py::object &obj){ DEBUG << py::str(obj).cast<QString>(); });
m.def("info", [](const py::object &obj){ INFO << py::str(obj).cast<QString>(); });
m.def("warning", [](const py::object &obj){ WARNING << py::str(obj).cast<QString>(); });
m.def("critical", [](const py::object &obj){ CRITICAL << py::str(obj).cast<QString>(); });
m.def("iconLookup", [](const py::str &str){ return XDG::IconLookup::iconPath(str.cast<QString>()); });
/*
* 0.2
*/
m.def("configLocation", [](){ return QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); });
m.def("dataLocation", [](){ return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); });
m.def("cacheLocation", [](){ return QStandardPaths::writableLocation(QStandardPaths::CacheLocation); });
}
}
class Python::Private
{
public:
unique_ptr<py::gil_scoped_release> release;
QPointer<ConfigWidget> widget;
vector<unique_ptr<PythonModuleV1>> modules;
QFileSystemWatcher extensionDirectoryWatcher;
QFileSystemWatcher sourcesWatcher;
QStringList enabledModules;
};
/** ***************************************************************************/
Python::Extension::Extension()
: Core::Extension("org.albert.extension.python"), // Must match the id in metadata
Core::QueryHandler(Core::Plugin::id()),
d(new Private) {
/*
* The python interpreter is never unloaded once it has been loaded. This is working around the
* ugly segfault that occur when third-party libraries have been loaded an the interpreter is
* finalized and initialized.
*/
if ( !Py_IsInitialized() )
py::initialize_interpreter(false);
d->release.reset(new py::gil_scoped_release);
d->enabledModules = settings().value(CFG_ENABLEDMODS).toStringList();
if ( !dataLocation().exists(MODULES_DIR) )
dataLocation().mkdir(MODULES_DIR);
// Watch the modules directories for changes
for (const QString &dataDir : QStandardPaths::locateAll(QStandardPaths::DataLocation,
Core::Plugin::id(),
QStandardPaths::LocateDirectory) ) {
QDir dir{dataDir};
if (dir.cd(MODULES_DIR))
d->extensionDirectoryWatcher.addPath(dir.path());
}
connect(&d->extensionDirectoryWatcher, &QFileSystemWatcher::directoryChanged,
this, &Extension::reloadModules);
connect(&d->sourcesWatcher, &QFileSystemWatcher::fileChanged,
this, &Extension::reloadModules);
reloadModules();
registerQueryHandler(this);
}
/** ***************************************************************************/
Python::Extension::~Extension() {
d->modules.clear();
}
/** ***************************************************************************/
QWidget *Python::Extension::widget(QWidget *parent) {
if (d->widget.isNull()) {
d->widget = new ConfigWidget(parent);
ModulesModel *model = new ModulesModel(this, d->widget->ui.tableView);
d->widget->ui.tableView->setModel(model);
connect(d->widget->ui.tableView, &QTableView::activated,
this, [this](const QModelIndex &index){
QDesktopServices::openUrl(QUrl(d->modules[static_cast<size_t>(index.row())]->path()));
});
}
return d->widget;
}
/** ***************************************************************************/
void Python::Extension::handleQuery(Core::Query *query) const {
if ( query->isTriggered() ) {
for ( auto & module : d->modules ) {
if ( d->enabledModules.contains(module->id())
&& module->state() == PythonModuleV1::State::Loaded
&& module->trigger() == query->trigger() ) {
module->handleQuery(query);
return;
}
}
}
else {
for ( auto & module : d->modules ) {
if ( d->enabledModules.contains(module->id())
&& module->state() == PythonModuleV1::State::Loaded) {
module->handleQuery(query);
if ( !query->isValid() )
return;
}
}
}
}
/** ***************************************************************************/
QStringList Python::Extension::triggers() const {
QStringList retval;
for ( auto &module : d->modules )
retval << module->trigger();
return retval;
}
/** ***************************************************************************/
const std::vector<std::unique_ptr<Python::PythonModuleV1> > &Python::Extension::modules() {
return d->modules;
}
/** ***************************************************************************/
bool Python::Extension::isEnabled(Python::PythonModuleV1 &module) {
return d->enabledModules.contains(module.id());
}
/** ***************************************************************************/
void Python::Extension::setEnabled(Python::PythonModuleV1 &module, bool enable) {
if (enable)
d->enabledModules.append(module.id());
else
d->enabledModules.removeAll(module.id());
settings().setValue(CFG_ENABLEDMODS, d->enabledModules);
enable ? module.load() : module.unload();
}
/** ***************************************************************************/
void Python::Extension::reloadModules() {
// Reset
d->modules.clear();
d->sourcesWatcher.removePaths(d->sourcesWatcher.files());
// Get all module source paths
QStringList paths;
for (const QString &dataDir : QStandardPaths::locateAll(QStandardPaths::DataLocation,
Core::Plugin::id(),
QStandardPaths::LocateDirectory) ) {
QDir dir{dataDir};
if (dir.cd(MODULES_DIR)) {
for(const QFileInfo &fileInfo : dir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot)) {
QDir dir{fileInfo.filePath()};
if (dir.exists("__init__.py"))
paths.append(dir.absolutePath());
}
for(const QFileInfo &fileInfo : dir.entryInfoList({"*.py"}, QDir::Files))
paths.append(fileInfo.absoluteFilePath());
}
}
// Read metada, ignore dup ids, load id enabled, source file watcher
for(const QString &path : paths){
try {
auto module = make_unique<PythonModuleV1>(path);
// Skip if this id already exists
if ( find_if(d->modules.begin(), d->modules.end(),
[&module](const unique_ptr<PythonModuleV1> &rhs){return module->id() == rhs->id();})
!= d->modules.end() )
continue;
if (d->enabledModules.contains(module->id()))
module->load();
d->sourcesWatcher.addPath(module->sourcePath());
d->modules.emplace_back(move(module));
} catch (const std::exception &e) {
WARNING << e.what() << path;
}
}
std::sort(d->modules.begin(), d->modules.end(),
[](auto& lhs, auto& rhs){ return 0 > lhs->name().localeAwareCompare(rhs->name()); });
emit modulesChanged();
}