ctkWorkflow.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. delete d->RegisteredSteps.takeFirst();
  472. }
  473. }
  474. // --------------------------------------------------------------------------
  475. bool ctkWorkflow::addTransition(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  476. const QString& branchId,
  477. const ctkWorkflow::TransitionDirectionality directionality)
  478. {
  479. Q_D(ctkWorkflow);
  480. if (d->StateMachine->isRunning())
  481. {
  482. logger.warn("addTransition - Cannot add a transition while the workflow is started !");
  483. return false;
  484. }
  485. // Set origin id if empty
  486. if (origin && origin->id().isEmpty())
  487. {
  488. origin->setId(QString("step%1").arg(d->StepToForwardAndBackwardStepMap.count()));
  489. }
  490. // cannot currently create a transition between two steps of the same id, which is equivalent to
  491. // adding a transition from a step to itself
  492. if (origin && destination && (QString::compare(origin->id(), destination->id(), Qt::CaseInsensitive) == 0))
  493. {
  494. logger.error("addTransition - Workflow does not currently support a transition"
  495. " from a step to itself. Use GoToStep instead !");
  496. return false;
  497. }
  498. // add the origin step if it doesn't exist in the workflow yet
  499. if (origin && !this->hasStep(origin->id()))
  500. {
  501. bool ok = d->addStep(origin);
  502. if (!ok)
  503. {
  504. return false;
  505. }
  506. }
  507. // Set destination id if empty
  508. if (destination && destination->id().isEmpty())
  509. {
  510. destination->setId(QString("step%1").arg(d->StepToForwardAndBackwardStepMap.count()));
  511. }
  512. // add the destination step if it doesn't exist in the workflow yet
  513. if (destination && !this->hasStep(destination->id()))
  514. {
  515. bool ok = d->addStep(destination);
  516. if (!ok)
  517. {
  518. return false;
  519. }
  520. }
  521. if (origin && destination)
  522. {
  523. // ensure we haven't already added a transition with the same origin, destination and directionality
  524. if (this->hasTransition(origin, destination, branchId, directionality))
  525. {
  526. logger.warn("addTransition - Cannot create a transition that matches a "
  527. "previously created transition");
  528. return false;
  529. }
  530. // create the forward transition
  531. if (directionality == ctkWorkflow::Forward
  532. || directionality == ctkWorkflow::Bidirectional)
  533. {
  534. //qDebug() << "addTransition" << origin->id() << "->" << destination->id();
  535. d->createTransitionToNextStep(origin, destination, branchId);
  536. }
  537. // create the backward transition
  538. if (directionality == ctkWorkflow::Backward
  539. || directionality == ctkWorkflow::Bidirectional)
  540. {
  541. //qDebug() << "addTransition" << origin->id() << "<-" << destination->id();
  542. d->createTransitionToPreviousStep(origin, destination, branchId);
  543. }
  544. }
  545. // Set initialStep if needed
  546. if (origin && d->StepToForwardAndBackwardStepMap.count() == 2 && !this->initialStep())
  547. {
  548. this->setInitialStep(origin);
  549. }
  550. return true;
  551. }
  552. // --------------------------------------------------------------------------
  553. bool ctkWorkflow::hasTransition(ctkWorkflowStep* origin, ctkWorkflowStep* destination,
  554. const QString& branchId,
  555. const ctkWorkflow::TransitionDirectionality directionality)
  556. {
  557. Q_D(ctkWorkflow);
  558. // we have a bidirectional transition if we have both a forward and a backward transition
  559. if (directionality == ctkWorkflow::Bidirectional)
  560. {
  561. return this->hasTransition(origin, destination, branchId, ctkWorkflow::Forward)
  562. && this->hasTransition(origin, destination, branchId, ctkWorkflow::Backward);
  563. }
  564. else
  565. {
  566. if (branchId.isEmpty())
  567. {
  568. return d->hasDuplicateTransition(origin, destination, directionality);
  569. }
  570. else
  571. {
  572. return d->hasDuplicateTransition(origin, destination, directionality)
  573. || d->hasTransitionWithSameBranchId(origin, destination, branchId, directionality);
  574. }
  575. }
  576. }
  577. // --------------------------------------------------------------------------
  578. QList<ctkWorkflowStep*> ctkWorkflow::forwardSteps(ctkWorkflowStep* step)const
  579. {
  580. Q_D(const ctkWorkflow);
  581. // use the given step if provided, otherwise use the workflow's current step
  582. if (step && d->StepToForwardAndBackwardStepMap.contains(step))
  583. {
  584. return d->StepToForwardAndBackwardStepMap.value(step)->forwardSteps();
  585. }
  586. else if (d->CurrentStep && d->StepToForwardAndBackwardStepMap.contains(d->CurrentStep))
  587. {
  588. return d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->forwardSteps();
  589. }
  590. else
  591. {
  592. return QList<ctkWorkflowStep*>();
  593. }
  594. }
  595. // --------------------------------------------------------------------------
  596. QList<ctkWorkflowStep*> ctkWorkflow::backwardSteps(ctkWorkflowStep* step)const
  597. {
  598. Q_D(const ctkWorkflow);
  599. // use the current step if provided, otherwise use the workflow's current step
  600. if (step && d->StepToForwardAndBackwardStepMap.contains(step))
  601. {
  602. return d->StepToForwardAndBackwardStepMap.value(step)->backwardSteps();
  603. }
  604. else if (d->CurrentStep && d->StepToForwardAndBackwardStepMap.contains(d->CurrentStep))
  605. {
  606. return d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->backwardSteps();
  607. }
  608. else
  609. {
  610. return QList<ctkWorkflowStep*>();
  611. }
  612. }
  613. // --------------------------------------------------------------------------
  614. QList<ctkWorkflowStep*> ctkWorkflow::finishSteps()const
  615. {
  616. Q_D(const ctkWorkflow);
  617. // iterate through our list of steps, and keep the steps that don't have anything following them
  618. QList<ctkWorkflowStep*> finishSteps;
  619. foreach (ctkWorkflowStep* step, d->StepToForwardAndBackwardStepMap.keys())
  620. {
  621. if (!this->canGoForward(step))
  622. {
  623. finishSteps.append(step);
  624. }
  625. }
  626. return finishSteps;
  627. }
  628. // --------------------------------------------------------------------------
  629. QList<ctkWorkflowStep*> ctkWorkflow::steps()const
  630. {
  631. Q_D(const ctkWorkflow);
  632. return d->RegisteredSteps;
  633. }
  634. // --------------------------------------------------------------------------
  635. bool ctkWorkflow::canGoForward(ctkWorkflowStep* step)const
  636. {
  637. return (!this->forwardSteps(step).isEmpty());
  638. }
  639. // --------------------------------------------------------------------------
  640. bool ctkWorkflow::canGoBackward(ctkWorkflowStep* step)const
  641. {
  642. return (!this->backwardSteps(step).isEmpty());
  643. }
  644. // --------------------------------------------------------------------------
  645. bool ctkWorkflow::canGoToStep(const QString& targetId, ctkWorkflowStep* step)const
  646. {
  647. Q_D(const ctkWorkflow);
  648. return d->pathExists(targetId, step);
  649. }
  650. // --------------------------------------------------------------------------
  651. bool ctkWorkflow::hasStep(const QString& id)const
  652. {
  653. Q_D(const ctkWorkflow);
  654. return d->stepFromId(id);
  655. }
  656. // --------------------------------------------------------------------------
  657. // Convenience method to set the QStateMachine's initialState to a
  658. // specific step's processing state.
  659. CTK_GET_CPP(ctkWorkflow, ctkWorkflowStep*, initialStep, InitialStep);
  660. CTK_SET_CPP(ctkWorkflow, ctkWorkflowStep*, setInitialStep, InitialStep);
  661. // --------------------------------------------------------------------------
  662. CTK_GET_CPP(ctkWorkflow, ctkWorkflowStep*, currentStep, CurrentStep);
  663. // --------------------------------------------------------------------------
  664. void ctkWorkflow::start()
  665. {
  666. Q_D(ctkWorkflow);
  667. if (!d->InitialStep)
  668. {
  669. logger.warn("start - Cannot start workflow without an initial step");
  670. return;
  671. }
  672. // Setup to do the entry processing for the initial setp
  673. d->StateMachine->setInitialState(d->InitialStep->processingState());
  674. d->OriginStep = 0;
  675. d->DestinationStep = d->InitialStep;
  676. d->TransitionType = ctkWorkflowInterstepTransition::StartingWorkflow;
  677. d->onEntryInternal(d->DestinationStep, d->OriginStep, d->TransitionType);
  678. d->StateMachine->start();
  679. }
  680. // --------------------------------------------------------------------------
  681. bool ctkWorkflow::isRunning()const
  682. {
  683. Q_D(const ctkWorkflow);
  684. return d->StateMachine->isRunning();
  685. }
  686. // --------------------------------------------------------------------------
  687. void ctkWorkflow::stop()
  688. {
  689. Q_D(ctkWorkflow);
  690. if (!d->StateMachine->isRunning())
  691. {
  692. return;
  693. }
  694. // Setup to do the exit processing for the current step
  695. if (d->CurrentStep)
  696. {
  697. d->OriginStep = d->CurrentStep;
  698. d->DestinationStep = 0;
  699. d->TransitionType = ctkWorkflowInterstepTransition::StoppingWorkflow;
  700. d->onExitInternal(d->OriginStep, d->DestinationStep, d->TransitionType);
  701. }
  702. d->StateMachine->stop();
  703. }
  704. // --------------------------------------------------------------------------
  705. void ctkWorkflow::goForward(const QString& desiredBranchId)
  706. {
  707. Q_D(ctkWorkflow);
  708. if (!this->isRunning())
  709. {
  710. logger.warn("goForward - The workflow is not running !");
  711. return;
  712. }
  713. // if we're just going to the next step and not to a 'goTo' step, then check to make sure that
  714. // there exists a step following the current step
  715. if (!d->GoToStep)
  716. {
  717. if (!this->canGoForward())
  718. {
  719. logger.warn("goForward - Attempt to goForward from a finish step !");
  720. return;
  721. }
  722. }
  723. d->DesiredBranchId = desiredBranchId;
  724. logger.info("goForward - posting ValidationTransition");
  725. d->StateMachine->postEvent(
  726. new ctkWorkflowIntrastepTransitionEvent(ctkWorkflowIntrastepTransition::ValidationTransition));
  727. }
  728. // --------------------------------------------------------------------------
  729. void ctkWorkflow::goBackward(const QString& desiredBranchId)
  730. {
  731. Q_D(ctkWorkflow);
  732. if (!this->isRunning())
  733. {
  734. logger.warn("goBackward - The workflow is not running !");
  735. return;
  736. }
  737. if (!this->canGoBackward())
  738. {
  739. logger.warn("goBackward - Attempt to goBackward from first step !");
  740. return;
  741. }
  742. ctkWorkflowStep* previousStep = d->StepToPreviousStepMap[d->CurrentStep];
  743. Q_ASSERT(previousStep);
  744. QString branchId = d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->backwardBranchId(previousStep);
  745. Q_ASSERT(!branchId.isEmpty());
  746. d->DesiredBranchId = desiredBranchId;
  747. logger.info("goBackward - posting TransitionToPreviousStep");
  748. d->StateMachine->postEvent(
  749. new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToPreviousStep, branchId));
  750. }
  751. // --------------------------------------------------------------------------
  752. CTK_GET_CPP(ctkWorkflow, bool, goBackToOriginStepUponSuccess, GoBackToOriginStepUponSuccess);
  753. CTK_SET_CPP(ctkWorkflow, bool, setGoBackToOriginStepUponSuccess, GoBackToOriginStepUponSuccess);
  754. // --------------------------------------------------------------------------
  755. void ctkWorkflow::goToStep(const QString& targetId)
  756. {
  757. Q_D(ctkWorkflow);
  758. if (!this->isRunning())
  759. {
  760. logger.warn("goToStep - The workflow is not running !");
  761. return;
  762. }
  763. // TODO currently returns true only if the workflow is running - need logic here
  764. if (!this->canGoToStep(targetId))
  765. {
  766. logger.warn(QString("goToStep - Cannot goToStep %1 ").arg(targetId));
  767. return;
  768. }
  769. #ifndef QT_NO_DEBUG
  770. ctkWorkflowStep* step = d->stepFromId(targetId);
  771. Q_ASSERT(step);
  772. #endif
  773. logger.info(QString("goToStep - Attempting to go to finish step %1").arg(targetId));
  774. // if (step == d->CurrentStep)
  775. // {
  776. // qDebug() << "we are already in the desired finish step";
  777. // return;
  778. // }
  779. d->GoToStep = d->stepFromId(targetId);
  780. d->StartingStep = d->CurrentStep;
  781. this->goForward();
  782. }
  783. // --------------------------------------------------------------------------
  784. void ctkWorkflow::attemptToGoToNextStep()
  785. {
  786. logger.info("attemptToGoToNextStep - Attempting to go to the next step ");
  787. Q_D(ctkWorkflow);
  788. Q_ASSERT(d->CurrentStep);
  789. //Q_ASSERT(this->canGoForward(d->CurrentStep));
  790. d->validateInternal(d->CurrentStep);
  791. }
  792. // --------------------------------------------------------------------------
  793. void ctkWorkflow::evaluateValidationResults(bool validationSucceeded, const QString& branchId)
  794. {
  795. if (validationSucceeded)
  796. {
  797. this->goToNextStepAfterSuccessfulValidation(branchId);
  798. }
  799. else
  800. {
  801. this->goToProcessingStateAfterValidationFailed();
  802. }
  803. }
  804. // --------------------------------------------------------------------------
  805. // if ctkWorkflowStep::validationComplete() did not provide a branchId, then:
  806. // - if there is one step following the current step, we will follow that transition
  807. // - if there are multiple steps following the current step, then we will follow the first
  808. // transition that was added
  809. // (either way this corresponds to following the first forwardBranchId we've recorded)
  810. // if ctkWorkflowStep::validationComplete() provided a branchId, then:
  811. // - if there is one transition following the current step that was not created using a branchId,
  812. // then we will follow it
  813. // - otherwise do a conditional branching based on the branchId provided by validationComplete()
  814. void ctkWorkflow::goToNextStepAfterSuccessfulValidation(const QString& branchId)
  815. {
  816. Q_D(ctkWorkflow);
  817. logger.debug("goToNextStepAfterSuccessfulValidation - Calidation succeeded");
  818. logger.info("goToNextStepAfterSuccessfulValidation - Posting TransitionToNextStep");
  819. // we may already be in the 'goTo' step - i.e. looping on a finish step
  820. if (d->GoToStep && d->CurrentStep == d->GoToStep)
  821. {
  822. this->goToStepSucceeded();
  823. return;
  824. }
  825. QString transitionBranchId;
  826. // these values are helpful for the logic below
  827. QString firstForwardBranchId = d->StepToForwardAndBackwardStepMap.value(d->CurrentStep)->firstForwardBranchId();
  828. int numberOfForwardSteps = d->numberOfForwardSteps(d->CurrentStep);
  829. Q_ASSERT(!firstForwardBranchId.isEmpty());
  830. Q_ASSERT(numberOfForwardSteps);
  831. // validationComplete() does not give us a branchId
  832. if (branchId.isEmpty())
  833. {
  834. transitionBranchId = firstForwardBranchId;
  835. if (numberOfForwardSteps > 1)
  836. {
  837. logger.warn("goToNextStepAfterSuccessfulValidation - ctkWorkflowStep::ValidatComplete() "
  838. "did not provide branchId at a branch in the workflow - will follow first "
  839. "transition that was created");
  840. }
  841. }
  842. // validationComplete() gives us a branchId
  843. else
  844. {
  845. if (numberOfForwardSteps == 1 && firstForwardBranchId.contains(d->ARTIFICIAL_BRANCH_ID_PREFIX))
  846. {
  847. transitionBranchId = firstForwardBranchId;
  848. logger.warn("goToNextStepAfterSuccessfulValidation - ctkWorkflowStep::ValidationComplete()"
  849. " returns a branchId, but was overridden by the workflow");
  850. }
  851. else
  852. {
  853. transitionBranchId = branchId;
  854. }
  855. }
  856. // 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
  857. if (d->GoToStep && !d->pathExistsFromNextStep(d->GoToStep->id(), transitionBranchId))
  858. {
  859. this->goToProcessingStateAfterValidationFailed();
  860. return;
  861. }
  862. d->StateMachine->postEvent(new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToNextStep, transitionBranchId));
  863. }
  864. // --------------------------------------------------------------------------
  865. void ctkWorkflow::goToProcessingStateAfterValidationFailed()
  866. {
  867. logger.debug("goToNextStepAfterSuccessfulValidation - Validation failed");
  868. Q_D(ctkWorkflow);
  869. // Validation failed in the process of attempting to go to the finish step
  870. if (d->GoToStep)
  871. {
  872. this->goToStepFailed();
  873. }
  874. logger.info("goToNextStepAfterSuccessfulValidation - Posting ValidationFailedTransition");
  875. d->StateMachine->postEvent(new ctkWorkflowIntrastepTransitionEvent(ctkWorkflowIntrastepTransition::ValidationFailedTransition));
  876. }
  877. // --------------------------------------------------------------------------
  878. void ctkWorkflow::performTransitionBetweenSteps()
  879. {
  880. Q_D(ctkWorkflow);
  881. logger.debug("performTransitionBetweenSteps - Performing transition between steps");
  882. // Alternative: could find the origin and destination step based on
  883. // d->CurrentStep rather than QObject::sender(), but would require
  884. // keeping track of an origin step's destination step (and would be
  885. // tricky in an extension to branching workflows, unless we change
  886. // this method signature)
  887. ctkWorkflowInterstepTransition* transition = qobject_cast<ctkWorkflowInterstepTransition*>(QObject::sender());
  888. Q_ASSERT(transition);
  889. d->OriginStep = d->stepFromState(transition->sourceState());
  890. d->DestinationStep = d->stepFromState(transition->targetState());
  891. d->TransitionType = transition->transitionType();
  892. Q_ASSERT(d->TransitionType == ctkWorkflowInterstepTransition::TransitionToNextStep
  893. || d->TransitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStep
  894. || d->TransitionType == ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep);
  895. // update the map from the step to the previous step if we are going forward
  896. if (d->TransitionType == ctkWorkflowInterstepTransition::TransitionToNextStep)
  897. {
  898. d->StepToPreviousStepMap.insert(d->DestinationStep, d->OriginStep);
  899. }
  900. // exit the destination step
  901. d->onExitInternal(d->OriginStep, d->DestinationStep, d->TransitionType);
  902. }
  903. // --------------------------------------------------------------------------
  904. void ctkWorkflow::goToStepSucceeded()
  905. {
  906. Q_D(ctkWorkflow);
  907. logger.debug("goToStepSucceeded");
  908. // after success, go back to the step at which we begin looking for
  909. // the finish step (will exit the current step and enter the starting step)
  910. // only if the property goBackToOriginStepUponSuccess is true.
  911. if (this->goBackToOriginStepUponSuccess())
  912. {
  913. d->createTransitionToPreviousStartingStep(d->StartingStep, d->CurrentStep);
  914. }
  915. d->GoToStep = 0;
  916. d->StartingStep->setStatusText("Attempt to go to the finish step succeeded");
  917. d->StartingStep = 0;
  918. if (this->goBackToOriginStepUponSuccess())
  919. {
  920. this->goFromGoToStepToStartingStep();
  921. }
  922. }
  923. // --------------------------------------------------------------------------
  924. void ctkWorkflow::goFromGoToStepToStartingStep()
  925. {
  926. Q_D(ctkWorkflow);
  927. logger.info("goFromGoToStepToStartingStep - Posting TransitionToPreviousStartingStep");
  928. d->StateMachine->postEvent(new ctkWorkflowInterstepTransitionEvent(ctkWorkflowInterstepTransition::TransitionToPreviousStartingStepAfterSuccessfulGoToFinishStep));
  929. }
  930. // --------------------------------------------------------------------------
  931. void ctkWorkflow::goToStepFailed()
  932. {
  933. // Abort attempt to get to the finish step
  934. Q_D(ctkWorkflow);
  935. d->GoToStep = 0;
  936. d->StartingStep = 0;
  937. // We don't need to transition between steps - leave the user at the
  938. // point of failure, so that they can try to continue manually
  939. // Emit the signal that we have changed the current step, since it wasn't emitted in the process
  940. // of going to the 'goTo' step.
  941. emit this->currentStepChanged(d->CurrentStep);
  942. // if (failedOnBranch)
  943. // {
  944. // this->goToProcessingStateAfterValidationFailed();
  945. // }
  946. }