ctkPlugin_p.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkPlugin_p.h"
  16. #include "ctkPluginConstants.h"
  17. #include "ctkPluginDatabaseException.h"
  18. #include "ctkPluginArchive_p.h"
  19. #include "ctkPluginFrameworkContext_p.h"
  20. #include "ctkPluginFrameworkUtil_p.h"
  21. #include "ctkPluginActivator.h"
  22. #include "ctkPluginContext_p.h"
  23. #include "ctkServiceReference_p.h"
  24. #include "ctkServiceRegistration.h"
  25. #include "ctkServices_p.h"
  26. // for ctk::msecsTo() - remove after switching to Qt 4.7
  27. #include <ctkUtils.h>
  28. #include <typeinfo>
  29. const ctkPlugin::States ctkPluginPrivate::RESOLVED_FLAGS = ctkPlugin::RESOLVED | ctkPlugin::STARTING | ctkPlugin::ACTIVE | ctkPlugin::STOPPING;
  30. //----------------------------------------------------------------------------
  31. void ctkPluginPrivate::LockObject::lock()
  32. {
  33. m_Lock.lock();
  34. }
  35. //----------------------------------------------------------------------------
  36. bool ctkPluginPrivate::LockObject::tryLock()
  37. {
  38. return m_Lock.tryLock();
  39. }
  40. //----------------------------------------------------------------------------
  41. bool ctkPluginPrivate::LockObject::tryLock(int timeout)
  42. {
  43. return m_Lock.tryLock(timeout);
  44. }
  45. //----------------------------------------------------------------------------
  46. void ctkPluginPrivate::LockObject::unlock()
  47. {
  48. m_Lock.unlock();
  49. }
  50. //----------------------------------------------------------------------------
  51. bool ctkPluginPrivate::LockObject::wait(unsigned long time)
  52. {
  53. return m_Condition.wait(&m_Lock, time);
  54. }
  55. //----------------------------------------------------------------------------
  56. void ctkPluginPrivate::LockObject::wakeAll()
  57. {
  58. m_Condition.wakeAll();
  59. }
  60. //----------------------------------------------------------------------------
  61. void ctkPluginPrivate::LockObject::wakeOne()
  62. {
  63. m_Condition.wakeOne();
  64. }
  65. //----------------------------------------------------------------------------
  66. ctkPluginPrivate::ctkPluginPrivate(
  67. QWeakPointer<ctkPlugin> qq,
  68. ctkPluginFrameworkContext* fw,
  69. QSharedPointer<ctkPluginArchive> pa)
  70. : q_ptr(qq), fwCtx(fw), id(pa->getPluginId()),
  71. location(pa->getPluginLocation().toString()), state(ctkPlugin::INSTALLED),
  72. archive(pa), pluginContext(0), pluginActivator(0), pluginLoader(pa->getLibLocation()),
  73. resolveFailException(0), eagerActivation(false), wasStarted(false)
  74. {
  75. //TODO
  76. //checkCertificates(pa);
  77. // Get library load hints
  78. if (fw->props.contains(ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS))
  79. {
  80. QVariant loadHintsVariant = fw->props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
  81. if (loadHintsVariant.isValid())
  82. {
  83. QLibrary::LoadHints loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
  84. pluginLoader.setLoadHints(loadHints);
  85. }
  86. }
  87. checkManifestHeaders();
  88. pluginDir = fwCtx->getDataStorage(id);
  89. // int oldStartLevel = archive->getStartLevel();
  90. try
  91. {
  92. //TODO: StartLevel Service
  93. //if (fwCtx->startLevelController == 0)
  94. //{
  95. archive->setStartLevel(0);
  96. //}
  97. // else
  98. // {
  99. // if (oldStartLevel == -1)
  100. // {
  101. // archive->setStartLevel(fwCtx->startLevelController->getInitialPluginStartLevel());
  102. // }
  103. // }
  104. }
  105. catch (const std::exception& e)
  106. {
  107. qDebug() << "Failed to set start level on #" << id << ":" << e.what();
  108. }
  109. lastModified = archive->getLastModified();
  110. if (lastModified.isNull())
  111. {
  112. modified();
  113. }
  114. // fill require list
  115. QString requireString = archive->getAttribute(ctkPluginConstants::REQUIRE_PLUGIN);
  116. QList<QMap<QString, QStringList> > requireList = ctkPluginFrameworkUtil::parseEntries(ctkPluginConstants::REQUIRE_PLUGIN,
  117. requireString, true, true, false);
  118. QListIterator<QMap<QString, QStringList> > i(requireList);
  119. while (i.hasNext())
  120. {
  121. const QMap<QString, QStringList>& e = i.next();
  122. const QStringList& res = e.value(ctkPluginConstants::RESOLUTION_DIRECTIVE);
  123. const QStringList& version = e.value(ctkPluginConstants::PLUGIN_VERSION_ATTRIBUTE);
  124. ctkRequirePlugin* rp = new ctkRequirePlugin(this, e.value("$key").front(),
  125. res.empty() ? QString() : res.front(),
  126. version.empty() ? QString() : version.front());
  127. require.push_back(rp);
  128. }
  129. }
  130. //----------------------------------------------------------------------------
  131. ctkPluginPrivate::ctkPluginPrivate(QWeakPointer<ctkPlugin> qq,
  132. ctkPluginFrameworkContext* fw,
  133. long id, const QString& loc, const QString& sym, const ctkVersion& ver)
  134. : q_ptr(qq), fwCtx(fw), id(id), location(loc), symbolicName(sym), version(ver),
  135. state(ctkPlugin::INSTALLED), archive(0), pluginContext(0),
  136. pluginActivator(0), resolveFailException(0),
  137. eagerActivation(false), wasStarted(false)
  138. {
  139. modified();
  140. }
  141. //----------------------------------------------------------------------------
  142. ctkPluginPrivate::~ctkPluginPrivate()
  143. {
  144. qDeleteAll(require);
  145. }
  146. //----------------------------------------------------------------------------
  147. ctkPlugin::State ctkPluginPrivate::getUpdatedState()
  148. {
  149. if (state & ctkPlugin::INSTALLED)
  150. {
  151. Locker sync(&operationLock);
  152. getUpdatedState_unlocked();
  153. }
  154. return state;
  155. }
  156. //----------------------------------------------------------------------------
  157. ctkPlugin::State ctkPluginPrivate::getUpdatedState_unlocked()
  158. {
  159. if (state & ctkPlugin::INSTALLED)
  160. {
  161. try
  162. {
  163. if (state == ctkPlugin::INSTALLED)
  164. {
  165. operation.fetchAndStoreOrdered(RESOLVING);
  166. fwCtx->resolvePlugin(this);
  167. state = ctkPlugin::RESOLVED;
  168. // TODO plugin threading
  169. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.RESOLVED, this));
  170. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, this->q_func()));
  171. operation.fetchAndStoreOrdered(IDLE);
  172. }
  173. }
  174. catch (const ctkPluginException& pe)
  175. {
  176. if (resolveFailException) delete resolveFailException;
  177. resolveFailException = new ctkPluginException(pe);
  178. this->fwCtx->listeners.frameworkError(this->q_func(), pe);
  179. }
  180. }
  181. return state;
  182. }
  183. //----------------------------------------------------------------------------
  184. QFileInfo ctkPluginPrivate::getDataRoot()
  185. {
  186. return pluginDir;
  187. }
  188. //----------------------------------------------------------------------------
  189. void ctkPluginPrivate::setStateInstalled(bool sendEvent)
  190. {
  191. Locker sync(&operationLock);
  192. // Make sure that the context is invalid
  193. if (pluginContext != 0)
  194. {
  195. pluginContext->d_func()->invalidate();
  196. pluginContext.reset();
  197. }
  198. state = ctkPlugin::INSTALLED;
  199. if (sendEvent)
  200. {
  201. operation.fetchAndStoreOrdered(UNRESOLVING);
  202. // TODO: plugin thread
  203. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  204. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  205. }
  206. operation.fetchAndStoreOrdered(IDLE);
  207. }
  208. //----------------------------------------------------------------------------
  209. void ctkPluginPrivate::purge()
  210. {
  211. if (state == ctkPlugin::UNINSTALLED)
  212. {
  213. fwCtx->plugins->remove(location);
  214. }
  215. // Vector fix = oldGenerations;
  216. // if (fix != null) {
  217. // oldGenerations = null;
  218. // for (Iterator i = fix.iterator(); i.hasNext();) {
  219. // ((BundleGeneration)i.next()).purge(true);
  220. // }
  221. // }
  222. }
  223. //----------------------------------------------------------------------------
  224. void ctkPluginPrivate::setAutostartSetting(const ctkPlugin::StartOptions& setting) {
  225. try
  226. {
  227. if (archive)
  228. {
  229. archive->setAutostartSetting(setting);
  230. }
  231. }
  232. catch (const ctkPluginDatabaseException& e)
  233. {
  234. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  235. }
  236. }
  237. //----------------------------------------------------------------------------
  238. void ctkPluginPrivate::ignoreAutostartSetting()
  239. {
  240. try
  241. {
  242. if (archive)
  243. {
  244. archive->setAutostartSetting(-1);
  245. }
  246. }
  247. catch (const ctkPluginDatabaseException& e)
  248. {
  249. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  250. }
  251. }
  252. //----------------------------------------------------------------------------
  253. void ctkPluginPrivate::modified()
  254. {
  255. lastModified = QDateTime::currentDateTime();
  256. if (archive)
  257. {
  258. archive->setLastModified(lastModified);
  259. }
  260. }
  261. //----------------------------------------------------------------------------
  262. void ctkPluginPrivate::checkManifestHeaders()
  263. {
  264. symbolicName = archive->getAttribute(ctkPluginConstants::PLUGIN_SYMBOLICNAME);
  265. if (symbolicName.isEmpty())
  266. {
  267. throw ctkInvalidArgumentException(QString("ctkPlugin has no symbolic name, location=") +
  268. location);
  269. }
  270. QString mpv = archive->getAttribute(ctkPluginConstants::PLUGIN_VERSION);
  271. if (!mpv.isEmpty())
  272. {
  273. try
  274. {
  275. version = ctkVersion(mpv);
  276. }
  277. catch (const std::exception& e)
  278. {
  279. throw ctkInvalidArgumentException(QString("ctkPlugin does not specify a valid ") +
  280. ctkPluginConstants::PLUGIN_VERSION + " header. Got exception: " + e.what());
  281. }
  282. }
  283. QSharedPointer<ctkPlugin> snp = fwCtx->plugins->getPlugin(symbolicName, version);
  284. // TBD! Should we allow update to same version?
  285. if (!snp.isNull() && snp->d_func() != this)
  286. {
  287. throw ctkInvalidArgumentException(QString("Plugin with same symbolic name and version is already installed (")
  288. + symbolicName + ", " + version.toString() + ")");
  289. }
  290. QString ap = archive->getAttribute(ctkPluginConstants::PLUGIN_ACTIVATIONPOLICY);
  291. if (ctkPluginConstants::ACTIVATION_EAGER == ap)
  292. {
  293. eagerActivation = true;
  294. }
  295. }
  296. //----------------------------------------------------------------------------
  297. void ctkPluginPrivate::finalizeActivation()
  298. {
  299. Locker sync(&operationLock);
  300. // 4: Resolve plugin (if needed)
  301. switch (getUpdatedState_unlocked())
  302. {
  303. case ctkPlugin::INSTALLED:
  304. Q_ASSERT_X(resolveFailException != 0, Q_FUNC_INFO, "no resolveFailException");
  305. throw ctkPluginException(*resolveFailException);
  306. case ctkPlugin::STARTING:
  307. if (operation.fetchAndAddOrdered(0) == ACTIVATING) return; // finalization already in progress.
  308. // Lazy activation; fall through to RESOLVED.
  309. case ctkPlugin::RESOLVED:
  310. {
  311. //6:
  312. state = ctkPlugin::STARTING;
  313. operation.fetchAndStoreOrdered(ACTIVATING);
  314. if (fwCtx->debug.lazy_activation)
  315. {
  316. qDebug() << "activating #" << this->id;
  317. }
  318. //7:
  319. if (!pluginContext)
  320. {
  321. pluginContext.reset(new ctkPluginContext(this));
  322. }
  323. // start dependencies
  324. startDependencies();
  325. //TODO plugin threading
  326. //ctkRuntimeException* e = bundleThread().callStart0(this);
  327. ctkRuntimeException* e = start0();
  328. operation.fetchAndStoreOrdered(IDLE);
  329. operationLock.wakeAll();
  330. if (e)
  331. {
  332. ctkRuntimeException re(*e);
  333. delete e;
  334. throw re;
  335. }
  336. break;
  337. }
  338. case ctkPlugin::ACTIVE:
  339. break;
  340. case ctkPlugin::STOPPING:
  341. // This happens if start is called from inside the ctkPluginActivator::stop method.
  342. // Don't allow it.
  343. throw ctkPluginException("start called from ctkPluginActivator::stop",
  344. ctkPluginException::ACTIVATOR_ERROR);
  345. case ctkPlugin::UNINSTALLED:
  346. throw ctkIllegalStateException("ctkPlugin is in UNINSTALLED state");
  347. }
  348. }
  349. //----------------------------------------------------------------------------
  350. const ctkRuntimeException* ctkPluginPrivate::stop0()
  351. {
  352. wasStarted = state == ctkPlugin::ACTIVE;
  353. // 5:
  354. state = ctkPlugin::STOPPING;
  355. operation.fetchAndStoreOrdered(DEACTIVATING);
  356. // 6-13:
  357. // TODO plugin threading
  358. //const ctkRuntimeException* savedException = pluginThread().callStop1(this);
  359. const ctkRuntimeException* savedException = stop1();
  360. if (state != ctkPlugin::UNINSTALLED)
  361. {
  362. state = ctkPlugin::RESOLVED;
  363. // TODO plugin threading
  364. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.STOPPED, this));
  365. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  366. operationLock.wakeAll();
  367. operation.fetchAndStoreOrdered(IDLE);
  368. }
  369. return savedException;
  370. }
  371. //----------------------------------------------------------------------------
  372. const ctkRuntimeException* ctkPluginPrivate::stop1()
  373. {
  374. const ctkRuntimeException* res = 0;
  375. //6:
  376. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, q_func()));
  377. //7:
  378. if (wasStarted && pluginActivator)
  379. {
  380. try
  381. {
  382. pluginActivator->stop(pluginContext.data());
  383. if (state != ctkPlugin::STOPPING)
  384. {
  385. if (state == ctkPlugin::UNINSTALLED)
  386. {
  387. return new ctkIllegalStateException("Plug-in is uninstalled");
  388. }
  389. else
  390. {
  391. return new ctkIllegalStateException("Plug-in changed state because of refresh during stop");
  392. }
  393. }
  394. }
  395. catch (const ctkException& e)
  396. {
  397. res = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  398. ctkPluginException::ACTIVATOR_ERROR, e);
  399. }
  400. catch (...)
  401. {
  402. res = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  403. ctkPluginException::ACTIVATOR_ERROR);
  404. }
  405. pluginActivator = 0;
  406. }
  407. if (operation.fetchAndAddOrdered(0) == DEACTIVATING)
  408. {
  409. // Call hooks after we've called PluginActivator::stop(), but before we've
  410. // cleared all resources
  411. if (pluginContext)
  412. {
  413. // TODO service listener hooks
  414. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  415. //8-10:
  416. removePluginResources();
  417. pluginContext->d_func()->invalidate();
  418. pluginContext.reset();
  419. }
  420. }
  421. // This would unload the shared library and delete the activator if
  422. // there are no dependencies. However, objects from the plug-in might
  423. // have been created via C-function symbol lookups. Hence we cannot
  424. // safely unload the DLL. Maybe implement a in-DLL counter later
  425. // (http://stackoverflow.com/questions/460809/c-dll-unloading-issue and
  426. // http://boost.2283326.n4.nabble.com/shared-ptr-A-smarter-smart-pointer-proposal-for-dynamic-libraries-td2649749.html).
  427. // The activator itself will be delete during program termination
  428. // (by the QPluginLoader instance).
  429. //pluginLoader.unload();
  430. return res;
  431. }
  432. //----------------------------------------------------------------------------
  433. void ctkPluginPrivate::update0(const QUrl& updateLocation, bool wasActive)
  434. {
  435. const bool wasResolved = state == ctkPlugin::RESOLVED;
  436. const int oldStartLevel = getStartLevel();
  437. QSharedPointer<ctkPluginArchive> newArchive;
  438. operation.fetchAndStoreOrdered(UPDATING);
  439. try
  440. {
  441. // New plugin as stream supplied?
  442. QUrl updateUrl(updateLocation);
  443. if (updateUrl.isEmpty())
  444. {
  445. // Try Plugin-UpdateLocation
  446. QString update = archive != 0 ? archive->getAttribute(ctkPluginConstants::PLUGIN_UPDATELOCATION) : QString();
  447. if (update.isEmpty())
  448. {
  449. // Take original location
  450. updateUrl = location;
  451. }
  452. }
  453. if(updateUrl.scheme() != "file")
  454. {
  455. QString msg = "Unsupported update URL:";
  456. msg += updateUrl.toString();
  457. throw ctkPluginException(msg);
  458. }
  459. newArchive = fwCtx->storage->updatePluginArchive(archive, updateUrl, updateUrl.toLocalFile());
  460. //checkCertificates(newArchive);
  461. checkManifestHeaders();
  462. newArchive->setStartLevel(oldStartLevel);
  463. fwCtx->storage->replacePluginArchive(archive, newArchive);
  464. }
  465. catch (const std::exception& e)
  466. {
  467. if (!newArchive.isNull())
  468. {
  469. newArchive->purge();
  470. }
  471. operation.fetchAndStoreOrdered(IDLE);
  472. if (wasActive)
  473. {
  474. try
  475. {
  476. this->q_func().data()->start();
  477. }
  478. catch (const ctkPluginException& pe)
  479. {
  480. fwCtx->listeners.frameworkError(this->q_func(), pe);
  481. }
  482. }
  483. try
  484. {
  485. const ctkPluginException& pe = dynamic_cast<const ctkPluginException&>(e);
  486. throw pe;
  487. }
  488. catch (std::bad_cast)
  489. {
  490. throw ctkPluginException(QString("Failed to get update plugin: ") + e.what(),
  491. ctkPluginException::UNSPECIFIED);
  492. }
  493. }
  494. bool purgeOld = false;
  495. // TODO: check if dependent plug-ins are started. If not, set purgeOld to true.
  496. // Activate new plug-in
  497. QSharedPointer<ctkPluginArchive> oldArchive = archive;
  498. archive = newArchive;
  499. cachedRawHeaders.clear();
  500. state = ctkPlugin::INSTALLED;
  501. // Purge old archive
  502. if (purgeOld)
  503. {
  504. //secure.purge(this, oldProtectionDomain);
  505. if (oldArchive != 0)
  506. {
  507. oldArchive->purge();
  508. }
  509. }
  510. // Broadcast events
  511. if (wasResolved)
  512. {
  513. // TODO: use plugin threading
  514. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  515. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  516. }
  517. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UPDATED, this));
  518. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UPDATED, this->q_func()));
  519. operation.fetchAndStoreOrdered(IDLE);
  520. // Restart plugin previously stopped in the operation
  521. if (wasActive)
  522. {
  523. try
  524. {
  525. this->q_func().data()->start();
  526. }
  527. catch (const ctkPluginException& pe)
  528. {
  529. fwCtx->listeners.frameworkError(this->q_func(), pe);
  530. }
  531. }
  532. }
  533. //----------------------------------------------------------------------------
  534. int ctkPluginPrivate::getStartLevel()
  535. {
  536. if (archive != 0)
  537. {
  538. return archive->getStartLevel();
  539. }
  540. else
  541. {
  542. return 0;
  543. }
  544. }
  545. //----------------------------------------------------------------------------
  546. void ctkPluginPrivate::waitOnOperation(LockObject* lock, const QString& src, bool longWait)
  547. {
  548. if (operation.fetchAndAddOrdered(0) != IDLE)
  549. {
  550. qint64 left = longWait ? 20000 : 500;
  551. QDateTime waitUntil = QDateTime::currentDateTime().addMSecs(left);
  552. do
  553. {
  554. lock->wait(left);
  555. if (operation.fetchAndAddOrdered(0) == IDLE)
  556. {
  557. return;
  558. }
  559. // TODO use Qt 4.7 QDateTime::msecsTo() API
  560. //left = QDateTime::currentDateTime().msecsTo(waitUntil);
  561. left = ctk::msecsTo(QDateTime::currentDateTime(), waitUntil);
  562. } while (left > 0);
  563. QString op;
  564. switch (operation.fetchAndAddOrdered(0))
  565. {
  566. case IDLE:
  567. // Should not happen!
  568. return;
  569. case ACTIVATING:
  570. op = "start";
  571. break;
  572. case DEACTIVATING:
  573. op = "stop";
  574. break;
  575. case RESOLVING:
  576. op = "resolve";
  577. break;
  578. case UNINSTALLING:
  579. op = "uninstall";
  580. break;
  581. case UNRESOLVING:
  582. op = "unresolve";
  583. break;
  584. case UPDATING:
  585. op = "update";
  586. break;
  587. default:
  588. op = "unknown operation";
  589. break;
  590. }
  591. throw ctkPluginException(src + " called during " + op + " of plug-in",
  592. ctkPluginException::STATECHANGE_ERROR);
  593. }
  594. }
  595. //----------------------------------------------------------------------------
  596. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  597. const QString& pattern, bool recurse) const
  598. {
  599. QStringList result;
  600. QStringList resources = archive->findResourcesPath(path);
  601. foreach(QString fp, resources)
  602. {
  603. QString lastComponentOfPath = fp.section('/', -1);
  604. bool isDirectory = fp.endsWith("/");
  605. if (!isDirectory &&
  606. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  607. {
  608. result << (path + fp);
  609. }
  610. if (isDirectory && recurse)
  611. {
  612. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  613. foreach (QString subResource, subResources)
  614. {
  615. result << (path + subResource);
  616. }
  617. }
  618. }
  619. return result;
  620. }
  621. //----------------------------------------------------------------------------
  622. void ctkPluginPrivate::startDependencies()
  623. {
  624. QListIterator<ctkRequirePlugin*> i(this->require);
  625. while (i.hasNext())
  626. {
  627. ctkRequirePlugin* pr = i.next();
  628. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  629. if (pl.isEmpty())
  630. {
  631. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  632. {
  633. // We should never get here, since the plugin can only be
  634. // started if all its dependencies could be resolved.
  635. throw ctkPluginException(
  636. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  637. arg(pr->name).arg(pr->pluginRange.toString()));
  638. }
  639. else
  640. {
  641. continue;
  642. }
  643. }
  644. // We take the first plugin in the list (highest version number)
  645. // Immediately start the dependencies (no lazy activation) but do not
  646. // change the autostart setting of the plugin.
  647. pl.front()->start(ctkPlugin::START_TRANSIENT);
  648. }
  649. }
  650. //----------------------------------------------------------------------------
  651. ctkPluginException* ctkPluginPrivate::start0()
  652. {
  653. ctkPluginException* res = 0;
  654. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  655. ctkPluginException::Type error_type = ctkPluginException::MANIFEST_ERROR;
  656. try {
  657. pluginLoader.load();
  658. if (!pluginLoader.isLoaded())
  659. {
  660. error_type = ctkPluginException::ACTIVATOR_ERROR;
  661. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  662. ctkPluginException::ACTIVATOR_ERROR);
  663. }
  664. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  665. if (!pluginActivator)
  666. {
  667. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  668. ctkPluginException::ACTIVATOR_ERROR);
  669. }
  670. pluginActivator->start(pluginContext.data());
  671. if (state != ctkPlugin::STARTING)
  672. {
  673. error_type = ctkPluginException::STATECHANGE_ERROR;
  674. if (ctkPlugin::UNINSTALLED == state)
  675. {
  676. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  677. }
  678. else
  679. {
  680. throw ctkPluginException("ctkPlugin changed state because of refresh during start()", ctkPluginException::STATECHANGE_ERROR);
  681. }
  682. }
  683. state = ctkPlugin::ACTIVE;
  684. }
  685. catch (const ctkException& e)
  686. {
  687. res = new ctkPluginException("ctkPlugin start failed", error_type, e);
  688. }
  689. catch (...)
  690. {
  691. res = new ctkPluginException("ctkPlugin start failed", error_type);
  692. }
  693. if (fwCtx->debug.lazy_activation)
  694. {
  695. qDebug() << "activating #" << id << "completed.";
  696. }
  697. if (res == 0)
  698. {
  699. //10:
  700. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  701. }
  702. else if (operation.fetchAndAddOrdered(0) == ACTIVATING)
  703. {
  704. // 8:
  705. state = ctkPlugin::STOPPING;
  706. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  707. removePluginResources();
  708. pluginContext->d_func()->invalidate();
  709. pluginContext.reset();
  710. state = ctkPlugin::RESOLVED;
  711. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  712. }
  713. return res;
  714. }
  715. //----------------------------------------------------------------------------
  716. void ctkPluginPrivate::removePluginResources()
  717. {
  718. // automatic disconnect due to Qt signal slot
  719. //fwCtx->listeners.removeAllListeners(this);
  720. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  721. QMutableListIterator<ctkServiceRegistration> i(srs);
  722. while (i.hasNext())
  723. {
  724. try
  725. {
  726. i.next().unregister();
  727. }
  728. catch (const ctkIllegalStateException& /*ignore*/)
  729. {
  730. // Someone has unregistered the service after stop completed.
  731. // This should not occur, but we don't want get stuck in
  732. // an illegal state so we catch it.
  733. }
  734. }
  735. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  736. QListIterator<ctkServiceRegistration> i2(s);
  737. while (i2.hasNext())
  738. {
  739. i2.next().getReference().d_func()->ungetService(q_func(), false);
  740. }
  741. }