ctkPluginPrivate.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. const ctkPlugin::States ctkPluginPrivate::RESOLVED_FLAGS = ctkPlugin::RESOLVED | ctkPlugin::STARTING | ctkPlugin::ACTIVE | ctkPlugin::STOPPING;
  27. //----------------------------------------------------------------------------
  28. void ctkPluginPrivate::LockObject::lock()
  29. {
  30. m_Lock.lock();
  31. }
  32. //----------------------------------------------------------------------------
  33. bool ctkPluginPrivate::LockObject::tryLock()
  34. {
  35. return m_Lock.tryLock();
  36. }
  37. //----------------------------------------------------------------------------
  38. bool ctkPluginPrivate::LockObject::tryLock(int timeout)
  39. {
  40. return m_Lock.tryLock(timeout);
  41. }
  42. //----------------------------------------------------------------------------
  43. void ctkPluginPrivate::LockObject::unlock()
  44. {
  45. m_Lock.unlock();
  46. }
  47. //----------------------------------------------------------------------------
  48. bool ctkPluginPrivate::LockObject::wait(unsigned long time)
  49. {
  50. return m_Condition.wait(&m_Lock, time);
  51. }
  52. //----------------------------------------------------------------------------
  53. void ctkPluginPrivate::LockObject::wakeAll()
  54. {
  55. m_Condition.wakeAll();
  56. }
  57. //----------------------------------------------------------------------------
  58. void ctkPluginPrivate::LockObject::wakeOne()
  59. {
  60. m_Condition.wakeOne();
  61. }
  62. //----------------------------------------------------------------------------
  63. ctkPluginPrivate::ctkPluginPrivate(
  64. QWeakPointer<ctkPlugin> qq,
  65. ctkPluginFrameworkContext* fw,
  66. ctkPluginArchive* pa)
  67. : q_ptr(qq), fwCtx(fw), id(pa->getPluginId()),
  68. location(pa->getPluginLocation().toString()), state(ctkPlugin::INSTALLED),
  69. archive(pa), pluginContext(0), pluginActivator(0), pluginLoader(pa->getLibLocation()),
  70. resolveFailException(0), eagerActivation(false), wasStarted(false)
  71. {
  72. //TODO
  73. //checkCertificates(pa);
  74. // Get library load hints
  75. if (fw->props.contains(ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS))
  76. {
  77. QVariant loadHintsVariant = fw->props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
  78. if (loadHintsVariant.isValid())
  79. {
  80. QLibrary::LoadHints loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
  81. pluginLoader.setLoadHints(loadHints);
  82. }
  83. }
  84. checkManifestHeaders();
  85. pluginDir = fwCtx->getDataStorage(id);
  86. // int oldStartLevel = archive->getStartLevel();
  87. try
  88. {
  89. //TODO: StartLevel Service
  90. //if (fwCtx->startLevelController == 0)
  91. //{
  92. archive->setStartLevel(0);
  93. //}
  94. // else
  95. // {
  96. // if (oldStartLevel == -1)
  97. // {
  98. // archive->setStartLevel(fwCtx->startLevelController->getInitialPluginStartLevel());
  99. // }
  100. // }
  101. }
  102. catch (const std::exception& e)
  103. {
  104. qDebug() << "Failed to set start level on #" << id << ":" << e.what();
  105. }
  106. lastModified = archive->getLastModified();
  107. if (lastModified.isNull())
  108. {
  109. modified();
  110. }
  111. // fill require list
  112. QString requireString = archive->getAttribute(ctkPluginConstants::REQUIRE_PLUGIN);
  113. QList<QMap<QString, QStringList> > requireList = ctkPluginFrameworkUtil::parseEntries(ctkPluginConstants::REQUIRE_PLUGIN,
  114. requireString, true, true, false);
  115. QListIterator<QMap<QString, QStringList> > i(requireList);
  116. while (i.hasNext())
  117. {
  118. const QMap<QString, QStringList>& e = i.next();
  119. const QStringList& res = e.value(ctkPluginConstants::RESOLUTION_DIRECTIVE);
  120. const QStringList& version = e.value(ctkPluginConstants::PLUGIN_VERSION_ATTRIBUTE);
  121. ctkRequirePlugin* rp = new ctkRequirePlugin(this, e.value("$key").front(),
  122. res.empty() ? QString() : res.front(),
  123. version.empty() ? QString() : version.front());
  124. require.push_back(rp);
  125. }
  126. }
  127. //----------------------------------------------------------------------------
  128. ctkPluginPrivate::ctkPluginPrivate(QWeakPointer<ctkPlugin> qq,
  129. ctkPluginFrameworkContext* fw,
  130. long id, const QString& loc, const QString& sym, const ctkVersion& ver)
  131. : q_ptr(qq), fwCtx(fw), id(id), location(loc), symbolicName(sym), version(ver),
  132. state(ctkPlugin::INSTALLED), archive(0), pluginContext(0),
  133. pluginActivator(0), resolveFailException(0),
  134. eagerActivation(false), wasStarted(false)
  135. {
  136. modified();
  137. }
  138. //----------------------------------------------------------------------------
  139. ctkPluginPrivate::~ctkPluginPrivate()
  140. {
  141. qDeleteAll(require);
  142. delete archive;
  143. }
  144. //----------------------------------------------------------------------------
  145. ctkPlugin::State ctkPluginPrivate::getUpdatedState()
  146. {
  147. if (state & ctkPlugin::INSTALLED)
  148. {
  149. try
  150. {
  151. // NYI, fix double locking
  152. Locker sync(&operationLock);
  153. if (state == ctkPlugin::INSTALLED)
  154. {
  155. fwCtx->resolvePlugin(this);
  156. state = ctkPlugin::RESOLVED;
  157. operation.fetchAndStoreOrdered(RESOLVING);
  158. // TODO plugin threading
  159. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.RESOLVED, this));
  160. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, this->q_func()));
  161. operation.fetchAndStoreOrdered(IDLE);
  162. }
  163. }
  164. catch (const ctkPluginException& pe)
  165. {
  166. if (resolveFailException) delete resolveFailException;
  167. resolveFailException = new ctkPluginException(pe);
  168. this->fwCtx->listeners.frameworkError(this->q_func(), pe);
  169. }
  170. }
  171. return state;
  172. }
  173. //----------------------------------------------------------------------------
  174. QFileInfo ctkPluginPrivate::getDataRoot()
  175. {
  176. return pluginDir;
  177. }
  178. //----------------------------------------------------------------------------
  179. void ctkPluginPrivate::setStateInstalled(bool sendEvent)
  180. {
  181. Locker sync(&operationLock);
  182. // Make sure that the context is invalid
  183. if (pluginContext != 0)
  184. {
  185. pluginContext->d_func()->invalidate();
  186. pluginContext.reset();
  187. }
  188. state = ctkPlugin::INSTALLED;
  189. if (sendEvent)
  190. {
  191. operation.fetchAndStoreOrdered(UNRESOLVING);
  192. // TODO: plugin thread
  193. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  194. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  195. }
  196. operation.fetchAndStoreOrdered(IDLE);
  197. }
  198. //----------------------------------------------------------------------------
  199. void ctkPluginPrivate::purge()
  200. {
  201. if (state == ctkPlugin::UNINSTALLED)
  202. {
  203. fwCtx->plugins->remove(location);
  204. }
  205. // Vector fix = oldGenerations;
  206. // if (fix != null) {
  207. // oldGenerations = null;
  208. // for (Iterator i = fix.iterator(); i.hasNext();) {
  209. // ((BundleGeneration)i.next()).purge(true);
  210. // }
  211. // }
  212. }
  213. //----------------------------------------------------------------------------
  214. void ctkPluginPrivate::setAutostartSetting(const ctkPlugin::StartOptions& setting) {
  215. try
  216. {
  217. if (archive)
  218. {
  219. archive->setAutostartSetting(setting);
  220. }
  221. }
  222. catch (const ctkPluginDatabaseException& e)
  223. {
  224. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  225. }
  226. }
  227. //----------------------------------------------------------------------------
  228. void ctkPluginPrivate::ignoreAutostartSetting()
  229. {
  230. try
  231. {
  232. if (archive)
  233. {
  234. archive->setAutostartSetting(-1);
  235. }
  236. }
  237. catch (const ctkPluginDatabaseException& e)
  238. {
  239. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  240. }
  241. }
  242. //----------------------------------------------------------------------------
  243. void ctkPluginPrivate::modified()
  244. {
  245. lastModified = QDateTime::currentDateTime();
  246. if (archive)
  247. {
  248. archive->setLastModified(lastModified);
  249. }
  250. }
  251. //----------------------------------------------------------------------------
  252. void ctkPluginPrivate::checkManifestHeaders()
  253. {
  254. symbolicName = archive->getAttribute(ctkPluginConstants::PLUGIN_SYMBOLICNAME);
  255. if (symbolicName.isEmpty())
  256. {
  257. throw std::invalid_argument(std::string("ctkPlugin has no symbolic name, location=") +
  258. qPrintable(location));
  259. }
  260. QString mpv = archive->getAttribute(ctkPluginConstants::PLUGIN_VERSION);
  261. if (!mpv.isEmpty())
  262. {
  263. try
  264. {
  265. version = ctkVersion(mpv);
  266. }
  267. catch (const std::exception& e)
  268. {
  269. throw std::invalid_argument(std::string("ctkPlugin does not specify a valid ") +
  270. qPrintable(ctkPluginConstants::PLUGIN_VERSION) + " header. Got exception: " + e.what());
  271. }
  272. }
  273. QSharedPointer<ctkPlugin> snp = fwCtx->plugins->getPlugin(symbolicName, version);
  274. // TBD! Should we allow update to same version?
  275. if (!snp.isNull() && snp->d_func() != this)
  276. {
  277. throw std::invalid_argument(std::string("Plugin with same symbolic name and version is already installed (")
  278. + symbolicName.toStdString() + ", " + version.toString().toStdString() + ")");
  279. }
  280. QString ap = archive->getAttribute(ctkPluginConstants::PLUGIN_ACTIVATIONPOLICY);
  281. if (ctkPluginConstants::ACTIVATION_EAGER == ap)
  282. {
  283. eagerActivation = true;
  284. }
  285. }
  286. //----------------------------------------------------------------------------
  287. void ctkPluginPrivate::finalizeActivation()
  288. {
  289. Locker sync(&operationLock);
  290. // 4: Resolve plugin (if needed)
  291. switch (getUpdatedState())
  292. {
  293. case ctkPlugin::INSTALLED:
  294. Q_ASSERT_X(resolveFailException != 0, Q_FUNC_INFO, "no resolveFailException");
  295. throw ctkPluginException(*resolveFailException);
  296. case ctkPlugin::STARTING:
  297. if (operation.fetchAndAddOrdered(0) == ACTIVATING) return; // finalization already in progress.
  298. // Lazy activation; fall through to RESOLVED.
  299. case ctkPlugin::RESOLVED:
  300. {
  301. //6:
  302. state = ctkPlugin::STARTING;
  303. operation.fetchAndStoreOrdered(ACTIVATING);
  304. if (fwCtx->debug.lazy_activation)
  305. {
  306. qDebug() << "activating #" << this->id;
  307. }
  308. //7:
  309. if (!pluginContext)
  310. {
  311. pluginContext.reset(new ctkPluginContext(this));
  312. }
  313. // start dependencies
  314. startDependencies();
  315. //TODO plugin threading
  316. //ctkRuntimeException* e = bundleThread().callStart0(this);
  317. ctkRuntimeException* e = start0();
  318. operation.fetchAndStoreOrdered(IDLE);
  319. operationLock.wakeAll();
  320. if (e)
  321. {
  322. ctkRuntimeException re(*e);
  323. delete e;
  324. throw re;
  325. }
  326. break;
  327. }
  328. case ctkPlugin::ACTIVE:
  329. break;
  330. case ctkPlugin::STOPPING:
  331. // This happens if start is called from inside the ctkPluginActivator::stop method.
  332. // Don't allow it.
  333. throw ctkPluginException("start called from ctkPluginActivator::stop",
  334. ctkPluginException::ACTIVATOR_ERROR);
  335. case ctkPlugin::UNINSTALLED:
  336. throw ctkIllegalStateException("ctkPlugin is in UNINSTALLED state");
  337. }
  338. }
  339. //----------------------------------------------------------------------------
  340. const ctkRuntimeException* ctkPluginPrivate::stop0()
  341. {
  342. wasStarted = state == ctkPlugin::ACTIVE;
  343. // 5:
  344. state = ctkPlugin::STOPPING;
  345. operation.fetchAndStoreOrdered(DEACTIVATING);
  346. // 6-13:
  347. // TODO plugin threading
  348. //const ctkRuntimeException* savedException = pluginThread().callStop1(this);
  349. const ctkRuntimeException* savedException = stop1();
  350. if (state != ctkPlugin::UNINSTALLED)
  351. {
  352. state = ctkPlugin::RESOLVED;
  353. // TODO plugin threading
  354. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.STOPPED, this));
  355. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  356. operationLock.wakeAll();
  357. operation.fetchAndStoreOrdered(IDLE);
  358. }
  359. return savedException;
  360. }
  361. //----------------------------------------------------------------------------
  362. const ctkRuntimeException* ctkPluginPrivate::stop1()
  363. {
  364. const ctkRuntimeException* res = 0;
  365. //6:
  366. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, q_func()));
  367. //7:
  368. if (wasStarted && pluginActivator)
  369. {
  370. try
  371. {
  372. pluginActivator->stop(pluginContext.data());
  373. if (state != ctkPlugin::STOPPING)
  374. {
  375. if (state == ctkPlugin::UNINSTALLED)
  376. {
  377. return new ctkIllegalStateException("Plug-in is uninstalled");
  378. }
  379. else
  380. {
  381. return new ctkIllegalStateException("Plug-in changed state because of refresh during stop");
  382. }
  383. }
  384. }
  385. catch (const std::exception& e)
  386. {
  387. res = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  388. ctkPluginException::ACTIVATOR_ERROR, &e);
  389. }
  390. pluginActivator = 0;
  391. }
  392. if (operation.fetchAndAddOrdered(0) == DEACTIVATING)
  393. {
  394. // Call hooks after we've called PluginActivator::stop(), but before we've
  395. // cleared all resources
  396. if (pluginContext)
  397. {
  398. // TODO service listener hooks
  399. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  400. //8-10:
  401. removePluginResources();
  402. pluginContext->d_func()->invalidate();
  403. pluginContext.reset();
  404. }
  405. }
  406. // This would unload the shared library and delete the activator if
  407. // there are no dependencies. However, objects from the plug-in might
  408. // have been created via C-function symbol lookups. Hence we cannot
  409. // safely unload the DLL. Maybe implement a in-DLL counter later
  410. // (http://stackoverflow.com/questions/460809/c-dll-unloading-issue and
  411. // http://boost.2283326.n4.nabble.com/shared-ptr-A-smarter-smart-pointer-proposal-for-dynamic-libraries-td2649749.html).
  412. // The activator itself will be delete during program termination
  413. // (by the QPluginLoader instance).
  414. //pluginLoader.unload();
  415. return res;
  416. }
  417. //----------------------------------------------------------------------------
  418. void ctkPluginPrivate::waitOnOperation(LockObject* lock, const QString& src, bool longWait)
  419. {
  420. if (operation.fetchAndAddOrdered(0) != IDLE)
  421. {
  422. qint64 left = longWait ? 20000 : 500;
  423. QDateTime waitUntil = QDateTime::currentDateTime().addMSecs(left);
  424. do
  425. {
  426. lock->wait(left);
  427. if (operation.fetchAndAddOrdered(0) == IDLE)
  428. {
  429. return;
  430. }
  431. left = QDateTime::currentDateTime().msecsTo(waitUntil);
  432. } while (left > 0);
  433. QString op;
  434. switch (operation.fetchAndAddOrdered(0))
  435. {
  436. case IDLE:
  437. // Should not happen!
  438. return;
  439. case ACTIVATING:
  440. op = "start";
  441. break;
  442. case DEACTIVATING:
  443. op = "stop";
  444. break;
  445. case RESOLVING:
  446. op = "resolve";
  447. break;
  448. case UNINSTALLING:
  449. op = "uninstall";
  450. break;
  451. case UNRESOLVING:
  452. op = "unresolve";
  453. break;
  454. case UPDATING:
  455. op = "update";
  456. break;
  457. default:
  458. op = "unknown operation";
  459. break;
  460. }
  461. throw ctkPluginException(src + " called during " + op + " of plug-in",
  462. ctkPluginException::STATECHANGE_ERROR);
  463. }
  464. }
  465. //----------------------------------------------------------------------------
  466. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  467. const QString& pattern, bool recurse) const
  468. {
  469. QStringList result;
  470. QStringList resources = archive->findResourcesPath(path);
  471. foreach(QString fp, resources)
  472. {
  473. QString lastComponentOfPath = fp.section('/', -1);
  474. bool isDirectory = fp.endsWith("/");
  475. if (!isDirectory &&
  476. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  477. {
  478. result << (path + fp);
  479. }
  480. if (isDirectory && recurse)
  481. {
  482. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  483. foreach (QString subResource, subResources)
  484. {
  485. result << (path + subResource);
  486. }
  487. }
  488. }
  489. return result;
  490. }
  491. //----------------------------------------------------------------------------
  492. void ctkPluginPrivate::startDependencies()
  493. {
  494. QListIterator<ctkRequirePlugin*> i(this->require);
  495. while (i.hasNext())
  496. {
  497. ctkRequirePlugin* pr = i.next();
  498. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  499. if (pl.isEmpty())
  500. {
  501. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  502. {
  503. // We should never get here, since the plugin can only be
  504. // started if all its dependencies could be resolved.
  505. throw ctkPluginException(
  506. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  507. arg(pr->name).arg(pr->pluginRange.toString()));
  508. }
  509. else
  510. {
  511. continue;
  512. }
  513. }
  514. // We take the first plugin in the list (highest version number)
  515. // Immediately start the dependencies (no lazy activation) but do not
  516. // change the autostart setting of the plugin.
  517. pl.front()->start(ctkPlugin::START_TRANSIENT);
  518. }
  519. }
  520. //----------------------------------------------------------------------------
  521. ctkPluginException* ctkPluginPrivate::start0()
  522. {
  523. ctkPluginException* res = 0;
  524. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  525. ctkPluginException::Type error_type = ctkPluginException::MANIFEST_ERROR;
  526. try {
  527. pluginLoader.load();
  528. if (!pluginLoader.isLoaded())
  529. {
  530. error_type = ctkPluginException::ACTIVATOR_ERROR;
  531. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  532. ctkPluginException::ACTIVATOR_ERROR);
  533. }
  534. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  535. if (!pluginActivator)
  536. {
  537. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  538. ctkPluginException::ACTIVATOR_ERROR);
  539. }
  540. pluginActivator->start(pluginContext.data());
  541. if (state != ctkPlugin::STARTING)
  542. {
  543. error_type = ctkPluginException::STATECHANGE_ERROR;
  544. if (ctkPlugin::UNINSTALLED == state)
  545. {
  546. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  547. }
  548. else
  549. {
  550. throw ctkPluginException("ctkPlugin changed state because of refresh during start()", ctkPluginException::STATECHANGE_ERROR);
  551. }
  552. }
  553. state = ctkPlugin::ACTIVE;
  554. }
  555. catch (const std::exception& e)
  556. {
  557. res = new ctkPluginException("ctkPlugin start failed", error_type, &e);
  558. }
  559. if (fwCtx->debug.lazy_activation)
  560. {
  561. qDebug() << "activating #" << id << "completed.";
  562. }
  563. if (res == 0)
  564. {
  565. //10:
  566. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  567. }
  568. else if (operation.fetchAndAddOrdered(0) == ACTIVATING)
  569. {
  570. // 8:
  571. state = ctkPlugin::STOPPING;
  572. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  573. removePluginResources();
  574. pluginContext->d_func()->invalidate();
  575. pluginContext.reset();
  576. state = ctkPlugin::RESOLVED;
  577. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  578. }
  579. return res;
  580. }
  581. //----------------------------------------------------------------------------
  582. void ctkPluginPrivate::removePluginResources()
  583. {
  584. // automatic disconnect due to Qt signal slot
  585. //fwCtx->listeners.removeAllListeners(this);
  586. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  587. QMutableListIterator<ctkServiceRegistration> i(srs);
  588. while (i.hasNext())
  589. {
  590. try
  591. {
  592. i.next().unregister();
  593. }
  594. catch (const std::logic_error& /*ignore*/)
  595. {
  596. // Someone has unregistered the service after stop completed.
  597. // This should not occur, but we don't want get stuck in
  598. // an illegal state so we catch it.
  599. }
  600. }
  601. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  602. QListIterator<ctkServiceRegistration> i2(s);
  603. while (i2.hasNext())
  604. {
  605. i2.next().getReference().d_func()->ungetService(q_func(), false);
  606. }
  607. }