ctkPluginPrivate.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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 "ctkPluginPrivate_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 "ctkServices_p.h"
  24. #include "ctkServiceReferencePrivate.h"
  25. #include "ctkServiceRegistration.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 std::invalid_argument(std::string("ctkPlugin has no symbolic name, location=") +
  268. qPrintable(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 std::invalid_argument(std::string("ctkPlugin does not specify a valid ") +
  280. qPrintable(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 std::invalid_argument(std::string("Plugin with same symbolic name and version is already installed (")
  288. + symbolicName.toStdString() + ", " + version.toString().toStdString() + ")");
  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 std::exception& e)
  396. {
  397. res = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  398. ctkPluginException::ACTIVATOR_ERROR, &e);
  399. }
  400. pluginActivator = 0;
  401. }
  402. if (operation.fetchAndAddOrdered(0) == DEACTIVATING)
  403. {
  404. // Call hooks after we've called PluginActivator::stop(), but before we've
  405. // cleared all resources
  406. if (pluginContext)
  407. {
  408. // TODO service listener hooks
  409. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  410. //8-10:
  411. removePluginResources();
  412. pluginContext->d_func()->invalidate();
  413. pluginContext.reset();
  414. }
  415. }
  416. // This would unload the shared library and delete the activator if
  417. // there are no dependencies. However, objects from the plug-in might
  418. // have been created via C-function symbol lookups. Hence we cannot
  419. // safely unload the DLL. Maybe implement a in-DLL counter later
  420. // (http://stackoverflow.com/questions/460809/c-dll-unloading-issue and
  421. // http://boost.2283326.n4.nabble.com/shared-ptr-A-smarter-smart-pointer-proposal-for-dynamic-libraries-td2649749.html).
  422. // The activator itself will be delete during program termination
  423. // (by the QPluginLoader instance).
  424. //pluginLoader.unload();
  425. return res;
  426. }
  427. //----------------------------------------------------------------------------
  428. void ctkPluginPrivate::update0(const QUrl& updateLocation, bool wasActive)
  429. {
  430. const bool wasResolved = state == ctkPlugin::RESOLVED;
  431. const int oldStartLevel = getStartLevel();
  432. QSharedPointer<ctkPluginArchive> newArchive;
  433. operation.fetchAndStoreOrdered(UPDATING);
  434. try
  435. {
  436. // New plugin as stream supplied?
  437. QUrl updateUrl(updateLocation);
  438. if (updateUrl.isEmpty())
  439. {
  440. // Try Plugin-UpdateLocation
  441. QString update = archive != 0 ? archive->getAttribute(ctkPluginConstants::PLUGIN_UPDATELOCATION) : QString();
  442. if (update.isEmpty())
  443. {
  444. // Take original location
  445. updateUrl = location;
  446. }
  447. }
  448. if(updateUrl.scheme() != "file")
  449. {
  450. QString msg = "Unsupported update URL:";
  451. msg += updateUrl.toString();
  452. throw ctkPluginException(msg);
  453. }
  454. newArchive = fwCtx->storage->updatePluginArchive(archive, updateUrl, updateUrl.toLocalFile());
  455. //checkCertificates(newArchive);
  456. checkManifestHeaders();
  457. newArchive->setStartLevel(oldStartLevel);
  458. fwCtx->storage->replacePluginArchive(archive, newArchive);
  459. }
  460. catch (const std::exception& e)
  461. {
  462. if (!newArchive.isNull())
  463. {
  464. newArchive->purge();
  465. }
  466. operation.fetchAndStoreOrdered(IDLE);
  467. if (wasActive)
  468. {
  469. try
  470. {
  471. this->q_func().data()->start();
  472. }
  473. catch (const ctkPluginException& pe)
  474. {
  475. fwCtx->listeners.frameworkError(this->q_func(), e);
  476. }
  477. }
  478. try
  479. {
  480. const ctkPluginException& pe = dynamic_cast<const ctkPluginException&>(e);
  481. throw pe;
  482. }
  483. catch (std::bad_cast)
  484. {
  485. throw ctkPluginException("Failed to get update plugin",
  486. ctkPluginException::UNSPECIFIED, &e);
  487. }
  488. }
  489. bool purgeOld = false;
  490. // TODO: check if dependent plug-ins are started. If not, set purgeOld to true.
  491. // Activate new plug-in
  492. QSharedPointer<ctkPluginArchive> oldArchive = archive;
  493. archive = newArchive;
  494. cachedRawHeaders.clear();
  495. state = ctkPlugin::INSTALLED;
  496. // Purge old archive
  497. if (purgeOld)
  498. {
  499. //secure.purge(this, oldProtectionDomain);
  500. if (oldArchive != 0)
  501. {
  502. oldArchive->purge();
  503. }
  504. }
  505. // Broadcast events
  506. if (wasResolved)
  507. {
  508. // TODO: use plugin threading
  509. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  510. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  511. }
  512. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UPDATED, this));
  513. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UPDATED, this->q_func()));
  514. operation.fetchAndStoreOrdered(IDLE);
  515. // Restart plugin previously stopped in the operation
  516. if (wasActive)
  517. {
  518. try
  519. {
  520. this->q_func().data()->start();
  521. }
  522. catch (const ctkPluginException& pe)
  523. {
  524. fwCtx->listeners.frameworkError(this->q_func(), pe);
  525. }
  526. }
  527. }
  528. //----------------------------------------------------------------------------
  529. int ctkPluginPrivate::getStartLevel()
  530. {
  531. if (archive != 0)
  532. {
  533. return archive->getStartLevel();
  534. }
  535. else
  536. {
  537. return 0;
  538. }
  539. }
  540. //----------------------------------------------------------------------------
  541. void ctkPluginPrivate::waitOnOperation(LockObject* lock, const QString& src, bool longWait)
  542. {
  543. if (operation.fetchAndAddOrdered(0) != IDLE)
  544. {
  545. qint64 left = longWait ? 20000 : 500;
  546. QDateTime waitUntil = QDateTime::currentDateTime().addMSecs(left);
  547. do
  548. {
  549. lock->wait(left);
  550. if (operation.fetchAndAddOrdered(0) == IDLE)
  551. {
  552. return;
  553. }
  554. // TODO use Qt 4.7 QDateTime::msecsTo() API
  555. //left = QDateTime::currentDateTime().msecsTo(waitUntil);
  556. left = ctk::msecsTo(QDateTime::currentDateTime(), waitUntil);
  557. } while (left > 0);
  558. QString op;
  559. switch (operation.fetchAndAddOrdered(0))
  560. {
  561. case IDLE:
  562. // Should not happen!
  563. return;
  564. case ACTIVATING:
  565. op = "start";
  566. break;
  567. case DEACTIVATING:
  568. op = "stop";
  569. break;
  570. case RESOLVING:
  571. op = "resolve";
  572. break;
  573. case UNINSTALLING:
  574. op = "uninstall";
  575. break;
  576. case UNRESOLVING:
  577. op = "unresolve";
  578. break;
  579. case UPDATING:
  580. op = "update";
  581. break;
  582. default:
  583. op = "unknown operation";
  584. break;
  585. }
  586. throw ctkPluginException(src + " called during " + op + " of plug-in",
  587. ctkPluginException::STATECHANGE_ERROR);
  588. }
  589. }
  590. //----------------------------------------------------------------------------
  591. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  592. const QString& pattern, bool recurse) const
  593. {
  594. QStringList result;
  595. QStringList resources = archive->findResourcesPath(path);
  596. foreach(QString fp, resources)
  597. {
  598. QString lastComponentOfPath = fp.section('/', -1);
  599. bool isDirectory = fp.endsWith("/");
  600. if (!isDirectory &&
  601. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  602. {
  603. result << (path + fp);
  604. }
  605. if (isDirectory && recurse)
  606. {
  607. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  608. foreach (QString subResource, subResources)
  609. {
  610. result << (path + subResource);
  611. }
  612. }
  613. }
  614. return result;
  615. }
  616. //----------------------------------------------------------------------------
  617. void ctkPluginPrivate::startDependencies()
  618. {
  619. QListIterator<ctkRequirePlugin*> i(this->require);
  620. while (i.hasNext())
  621. {
  622. ctkRequirePlugin* pr = i.next();
  623. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  624. if (pl.isEmpty())
  625. {
  626. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  627. {
  628. // We should never get here, since the plugin can only be
  629. // started if all its dependencies could be resolved.
  630. throw ctkPluginException(
  631. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  632. arg(pr->name).arg(pr->pluginRange.toString()));
  633. }
  634. else
  635. {
  636. continue;
  637. }
  638. }
  639. // We take the first plugin in the list (highest version number)
  640. // Immediately start the dependencies (no lazy activation) but do not
  641. // change the autostart setting of the plugin.
  642. pl.front()->start(ctkPlugin::START_TRANSIENT);
  643. }
  644. }
  645. //----------------------------------------------------------------------------
  646. ctkPluginException* ctkPluginPrivate::start0()
  647. {
  648. ctkPluginException* res = 0;
  649. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  650. ctkPluginException::Type error_type = ctkPluginException::MANIFEST_ERROR;
  651. try {
  652. pluginLoader.load();
  653. if (!pluginLoader.isLoaded())
  654. {
  655. error_type = ctkPluginException::ACTIVATOR_ERROR;
  656. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  657. ctkPluginException::ACTIVATOR_ERROR);
  658. }
  659. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  660. if (!pluginActivator)
  661. {
  662. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  663. ctkPluginException::ACTIVATOR_ERROR);
  664. }
  665. pluginActivator->start(pluginContext.data());
  666. if (state != ctkPlugin::STARTING)
  667. {
  668. error_type = ctkPluginException::STATECHANGE_ERROR;
  669. if (ctkPlugin::UNINSTALLED == state)
  670. {
  671. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  672. }
  673. else
  674. {
  675. throw ctkPluginException("ctkPlugin changed state because of refresh during start()", ctkPluginException::STATECHANGE_ERROR);
  676. }
  677. }
  678. state = ctkPlugin::ACTIVE;
  679. }
  680. catch (const std::exception& e)
  681. {
  682. res = new ctkPluginException("ctkPlugin start failed", error_type, &e);
  683. }
  684. if (fwCtx->debug.lazy_activation)
  685. {
  686. qDebug() << "activating #" << id << "completed.";
  687. }
  688. if (res == 0)
  689. {
  690. //10:
  691. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  692. }
  693. else if (operation.fetchAndAddOrdered(0) == ACTIVATING)
  694. {
  695. // 8:
  696. state = ctkPlugin::STOPPING;
  697. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  698. removePluginResources();
  699. pluginContext->d_func()->invalidate();
  700. pluginContext.reset();
  701. state = ctkPlugin::RESOLVED;
  702. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  703. }
  704. return res;
  705. }
  706. //----------------------------------------------------------------------------
  707. void ctkPluginPrivate::removePluginResources()
  708. {
  709. // automatic disconnect due to Qt signal slot
  710. //fwCtx->listeners.removeAllListeners(this);
  711. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  712. QMutableListIterator<ctkServiceRegistration> i(srs);
  713. while (i.hasNext())
  714. {
  715. try
  716. {
  717. i.next().unregister();
  718. }
  719. catch (const std::logic_error& /*ignore*/)
  720. {
  721. // Someone has unregistered the service after stop completed.
  722. // This should not occur, but we don't want get stuck in
  723. // an illegal state so we catch it.
  724. }
  725. }
  726. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  727. QListIterator<ctkServiceRegistration> i2(s);
  728. while (i2.hasNext())
  729. {
  730. i2.next().getReference().d_func()->ungetService(q_func(), false);
  731. }
  732. }