ctkWorkflow.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QDebug>
  16. #include <QStateMachine>
  17. #include <QState>
  18. // CTK includes
  19. #include "ctkWorkflow.h"
  20. #include "ctkWorkflowStep.h"
  21. #include "ctkWorkflowStep_p.h"
  22. #include "ctkWorkflowTransitions.h"
  23. #include "ctkLogger.h"
  24. // STD includes
  25. #include <iostream>
  26. //--------------------------------------------------------------------------
  27. static ctkLogger logger("org.commontk.libs.core.ctkWorkflow");
  28. //--------------------------------------------------------------------------
  29. // --------------------------------------------------------------------------
  30. // ctkWorkflowPrivate methods
  31. // --------------------------------------------------------------------------
  32. ctkWorkflowPrivate::ctkWorkflowPrivate(ctkWorkflow& object)
  33. :q_ptr(&object)
  34. {
  35. this->InitialStep = 0;
  36. this->CurrentStep = 0;
  37. this->OriginStep = 0;
  38. this->DestinationStep = 0;
  39. this->GoToStep = 0;
  40. this->StartingStep = 0;
  41. this->TransitionToPreviousStartingStep = 0;
  42. // By default, go back to the origin step upon success of the goToStep(targetId) attempt.
  43. this->GoBackToOriginStepUponSuccess = true;
  44. this->ARTIFICIAL_BRANCH_ID_PREFIX = "ctkWorkflowArtificialBranchId_";
  45. }
  46. // --------------------------------------------------------------------------
  47. ctkWorkflowPrivate::~ctkWorkflowPrivate()
  48. {
  49. }
  50. // --------------------------------------------------------------------------
  51. bool ctkWorkflowPrivate::addStep(ctkWorkflowStep* step)
  52. {
  53. Q_Q(ctkWorkflow);
  54. Q_ASSERT(step);
  55. Q_ASSERT(!q->hasStep(step->id()));
  56. Q_ASSERT(!this->StateMachine->isRunning());
  57. if (!step->workflow())
  58. {
  59. step->setWorkflow(q);
  60. }
  61. if (step->workflow() != q)
  62. {
  63. // Check if steps are not already associated with a different workflow
  64. QString msg("addStep - step [%1] already associated with a different workfow !");
  65. logger.error(msg.arg(step->id()));
  66. return false;
  67. }
  68. if (!this->RegisteredSteps.contains(step))
  69. {
  70. this->RegisteredSteps << step;
  71. emit q->stepRegistered(step);
  72. }
  73. // Add the states, creating them if necessary
  74. this->StateMachine->addState(step->processingState());
  75. this->StateMachine->addState(step->validationState());
  76. // Update the map of steps to transitions and the <state,step> map
  77. this->StepToForwardAndBackwardStepMap.insert(step, new forwardAndBackwardSteps);
  78. this->StateToStepMap[step->processingState()] = step;
  79. this->StateToStepMap[step->validationState()] = step;
  80. // Setup the signal/slot that triggers the attempt to go to the next step
  81. QObject::connect(step->validationState(), SIGNAL(entered()),
  82. q, SLOT(attemptToGoToNextStep()));
  83. // Setup the signal/slot that triggers the evaluation of the validation results
  84. // after validate(const QString&) is called
  85. this->connect(
  86. step->ctkWorkflowStepQObject(), SIGNAL(validationComplete(bool,QString)),
  87. q, SLOT(evaluateValidationResults(bool,QString)));
  88. this->connect(
  89. step->ctkWorkflowStepQObject(), SIGNAL(onEntryComplete()),
  90. SLOT(processingAfterOnEntry()));
  91. this->connect(
  92. step->ctkWorkflowStepQObject(), SIGNAL(onExitComplete()),
  93. SLOT(processingAfterOnExit()));
  94. return true;
  95. }
  96. // --------------------------------------------------------------------------
  97. bool ctkWorkflowPrivate::hasDuplicateTransition(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  98. const ctkWorkflow::TransitionDirectionality directionality)
  99. {
  100. Q_Q(ctkWorkflow);
  101. Q_ASSERT(origin);
  102. Q_ASSERT(destination);
  103. Q_ASSERT(directionality == ctkWorkflow::Forward || ctkWorkflow::Backward);
  104. ctkWorkflowPrivate::StepListType stepList;
  105. ctkWorkflowStep* targetStep = 0;
  106. if (directionality == ctkWorkflow::Forward)
  107. {
  108. stepList = q->forwardSteps(origin);
  109. targetStep = destination;
  110. }
  111. else if (directionality == ctkWorkflow::Backward)
  112. {
  113. stepList = q->backwardSteps(destination);
  114. targetStep = origin;
  115. }
  116. foreach(ctkWorkflowStep * step, stepList)
  117. {
  118. if (step == targetStep)
  119. {
  120. return true;
  121. }
  122. }
  123. return false;
  124. }
  125. // --------------------------------------------------------------------------
  126. bool ctkWorkflowPrivate::hasTransitionWithSameBranchId(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  127. const QString& branchId,
  128. const ctkWorkflow::TransitionDirectionality directionality)
  129. {
  130. Q_ASSERT(origin);
  131. Q_ASSERT(destination);
  132. Q_ASSERT(directionality == ctkWorkflow::Forward || ctkWorkflow::Backward);
  133. Q_ASSERT(!branchId.isEmpty());
  134. QList<QString> branchIdList;
  135. if (directionality == ctkWorkflow::Forward)
  136. {
  137. branchIdList = this->forwardBranchIds(origin);
  138. }
  139. else if (directionality == ctkWorkflow::Backward)
  140. {
  141. branchIdList = this->backwardBranchIds(destination);
  142. }
  143. foreach(QString id, branchIdList)
  144. {
  145. if (QString::compare(id, branchId, Qt::CaseInsensitive) == 0)
  146. {
  147. return true;
  148. }
  149. }
  150. return false;
  151. }
  152. // --------------------------------------------------------------------------
  153. void ctkWorkflowPrivate::createTransitionToNextStep(ctkWorkflowStep* origin,
  154. ctkWorkflowStep* destination,
  155. const QString& branchId)
  156. {
  157. Q_Q(ctkWorkflow);
  158. Q_ASSERT(origin);
  159. Q_ASSERT(destination);
  160. Q_ASSERT(!q->hasTransition(origin, destination, branchId, ctkWorkflow::Forward));
  161. QString id;
  162. // create an artificial branchId if one is not given
  163. if (branchId.isEmpty())
  164. {
  165. id.setNum(this->numberOfForwardSteps(origin));
  166. id.prepend(this->ARTIFICIAL_BRANCH_ID_PREFIX);
  167. }
  168. else
  169. {
  170. id = branchId;
  171. }
  172. // Create the transition
  173. ctkWorkflowInterstepTransition* transition = new ctkWorkflowInterstepTransition(ctkWorkflowInterstepTransition::TransitionToNextStep, id);
  174. transition->setTargetState(destination->processingState());
  175. origin->validationState()->addTransition(transition);
  176. // Update the step to transitions map
  177. this->StepToForwardAndBackwardStepMap.value(origin)->appendForwardStep(destination, id);
  178. // Setup the signal/slot that shows and hides the steps' user interfaces
  179. // on transition to the next step
  180. QObject::connect(transition, SIGNAL(triggered()), q, SLOT(performTransitionBetweenSteps()));
  181. }
  182. // --------------------------------------------------------------------------
  183. void ctkWorkflowPrivate::createTransitionToPreviousStep(ctkWorkflowStep* origin,
  184. ctkWorkflowStep* destination,
  185. const QString& branchId)
  186. {
  187. Q_Q(ctkWorkflow);
  188. Q_ASSERT(origin);
  189. Q_ASSERT(destination);
  190. Q_ASSERT(!q->hasTransition(origin, destination, branchId, ctkWorkflow::Backward));
  191. QString id;
  192. // create an artificial branchId if one is not given
  193. if (branchId.isEmpty())
  194. {
  195. id.setNum(this->numberOfBackwardSteps(destination));
  196. id.prepend(this->ARTIFICIAL_BRANCH_ID_PREFIX);
  197. }
  198. else
  199. {
  200. id = branchId;
  201. }
  202. ctkWorkflowInterstepTransition* transition = new ctkWorkflowInterstepTransition(ctkWorkflowInterstepTransition::TransitionToPreviousStep, id);
  203. transition->setTargetState(origin->processingState());
  204. destination->processingState()->addTransition(transition);
  205. // Update the step to transitions map
  206. this->StepToForwardAndBackwardStepMap.value(destination)->appendBackwardStep(origin, id);
  207. // Setup the signal/slot that shows and hides the steps' user
  208. // interfaces on transition to the previous step
  209. QObject::connect(transition, SIGNAL(triggered()), q, SLOT(performTransitionBetweenSteps()));
  210. }
  211. // --------------------------------------------------------------------------
  212. void ctkWorkflowPrivate::createTransitionToPreviousStartingStep(ctkWorkflowStep* startingStep,
  213. ctkWorkflowStep* currentStep)
  214. {
  215. Q_Q(ctkWorkflow);
  216. Q_ASSERT(startingStep);
  217. Q_ASSERT(currentStep);
  218. if (!this->TransitionToPreviousStartingStep)
  219. {
  220. ctkWorkflowInterstepTransition* transition = new ctkWorkflowInterstepTransition(
  221. ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep);
  222. // Setup the signal/slot that shows and hides the steps' user interfaces
  223. // on transition to the previous step
  224. QObject::connect(transition, SIGNAL(triggered()), q, SLOT(performTransitionBetweenSteps()));
  225. this->TransitionToPreviousStartingStep = transition;
  226. }
  227. QState* currentState;
  228. // looping on the finish step
  229. if (startingStep == currentStep)
  230. {
  231. currentState = currentStep->validationState();
  232. }
  233. else
  234. {
  235. currentState = currentStep->processingState();
  236. }
  237. this->TransitionToPreviousStartingStep->setTargetState(startingStep->processingState());
  238. currentState->addTransition(this->TransitionToPreviousStartingStep);
  239. }
  240. // --------------------------------------------------------------------------
  241. ctkWorkflowStep* ctkWorkflowPrivate::stepFromId(const QString& id)const
  242. {
  243. foreach(ctkWorkflowStep* step, this->StepToForwardAndBackwardStepMap.keys())
  244. {
  245. Q_ASSERT(step);
  246. if (QString::compare(step->id(), id, Qt::CaseInsensitive) == 0)
  247. {
  248. return step;
  249. }
  250. }
  251. return 0;
  252. }
  253. // --------------------------------------------------------------------------
  254. QList<QString> ctkWorkflowPrivate::forwardBranchIds(ctkWorkflowStep* step)const
  255. {
  256. Q_ASSERT(step);
  257. return this->StepToForwardAndBackwardStepMap.value(step)->forwardBranchIds();
  258. }
  259. // --------------------------------------------------------------------------
  260. QList<QString> ctkWorkflowPrivate::backwardBranchIds(ctkWorkflowStep* step)const
  261. {
  262. Q_ASSERT(step);
  263. return this->StepToForwardAndBackwardStepMap.value(step)->backwardBranchIds();
  264. }
  265. //---------------------------------------------------------------------------
  266. void ctkWorkflowPrivate::validateInternal(ctkWorkflowStep* step)
  267. {
  268. Q_ASSERT(step);
  269. logger.debug(QString("validateInternal - validating input from %1").arg(step->name()));
  270. if (step->hasValidateCommand())
  271. {
  272. step->invokeValidateCommand(this->DesiredBranchId);
  273. }
  274. else
  275. {
  276. step->validate(this->DesiredBranchId);
  277. }
  278. }
  279. // --------------------------------------------------------------------------
  280. void ctkWorkflowPrivate::onEntryInternal(
  281. ctkWorkflowStep* step,
  282. ctkWorkflowStep* comingFrom,
  283. const ctkWorkflowInterstepTransition::InterstepTransitionType& transitionType)
  284. {
  285. Q_ASSERT(step);
  286. logger.debug(QString("onEntryInternal - entering input from %1").arg(step->name()));
  287. //Ensure we are transitioning between steps or starting the workflow
  288. Q_ASSERT(transitionType == ctkWorkflowInterstepTransition::TransitionToNextStep
  289. || transitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStep
  290. || transitionType == ctkWorkflowInterstepTransition::StartingWorkflow
  291. || transitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep);
  292. if (step->hasOnEntryCommand())
  293. {
  294. step->invokeOnEntryCommand(comingFrom, transitionType);
  295. }
  296. else
  297. {
  298. step->onEntry(comingFrom, transitionType);
  299. }
  300. }
  301. // --------------------------------------------------------------------------
  302. void ctkWorkflowPrivate::processingAfterOnEntry()
  303. {
  304. Q_Q(ctkWorkflow);
  305. logger.debug("processingAfterOnEntry");
  306. if (!this->DestinationStep)
  307. {
  308. logger.error("processingAfterOnEntry - Called processingAfterOnEntry without "
  309. "having set a destination step");
  310. return;
  311. }
  312. // Update the currentStep and previous step
  313. this->CurrentStep = this->DestinationStep;
  314. // Reset the pointers used internally for performing a transition
  315. this->OriginStep = 0;
  316. this->DestinationStep = 0;
  317. // // Reset the pointers used internally for performing a transition
  318. // // back to the starting step
  319. // if (d->TransitionToPreviousStartingStep)
  320. // {
  321. // std::cout << "TRANSITION TO PREVIOUS STARTING STEP EXISTS" << std::endl;
  322. // //d->TransitionToPreviousStartingStep->sourceState()->removeTransition(d->TransitionToPreviousStartingStep);
  323. // //std::cout << "removed" << std::endl;
  324. // // d->TransitionToPreviousStartingStep = 0;
  325. // //destination->processingState()->removeTransition(d->TransitionToPreviousStartingStep);
  326. // //delete d->TransitionToPreviousStartingStep;
  327. // // d->TransitionToPreviousStartingStep = 0;
  328. // std::cout << "here" << std::endl;
  329. // }
  330. // If we are trying to get to the finish step, then check if we are
  331. // finished.
  332. if (this->GoToStep)
  333. {
  334. if (this->CurrentStep == this->GoToStep)
  335. {
  336. q->goToStepSucceeded();
  337. }
  338. // if we're not finished, continue transitioning to the next step
  339. else
  340. {
  341. q->goForward();
  342. }
  343. }
  344. else
  345. {
  346. emit q->currentStepChanged(this->CurrentStep);
  347. }
  348. }
  349. // --------------------------------------------------------------------------
  350. void ctkWorkflowPrivate::onExitInternal(
  351. ctkWorkflowStep* step,
  352. ctkWorkflowStep* goingTo,
  353. const ctkWorkflowInterstepTransition::InterstepTransitionType& transitionType)
  354. {
  355. Q_ASSERT(step);
  356. logger.debug(QString("onExitInternal - exiting %1").arg(step->name()));
  357. // Ensure we are transitioning between steps or starting the workflow
  358. Q_ASSERT (transitionType == ctkWorkflowInterstepTransition::TransitionToNextStep ||
  359. transitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStep ||
  360. transitionType == ctkWorkflowInterstepTransition::StoppingWorkflow ||
  361. transitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep);
  362. if (step->hasOnExitCommand())
  363. {
  364. step->invokeOnExitCommand(goingTo, transitionType);
  365. }
  366. else
  367. {
  368. step->onExit(goingTo, transitionType);
  369. }
  370. }
  371. // --------------------------------------------------------------------------
  372. void ctkWorkflowPrivate::processingAfterOnExit()
  373. {
  374. // enter the destination step if we have one
  375. if (this->DestinationStep)
  376. {
  377. this->onEntryInternal(this->DestinationStep, this->OriginStep, this->TransitionType);
  378. }
  379. // reset the pointers used internally for performing a transition if we're done
  380. else
  381. {
  382. this->OriginStep = 0;
  383. this->DestinationStep = 0;
  384. // we've exited the CurrentStep and haven't gone into another step, so we no longer have a
  385. // currentStep.
  386. this->CurrentStep = 0;
  387. }
  388. }
  389. // --------------------------------------------------------------------------
  390. ctkWorkflowStep* ctkWorkflowPrivate::stepFromState(const QAbstractState* state)
  391. {
  392. if (state)
  393. {
  394. return this->StateToStepMap.value(state);
  395. }
  396. return 0;
  397. }
  398. // --------------------------------------------------------------------------
  399. int ctkWorkflowPrivate::numberOfForwardSteps(ctkWorkflowStep* step)
  400. {
  401. Q_Q(ctkWorkflow);
  402. return q->forwardSteps(step).length();
  403. }
  404. // --------------------------------------------------------------------------
  405. int ctkWorkflowPrivate::numberOfBackwardSteps(ctkWorkflowStep* step)
  406. {
  407. Q_Q(ctkWorkflow);
  408. return q->backwardSteps(step).length();
  409. }
  410. // --------------------------------------------------------------------------
  411. bool ctkWorkflowPrivate::pathExists(const QString& goalId, ctkWorkflowStep* origin)const
  412. {
  413. Q_Q(const ctkWorkflow);
  414. Q_ASSERT(!goalId.isEmpty());
  415. Q_ASSERT(this->CurrentStep);
  416. QString originId;
  417. if (origin)
  418. {
  419. originId = origin->id();
  420. }
  421. else
  422. {
  423. originId = this->CurrentStep->id();
  424. }
  425. // there exists a path from the origin to the goal if:
  426. // - there is a goal AND
  427. // - either:
  428. // - the origin is already the goal
  429. // - there is a path from at least one of the origin's successors to the goal
  430. return (q->hasStep(goalId)
  431. && ((QString::compare(goalId, originId, Qt::CaseInsensitive) == 0)
  432. || (q->canGoForward(origin)))); // <-- TODO insert logic here for looking at graph
  433. }
  434. // --------------------------------------------------------------------------
  435. bool ctkWorkflowPrivate::pathExistsFromNextStep(const QString& goalId, const QString& branchId)const
  436. {
  437. Q_ASSERT(!goalId.isEmpty());
  438. Q_ASSERT(!branchId.isEmpty());
  439. Q_ASSERT(this->CurrentStep);
  440. // return whether there exists a path from the the step that will be followed (given the branchId) to the goal
  441. ctkWorkflowStep* nextStep = this->StepToForwardAndBackwardStepMap.value(this->CurrentStep)->forwardStep(branchId);
  442. if (!nextStep)
  443. {
  444. return false;
  445. }
  446. else
  447. {
  448. return this->pathExists(goalId, nextStep);
  449. }
  450. }
  451. // --------------------------------------------------------------------------
  452. // ctkWorkflow methods
  453. // --------------------------------------------------------------------------
  454. ctkWorkflow::ctkWorkflow(QObject* _parent) : Superclass(_parent)
  455. , d_ptr(new ctkWorkflowPrivate(*this))
  456. {
  457. Q_D(ctkWorkflow);
  458. d->StateMachine = new QStateMachine(this);
  459. }
  460. // --------------------------------------------------------------------------
  461. ctkWorkflow::~ctkWorkflow()
  462. {
  463. Q_D(ctkWorkflow);
  464. if (d->StateMachine->isRunning())
  465. {
  466. d->StateMachine->stop();
  467. }
  468. // Clean registered step
  469. while (!d->RegisteredSteps.isEmpty())
  470. {
  471. ctkWorkflowStep * step = d->RegisteredSteps.takeFirst();
  472. if (!step->isWidgetType())
  473. {
  474. delete step;
  475. }
  476. }
  477. }
  478. // --------------------------------------------------------------------------
  479. bool ctkWorkflow::addTransition(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  480. const QString& branchId,
  481. const ctkWorkflow::TransitionDirectionality directionality)
  482. {
  483. Q_D(ctkWorkflow);
  484. if (d->StateMachine->isRunning())
  485. {
  486. logger.warn("addTransition - Cannot add a transition while the workflow is started !");
  487. return false;
  488. }
  489. // Set origin id if empty
  490. if (origin && origin->id().isEmpty())
  491. {
  492. origin->setId(QString("step%1").arg(d->StepToForwardAndBackwardStepMap.count()));
  493. }
  494. // cannot currently create a transition between two steps of the same id, which is equivalent to
  495. // adding a transition from a step to itself
  496. if (origin && destination && (QString::compare(origin->id(), destination->id(), Qt::CaseInsensitive) == 0))
  497. {
  498. logger.error("addTransition - Workflow does not currently support a transition"
  499. " from a step to itself. Use GoToStep instead !");
  500. return false;
  501. }
  502. // add the origin step if it doesn't exist in the workflow yet
  503. if (origin && !this->hasStep(origin->id()))
  504. {
  505. bool ok = d->addStep(origin);
  506. if (!ok)
  507. {
  508. return false;
  509. }
  510. }
  511. // Set destination id if empty
  512. if (destination && destination->id().isEmpty())
  513. {
  514. destination->setId(QString("step%1").arg(d->StepToForwardAndBackwardStepMap.count()));
  515. }
  516. // add the destination step if it doesn't exist in the workflow yet
  517. if (destination && !this->hasStep(destination->id()))
  518. {
  519. bool ok = d->addStep(destination);
  520. if (!ok)
  521. {
  522. return false;
  523. }
  524. }
  525. if (origin && destination)
  526. {
  527. // ensure we haven't already added a transition with the same origin, destination and directionality
  528. if (this->hasTransition(origin, destination, branchId, directionality))
  529. {
  530. logger.warn("addTransition - Cannot create a transition that matches a "
  531. "previously created transition");
  532. return false;
  533. }
  534. // create the forward transition
  535. if (directionality == ctkWorkflow::Forward
  536. || directionality == ctkWorkflow::Bidirectional)
  537. {
  538. //qDebug() << "addTransition" << origin->id() << "->" << destination->id();
  539. d->createTransitionToNextStep(origin, destination, branchId);
  540. }
  541. // create the backward transition
  542. if (directionality == ctkWorkflow::Backward
  543. || directionality == ctkWorkflow::Bidirectional)
  544. {
  545. //qDebug() << "addTransition" << origin->id() << "<-" << destination->id();
  546. d->createTransitionToPreviousStep(origin, destination, branchId);
  547. }
  548. }
  549. // Set initialStep if needed
  550. if (origin && d->StepToForwardAndBackwardStepMap.count() == 2 && !this->initialStep())
  551. {
  552. this->setInitialStep(origin);
  553. }
  554. return true;
  555. }
  556. // --------------------------------------------------------------------------
  557. bool ctkWorkflow::hasTransition(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  558. const QString& branchId,
  559. const ctkWorkflow::TransitionDirectionality directionality)
  560. {
  561. Q_D(ctkWorkflow);
  562. // we have a bidirectional transition if we have both a forward and a backward transition
  563. if (directionality == ctkWorkflow::Bidirectional)
  564. {
  565. return this->hasTransition(origin, destination, branchId, ctkWorkflow::Forward)
  566. && this->hasTransition(origin, destination, branchId, ctkWorkflow::Backward);
  567. }
  568. else
  569. {
  570. if (branchId.isEmpty())
  571. {
  572. return d->hasDuplicateTransition(origin, destination, directionality);
  573. }
  574. else
  575. {
  576. return d->hasDuplicateTransition(origin, destination, directionality)
  577. || d->hasTransitionWithSameBranchId(origin, destination, branchId, directionality);
  578. }
  579. }
  580. }
  581. // --------------------------------------------------------------------------
  582. QList<ctkWorkflowStep*> ctkWorkflow::forwardSteps(ctkWorkflowStep* step)const
  583. {
  584. Q_D(const ctkWorkflow);
  585. // use the given step if provided, otherwise use the workflow's current step
  586. if (step && d->StepToForwardAndBackwardStepMap.contains(step))
  587. {
  588. return d->StepToForwardAndBackwardStepMap.value(step)->forwardSteps();
  589. }
  590. else if (d->CurrentStep && d->StepToForwardAndBackwardStepMap.contains(d->CurrentStep))
  591. {
  592. return d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->forwardSteps();
  593. }
  594. else
  595. {
  596. return QList<ctkWorkflowStep*>();
  597. }
  598. }
  599. // --------------------------------------------------------------------------
  600. QList<ctkWorkflowStep*> ctkWorkflow::backwardSteps(ctkWorkflowStep* step)const
  601. {
  602. Q_D(const ctkWorkflow);
  603. // use the current step if provided, otherwise use the workflow's current step
  604. if (step && d->StepToForwardAndBackwardStepMap.contains(step))
  605. {
  606. return d->StepToForwardAndBackwardStepMap.value(step)->backwardSteps();
  607. }
  608. else if (d->CurrentStep && d->StepToForwardAndBackwardStepMap.contains(d->CurrentStep))
  609. {
  610. return d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->backwardSteps();
  611. }
  612. else
  613. {
  614. return QList<ctkWorkflowStep*>();
  615. }
  616. }
  617. // --------------------------------------------------------------------------
  618. QList<ctkWorkflowStep*> ctkWorkflow::finishSteps()const
  619. {
  620. Q_D(const ctkWorkflow);
  621. // iterate through our list of steps, and keep the steps that don't have anything following them
  622. QList<ctkWorkflowStep*> finishSteps;
  623. foreach (ctkWorkflowStep* step, d->StepToForwardAndBackwardStepMap.keys())
  624. {
  625. if (!this->canGoForward(step))
  626. {
  627. finishSteps.append(step);
  628. }
  629. }
  630. return finishSteps;
  631. }
  632. // --------------------------------------------------------------------------
  633. QList<ctkWorkflowStep*> ctkWorkflow::steps()const
  634. {
  635. Q_D(const ctkWorkflow);
  636. return d->RegisteredSteps;
  637. }
  638. // --------------------------------------------------------------------------
  639. bool ctkWorkflow::canGoForward(ctkWorkflowStep* step)const
  640. {
  641. return (!this->forwardSteps(step).isEmpty());
  642. }
  643. // --------------------------------------------------------------------------
  644. bool ctkWorkflow::canGoBackward(ctkWorkflowStep* step)const
  645. {
  646. return (!this->backwardSteps(step).isEmpty());
  647. }
  648. // --------------------------------------------------------------------------
  649. bool ctkWorkflow::canGoToStep(const QString& targetId, ctkWorkflowStep* step)const
  650. {
  651. Q_D(const ctkWorkflow);
  652. return d->pathExists(targetId, step);
  653. }
  654. // --------------------------------------------------------------------------
  655. bool ctkWorkflow::hasStep(const QString& id)const
  656. {
  657. Q_D(const ctkWorkflow);
  658. return d->stepFromId(id);
  659. }
  660. // --------------------------------------------------------------------------
  661. // Convenience method to set the QStateMachine's initialState to a
  662. // specific step's processing state.
  663. CTK_GET_CPP(ctkWorkflow, ctkWorkflowStep*, initialStep, InitialStep);
  664. CTK_SET_CPP(ctkWorkflow, ctkWorkflowStep*, setInitialStep, InitialStep);
  665. // --------------------------------------------------------------------------
  666. CTK_GET_CPP(ctkWorkflow, ctkWorkflowStep*, currentStep, CurrentStep);
  667. // --------------------------------------------------------------------------
  668. void ctkWorkflow::start()
  669. {
  670. Q_D(ctkWorkflow);
  671. if (!d->InitialStep)
  672. {
  673. logger.warn("start - Cannot start workflow without an initial step");
  674. return;
  675. }
  676. // Setup to do the entry processing for the initial setp
  677. d->StateMachine->setInitialState(d->InitialStep->processingState());
  678. d->OriginStep = 0;
  679. d->DestinationStep = d->InitialStep;
  680. d->TransitionType = ctkWorkflowInterstepTransition::StartingWorkflow;
  681. d->onEntryInternal(d->DestinationStep, d->OriginStep, d->TransitionType);
  682. d->StateMachine->start();
  683. }
  684. // --------------------------------------------------------------------------
  685. bool ctkWorkflow::isRunning()const
  686. {
  687. Q_D(const ctkWorkflow);
  688. return d->StateMachine->isRunning();
  689. }
  690. // --------------------------------------------------------------------------
  691. void ctkWorkflow::stop()
  692. {
  693. Q_D(ctkWorkflow);
  694. if (!d->StateMachine->isRunning())
  695. {
  696. return;
  697. }
  698. // Setup to do the exit processing for the current step
  699. if (d->CurrentStep)
  700. {
  701. d->OriginStep = d->CurrentStep;
  702. d->DestinationStep = 0;
  703. d->TransitionType = ctkWorkflowInterstepTransition::StoppingWorkflow;
  704. d->onExitInternal(d->OriginStep, d->DestinationStep, d->TransitionType);
  705. }
  706. d->StateMachine->stop();
  707. }
  708. // --------------------------------------------------------------------------
  709. void ctkWorkflow::goForward(const QString& desiredBranchId)
  710. {
  711. Q_D(ctkWorkflow);
  712. if (!this->isRunning())
  713. {
  714. logger.warn("goForward - The workflow is not running !");
  715. return;
  716. }
  717. // if we're just going to the next step and not to a 'goTo' step, then check to make sure that
  718. // there exists a step following the current step
  719. if (!d->GoToStep)
  720. {
  721. if (!this->canGoForward())
  722. {
  723. logger.warn("goForward - Attempt to goForward from a finish step !");
  724. return;
  725. }
  726. }
  727. d->DesiredBranchId = desiredBranchId;
  728. logger.info("goForward - posting ValidationTransition");
  729. d->StateMachine->postEvent(
  730. new ctkWorkflowIntrastepTransitionEvent(ctkWorkflowIntrastepTransition::ValidationTransition));
  731. }
  732. // --------------------------------------------------------------------------
  733. void ctkWorkflow::goBackward(const QString& desiredBranchId)
  734. {
  735. Q_D(ctkWorkflow);
  736. if (!this->isRunning())
  737. {
  738. logger.warn("goBackward - The workflow is not running !");
  739. return;
  740. }
  741. if (!this->canGoBackward())
  742. {
  743. logger.warn("goBackward - Attempt to goBackward from first step !");
  744. return;
  745. }
  746. ctkWorkflowStep* previousStep = d->StepToPreviousStepMap[d->CurrentStep];
  747. Q_ASSERT(previousStep);
  748. QString branchId = d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->backwardBranchId(previousStep);
  749. Q_ASSERT(!branchId.isEmpty());
  750. d->DesiredBranchId = desiredBranchId;
  751. logger.info("goBackward - posting TransitionToPreviousStep");
  752. d->StateMachine->postEvent(
  753. new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToPreviousStep, branchId));
  754. }
  755. // --------------------------------------------------------------------------
  756. CTK_GET_CPP(ctkWorkflow, bool, goBackToOriginStepUponSuccess, GoBackToOriginStepUponSuccess);
  757. CTK_SET_CPP(ctkWorkflow, bool, setGoBackToOriginStepUponSuccess, GoBackToOriginStepUponSuccess);
  758. // --------------------------------------------------------------------------
  759. void ctkWorkflow::goToStep(const QString& targetId)
  760. {
  761. Q_D(ctkWorkflow);
  762. if (!this->isRunning())
  763. {
  764. logger.warn("goToStep - The workflow is not running !");
  765. return;
  766. }
  767. // TODO currently returns true only if the workflow is running - need logic here
  768. if (!this->canGoToStep(targetId))
  769. {
  770. logger.warn(QString("goToStep - Cannot goToStep %1 ").arg(targetId));
  771. return;
  772. }
  773. #ifndef QT_NO_DEBUG
  774. ctkWorkflowStep* step = d->stepFromId(targetId);
  775. Q_ASSERT(step);
  776. #endif
  777. logger.info(QString("goToStep - Attempting to go to finish step %1").arg(targetId));
  778. // if (step == d->CurrentStep)
  779. // {
  780. // qDebug() << "we are already in the desired finish step";
  781. // return;
  782. // }
  783. d->GoToStep = d->stepFromId(targetId);
  784. d->StartingStep = d->CurrentStep;
  785. this->goForward();
  786. }
  787. // --------------------------------------------------------------------------
  788. void ctkWorkflow::attemptToGoToNextStep()
  789. {
  790. logger.info("attemptToGoToNextStep - Attempting to go to the next step ");
  791. Q_D(ctkWorkflow);
  792. Q_ASSERT(d->CurrentStep);
  793. //Q_ASSERT(this->canGoForward(d->CurrentStep));
  794. d->validateInternal(d->CurrentStep);
  795. }
  796. // --------------------------------------------------------------------------
  797. void ctkWorkflow::evaluateValidationResults(bool validationSucceeded, const QString& branchId)
  798. {
  799. if (validationSucceeded)
  800. {
  801. this->goToNextStepAfterSuccessfulValidation(branchId);
  802. }
  803. else
  804. {
  805. this->goToProcessingStateAfterValidationFailed();
  806. }
  807. }
  808. // --------------------------------------------------------------------------
  809. // if ctkWorkflowStep::validationComplete() did not provide a branchId, then:
  810. // - if there is one step following the current step, we will follow that transition
  811. // - if there are multiple steps following the current step, then we will follow the first
  812. // transition that was added
  813. // (either way this corresponds to following the first forwardBranchId we've recorded)
  814. // if ctkWorkflowStep::validationComplete() provided a branchId, then:
  815. // - if there is one transition following the current step that was not created using a branchId,
  816. // then we will follow it
  817. // - otherwise do a conditional branching based on the branchId provided by validationComplete()
  818. void ctkWorkflow::goToNextStepAfterSuccessfulValidation(const QString& branchId)
  819. {
  820. Q_D(ctkWorkflow);
  821. logger.debug("goToNextStepAfterSuccessfulValidation - Calidation succeeded");
  822. logger.info("goToNextStepAfterSuccessfulValidation - Posting TransitionToNextStep");
  823. // we may already be in the 'goTo' step - i.e. looping on a finish step
  824. if (d->GoToStep && d->CurrentStep == d->GoToStep)
  825. {
  826. this->goToStepSucceeded();
  827. return;
  828. }
  829. QString transitionBranchId;
  830. // these values are helpful for the logic below
  831. QString firstForwardBranchId = d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->firstForwardBranchId();
  832. int numberOfForwardSteps = d->numberOfForwardSteps(d->CurrentStep);
  833. Q_ASSERT(!firstForwardBranchId.isEmpty());
  834. Q_ASSERT(numberOfForwardSteps);
  835. // validationComplete() does not give us a branchId
  836. if (branchId.isEmpty())
  837. {
  838. transitionBranchId = firstForwardBranchId;
  839. if (numberOfForwardSteps > 1)
  840. {
  841. logger.warn("goToNextStepAfterSuccessfulValidation - ctkWorkflowStep::ValidatComplete() "
  842. "did not provide branchId at a branch in the workflow - will follow first "
  843. "transition that was created");
  844. }
  845. }
  846. // validationComplete() gives us a branchId
  847. else
  848. {
  849. if (numberOfForwardSteps == 1 && firstForwardBranchId.contains(d->ARTIFICIAL_BRANCH_ID_PREFIX))
  850. {
  851. transitionBranchId = firstForwardBranchId;
  852. logger.warn("goToNextStepAfterSuccessfulValidation - ctkWorkflowStep::ValidationComplete()"
  853. " returns a branchId, but was overridden by the workflow");
  854. }
  855. else
  856. {
  857. transitionBranchId = branchId;
  858. }
  859. }
  860. // if we are trying to go to a 'goTo' step, check that the selected branch will still take us along a path that leads to the 'goTo' step, and fail if not
  861. if (d->GoToStep && !d->pathExistsFromNextStep(d->GoToStep->id(), transitionBranchId))
  862. {
  863. this->goToProcessingStateAfterValidationFailed();
  864. return;
  865. }
  866. d->StateMachine->postEvent(new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToNextStep, transitionBranchId));
  867. }
  868. // --------------------------------------------------------------------------
  869. void ctkWorkflow::goToProcessingStateAfterValidationFailed()
  870. {
  871. logger.debug("goToNextStepAfterSuccessfulValidation - Validation failed");
  872. Q_D(ctkWorkflow);
  873. // Validation failed in the process of attempting to go to the finish step
  874. if (d->GoToStep)
  875. {
  876. this->goToStepFailed();
  877. }
  878. logger.info("goToNextStepAfterSuccessfulValidation - Posting ValidationFailedTransition");
  879. d->StateMachine->postEvent(new ctkWorkflowIntrastepTransitionEvent(ctkWorkflowIntrastepTransition::ValidationFailedTransition));
  880. }
  881. // --------------------------------------------------------------------------
  882. void ctkWorkflow::performTransitionBetweenSteps()
  883. {
  884. Q_D(ctkWorkflow);
  885. logger.debug("performTransitionBetweenSteps - Performing transition between steps");
  886. // Alternative: could find the origin and destination step based on
  887. // d->CurrentStep rather than QObject::sender(), but would require
  888. // keeping track of an origin step's destination step (and would be
  889. // tricky in an extension to branching workflows, unless we change
  890. // this method signature)
  891. ctkWorkflowInterstepTransition* transition = qobject_cast<ctkWorkflowInterstepTransition*>(QObject::sender());
  892. Q_ASSERT(transition);
  893. d->OriginStep = d->stepFromState(transition->sourceState());
  894. d->DestinationStep = d->stepFromState(transition->targetState());
  895. d->TransitionType = transition->transitionType();
  896. Q_ASSERT(d->TransitionType == ctkWorkflowInterstepTransition::TransitionToNextStep
  897. || d->TransitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStep
  898. || d->TransitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep);
  899. // update the map from the step to the previous step if we are going forward
  900. if (d->TransitionType == ctkWorkflowInterstepTransition::TransitionToNextStep)
  901. {
  902. d->StepToPreviousStepMap.insert(d->DestinationStep, d->OriginStep);
  903. }
  904. // exit the destination step
  905. d->onExitInternal(d->OriginStep, d->DestinationStep, d->TransitionType);
  906. }
  907. // --------------------------------------------------------------------------
  908. void ctkWorkflow::goToStepSucceeded()
  909. {
  910. Q_D(ctkWorkflow);
  911. logger.debug("goToStepSucceeded");
  912. // after success, go back to the step at which we begin looking for
  913. // the finish step (will exit the current step and enter the starting step)
  914. // only if the property goBackToOriginStepUponSuccess is true.
  915. if (this->goBackToOriginStepUponSuccess())
  916. {
  917. d->createTransitionToPreviousStartingStep(d->StartingStep, d->CurrentStep);
  918. }
  919. d->GoToStep = 0;
  920. d->StartingStep->setStatusText("Attempt to go to the finish step succeeded");
  921. d->StartingStep = 0;
  922. if (this->goBackToOriginStepUponSuccess())
  923. {
  924. this->goFromGoToStepToStartingStep();
  925. }
  926. }
  927. // --------------------------------------------------------------------------
  928. void ctkWorkflow::goFromGoToStepToStartingStep()
  929. {
  930. Q_D(ctkWorkflow);
  931. logger.info("goFromGoToStepToStartingStep - Posting TransitionToPreviousStartingStep");
  932. d->StateMachine->postEvent(new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep));
  933. }
  934. // --------------------------------------------------------------------------
  935. void ctkWorkflow::goToStepFailed()
  936. {
  937. // Abort attempt to get to the finish step
  938. Q_D(ctkWorkflow);
  939. d->GoToStep = 0;
  940. d->StartingStep = 0;
  941. // We don't need to transition between steps - leave the user at the
  942. // point of failure, so that they can try to continue manually
  943. // Emit the signal that we have changed the current step, since it wasn't emitted in the process
  944. // of going to the 'goTo' step.
  945. emit this->currentStepChanged(d->CurrentStep);
  946. // if (failedOnBranch)
  947. // {
  948. // this->goToProcessingStateAfterValidationFailed();
  949. // }
  950. }