diff --git a/Core/Code/Interactions/mitkStateMachine.cpp b/Core/Code/Interactions/mitkStateMachine.cpp index a446a96801..c3d9e5372a 100644 --- a/Core/Code/Interactions/mitkStateMachine.cpp +++ b/Core/Code/Interactions/mitkStateMachine.cpp @@ -1,320 +1,320 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStateMachine.h" #include "mitkStateTransitionOperation.h" #include "mitkInteractionConst.h" #include "mitkInteractor.h" #include "mitkTransition.h" #include "mitkOperationEvent.h" #include "mitkStateEvent.h" #include "mitkAction.h" #include "mitkUndoController.h" #include #include "mitkGlobalInteraction.h" #include /** * @brief Constructor * daclares a new StateMachine and connects * it to a StateMachine of Type type; * Also the undo mechanism is instanciated and enabled/disabled **/ mitk::StateMachine::StateMachine(const char * type) : m_UndoController(NULL), m_Type("") { if(type!=NULL) //no need to throw a warning here, because the statemachine yet here doesn't have to be set up. { m_Type = type; //the statemachine doesn't know yet anything about the number of timesteps of the data. So we initialize it with one element. this->InitializeStartStates(1); } if (!m_UndoController) { m_UndoController = new UndoController(UndoController::VERBOSE_LIMITEDLINEARUNDO);//switch to LLU or add LLU /** * here the Undo mechanism is enabled / disabled for all interactors. **/ m_UndoEnabled = true; } m_TimeStep = 0; } mitk::StateMachine::~StateMachine() { //clean up map using deletes for ( mitk::StateMachine::ActionFunctionsMapType::iterator iter = m_ActionFunctionsMap.begin(); iter != m_ActionFunctionsMap.end(); ++iter ) { delete iter->second; } delete m_UndoController; } std::string mitk::StateMachine::GetType() const { return m_Type; } const mitk::State* mitk::StateMachine::GetCurrentState(unsigned int timeStep) const { if (m_CurrentStateVector.size() > timeStep) //the size of the vector has to be one integer higher than the timeStep. return m_CurrentStateVector[timeStep].GetPointer(); return NULL; } void mitk::StateMachine::ResetStatemachineToStartState(unsigned int timeStep) { mitk::State* startState = mitk::GlobalInteraction::GetInstance()->GetStartState((const char *)(&m_Type[0])); if ( m_UndoEnabled ) //write to UndoMechanism if Undo is enabled { //UNDO for this statechange; StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, startState, timeStep); StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentStateVector[timeStep], timeStep); OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp); m_UndoController->SetOperationEvent(operationEvent); } //can be done without calling this->ExecuteOperation() m_CurrentStateVector[timeStep] = startState; } float mitk::StateMachine::CanHandleEvent(const StateEvent* /*stateEvent*/) const { return 0.5; } bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent) { if (stateEvent == NULL) return false; if (m_CurrentStateVector.empty()) { STATEMACHINE_ERROR << "Error in mitkStateMachine.cpp: StateMachine not initialized!\n"; return false;//m_CurrentStateVector needs to be initialized! } if (m_TimeStep >= m_CurrentStateVector.size()) { STATEMACHINE_ERROR << "Error in mitkStateMachine.cpp: StateMachine not initialized for this time step!\n"; return false; } if (m_CurrentStateVector[m_TimeStep].IsNull()) { STATEMACHINE_ERROR << "Error in mitkStateMachine.cpp: StateMachine not initialized with the right temporal information!\n"; return false;//m_CurrentState needs to be initialized! } //get the Transition from m_CurrentState which waits for this EventId const Transition *tempTransition = m_CurrentStateVector[m_TimeStep]->GetTransition(stateEvent->GetId()); if (tempTransition == NULL) //no transition in this state for that EventId { return false; } //get next State State *tempNextState = tempTransition->GetNextState(); if (tempNextState == NULL) //wrong built up statemachine! { STATEMACHINE_ERROR << "Error in mitkStateMachine.cpp: StateMachinePattern not defined correctly!\n"; return false; } //and ActionId to execute later on if ( m_CurrentStateVector[m_TimeStep]->GetId() != tempNextState->GetId() )//statechange only if there is a real statechange { if ( m_UndoEnabled ) //write to UndoMechanism if Undo is enabled { //UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState, m_TimeStep); StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentStateVector[m_TimeStep], m_TimeStep); OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp); m_UndoController->SetOperationEvent(operationEvent); } STATEMACHINE_DEBUG << "from " << m_CurrentStateVector[m_TimeStep]->GetId() << " " << m_CurrentStateVector[m_TimeStep]->GetName() << " to " << tempNextState->GetId() <<" "<GetName(); //first following StateChange(or calling ExecuteOperation(tempNextStateOp)), then operation(action) m_CurrentStateVector[m_TimeStep] = tempNextState; } mitk::Transition::ActionVectorIterator actionIdIterator = tempTransition->GetActionBeginIterator(); mitk::Transition::ActionVectorConstIterator actionIdIteratorEnd = tempTransition->GetActionEndIterator(); bool ok = true; while ( actionIdIterator != actionIdIteratorEnd ) { if ( !ExecuteAction(*actionIdIterator, stateEvent) ) { ok = false; } actionIdIterator++; } return ok; } void mitk::StateMachine::EnableUndo(bool enable) { m_UndoEnabled = enable; } void mitk::StateMachine::IncCurrGroupEventId() { mitk::OperationEvent::IncCurrGroupEventId(); } /// look up which object method is associated to the given action and call the method bool mitk::StateMachine::ExecuteAction(Action* action, StateEvent const* stateEvent) { if (!action) return false; int actionId = action->GetActionId(); TStateMachineFunctor* actionFunction = m_ActionFunctionsMap[actionId]; if (!actionFunction) return false; bool retVal = actionFunction->DoAction(action, stateEvent); return retVal; } void mitk::StateMachine::AddActionFunction(int action, mitk::TStateMachineFunctor* functor) { if (!functor) return; // make sure double calls for same action won't cause memory leaks delete m_ActionFunctionsMap[action]; // delete NULL does no harm m_ActionFunctionsMap[action] = functor; } void mitk::StateMachine::ExecuteOperation(Operation* operation) { switch (operation->GetOperationType()) { case OpNOTHING: break; case OpSTATECHANGE: { mitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation); if (stateTransOp == NULL) { STATEMACHINE_WARN<<"Error! see mitkStateMachine.cpp"; return; } unsigned int time = stateTransOp->GetTime(); m_CurrentStateVector[time] = stateTransOp->GetState(); } break; case OpTIMECHANGE: { mitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation); if (stateTransOp == NULL) { STATEMACHINE_WARN<<"Error! see mitkStateMachine.cpp"; return; } m_TimeStep = stateTransOp->GetTime(); } break; case OpDELETE: { //delete this! //before all lower statemachines has to be deleted in a action //this->Delete();//might not work!!!check itk! } case OpUNDELETE: { //now the m_CurrentState has to be set on a special State //that way a delete of a StateMachine can be undone //IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this! mitk::StateTransitionOperation* stateTransOp = dynamic_cast(operation); if (stateTransOp != NULL) { unsigned int time = stateTransOp->GetTime(); m_CurrentStateVector[time] = stateTransOp->GetState(); } } default: ; } } void mitk::StateMachine::InitializeStartStates(unsigned int timeSteps) { //get the startstate of the pattern State::Pointer startState = mitk::GlobalInteraction::GetInstance()->GetStartState(m_Type.c_str()); if (startState.IsNull()) { STATEMACHINE_FATAL << "Fatal Error in mitkStateMachine.cpp: Initialization of statemachine unsuccessfull! Initialize GlobalInteraction!\n"; } //clear the vector m_CurrentStateVector.clear(); //add n=timesteps pointers pointing to to the startstate for (unsigned int i = 0; i < timeSteps; i++) m_CurrentStateVector.push_back(startState); } // Check if the vector is long enough to contain the new element // at the given position. If not, expand it with sufficient pre-initialized // elements. // // NOTE: This method will never REDUCE the vector size; it should only // be used to make sure that the vector has enough elements to include the // specified time step. void mitk::StateMachine::ExpandStartStateVector(unsigned int timeSteps) { - unsigned int oldSize = m_CurrentStateVector.size(); + size_t oldSize = m_CurrentStateVector.size(); if ( timeSteps > oldSize ) { State::Pointer startState = mitk::GlobalInteraction::GetInstance()->GetStartState(m_Type.c_str()); - for ( unsigned int i = oldSize; i < timeSteps; ++i ) + for ( size_t i = oldSize; i < timeSteps; ++i ) m_CurrentStateVector.insert(m_CurrentStateVector.end(), startState); } } void mitk::StateMachine::UpdateTimeStep(unsigned int timeStep) { //don't need to fill up the memory if the time is uptodate if (timeStep == m_TimeStep) return; //create an operation that changes the time and send it to undocontroller StateTransitionOperation* doOp = new StateTransitionOperation(OpTIMECHANGE, NULL, timeStep); if ( m_UndoEnabled ) //write to UndoMechanism if Undo is enabled { StateTransitionOperation* undoOp = new StateTransitionOperation(OpTIMECHANGE, NULL, m_TimeStep); OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp); m_UndoController->SetOperationEvent(operationEvent); } this->ExecuteOperation(doOp); } diff --git a/Core/Code/Interactions/mitkStateMachineFactory.cpp b/Core/Code/Interactions/mitkStateMachineFactory.cpp index 5193ad4259..80089ce428 100755 --- a/Core/Code/Interactions/mitkStateMachineFactory.cpp +++ b/Core/Code/Interactions/mitkStateMachineFactory.cpp @@ -1,461 +1,461 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStateMachineFactory.h" #include "mitkGlobalInteraction.h" #include #include #include #include #include /** * @brief This class builds up all the necessary structures for a statemachine. * and stores one start-state for all built statemachines. **/ //mitk::StateMachineFactory::StartStateMap mitk::StateMachineFactory::m_StartStates; //mitk::StateMachineFactory::AllStateMachineMapType mitk::StateMachineFactory::m_AllStateMachineMap; //std::string mitk::StateMachineFactory::s_LastLoadedBehavior; //XML StateMachine const std::string STYLE = "STYLE"; const std::string NAME = "NAME"; const std::string ID = "ID"; const std::string START_STATE = "START_STATE"; const std::string NEXT_STATE_ID = "NEXT_STATE_ID"; const std::string EVENT_ID = "EVENT_ID"; const std::string SIDE_EFFECT_ID = "SIDE_EFFECT_ID"; const std::string ISTRUE = "TRUE"; const std::string ISFALSE = "FALSE"; const std::string STATE_MACHINE = "stateMachine"; const std::string STATE = "state"; const std::string TRANSITION = "transition"; const std::string STATE_MACHINE_NAME = "stateMachine"; const std::string ACTION = "action"; const std::string BOOL_PARAMETER = "boolParameter"; const std::string INT_PARAMETER = "intParameter"; const std::string FLOAT_PARAMETER = "floatParameter"; const std::string DOUBLE_PARAMETER = "doubleParameter"; const std::string STRING_PARAMETER = "stringParameter"; const std::string VALUE = "VALUE"; #include namespace mitk { vtkStandardNewMacro(StateMachineFactory); } mitk::StateMachineFactory::StateMachineFactory() : m_AktStateMachineName(""), m_SkipStateMachine(false) {} mitk::StateMachineFactory::~StateMachineFactory() { //free memory while (!m_AllStateMachineMap.empty()) { StateMachineMapType* temp = m_AllStateMachineMap.begin()->second; m_AllStateMachineMap.erase(m_AllStateMachineMap.begin()); delete temp; } //should not be necessary due to SmartPointers m_StartStates.clear(); //delete WeakPointer if (m_AktTransition) delete m_AktTransition; } /** * @brief Returns NULL if no entry with string type is found. **/ mitk::State* mitk::StateMachineFactory::GetStartState(const char * type) { StartStateMapIter tempState = m_StartStates.find(type); if( tempState != m_StartStates.end() ) return (tempState)->second.GetPointer(); MITK_ERROR << "Error in StateMachineFactory: StartState for pattern \""<< type<< "\"not found! StateMachine might not work!\n"; return NULL; } /** * @brief Loads the xml file filename and generates the necessary instances. **/ bool mitk::StateMachineFactory::LoadBehavior(std::string fileName) { if ( fileName.empty() ) return false; m_LastLoadedBehavior = fileName; this->SetFileName(fileName.c_str()); return this->Parse(); } /** * @brief Loads the xml string and generates the necessary instances. **/ bool mitk::StateMachineFactory::LoadBehaviorString(std::string xmlString) { if ( xmlString.empty() ) return false; m_LastLoadedBehavior = "String"; - return ( this->Parse(xmlString.c_str(), xmlString.length()) ); + return ( this->Parse(xmlString.c_str(), (unsigned int) xmlString.length()) ); } bool mitk::StateMachineFactory::LoadStandardBehavior() { std::string xmlFileName( mitk::StandardFileLocations::GetInstance()->FindFile("StateMachine.xml", "Core/Code/Interactions") ); if (!xmlFileName.empty()) return this->LoadBehavior(xmlFileName); else return false; } /** * @brief Recursive method, that parses this brand of * the stateMachine; if the history has the same * size at the end, then the StateMachine is correct **/ bool mitk::StateMachineFactory::RParse(mitk::State::StateMap* states, mitk::State::StateMapIter thisState, HistorySet *history) { history->insert((thisState->second)->GetId());//log our path //or thisState->first. but this seems safer std::set nextStatesSet = (thisState->second)->GetAllNextStates(); //remove loops in nextStatesSet; //nether do we have to go there, nor will it clear a deadlock std::set::iterator position = nextStatesSet.find((thisState->second)->GetId());//look for the same state in nextStateSet if (position != nextStatesSet.end()) {//found the same state we are in! nextStatesSet.erase(position);//delete it, cause, we don't have to go there a second time! } //nextStatesSet is empty, so deadlock! if ( nextStatesSet.empty() ) { MITK_INFO<::iterator i = nextStatesSet.begin(); i != nextStatesSet.end(); i++) { if ( history->find(*i) == history->end() )//if we haven't been in this nextstate { mitk::State::StateMapIter nextState = states->find(*i);//search the iterator for our nextState if (nextState == states->end()) { MITK_INFO<size() > 1)//only one state; don't have to be parsed for deadlocks! { //parse all the given states an check for deadlock or not connected states HistorySet *history = new HistorySet; mitk::State::StateMapIter firstState = states->begin(); //parse through all the given states, log the parsed elements in history bool ok = RParse( states, firstState, history); if ( (states->size() == history->size()) && ok ) { delete history; } else //ether !ok or sizeA!=sizeB { delete history; MITK_INFO<begin(); tempState != states->end(); tempState++) { //searched through the States and Connects all Transitions bool tempbool = ( ( tempState->second )->ConnectTransitions( states ) ); if ( tempbool == false ) { MITK_INFO< ok = m_AllStatesOfOneStateMachine.insert(mitk::State::StateMap::value_type(id , m_AktState)); if ( ok.second == false ) { MITK_INFO<AddTransition( m_AktTransition ); } else if ( name == ACTION ) { int actionId = ReadXMLIntegerAttribut( ID, atts ); m_AktAction = Action::New( actionId ); m_AktTransition->AddAction( m_AktAction ); } else if ( name == BOOL_PARAMETER ) { if ( !m_AktAction ) return; bool value = ReadXMLBooleanAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), BoolProperty::New( value ) ); } else if ( name == INT_PARAMETER ) { if ( !m_AktAction ) return; int value = ReadXMLIntegerAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), IntProperty::New( value ) ); } else if ( name == FLOAT_PARAMETER ) { if ( !m_AktAction ) return; float value = ReadXMLIntegerAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), FloatProperty::New( value ) ); } else if ( name == DOUBLE_PARAMETER ) { if ( !m_AktAction ) return; double value = ReadXMLDoubleAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), DoubleProperty::New( value ) ); } else if ( name == STRING_PARAMETER ) { if ( !m_AktAction ) return; std::string value = ReadXMLStringAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), StringProperty::New( value ) ); } } void mitk::StateMachineFactory::EndElement (const char* elementName) { //bool ok = true; std::string name(elementName); //skip the state machine pattern because the name was not unique! if (m_SkipStateMachine && (name != STATE_MACHINE) ) return; if ( name == STATE_MACHINE_NAME ) { if (m_SkipStateMachine) { m_SkipStateMachine = false; return; } /*ok =*/ ConnectStates(&m_AllStatesOfOneStateMachine); m_AllStatesOfOneStateMachine.clear(); } else if ( name == STATE_MACHINE ) { //doesn't have to be done } else if ( name == TRANSITION ) { m_AktTransition = NULL; //pointer stored in its state. memory will be freed in destructor of class state } else if ( name == ACTION ) { m_AktAction = NULL; } else if ( name == STATE ) { m_AktState = NULL; } } std::string mitk::StateMachineFactory::ReadXMLStringAttribut( std::string name, const char** atts ) { if(atts) { const char** attsIter = atts; while(*attsIter) { if ( name == *attsIter ) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } int mitk::StateMachineFactory::ReadXMLIntegerAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); return atoi( s.c_str() ); } float mitk::StateMachineFactory::ReadXMLFloatAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); return (float) atof( s.c_str() ); } double mitk::StateMachineFactory::ReadXMLDoubleAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); return atof( s.c_str() ); } bool mitk::StateMachineFactory::ReadXMLBooleanAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); if ( s == ISTRUE ) return true; else return false; } mitk::State* mitk::StateMachineFactory::GetState( const char * type, int StateId ) { //check if the state exists AllStateMachineMapType::iterator i = m_AllStateMachineMap.find( type ); if ( i == m_AllStateMachineMap.end() ) return NULL; //get the statemachine of the state StateMachineMapType* sm = m_AllStateMachineMap[type]; //get the state from its statemachine if ( sm != NULL ) return (*sm)[StateId].GetPointer(); else return NULL; } bool mitk::StateMachineFactory::AddStateMachinePattern(const char * type, mitk::State* startState, mitk::StateMachineFactory::StateMachineMapType* allStatesOfStateMachine) { if (startState == NULL || allStatesOfStateMachine == NULL) return false; //check if the pattern has already been added StartStateMapIter tempState = m_StartStates.find(type); if( tempState != m_StartStates.end() ) { MITK_WARN << "Pattern " << type << " has already been added!\n"; return false; } //add the start state m_StartStates.insert(StartStateMap::value_type(type, startState)); //add all states of the new pattern to hold their references m_AllStateMachineMap.insert(AllStateMachineMapType::value_type(type, allStatesOfStateMachine)); return true; }