-
Notifications
You must be signed in to change notification settings - Fork 4
/
JepAPI.cpp
618 lines (499 loc) · 15.7 KB
/
JepAPI.cpp
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
#include "JepAPI.h"
#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QAction>
#include <QPushButton>
#include <QCheckBox>
#include <QRadioButton>
#include <QToolButton>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QToolBar>
#include <QToolButton>
#include <QtQml>
#include <QQuickView>
#include <QQuickItem>
#include <extensionsystem/iplugin.h>
#include <extensionsystem/pluginmanager.h>
using namespace JsExtensions::Internal;
MyEventFilter::MyEventFilter(QDialog* dlg, QWidget* w, QQuickView *v)
: QObject(dlg),
m_dlg(dlg), m_w(w), m_v(v)
{
if (m_v->status() == QQuickView::Ready) {
QObject::connect(m_v->rootObject(), SIGNAL(close(int)), m_dlg, SLOT(done(int)));
}
}
MyEventFilter::~MyEventFilter()
{
}
bool MyEventFilter::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::Resize) {
m_w->resize(m_dlg->size());
}
return true;
}
static int coreTypeId = qmlRegisterType<GCore>();
static int messageManagerTypeId = qmlRegisterType<GMessageManager>();
static int modeManagerTypeId = qmlRegisterType<GModeManager>();
static int commandTypeId = qmlRegisterType<GCommand>();
static int editorCommandTypeId = qmlRegisterType<Core::IEditor>();
static int actionContainerTypeId = qmlRegisterType<GActionContainer>();
static int actionManagerTypeId = qmlRegisterType<GActionManager>();
static int actionTypeId = qmlRegisterType<QAction>();
void JsPluginInfo::save(QSettings* settings) const
{
settings->beginGroup(QString("Plugin_%1").arg(name));
{
settings->setValue("priority", priority);
settings->setValue("isEnabled", isEnabled);
settings->setValue("trace", trace);
}
settings->endGroup();
}
void JsPluginInfo::restore(QSettings* settings)
{
settings->beginGroup(QString("Plugin_%1").arg(name));
{
if (settings->contains("priority"))
priority = settings->value("priority", priority).toInt();
if (settings->contains("isEnabled"))
isEnabled = settings->value("isEnabled", isEnabled).toBool();
if (settings->contains("trace"))
trace = settings->value("trace", trace).toBool();
}
settings->endGroup();
}
bool JsPluginInfo::hasSettings()
{
if (!plugin)
return false;
QJSValue settingsFn = plugin->jsEngine()->evaluate("settings");
if (!settingsFn.isCallable())
return false;
return true;
}
bool JsPluginInfo::invokeSettings(QObject *parent, QString &errors)
{
if (!plugin)
return false;
QJSValue settingsFn = plugin->jsEngine()->evaluate("settings");
if (!settingsFn.isCallable())
return false;
QJSValueList args;
args << plugin->jsEngine()->toScriptValue(parent);
QJSValue res = settingsFn.call(args);
if (res.isError()) {
errors += res.toString();
return false;
}
return true;
}
#define REG_O_FACTORY(ClassName) \
m_factories.insert(#ClassName, [](QObject* parent)->QObject* { \
return new ClassName(parent); \
})
#define REG_W_FACTORY(ClassName) \
m_factories.insert(#ClassName, [](QObject* parent)->QObject* { \
return new ClassName(qobject_cast<QWidget*>(parent)); \
})
JsPlugin::JsPlugin(QObject* parent)
: QObject(parent),
m_debugIndent(0)
{
// register creatable objects
REG_O_FACTORY(QAction);
REG_W_FACTORY(QWidget);
REG_W_FACTORY(QPushButton);
REG_W_FACTORY(QCheckBox);
REG_W_FACTORY(QRadioButton);
REG_W_FACTORY(QToolButton);
REG_W_FACTORY(QLabel);
REG_W_FACTORY(QLineEdit);
REG_W_FACTORY(QMessageBox);
REG_W_FACTORY(QToolBar);
REG_W_FACTORY(QToolButton);
}
JsPlugin::~JsPlugin()
{
// first of all delete JS engine
m_jsEngine.reset();
}
class JepAPIException
{
public:
JepAPIException(QString error)
: error(error)
{}
QString error;
};
bool JsPlugin::loadPlugin(QString pluginPath, QString* errorString)
{
if (!m_jsEngine.isNull())
{
*errorString = "JepAPI is initialized already.";
return false;
}
try
{
// save plugin path and name
m_pluginPath = pluginPath;
m_info.name = QFileInfo(m_pluginPath).baseName();
// open plugin file
QFile scriptFile(pluginPath);
if (!scriptFile.open(QIODevice::ReadOnly))
{
throw JepAPIException("Cannot open file.");
}
// read script
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
// prepare java script engine
m_jsEngine.reset(new QJSEngine());
installJsContext(m_jsEngine.data());
// load script
QJSValue res = m_jsEngine->evaluate(contents, pluginPath);
if (res.isError())
{
throw JepAPIException(QString("Script error: '%1'.").arg(res.toString()));
}
// try to find "pluginDescription" variable
res = m_jsEngine->evaluate("pluginDescription");
if (res.isString())
{
m_info.description = res.toString();
}
// try to find "pluginEnable" variable
res = m_jsEngine->evaluate("pluginEnable");
if (res.isBool())
{
m_info.isEnabled = res.toBool();
}
// try to find "pluginPriority" variable
res = m_jsEngine->evaluate("pluginPriority");
if (res.isNumber())
{
m_info.priority = res.toInt();
}
// try to find "pluginTrace" variable
res = m_jsEngine->evaluate("pluginTrace");
if (res.isBool())
{
m_info.trace = res.toBool();
}
}
catch (const JepAPIException& exception)
{
*errorString = QString("%1\nScript file: '%2'").arg(exception.error, pluginPath);
m_jsEngine.reset();
return false;
}
catch (...)
{
*errorString = QString("Unhandled exception in plugin '%1'.").arg(pluginPath);
m_jsEngine.reset();
return false;
}
return true;
}
void JsPlugin::installJsContext(QJSEngine* jsEngine)
{
QJSValue globalObject = jsEngine->globalObject();
GContext gContext;
gContext.plugin = this;
gContext.jsEngine = jsEngine;
// setup objects to js context
GCore* c(new GCore(gContext));
globalObject.setProperty("core", jsEngine->newQObject(c));
GMessageManager* msm(new GMessageManager(gContext));
globalObject.setProperty("messageManager", jsEngine->newQObject(msm));
GActionManager* am(new GActionManager(gContext));
globalObject.setProperty("actionManager", jsEngine->newQObject(am));
GModeManager* mm(new GModeManager(gContext));
globalObject.setProperty("modeManager", jsEngine->newQObject(mm));
globalObject.setProperty("jepAPI", jsEngine->toScriptValue(static_cast<QObject*>(this)));
}
void JsPlugin::installQmlContext(QQmlEngine* qmlEngine)
{
QQmlContext* context = qmlEngine->rootContext();
GContext gContext;
gContext.plugin = this;
gContext.jsEngine = qmlEngine;
// setup objects to qml context
QObject* c(new GCore(gContext));
context->setContextProperty("core", c);
QObject* msm(new GMessageManager(gContext));
context->setContextProperty("messageManager", msm);
QObject* am(new GActionManager(gContext));
context->setContextProperty("actionManager", am);
QObject* mm(new GModeManager(gContext));
context->setContextProperty("modeManager", mm);
context->setContextProperty("jepAPI", static_cast<QObject*>(this));
}
void JsPlugin::changeDebugIndent(qint32 delta)
{
m_debugIndent += delta;
Q_ASSERT(m_debugIndent >= 0);
if (m_debugIndent < 0)
m_debugIndent = 0;
}
QPair<QWidget*, QQuickView*> JsPlugin::createQuickViewWidget(QString qmlUrl, QObject* parent)
{
QPair<QWidget*, QQuickView*> result(nullptr, nullptr);
QScopedPointer<QQmlEngine> qmlEngine(new QQmlEngine(this));
installQmlContext(qmlEngine.data());
QScopedPointer<QQuickView> view(new QQuickView(qmlEngine.data(), nullptr));
// make absolute file path related to plugin dir
QString url = normalizeFileName(qmlUrl);
QFileInfo fi(url);
if (fi.isFile())
{
view->setSource(QUrl::fromLocalFile(url));
}
else
{
view->setSource(QUrl(url));
}
if (view->status() == QQuickView::Error)
{
foreach (const QQmlError& error, view->errors())
{
debug(error.toString());
}
return result;
}
QScopedPointer<QWidget> container(QWidget::createWindowContainer(view.data(), qobject_cast<QWidget*>(parent)));
container->setFocusPolicy(Qt::TabFocus);
QSize s = view->initialSize();
container->setMinimumSize(s);
view->setResizeMode(QQuickView::SizeRootObjectToView);
qmlEngine.take();
result.first = container.take();
result.second = view.take();
return result;
}
QJSValue JsPlugin::createQuickView(QString qmlUrl, QObject* parent)
{
G_TRACE2(this);
QPair<QWidget*, QQuickView*> result = createQuickViewWidget(qmlUrl, parent);
QJSValue res = m_jsEngine->toScriptValue(static_cast<QObject*>(result.first));
res.setProperty("quickView", m_jsEngine->toScriptValue(static_cast<QObject*>(result.second)));
return res;
}
int JsPlugin::quickDialogExec(QString qmlUrl, QObject* parent)
{
G_TRACE2(this);
QDialog dlg(qobject_cast<QWidget*>(parent));
QPair<QWidget*, QQuickView*> result = createQuickViewWidget(qmlUrl, &dlg);
dlg.installEventFilter(new MyEventFilter(&dlg, result.first, result.second));
return dlg.exec();
}
QJSValue JsPlugin::createQObject(QString type, QObject* parent)
{
G_TRACE2(this);
auto it = m_factories.find(type.toLatin1());
if (it == m_factories.end())
return QJSValue();
QObject* object = it.value()(parent);
return m_jsEngine->toScriptValue(object);
}
GNavigationWidgetFactory::GNavigationWidgetFactory(JsPlugin* owner, QJSValue factory, QString displayName, int priority, QString id, QString activationSequence)
: m_owner(owner),
m_factory(factory),
m_displayName(displayName),
m_priority(priority),
m_id(id),
m_activationSequence(activationSequence)
{
Q_ASSERT(m_owner);
setObjectName(QString("JEP_NavigationWidgetFactory_%1").arg(m_displayName));
}
Core::NavigationView GNavigationWidgetFactory::createWidget()
{
G_TRACE2(m_owner);
Core::NavigationView nv;
nv.widget = nullptr;
if (m_factory.isString())
{
// try load QML view
QPair<QWidget*, QQuickView*> result = m_owner->createQuickViewWidget(m_factory.toString(), this);
nv.widget = result.first;
result.second->setResizeMode(QQuickView::SizeRootObjectToView);
}
else if (m_factory.isCallable())
{
// try call factory
QJSValue res = m_factory.call();
if (res.isQObject())
{
nv.widget = qobject_cast<QWidget*>(res.toQObject());
}
if (!nv.widget)
{
m_owner->debug("NavigationWidgetFactory: function doesn't return QWidget*.");
}
}
else
{
m_owner->debug("NavigationWidgetFactory: factory is not string or function.");
}
if (!nv.widget) {
nv.widget = new QLabel("<Cannot create widget>");
}
return nv;
}
bool JsPlugin::registerNavigationWidgetFactory(QJSValue factory, QString displayName, int priority, QString id, QString activationSequence)
{
ExtensionSystem::IPlugin* plugin = qobject_cast<ExtensionSystem::IPlugin*>(parent());
if (!plugin)
return false;
plugin->addAutoReleasedObject(new GNavigationWidgetFactory(this, factory, displayName, priority, id, activationSequence));
return true;
}
void JsPlugin::dumpPluginManagerObjects()
{
QList<QObject*> objects = ExtensionSystem::PluginManager::allObjects();
int i = 0;
foreach (QObject* obj, objects)
{
debug(QString("%1: %2 (%3)").arg(i++).arg(obj->objectName()).arg(obj->metaObject()->className()));
}
}
bool JsPlugin::loadLib(QString libFileName)
{
G_TRACE2(this);
QLibrary library(normalizeFileName(libFileName), this);
if (!library.load())
{
debug(tr("Cannot load '%1'.").arg(libFileName));
return false;
}
// library should export C function
// extern "C" MY_EXPORT bool loadLib(QJSEngine* jsEngine, QString* errors)
typedef bool (*LoadLibFunction)(QJSEngine*, QString*);
LoadLibFunction loadLibFunc = (LoadLibFunction)library.resolve("loadLib");
if (!loadLibFunc)
{
debug(tr("Cannot resolve 'loadLib' function."));
library.unload();
return false;
}
QString errors;
if (!loadLibFunc(m_jsEngine.data(), &errors))
{
debug(tr("'loadLib' function failed (%1).").arg(errors));
library.unload();
return false;
}
return true;
}
QString JsPlugin::normalizeFileName(QString fileName)
{
QFileInfo fi(QFileInfo(m_pluginPath).absolutePath(), fileName);
if (fi.isFile())
return fi.absoluteFilePath();
else
return fileName;
}
bool JsPlugin::enableDebug()
{
if (!m_debugStream.isNull())
return true;
if (m_jsEngine.isNull())
return false;
QFile* file(new QFile(this));
file->setFileName(m_pluginPath + tr(".log"));
if (!file->open(QIODevice::WriteOnly))
{
delete file;
return false;
}
m_debugStream.reset(new QTextStream(file));
return true;
}
void JsPlugin::debug(QString str)
{
qDebug() << QString("%1 : %2").arg(m_info.name, str);
enableDebug();
if (m_debugStream)
{
QString indent(m_debugIndent, QChar::Space);
*m_debugStream << indent << str << endl;
m_debugStream->flush();
}
}
bool JsPlugin::include(QString jsFileName)
{
QString content = loadFile(jsFileName);
if (content.isEmpty()) {
debug(tr("cannot include file: %1.").arg(jsFileName));
return false;
}
QJSValue result = m_jsEngine->evaluate(content, jsFileName);
// dump error
if (result.isError()) {
debug(tr("include failed: %1.").arg(result.toString()));
return false;
}
return true;
}
QString JsPlugin::loadFile(QString fileName)
{
QFileInfo fi(QFileInfo(m_pluginPath).absolutePath(), fileName);
QFile file(fi.absoluteFilePath());
if (file.open(QIODevice::ReadOnly))
{
QTextStream str(&file);
return str.readAll();
}
return QString();
}
bool JsPlugin::saveFile(QString fileName, QString content)
{
QFileInfo fi(QFileInfo(m_pluginPath).absolutePath(), fileName);
QFile file(fi.absoluteFilePath());
if (file.open(QIODevice::WriteOnly|QIODevice::Truncate))
{
QTextStream str(&file);
str << content;
str.flush();
return str.status() == QTextStream::Ok;
}
return false;
}
bool JsPlugin::execute(QString cmd)
{
return QProcess::startDetached(cmd);
}
QString JsPlugin::getClipboard()
{
QClipboard *clipboard = QApplication::clipboard();
return clipboard->text();
}
void JsPlugin::setClipboard(QString content)
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(content);
}
QVariantMap JsPlugin::QObject2JsObject(QObject* qObject)
{
QVariantMap map;
const QMetaObject* metaObject = qObject->metaObject();
for (int i = 0, n = metaObject->propertyCount(); i < n; ++i) {
map[metaObject->property(i).name()] = metaObject->property(i).read(qObject);
}
return map;
}
void JsPlugin::JsObject2QObject(QVariantMap object, QObject* qObject)
{
const QMetaObject* metaObject = qObject->metaObject();
foreach (QString key, object.keys()) {
int propertyIndex = metaObject->indexOfProperty(key.toLatin1().data());
if (propertyIndex != -1)
metaObject->property(propertyIndex).write(qObject, object[key]);
}
}