ctkWorkflow.cpp 35 KB

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