ctkPluginPrivate.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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. 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. delete archive;
  146. }
  147. //----------------------------------------------------------------------------
  148. ctkPlugin::State ctkPluginPrivate::getUpdatedState()
  149. {
  150. if (state & ctkPlugin::INSTALLED)
  151. {
  152. Locker sync(&operationLock);
  153. getUpdatedState_unlocked();
  154. }
  155. return state;
  156. }
  157. //----------------------------------------------------------------------------
  158. ctkPlugin::State ctkPluginPrivate::getUpdatedState_unlocked()
  159. {
  160. if (state & ctkPlugin::INSTALLED)
  161. {
  162. try
  163. {
  164. if (state == ctkPlugin::INSTALLED)
  165. {
  166. operation.fetchAndStoreOrdered(RESOLVING);
  167. fwCtx->resolvePlugin(this);
  168. state = ctkPlugin::RESOLVED;
  169. // TODO plugin threading
  170. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.RESOLVED, this));
  171. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, this->q_func()));
  172. operation.fetchAndStoreOrdered(IDLE);
  173. }
  174. }
  175. catch (const ctkPluginException& pe)
  176. {
  177. if (resolveFailException) delete resolveFailException;
  178. resolveFailException = new ctkPluginException(pe);
  179. this->fwCtx->listeners.frameworkError(this->q_func(), pe);
  180. }
  181. }
  182. return state;
  183. }
  184. //----------------------------------------------------------------------------
  185. QFileInfo ctkPluginPrivate::getDataRoot()
  186. {
  187. return pluginDir;
  188. }
  189. //----------------------------------------------------------------------------
  190. void ctkPluginPrivate::setStateInstalled(bool sendEvent)
  191. {
  192. Locker sync(&operationLock);
  193. // Make sure that the context is invalid
  194. if (pluginContext != 0)
  195. {
  196. pluginContext->d_func()->invalidate();
  197. pluginContext.reset();
  198. }
  199. state = ctkPlugin::INSTALLED;
  200. if (sendEvent)
  201. {
  202. operation.fetchAndStoreOrdered(UNRESOLVING);
  203. // TODO: plugin thread
  204. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  205. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  206. }
  207. operation.fetchAndStoreOrdered(IDLE);
  208. }
  209. //----------------------------------------------------------------------------
  210. void ctkPluginPrivate::purge()
  211. {
  212. if (state == ctkPlugin::UNINSTALLED)
  213. {
  214. fwCtx->plugins->remove(location);
  215. }
  216. // Vector fix = oldGenerations;
  217. // if (fix != null) {
  218. // oldGenerations = null;
  219. // for (Iterator i = fix.iterator(); i.hasNext();) {
  220. // ((BundleGeneration)i.next()).purge(true);
  221. // }
  222. // }
  223. }
  224. //----------------------------------------------------------------------------
  225. void ctkPluginPrivate::setAutostartSetting(const ctkPlugin::StartOptions& setting) {
  226. try
  227. {
  228. if (archive)
  229. {
  230. archive->setAutostartSetting(setting);
  231. }
  232. }
  233. catch (const ctkPluginDatabaseException& e)
  234. {
  235. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  236. }
  237. }
  238. //----------------------------------------------------------------------------
  239. void ctkPluginPrivate::ignoreAutostartSetting()
  240. {
  241. try
  242. {
  243. if (archive)
  244. {
  245. archive->setAutostartSetting(-1);
  246. }
  247. }
  248. catch (const ctkPluginDatabaseException& e)
  249. {
  250. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  251. }
  252. }
  253. //----------------------------------------------------------------------------
  254. void ctkPluginPrivate::modified()
  255. {
  256. lastModified = QDateTime::currentDateTime();
  257. if (archive)
  258. {
  259. archive->setLastModified(lastModified);
  260. }
  261. }
  262. //----------------------------------------------------------------------------
  263. void ctkPluginPrivate::checkManifestHeaders()
  264. {
  265. symbolicName = archive->getAttribute(ctkPluginConstants::PLUGIN_SYMBOLICNAME);
  266. if (symbolicName.isEmpty())
  267. {
  268. throw std::invalid_argument(std::string("ctkPlugin has no symbolic name, location=") +
  269. qPrintable(location));
  270. }
  271. QString mpv = archive->getAttribute(ctkPluginConstants::PLUGIN_VERSION);
  272. if (!mpv.isEmpty())
  273. {
  274. try
  275. {
  276. version = ctkVersion(mpv);
  277. }
  278. catch (const std::exception& e)
  279. {
  280. throw std::invalid_argument(std::string("ctkPlugin does not specify a valid ") +
  281. qPrintable(ctkPluginConstants::PLUGIN_VERSION) + " header. Got exception: " + e.what());
  282. }
  283. }
  284. QSharedPointer<ctkPlugin> snp = fwCtx->plugins->getPlugin(symbolicName, version);
  285. // TBD! Should we allow update to same version?
  286. if (!snp.isNull() && snp->d_func() != this)
  287. {
  288. throw std::invalid_argument(std::string("Plugin with same symbolic name and version is already installed (")
  289. + symbolicName.toStdString() + ", " + version.toString().toStdString() + ")");
  290. }
  291. QString ap = archive->getAttribute(ctkPluginConstants::PLUGIN_ACTIVATIONPOLICY);
  292. if (ctkPluginConstants::ACTIVATION_EAGER == ap)
  293. {
  294. eagerActivation = true;
  295. }
  296. }
  297. //----------------------------------------------------------------------------
  298. void ctkPluginPrivate::finalizeActivation()
  299. {
  300. Locker sync(&operationLock);
  301. // 4: Resolve plugin (if needed)
  302. switch (getUpdatedState_unlocked())
  303. {
  304. case ctkPlugin::INSTALLED:
  305. Q_ASSERT_X(resolveFailException != 0, Q_FUNC_INFO, "no resolveFailException");
  306. throw ctkPluginException(*resolveFailException);
  307. case ctkPlugin::STARTING:
  308. if (operation.fetchAndAddOrdered(0) == ACTIVATING) return; // finalization already in progress.
  309. // Lazy activation; fall through to RESOLVED.
  310. case ctkPlugin::RESOLVED:
  311. {
  312. //6:
  313. state = ctkPlugin::STARTING;
  314. operation.fetchAndStoreOrdered(ACTIVATING);
  315. if (fwCtx->debug.lazy_activation)
  316. {
  317. qDebug() << "activating #" << this->id;
  318. }
  319. //7:
  320. if (!pluginContext)
  321. {
  322. pluginContext.reset(new ctkPluginContext(this));
  323. }
  324. // start dependencies
  325. startDependencies();
  326. //TODO plugin threading
  327. //ctkRuntimeException* e = bundleThread().callStart0(this);
  328. ctkRuntimeException* e = start0();
  329. operation.fetchAndStoreOrdered(IDLE);
  330. operationLock.wakeAll();
  331. if (e)
  332. {
  333. ctkRuntimeException re(*e);
  334. delete e;
  335. throw re;
  336. }
  337. break;
  338. }
  339. case ctkPlugin::ACTIVE:
  340. break;
  341. case ctkPlugin::STOPPING:
  342. // This happens if start is called from inside the ctkPluginActivator::stop method.
  343. // Don't allow it.
  344. throw ctkPluginException("start called from ctkPluginActivator::stop",
  345. ctkPluginException::ACTIVATOR_ERROR);
  346. case ctkPlugin::UNINSTALLED:
  347. throw ctkIllegalStateException("ctkPlugin is in UNINSTALLED state");
  348. }
  349. }
  350. //----------------------------------------------------------------------------
  351. const ctkRuntimeException* ctkPluginPrivate::stop0()
  352. {
  353. wasStarted = state == ctkPlugin::ACTIVE;
  354. // 5:
  355. state = ctkPlugin::STOPPING;
  356. operation.fetchAndStoreOrdered(DEACTIVATING);
  357. // 6-13:
  358. // TODO plugin threading
  359. //const ctkRuntimeException* savedException = pluginThread().callStop1(this);
  360. const ctkRuntimeException* savedException = stop1();
  361. if (state != ctkPlugin::UNINSTALLED)
  362. {
  363. state = ctkPlugin::RESOLVED;
  364. // TODO plugin threading
  365. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.STOPPED, this));
  366. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  367. operationLock.wakeAll();
  368. operation.fetchAndStoreOrdered(IDLE);
  369. }
  370. return savedException;
  371. }
  372. //----------------------------------------------------------------------------
  373. const ctkRuntimeException* ctkPluginPrivate::stop1()
  374. {
  375. const ctkRuntimeException* res = 0;
  376. //6:
  377. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, q_func()));
  378. //7:
  379. if (wasStarted && pluginActivator)
  380. {
  381. try
  382. {
  383. pluginActivator->stop(pluginContext.data());
  384. if (state != ctkPlugin::STOPPING)
  385. {
  386. if (state == ctkPlugin::UNINSTALLED)
  387. {
  388. return new ctkIllegalStateException("Plug-in is uninstalled");
  389. }
  390. else
  391. {
  392. return new ctkIllegalStateException("Plug-in changed state because of refresh during stop");
  393. }
  394. }
  395. }
  396. catch (const std::exception& e)
  397. {
  398. res = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  399. ctkPluginException::ACTIVATOR_ERROR, &e);
  400. }
  401. pluginActivator = 0;
  402. }
  403. if (operation.fetchAndAddOrdered(0) == DEACTIVATING)
  404. {
  405. // Call hooks after we've called PluginActivator::stop(), but before we've
  406. // cleared all resources
  407. if (pluginContext)
  408. {
  409. // TODO service listener hooks
  410. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  411. //8-10:
  412. removePluginResources();
  413. pluginContext->d_func()->invalidate();
  414. pluginContext.reset();
  415. }
  416. }
  417. // This would unload the shared library and delete the activator if
  418. // there are no dependencies. However, objects from the plug-in might
  419. // have been created via C-function symbol lookups. Hence we cannot
  420. // safely unload the DLL. Maybe implement a in-DLL counter later
  421. // (http://stackoverflow.com/questions/460809/c-dll-unloading-issue and
  422. // http://boost.2283326.n4.nabble.com/shared-ptr-A-smarter-smart-pointer-proposal-for-dynamic-libraries-td2649749.html).
  423. // The activator itself will be delete during program termination
  424. // (by the QPluginLoader instance).
  425. //pluginLoader.unload();
  426. return res;
  427. }
  428. //----------------------------------------------------------------------------
  429. void ctkPluginPrivate::update0(const QUrl& updateLocation, bool wasActive)
  430. {
  431. const bool wasResolved = state == ctkPlugin::RESOLVED;
  432. const int oldStartLevel = getStartLevel();
  433. ctkPluginArchive* newArchive = 0;
  434. operation.fetchAndStoreOrdered(UPDATING);
  435. try
  436. {
  437. // New plugin as stream supplied?
  438. QUrl updateUrl(updateLocation);
  439. if (updateUrl.isEmpty())
  440. {
  441. // Try Plugin-UpdateLocation
  442. QString update = archive != 0 ? archive->getAttribute(ctkPluginConstants::PLUGIN_UPDATELOCATION) : QString();
  443. if (update.isEmpty())
  444. {
  445. // Take original location
  446. updateUrl = location;
  447. }
  448. }
  449. if(updateUrl.scheme() != "file")
  450. {
  451. QString msg = "Unsupported update URL:";
  452. msg += updateUrl.toString();
  453. throw ctkPluginException(msg);
  454. }
  455. newArchive = fwCtx->storage->updatePluginArchive(archive, updateUrl, updateUrl.toLocalFile());
  456. //checkCertificates(newArchive);
  457. checkManifestHeaders();
  458. newArchive->setStartLevel(oldStartLevel);
  459. fwCtx->storage->replacePluginArchive(archive, newArchive);
  460. }
  461. catch (const std::exception& e)
  462. {
  463. if (newArchive != 0)
  464. {
  465. newArchive->purge();
  466. }
  467. operation.fetchAndStoreOrdered(IDLE);
  468. if (wasActive)
  469. {
  470. try
  471. {
  472. this->q_func().data()->start();
  473. }
  474. catch (const ctkPluginException& pe)
  475. {
  476. fwCtx->listeners.frameworkError(this->q_func(), e);
  477. }
  478. }
  479. try
  480. {
  481. const ctkPluginException& pe = dynamic_cast<const ctkPluginException&>(e);
  482. throw pe;
  483. }
  484. catch (std::bad_cast)
  485. {
  486. throw ctkPluginException("Failed to get update plugin",
  487. ctkPluginException::UNSPECIFIED, &e);
  488. }
  489. }
  490. bool purgeOld = false;
  491. // TODO: check if dependent plug-ins are started. If not, set purgeOld to true.
  492. // Activate new plug-in
  493. ctkPluginArchive* oldArchive = archive;
  494. archive = newArchive;
  495. cachedRawHeaders.clear();
  496. state = ctkPlugin::INSTALLED;
  497. // Purge old archive
  498. if (purgeOld)
  499. {
  500. //secure.purge(this, oldProtectionDomain);
  501. if (oldArchive != 0)
  502. {
  503. oldArchive->purge();
  504. }
  505. }
  506. // Broadcast events
  507. if (wasResolved)
  508. {
  509. // TODO: use plugin threading
  510. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
  511. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  512. }
  513. //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UPDATED, this));
  514. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UPDATED, this->q_func()));
  515. operation.fetchAndStoreOrdered(IDLE);
  516. // Restart plugin previously stopped in the operation
  517. if (wasActive)
  518. {
  519. try
  520. {
  521. this->q_func().data()->start();
  522. }
  523. catch (const ctkPluginException& pe)
  524. {
  525. fwCtx->listeners.frameworkError(this->q_func(), pe);
  526. }
  527. }
  528. }
  529. //----------------------------------------------------------------------------
  530. int ctkPluginPrivate::getStartLevel()
  531. {
  532. if (archive != 0)
  533. {
  534. return archive->getStartLevel();
  535. }
  536. else
  537. {
  538. return 0;
  539. }
  540. }
  541. //----------------------------------------------------------------------------
  542. void ctkPluginPrivate::waitOnOperation(LockObject* lock, const QString& src, bool longWait)
  543. {
  544. if (operation.fetchAndAddOrdered(0) != IDLE)
  545. {
  546. qint64 left = longWait ? 20000 : 500;
  547. QDateTime waitUntil = QDateTime::currentDateTime().addMSecs(left);
  548. do
  549. {
  550. lock->wait(left);
  551. if (operation.fetchAndAddOrdered(0) == IDLE)
  552. {
  553. return;
  554. }
  555. // TODO use Qt 4.7 QDateTime::msecsTo() API
  556. //left = QDateTime::currentDateTime().msecsTo(waitUntil);
  557. left = ctk::msecsTo(QDateTime::currentDateTime(), waitUntil);
  558. } while (left > 0);
  559. QString op;
  560. switch (operation.fetchAndAddOrdered(0))
  561. {
  562. case IDLE:
  563. // Should not happen!
  564. return;
  565. case ACTIVATING:
  566. op = "start";
  567. break;
  568. case DEACTIVATING:
  569. op = "stop";
  570. break;
  571. case RESOLVING:
  572. op = "resolve";
  573. break;
  574. case UNINSTALLING:
  575. op = "uninstall";
  576. break;
  577. case UNRESOLVING:
  578. op = "unresolve";
  579. break;
  580. case UPDATING:
  581. op = "update";
  582. break;
  583. default:
  584. op = "unknown operation";
  585. break;
  586. }
  587. throw ctkPluginException(src + " called during " + op + " of plug-in",
  588. ctkPluginException::STATECHANGE_ERROR);
  589. }
  590. }
  591. //----------------------------------------------------------------------------
  592. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  593. const QString& pattern, bool recurse) const
  594. {
  595. QStringList result;
  596. QStringList resources = archive->findResourcesPath(path);
  597. foreach(QString fp, resources)
  598. {
  599. QString lastComponentOfPath = fp.section('/', -1);
  600. bool isDirectory = fp.endsWith("/");
  601. if (!isDirectory &&
  602. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  603. {
  604. result << (path + fp);
  605. }
  606. if (isDirectory && recurse)
  607. {
  608. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  609. foreach (QString subResource, subResources)
  610. {
  611. result << (path + subResource);
  612. }
  613. }
  614. }
  615. return result;
  616. }
  617. //----------------------------------------------------------------------------
  618. void ctkPluginPrivate::startDependencies()
  619. {
  620. QListIterator<ctkRequirePlugin*> i(this->require);
  621. while (i.hasNext())
  622. {
  623. ctkRequirePlugin* pr = i.next();
  624. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  625. if (pl.isEmpty())
  626. {
  627. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  628. {
  629. // We should never get here, since the plugin can only be
  630. // started if all its dependencies could be resolved.
  631. throw ctkPluginException(
  632. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  633. arg(pr->name).arg(pr->pluginRange.toString()));
  634. }
  635. else
  636. {
  637. continue;
  638. }
  639. }
  640. // We take the first plugin in the list (highest version number)
  641. // Immediately start the dependencies (no lazy activation) but do not
  642. // change the autostart setting of the plugin.
  643. pl.front()->start(ctkPlugin::START_TRANSIENT);
  644. }
  645. }
  646. //----------------------------------------------------------------------------
  647. ctkPluginException* ctkPluginPrivate::start0()
  648. {
  649. ctkPluginException* res = 0;
  650. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  651. ctkPluginException::Type error_type = ctkPluginException::MANIFEST_ERROR;
  652. try {
  653. pluginLoader.load();
  654. if (!pluginLoader.isLoaded())
  655. {
  656. error_type = ctkPluginException::ACTIVATOR_ERROR;
  657. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  658. ctkPluginException::ACTIVATOR_ERROR);
  659. }
  660. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  661. if (!pluginActivator)
  662. {
  663. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  664. ctkPluginException::ACTIVATOR_ERROR);
  665. }
  666. pluginActivator->start(pluginContext.data());
  667. if (state != ctkPlugin::STARTING)
  668. {
  669. error_type = ctkPluginException::STATECHANGE_ERROR;
  670. if (ctkPlugin::UNINSTALLED == state)
  671. {
  672. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  673. }
  674. else
  675. {
  676. throw ctkPluginException("ctkPlugin changed state because of refresh during start()", ctkPluginException::STATECHANGE_ERROR);
  677. }
  678. }
  679. state = ctkPlugin::ACTIVE;
  680. }
  681. catch (const std::exception& e)
  682. {
  683. res = new ctkPluginException("ctkPlugin start failed", error_type, &e);
  684. }
  685. if (fwCtx->debug.lazy_activation)
  686. {
  687. qDebug() << "activating #" << id << "completed.";
  688. }
  689. if (res == 0)
  690. {
  691. //10:
  692. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  693. }
  694. else if (operation.fetchAndAddOrdered(0) == ACTIVATING)
  695. {
  696. // 8:
  697. state = ctkPlugin::STOPPING;
  698. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  699. removePluginResources();
  700. pluginContext->d_func()->invalidate();
  701. pluginContext.reset();
  702. state = ctkPlugin::RESOLVED;
  703. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  704. }
  705. return res;
  706. }
  707. //----------------------------------------------------------------------------
  708. void ctkPluginPrivate::removePluginResources()
  709. {
  710. // automatic disconnect due to Qt signal slot
  711. //fwCtx->listeners.removeAllListeners(this);
  712. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  713. QMutableListIterator<ctkServiceRegistration> i(srs);
  714. while (i.hasNext())
  715. {
  716. try
  717. {
  718. i.next().unregister();
  719. }
  720. catch (const std::logic_error& /*ignore*/)
  721. {
  722. // Someone has unregistered the service after stop completed.
  723. // This should not occur, but we don't want get stuck in
  724. // an illegal state so we catch it.
  725. }
  726. }
  727. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  728. QListIterator<ctkServiceRegistration> i2(s);
  729. while (i2.hasNext())
  730. {
  731. i2.next().getReference().d_func()->ungetService(q_func(), false);
  732. }
  733. }