-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpluginmanager.cpp
1847 lines (1607 loc) · 61.3 KB
/
pluginmanager.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "pluginmanager.h"
#include "extensionsystemtr.h"
#include "iplugin.h"
#include "optionsparser.h"
#include "pluginmanager_p.h"
#include "pluginspec.h"
#include "pluginspec_p.h"
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QGuiApplication>
#include <QLibrary>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QMetaProperty>
#include <QPushButton>
#include <QSysInfo>
#include <QTextStream>
#include <QTimer>
#include <QWriteLocker>
#include <utils/algorithm.h>
#include <utils/benchmarker.h>
#include <utils/executeondestruction.h>
//#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/mimeutils.h>
#include <utils/qtcassert.h>
//#include <utils/qtcprocess.h>
#include <utils/qtcsettings.h>
//#include <utils/threadutils.h>
#ifdef WITH_TESTS
#include <utils/hostosinfo.h>
#include <QTest>
#include <QThread>
#endif
#include <functional>
#include <memory>
Q_LOGGING_CATEGORY(pluginLog, "qtc.extensionsystem", QtWarningMsg)
const char C_IGNORED_PLUGINS[] = "Plugins/Ignored";
const char C_FORCEENABLED_PLUGINS[] = "Plugins/ForceEnabled";
const int DELAYED_INITIALIZE_INTERVAL = 20; // ms
enum { debugLeaks = 0 };
/*!
\namespace ExtensionSystem
\inmodule QtCreator
\brief The ExtensionSystem namespace provides classes that belong to the
core plugin system.
The basic extension system contains the plugin manager and its supporting classes,
and the IPlugin interface that must be implemented by plugin providers.
*/
/*!
\namespace ExtensionSystem::Internal
\internal
*/
/*!
\class ExtensionSystem::PluginManager
\inheaderfile extensionsystem/pluginmanager.h
\inmodule QtCreator
\ingroup mainclasses
\brief The PluginManager class implements the core plugin system that
manages the plugins, their life cycle, and their registered objects.
The plugin manager is used for the following tasks:
\list
\li Manage plugins and their state
\li Manipulate a \e {common object pool}
\endlist
\section1 Plugins
Plugins must derive from the IPlugin class and have the IID
\c "org.qt-project.Qt.QtCreatorPlugin".
The plugin manager is used to set a list of file system directories to search for
plugins, retrieve information about the state of these plugins, and to load them.
Usually, the application creates a PluginManager instance and initiates the
loading.
\code
// 'plugins' and subdirs will be searched for plugins
PluginManager::setPluginPaths(QStringList("plugins"));
PluginManager::loadPlugins(); // try to load all the plugins
\endcode
Additionally, it is possible to directly access plugin meta data, instances,
and state.
\section1 Object Pool
Plugins (and everybody else) can add objects to a common \e pool that is located in
the plugin manager. Objects in the pool must derive from QObject, there are no other
prerequisites. Objects can be retrieved from the object pool via the getObject()
and getObjectByName() functions.
Whenever the state of the object pool changes, a corresponding signal is
emitted by the plugin manager.
A common usecase for the object pool is that a plugin (or the application) provides
an \e {extension point} for other plugins, which is a class or interface that can
be implemented and added to the object pool. The plugin that provides the
extension point looks for implementations of the class or interface in the object pool.
\code
// Plugin A provides a "MimeTypeHandler" extension point
// in plugin B:
MyMimeTypeHandler *handler = new MyMimeTypeHandler();
PluginManager::instance()->addObject(handler);
// In plugin A:
MimeTypeHandler *mimeHandler =
PluginManager::getObject<MimeTypeHandler>();
\endcode
The ExtensionSystem::Invoker class template provides \e {syntactic sugar}
for using \e soft extension points that may or may not be provided by an
object in the pool. This approach neither requires the \e user plugin being
linked against the \e provider plugin nor a common shared
header file. The exposed interface is implicitly given by the
invokable functions of the provider object in the object pool.
The ExtensionSystem::invoke() function template encapsulates
ExtensionSystem::Invoker construction for the common case where
the success of the call is not checked.
\code
// In the "provide" plugin A:
namespace PluginA {
class SomeProvider : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE QString doit(const QString &msg, int n) {
{
qDebug() << "I AM DOING IT " << msg;
return QString::number(n);
}
};
} // namespace PluginA
// In the "user" plugin B:
int someFuntionUsingPluginA()
{
using namespace ExtensionSystem;
QObject *target = PluginManager::getObjectByClassName("PluginA::SomeProvider");
if (target) {
// Some random argument.
QString msg = "REALLY.";
// Plain function call, no return value.
invoke<void>(target, "doit", msg, 2);
// Plain function with no return value.
qDebug() << "Result: " << invoke<QString>(target, "doit", msg, 21);
// Record success of function call with return value.
Invoker<QString> in1(target, "doit", msg, 21);
qDebug() << "Success: (expected)" << in1.wasSuccessful();
// Try to invoke a non-existing function.
Invoker<QString> in2(target, "doitWrong", msg, 22);
qDebug() << "Success (not expected):" << in2.wasSuccessful();
} else {
// We have to cope with plugin A's absence.
}
};
\endcode
\note The type of the parameters passed to the \c{invoke()} calls
is deduced from the parameters themselves and must match the type of
the arguments of the called functions \e{exactly}. No conversion or even
integer promotions are applicable, so to invoke a function with a \c{long}
parameter explicitly, use \c{long(43)} or such.
\note The object pool manipulating functions are thread-safe.
*/
/*!
\fn template <typename T> *ExtensionSystem::PluginManager::getObject()
Retrieves the object of a given type from the object pool.
This function uses \c qobject_cast to determine the type of an object.
If there are more than one objects of the given type in
the object pool, this function will arbitrarily choose one of them.
\sa addObject()
*/
/*!
\fn template <typename T, typename Predicate> *ExtensionSystem::PluginManager::getObject(Predicate predicate)
Retrieves the object of a given type from the object pool that matches
the \a predicate.
This function uses \c qobject_cast to determine the type of an object.
The predicate must be a function taking T * and returning a bool.
If there is more than one object matching the type and predicate,
this function will arbitrarily choose one of them.
\sa addObject()
*/
using namespace Utils;
namespace ExtensionSystem {
using namespace Internal;
static Internal::PluginManagerPrivate *d = nullptr;
static PluginManager *m_instance = nullptr;
/*!
Gets the unique plugin manager instance.
*/
PluginManager *PluginManager::instance()
{
return m_instance;
}
/*!
Creates a plugin manager. Should be done only once per application.
*/
PluginManager::PluginManager()
{
m_instance = this;
d = new PluginManagerPrivate(this);
}
/*!
\internal
*/
PluginManager::~PluginManager()
{
delete d;
d = nullptr;
}
/*!
Adds the object \a obj to the object pool, so it can be retrieved
again from the pool by type.
The plugin manager does not do any memory management. Added objects
must be removed from the pool and deleted manually by whoever is responsible for the object.
Emits the \c objectAdded() signal.
\sa PluginManager::removeObject()
\sa PluginManager::getObject()
\sa PluginManager::getObjectByName()
*/
void PluginManager::addObject(QObject *obj)
{
d->addObject(obj);
}
/*!
Emits the \c aboutToRemoveObject() signal and removes the object \a obj
from the object pool.
\sa PluginManager::addObject()
*/
void PluginManager::removeObject(QObject *obj)
{
d->removeObject(obj);
}
/*!
Retrieves the list of all objects in the pool, unfiltered.
Usually, clients do not need to call this function.
\sa PluginManager::getObject()
*/
QVector<QObject *> PluginManager::allObjects()
{
return d->allObjects;
}
/*!
\internal
*/
QReadWriteLock *PluginManager::listLock()
{
return &d->m_lock;
}
/*!
Tries to load all the plugins that were previously found when
setting the plugin search paths. The plugin specs of the plugins
can be used to retrieve error and state information about individual plugins.
\sa setPluginPaths()
\sa plugins()
*/
void PluginManager::loadPlugins()
{
d->loadPlugins();
}
/*!
Returns \c true if any plugin has errors even though it is enabled.
Most useful to call after loadPlugins().
*/
bool PluginManager::hasError()
{
return Utils::anyOf(plugins(), [](PluginSpec *spec) {
// only show errors on startup if plugin is enabled.
return spec->hasError() && spec->isEffectivelyEnabled();
});
}
const QStringList PluginManager::allErrors()
{
return Utils::transform<QStringList>(Utils::filtered(plugins(), [](const PluginSpec *spec) {
return spec->hasError() && spec->isEffectivelyEnabled();
}), [](const PluginSpec *spec) {
return spec->name().append(": ").append(spec->errorString());
});
}
/*!
Returns all plugins that require \a spec to be loaded. Recurses into dependencies.
*/
const QSet<PluginSpec *> PluginManager::pluginsRequiringPlugin(PluginSpec *spec)
{
QSet<PluginSpec *> dependingPlugins({spec});
// recursively add plugins that depend on plugins that.... that depend on spec
for (PluginSpec *spec : d->loadQueue()) {
if (spec->requiresAny(dependingPlugins))
dependingPlugins.insert(spec);
}
dependingPlugins.remove(spec);
return dependingPlugins;
}
/*!
Returns all plugins that \a spec requires to be loaded. Recurses into dependencies.
*/
const QSet<PluginSpec *> PluginManager::pluginsRequiredByPlugin(PluginSpec *spec)
{
QSet<PluginSpec *> recursiveDependencies;
recursiveDependencies.insert(spec);
std::queue<PluginSpec *> queue;
queue.push(spec);
while (!queue.empty()) {
PluginSpec *checkSpec = queue.front();
queue.pop();
const QHash<PluginDependency, PluginSpec *> deps = checkSpec->dependencySpecs();
for (auto depIt = deps.cbegin(), end = deps.cend(); depIt != end; ++depIt) {
if (depIt.key().type != PluginDependency::Required)
continue;
PluginSpec *depSpec = depIt.value();
if (!recursiveDependencies.contains(depSpec)) {
recursiveDependencies.insert(depSpec);
queue.push(depSpec);
}
}
}
recursiveDependencies.remove(spec);
return recursiveDependencies;
}
/*!
Shuts down and deletes all plugins.
*/
void PluginManager::shutdown()
{
d->shutdown();
}
static auto filled(const QString &s, int min) -> QString
{
return s + QString(qMax(0, min - s.size()), ' ');
}
//QString PluginManager::systemInformation()
//{
// QString result;
// CommandLine qtDiag(FilePath::fromString(QLibraryInfo::location(QLibraryInfo::BinariesPath))
// .pathAppended("qtdiag").withExecutableSuffix());
// QtcProcess qtDiagProc;
// qtDiagProc.setCommand(qtDiag);
// qtDiagProc.runBlocking();
// if (qtDiagProc.result() == ProcessResult::FinishedWithSuccess)
// result += qtDiagProc.allOutput() + "\n";
// result += "Plugin information:\n\n";
// auto longestSpec = std::max_element(d->pluginSpecs.cbegin(), d->pluginSpecs.cend(),
// [](const PluginSpec *left, const PluginSpec *right) {
// return left->name().size() < right->name().size();
// });
// int size = (*longestSpec)->name().size();
// for (const PluginSpec *spec : plugins()) {
// result += QLatin1String(spec->isEffectivelyEnabled() ? "+ " : " ") + filled(spec->name(), size) +
// " " + spec->version() + "\n";
// }
// QString settingspath = QFileInfo(settings()->fileName()).path();
// if (settingspath.startsWith(QDir::homePath()))
// settingspath.replace(QDir::homePath(), "~");
// result += "\nUsed settingspath: " + settingspath + "\n";
// return result;
//}
/*!
The list of paths were the plugin manager searches for plugins.
\sa setPluginPaths()
*/
QStringList PluginManager::pluginPaths()
{
return d->pluginPaths;
}
/*!
Sets the plugin paths. All the specified \a paths and their subdirectory
trees are searched for plugins.
\sa pluginPaths()
\sa loadPlugins()
*/
void PluginManager::setPluginPaths(const QStringList &paths)
{
d->setPluginPaths(paths);
}
/*!
The IID that valid plugins must have.
\sa setPluginIID()
*/
QString PluginManager::pluginIID()
{
return d->pluginIID;
}
/*!
Sets the IID that valid plugins must have to \a iid. Only plugins with this
IID are loaded, others are silently ignored.
At the moment this must be called before setPluginPaths() is called.
\omit
// ### TODO let this + setPluginPaths read the plugin meta data lazyly whenever loadPlugins() or plugins() is called.
\endomit
*/
void PluginManager::setPluginIID(const QString &iid)
{
d->pluginIID = iid;
}
/*!
Defines the user specific \a settings to use for information about enabled and
disabled plugins.
Needs to be set before the plugin search path is set with setPluginPaths().
*/
void PluginManager::setSettings(QtcSettings *settings)
{
d->setSettings(settings);
}
/*!
Defines the global (user-independent) \a settings to use for information about
default disabled plugins.
Needs to be set before the plugin search path is set with setPluginPaths().
*/
void PluginManager::setGlobalSettings(QtcSettings *settings)
{
d->setGlobalSettings(settings);
}
/*!
Returns the user specific settings used for information about enabled and
disabled plugins.
*/
QtcSettings *PluginManager::settings()
{
return d->settings;
}
/*!
Returns the global (user-independent) settings used for information about default disabled plugins.
*/
QtcSettings *PluginManager::globalSettings()
{
return d->globalSettings;
}
void PluginManager::writeSettings()
{
d->writeSettings();
}
/*!
The arguments left over after parsing (that were neither startup nor plugin
arguments). Typically, this will be the list of files to open.
*/
QStringList PluginManager::arguments()
{
return d->arguments;
}
/*!
The arguments that should be used when automatically restarting the application.
This includes plugin manager related options for enabling or disabling plugins,
but excludes others, like the arguments returned by arguments() and the appOptions
passed to the parseOptions() method.
*/
QStringList PluginManager::argumentsForRestart()
{
return d->argumentsForRestart;
}
/*!
List of all plugins that have been found in the plugin search paths.
This list is valid directly after the setPluginPaths() call.
The plugin specifications contain plugin metadata and the current state
of the plugins. If a plugin's library has been already successfully loaded,
the plugin specification has a reference to the created plugin instance as well.
\sa setPluginPaths()
*/
const QVector<PluginSpec *> PluginManager::plugins()
{
return d->pluginSpecs;
}
QHash<QString, QVector<PluginSpec *>> PluginManager::pluginCollections()
{
return d->pluginCategories;
}
static const char argumentKeywordC[] = ":arguments";
static const char pwdKeywordC[] = ":pwd";
/*!
Serializes plugin options and arguments for sending in a single string
via QtSingleApplication:
":myplugin|-option1|-option2|:arguments|argument1|argument2",
as a list of lists started by a keyword with a colon. Arguments are last.
\sa setPluginPaths()
*/
QString PluginManager::serializedArguments()
{
const QChar separator = QLatin1Char('|');
QString rc;
for (const PluginSpec *ps : plugins()) {
if (!ps->arguments().isEmpty()) {
if (!rc.isEmpty())
rc += separator;
rc += QLatin1Char(':');
rc += ps->name();
rc += separator;
rc += ps->arguments().join(separator);
}
}
if (!rc.isEmpty())
rc += separator;
rc += QLatin1String(pwdKeywordC) + separator + QDir::currentPath();
if (!d->arguments.isEmpty()) {
if (!rc.isEmpty())
rc += separator;
rc += QLatin1String(argumentKeywordC);
for (const QString &argument : std::as_const(d->arguments))
rc += separator + argument;
}
return rc;
}
/* Extract a sublist from the serialized arguments
* indicated by a keyword starting with a colon indicator:
* ":a,i1,i2,:b:i3,i4" with ":a" -> "i1,i2"
*/
static auto subList(const QStringList &in, const QString &key) -> QStringList
{
QStringList rc;
// Find keyword and copy arguments until end or next keyword
const QStringList::const_iterator inEnd = in.constEnd();
QStringList::const_iterator it = std::find(in.constBegin(), inEnd, key);
if (it != inEnd) {
const QChar nextIndicator = QLatin1Char(':');
for (++it; it != inEnd && !it->startsWith(nextIndicator); ++it)
rc.append(*it);
}
return rc;
}
/*!
Parses the options encoded in \a serializedArgument
and passes them on to the respective plugins along with the arguments.
\a socket is passed for disconnecting the peer when the operation is done (for example,
document is closed) for supporting the \c -block flag.
*/
void PluginManager::remoteArguments(const QString &serializedArgument, QObject *socket)
{
if (serializedArgument.isEmpty())
return;
QStringList serializedArguments = serializedArgument.split(QLatin1Char('|'));
const QStringList pwdValue = subList(serializedArguments, QLatin1String(pwdKeywordC));
const QString workingDirectory = pwdValue.isEmpty() ? QString() : pwdValue.first();
const QStringList arguments = subList(serializedArguments, QLatin1String(argumentKeywordC));
for (const PluginSpec *ps : plugins()) {
if (ps->state() == PluginSpec::Running) {
const QStringList pluginOptions = subList(serializedArguments, QLatin1Char(':') + ps->name());
QObject *socketParent = ps->plugin()->remoteCommand(pluginOptions, workingDirectory,
arguments);
if (socketParent && socket) {
socket->setParent(socketParent);
socket = nullptr;
}
}
}
if (socket)
delete socket;
}
/*!
Takes the list of command line options in \a args and parses them.
The plugin manager itself might process some options itself directly
(\c {-noload <plugin>}), and adds options that are registered by
plugins to their plugin specs.
The caller (the application) may register itself for options via the
\a appOptions list, containing pairs of \e {option string} and a bool
that indicates whether the option requires an argument.
Application options always override any plugin's options.
\a foundAppOptions is set to pairs of (\e {option string}, \e argument)
for any application options that were found.
The command line options that were not processed can be retrieved via the arguments() function.
If an error occurred (like missing argument for an option that requires one), \a errorString contains
a descriptive message of the error.
Returns if there was an error.
*/
bool PluginManager::parseOptions(const QStringList &args,
const QMap<QString, bool> &appOptions,
QMap<QString, QString> *foundAppOptions,
QString *errorString)
{
OptionsParser options(args, appOptions, foundAppOptions, errorString, d);
return options.parse();
}
static inline void indent(QTextStream &str, int indent)
{
str << QString(indent, ' ');
}
static inline void formatOption(QTextStream &str,
const QString &opt, const QString &parm, const QString &description,
int optionIndentation, int descriptionIndentation)
{
int remainingIndent = descriptionIndentation - optionIndentation - opt.size();
indent(str, optionIndentation);
str << opt;
if (!parm.isEmpty()) {
str << " <" << parm << '>';
remainingIndent -= 3 + parm.size();
}
if (remainingIndent >= 1) {
indent(str, remainingIndent);
} else {
str << '\n';
indent(str, descriptionIndentation);
}
str << description << '\n';
}
/*!
Formats the startup options of the plugin manager for command line help with the specified
\a optionIndentation and \a descriptionIndentation.
Adds the result to \a str.
*/
void PluginManager::formatOptions(QTextStream &str, int optionIndentation, int descriptionIndentation)
{
formatOption(str, QLatin1String(OptionsParser::LOAD_OPTION),
QLatin1String("plugin"), QLatin1String("Load <plugin> and all plugins that it requires"),
optionIndentation, descriptionIndentation);
formatOption(str, QLatin1String(OptionsParser::LOAD_OPTION) + QLatin1String(" all"),
QString(), QLatin1String("Load all available plugins"),
optionIndentation, descriptionIndentation);
formatOption(str, QLatin1String(OptionsParser::NO_LOAD_OPTION),
QLatin1String("plugin"), QLatin1String("Do not load <plugin> and all plugins that require it"),
optionIndentation, descriptionIndentation);
formatOption(str, QLatin1String(OptionsParser::NO_LOAD_OPTION) + QLatin1String(" all"),
QString(), QString::fromLatin1("Do not load any plugin (useful when "
"followed by one or more \"%1\" arguments)")
.arg(QLatin1String(OptionsParser::LOAD_OPTION)),
optionIndentation, descriptionIndentation);
formatOption(str, QLatin1String(OptionsParser::PROFILE_OPTION),
QString(), QLatin1String("Profile plugin loading"),
optionIndentation, descriptionIndentation);
formatOption(str,
QLatin1String(OptionsParser::NO_CRASHCHECK_OPTION),
QString(),
QLatin1String("Disable startup check for previously crashed instance"),
optionIndentation,
descriptionIndentation);
#ifdef WITH_TESTS
formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION)
+ QLatin1String(" <plugin>[,testfunction[:testdata]]..."), QString(),
QLatin1String("Run plugin's tests (by default a separate settings path is used)"),
optionIndentation, descriptionIndentation);
formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION) + QLatin1String(" all"),
QString(), QLatin1String("Run tests from all plugins"),
optionIndentation, descriptionIndentation);
formatOption(str, QString::fromLatin1(OptionsParser::NOTEST_OPTION),
QLatin1String("plugin"), QLatin1String("Exclude all of the plugin's tests from the test run"),
optionIndentation, descriptionIndentation);
formatOption(str, QString::fromLatin1(OptionsParser::SCENARIO_OPTION),
QString("scenarioname"), QLatin1String("Run given scenario"),
optionIndentation, descriptionIndentation);
#endif
}
/*!
Formats the plugin options of the plugin specs for command line help with the specified
\a optionIndentation and \a descriptionIndentation.
Adds the result to \a str.
*/
void PluginManager::formatPluginOptions(QTextStream &str, int optionIndentation, int descriptionIndentation)
{
// Check plugins for options
for (PluginSpec *ps : std::as_const(d->pluginSpecs)) {
const PluginSpec::PluginArgumentDescriptions pargs = ps->argumentDescriptions();
if (!pargs.empty()) {
str << "\nPlugin: " << ps->name() << '\n';
for (const PluginArgumentDescription &pad : pargs)
formatOption(str, pad.name, pad.parameter, pad.description, optionIndentation, descriptionIndentation);
}
}
}
/*!
Formats the version of the plugin specs for command line help and adds it to \a str.
*/
void PluginManager::formatPluginVersions(QTextStream &str)
{
for (PluginSpec *ps : std::as_const(d->pluginSpecs))
str << " " << ps->name() << ' ' << ps->version() << ' ' << ps->description() << '\n';
}
/*!
\internal
*/
bool PluginManager::testRunRequested()
{
return !d->testSpecs.empty();
}
#ifdef WITH_TESTS
// Called in plugin initialization, the scenario function will be called later, from main
bool PluginManager::registerScenario(const QString &scenarioId, std::function<bool()> scenarioStarter)
{
if (d->m_scenarios.contains(scenarioId)) {
const QString warning = QString("Can't register scenario \"%1\" as the other scenario was "
"already registered with this name.").arg(scenarioId);
qWarning("%s", qPrintable(warning));
return false;
}
d->m_scenarios.insert(scenarioId, scenarioStarter);
return true;
}
// Called from main
bool PluginManager::isScenarioRequested()
{
return !d->m_requestedScenario.isEmpty();
}
// Called from main (may be squashed with the isScenarioRequested: runScenarioIfRequested).
// Returns false if scenario couldn't run (e.g. no Qt version set)
bool PluginManager::runScenario()
{
if (d->m_isScenarioRunning) {
qWarning("Scenario is already running. Can't run scenario recursively.");
return false;
}
if (d->m_requestedScenario.isEmpty()) {
qWarning("Can't run any scenario since no scenario was requested.");
return false;
}
if (!d->m_scenarios.contains(d->m_requestedScenario)) {
const QString warning = QString("Requested scenario \"%1\" was not registered.").arg(d->m_requestedScenario);
qWarning("%s", qPrintable(warning));
return false;
}
d->m_isScenarioRunning = true;
// The return value comes now from scenarioStarted() function. It may fail e.g. when
// no Qt version is set. Initializing the scenario may take some time, that's why
// waitForScenarioFullyInitialized() was added.
bool ret = d->m_scenarios[d->m_requestedScenario]();
QMutexLocker locker(&d->m_scenarioMutex);
d->m_scenarioFullyInitialized = true;
d->m_scenarioWaitCondition.wakeAll();
return ret;
}
// Called from scenario point (and also from runScenario - don't run scenarios recursively).
// This may be called from non-main thread. We assume that m_requestedScenario
// may only be changed from the main thread.
bool PluginManager::isScenarioRunning(const QString &scenarioId)
{
return d->m_isScenarioRunning && d->m_requestedScenario == scenarioId;
}
// This may be called from non-main thread.
bool PluginManager::finishScenario()
{
if (!d->m_isScenarioRunning)
return false; // Can't finish not running scenario
if (d->m_isScenarioFinished.exchange(true))
return false; // Finish was already called before. We return false, as we didn't finish it right now.
QMetaObject::invokeMethod(d, []() { emit m_instance->scenarioFinished(0); });
return true; // Finished successfully.
}
// Waits until the running scenario is fully initialized
void PluginManager::waitForScenarioFullyInitialized()
{
if (isMainThread()) {
qWarning("The waitForScenarioFullyInitialized() function can't be called from main thread.");
return;
}
QMutexLocker locker(&d->m_scenarioMutex);
if (d->m_scenarioFullyInitialized)
return;
d->m_scenarioWaitCondition.wait(&d->m_scenarioMutex);
}
#endif
void PluginManager::setCreatorProcessData(const PluginManager::ProcessData &data)
{
d->m_creatorProcessData = data;
}
PluginManager::ProcessData PluginManager::creatorProcessData()
{
return d->m_creatorProcessData;
}
/*!
\internal
*/
void PluginManager::profilingReport(const char *what, const PluginSpec *spec)
{
d->profilingReport(what, spec);
}
/*!
Returns a list of plugins in load order.
*/
QVector<PluginSpec *> PluginManager::loadQueue()
{
return d->loadQueue();
}
//============PluginManagerPrivate===========
/*!
\internal
*/
PluginSpec *PluginManagerPrivate::createSpec()
{
return new PluginSpec();
}
/*!
\internal
*/
void PluginManagerPrivate::setSettings(QtcSettings *s)
{
if (settings)
delete settings;
settings = s;
if (settings != nullptr)
settings->setParent(this);
}
/*!
\internal
*/
void PluginManagerPrivate::setGlobalSettings(QtcSettings *s)
{
if (globalSettings)
delete globalSettings;
globalSettings = s;
if (globalSettings != nullptr)
globalSettings->setParent(this);
}
/*!
\internal
*/
auto PluginManagerPrivate::privateSpec(PluginSpec *spec) -> PluginSpecPrivate *
{
return spec->d;
}
void PluginManagerPrivate::nextDelayedInitialize()
{
while (!delayedInitializeQueue.empty()) {
PluginSpec *spec = delayedInitializeQueue.front();
delayedInitializeQueue.pop();
profilingReport(">delayedInitialize", spec);
bool delay = spec->d->delayedInitialize();
profilingReport("<delayedInitialize", spec);
if (delay)
break; // do next delayedInitialize after a delay
}
if (delayedInitializeQueue.empty()) {
m_isInitializationDone = true;
delete delayedInitializeTimer;
delayedInitializeTimer = nullptr;
profilingSummary();
emit q->initializationDone();
#ifdef WITH_TESTS
if (PluginManager::testRunRequested())
startTests();
else if (PluginManager::isScenarioRequested()) {
if (PluginManager::runScenario()) {
const QString info = QString("Successfully started scenario \"%1\"...").arg(d->m_requestedScenario);
qInfo("%s", qPrintable(info));
} else {
QMetaObject::invokeMethod(this, []() { emit m_instance->scenarioFinished(1); });
}
}
#endif
} else {
delayedInitializeTimer->start();
}
}
/*!
\internal
*/
PluginManagerPrivate::PluginManagerPrivate(PluginManager *pluginManager) :
q(pluginManager)
{
}
/*!
\internal
*/
PluginManagerPrivate::~PluginManagerPrivate()
{
qDeleteAll(pluginSpecs);
}
/*!
\internal
*/
void PluginManagerPrivate::writeSettings()
{
if (settings == nullptr)
return;
QStringList tempDisabledPlugins;
QStringList tempForceEnabledPlugins;
for (PluginSpec *spec : std::as_const(pluginSpecs)) {
if (spec->isEnabledByDefault() && !spec->isEnabledBySettings())