Salome HOME
Merge remote-tracking branch 'remotes/origin/EDF_2020_Lot2'
[modules/shaper.git] / src / Model / Model_Session.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Session.h>
21 #include <ModelAPI_Feature.h>
22 #include <ModelAPI_Plugin.h>
23 #include <Model_Data.h>
24 #include <Model_Document.h>
25 #include <Model_Objects.h>
26 #include <Model_Application.h>
27 #include <Model_Events.h>
28 #include <Model_Validator.h>
29 #include <Model_FiltersFactory.h>
30 #include <ModelAPI_Events.h>
31 #include <Events_Loop.h>
32 #include <Events_InfoMessage.h>
33 #include <Config_FeatureMessage.h>
34 #include <Config_AttributeMessage.h>
35 #include <Config_ValidatorMessage.h>
36 #include <Config_ModuleReader.h>
37 #include <Config_ValidatorReader.h>
38 #include <Config_PluginMessage.h>
39
40 #include <ModelAPI_CompositeFeature.h>
41 #include <ModelAPI_ResultPart.h>
42 #include <ModelAPI_Tools.h>
43
44 #include <TDF_ChildIDIterator.hxx>
45 #include <TDF_CopyTool.hxx>
46 #include <TDF_DataSet.hxx>
47 #include <TDF_RelocationTable.hxx>
48 #include <TDF_ClosureTool.hxx>
49
50 #include <TNaming_Builder.hxx>
51 #include <TNaming_Iterator.hxx>
52 #include <TNaming_NamedShape.hxx>
53
54 #include <TopoDS_Shape.hxx>
55
56 static Model_Session* myImpl = new Model_Session();
57
58 // to redirect all calls to the root document
59 #define ROOT_DOC std::dynamic_pointer_cast<Model_Document>(moduleDocument())
60
61 bool Model_Session::load(const char* theFileName)
62 {
63   bool aRes = ROOT_DOC->load(theFileName, "root", ROOT_DOC);
64   return aRes;
65 }
66
67 bool Model_Session::save(const char* theFileName, std::list<std::string>& theResults)
68 {
69   return ROOT_DOC->save(theFileName, "root", theResults);
70 }
71
72 void Model_Session::closeAll()
73 {
74   Model_Application::getApplication()->deleteAllDocuments();
75   static const Events_ID aDocChangeEvent = Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED);
76   myCurrentDoc = NULL;
77   static std::shared_ptr<Events_Message> aMsg(new Events_Message(aDocChangeEvent));
78   Events_Loop::loop()->send(aMsg);
79   Events_Loop::loop()->flush(aDocChangeEvent);
80 }
81
82 void Model_Session::startOperation(const std::string& theId, const bool theAttachedToNested)
83 {
84   myOperationAttachedToNext.push_back(theAttachedToNested);
85   ROOT_DOC->startOperation();
86   ROOT_DOC->operationId(theId);
87   static std::shared_ptr<Events_Message> aStartedMsg
88     (new Events_Message(Events_Loop::eventByName("StartOperation")));
89   Events_Loop::loop()->send(aStartedMsg);
90   // remove all useless documents that has been closed: on start of operation undo/redo is cleared
91   // MPV: this code is dangerous now because it may close the document that is activated right now
92   // but not in the list of the opened documents yet (create, delete, undo, activate Part)
93   // later this must be updated by correct usage of uniques IDs of documents, not names of results
94   //std::list<std::shared_ptr<ModelAPI_Document> > aUsedDocs = allOpenedDocuments();
95   //Model_Application::getApplication()->removeUselessDocuments(aUsedDocs);
96 }
97
98 void Model_Session::finishOperation()
99 {
100   setCheckTransactions(false);
101   ROOT_DOC->finishOperation();
102   if (!myOperationAttachedToNext.empty()) {
103     while (myOperationAttachedToNext.back()) {
104       // with nested, the first transaction can not be attached
105       ROOT_DOC->finishOperation();
106       myOperationAttachedToNext.pop_back();
107     }
108     myOperationAttachedToNext.pop_back();
109   }
110   setCheckTransactions(true);
111 }
112
113 void Model_Session::abortOperation()
114 {
115   setCheckTransactions(false);
116   ROOT_DOC->abortOperation();
117   if (!myOperationAttachedToNext.empty()) {
118     while (myOperationAttachedToNext.back()) {
119       // with nested, the first transaction can not be attached
120       ROOT_DOC->abortOperation();
121       myOperationAttachedToNext.pop_back();
122     }
123     myOperationAttachedToNext.pop_back();
124   }
125   setCheckTransactions(true);
126   // here the update mechanism may work after abort, so, suppress the warnings about
127   // modifications outside of the transactions
128   bool aWasCheck = myCheckTransactions;
129   myCheckTransactions = false;
130   static std::shared_ptr<Events_Message> anAbortMsg
131     (new Events_Message(Events_Loop::eventByName("AbortOperation")));
132   Events_Loop::loop()->send(anAbortMsg);
133   myCheckTransactions = true;
134   myCheckTransactions = aWasCheck;
135 }
136
137 bool Model_Session::isOperation()
138 {
139   return ROOT_DOC->isOperation();
140 }
141
142 bool Model_Session::isModified()
143 {
144   return ROOT_DOC->isModified();
145 }
146
147 bool Model_Session::canUndo()
148 {
149   return ROOT_DOC->canUndo();
150 }
151
152 void Model_Session::undo()
153 {
154   setCheckTransactions(false);
155   ROOT_DOC->undo();
156   setCheckTransactions(true);
157 }
158
159 bool Model_Session::canRedo()
160 {
161   return ROOT_DOC->canRedo();
162 }
163
164 void Model_Session::redo()
165 {
166   setCheckTransactions(false);
167   ROOT_DOC->redo();
168   setCheckTransactions(true);
169 }
170
171 //! Returns stack of performed operations
172 std::list<std::string> Model_Session::undoList()
173 {
174   return ROOT_DOC->undoList();
175 }
176 //! Returns stack of rolled back operations
177 std::list<std::string> Model_Session::redoList()
178 {
179   return ROOT_DOC->redoList();
180 }
181
182 ModelAPI_Plugin* Model_Session::getPlugin(const std::string& thePluginName)
183 {
184   if (myPluginObjs.find(thePluginName) == myPluginObjs.end()) {
185     // before load the used plugins
186     if (myUsePlugins.find(thePluginName) != myUsePlugins.end()) {
187       std::string aUse = myUsePlugins[thePluginName];
188       std::stringstream aUseStream(aUse);
189       std::string aPluginName;
190       while (std::getline(aUseStream, aPluginName, ',')) {
191         if (myPluginObjs.find(aPluginName) == myPluginObjs.end())
192           getPlugin(aPluginName);
193       }
194     }
195     // load plugin library if not yet done
196     Config_ModuleReader::loadPlugin(thePluginName);
197   }
198   if (myPluginObjs.find(thePluginName) == myPluginObjs.end()) {
199     Events_InfoMessage("Model_Session", "Can not load plugin '%1'").arg(thePluginName).send();
200     return NULL;
201   }
202   return myPluginObjs[thePluginName];
203 }
204
205 FeaturePtr Model_Session::createFeature(std::string theFeatureID, Model_Document* theDocOwner)
206 {
207   if (this != myImpl) {
208     return myImpl->createFeature(theFeatureID, theDocOwner);
209   }
210
211   // load all information about plugins, features and attributes
212   LoadPluginsInfo();
213
214   if (myPlugins.find(theFeatureID) != myPlugins.end()) {
215     std::pair<std::string, std::string>& aPlugin = myPlugins[theFeatureID]; // plugin and doc kind
216     if (!aPlugin.second.empty() && aPlugin.second != theDocOwner->kind()) {
217       Events_InfoMessage("Model_Session",
218         "Feature '%1' can be created only in document '%2' by the XML definition")
219         .arg(theFeatureID).arg(aPlugin.second).send();
220       return FeaturePtr();
221     }
222     ModelAPI_Plugin* aPluginObj = getPlugin(aPlugin.first);
223     if (aPluginObj) {
224       FeaturePtr aCreated = aPluginObj->createFeature(theFeatureID);
225       if (!aCreated) {
226         Events_InfoMessage("Model_Session", "Can not initialize feature '%1' in plugin '%2'")
227           .arg(theFeatureID).arg(aPlugin.first).send();
228       }
229       return aCreated;
230     } else {
231       Events_InfoMessage("Model_Session", "Can not load plugin '%1'").arg(aPlugin.first).send();
232     }
233   } else {
234     Events_InfoMessage("Model_Session",
235       "Feature '%1' not found in any plugin").arg(theFeatureID).send();
236   }
237
238   return FeaturePtr();  // return nothing
239 }
240
241 std::shared_ptr<ModelAPI_Document> Model_Session::moduleDocument()
242 {
243   Handle(Model_Application) anApp = Model_Application::getApplication();
244   bool aFirstCall = !anApp->hasRoot();
245   if (aFirstCall) {
246     // to be sure that plugins are loaded,
247     // even before the first "createFeature" call (in unit tests)
248
249     LoadPluginsInfo();
250     // creation of the root document is always outside of the transaction, so, avoid checking it
251     setCheckTransactions(false);
252     anApp->createDocument(0); // 0 is a root ID
253     // creation of the root document is always outside of the transaction, so, avoid checking it
254     setCheckTransactions(true);
255     if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id())) {
256       myCurrentDoc = moduleDocument();
257       static std::shared_ptr<Events_Message> aMsg(
258         new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
259       Events_Loop::loop()->send(aMsg);
260     }
261   }
262   return anApp->rootDocument();
263 }
264
265 std::shared_ptr<ModelAPI_Document> Model_Session::document(int theDocID)
266 {
267   return std::shared_ptr<ModelAPI_Document>(
268       Model_Application::getApplication()->document(theDocID));
269 }
270
271 bool Model_Session::hasModuleDocument()
272 {
273   return Model_Application::getApplication()->hasRoot();
274 }
275
276 std::shared_ptr<ModelAPI_Document> Model_Session::activeDocument()
277 {
278   if (!myCurrentDoc || !Model_Application::getApplication()->hasDocument(myCurrentDoc->id())) {
279     return moduleDocument();
280   }
281   return myCurrentDoc;
282 }
283
284 /// makes the last feature in the document as the current
285 static void makeCurrentLast(std::shared_ptr<ModelAPI_Document> theDoc) {
286   if (theDoc.get()) {
287     FeaturePtr aLast = std::dynamic_pointer_cast<Model_Document>(theDoc)->lastFeature();
288     // if last is nested into something else, make this something else as last:
289     // otherwise it will look like edition of sub-element, so, the main will be disabled
290     if (aLast.get()) {
291       CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
292       while(aMain.get()) {
293         aLast = aMain;
294         aMain = ModelAPI_Tools::compositeOwner(aLast);
295       }
296     }
297     theDoc->setCurrentFeature(aLast, false);
298   }
299 }
300
301 void Model_Session::setActiveDocument(
302   std::shared_ptr<ModelAPI_Document> theDoc, bool theSendSignal)
303 {
304   if (myCurrentDoc != theDoc) {
305     if (myCurrentDoc.get())
306       myCurrentDoc->setActive(false);
307     if (theDoc.get())
308       theDoc->setActive(true);
309
310     std::shared_ptr<ModelAPI_Document> aPrevious = myCurrentDoc;
311     myCurrentDoc = theDoc;
312     if (theDoc.get() && theSendSignal) {
313       // this must be before the synchronization call because features in PartSet lower than this
314       // part feature must be disabled and don't recomputed anymore (issue 1156,
315       // translation feature is failed on activation of Part 2)
316       if (isOperation()) { // do it only in transaction, not on opening of document
317         DocumentPtr aRoot = moduleDocument();
318         if (myCurrentDoc != aRoot) {
319           FeaturePtr aPartFeat = ModelAPI_Tools::findPartFeature(aRoot, myCurrentDoc);
320           if (aPartFeat.get()) {
321             aRoot->setCurrentFeature(aPartFeat, false);
322           }
323         }
324       }
325       // synchronize the document: it may be just opened or opened but removed before
326       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theDoc);
327       if (aDoc.get()) {
328         bool aWasChecked = myCheckTransactions;
329         setCheckTransactions(false);
330         TDF_LabelList anEmptyUpdated;
331         aDoc->objects()->synchronizeFeatures(anEmptyUpdated, true, true, false, true);
332         if (aWasChecked)
333             setCheckTransactions(true);
334       }
335       static std::shared_ptr<Events_Message> aMsg(
336           new Events_Message(Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED)));
337       Events_Loop::loop()->send(aMsg);
338     }
339     // make the current state correct and synchronized in the module and sub-documents
340     if (isOperation()) { // do it only in transaction, not on opening of document
341       if (myCurrentDoc == moduleDocument()) {
342         // make the current feature the latest in root, in previous root current become also last
343         makeCurrentLast(aPrevious);
344         makeCurrentLast(myCurrentDoc);
345       } else {
346         // make the current feature the latest in sub, root current feature becomes this sub
347         makeCurrentLast(myCurrentDoc);
348       }
349     }
350   }
351 }
352
353 std::list<std::shared_ptr<ModelAPI_Document> > Model_Session::allOpenedDocuments()
354 {
355   std::list<std::shared_ptr<ModelAPI_Document> > aResult;
356   aResult.push_back(moduleDocument());
357   // add subs recursively
358   std::list<std::shared_ptr<ModelAPI_Document> >::iterator aDocIt = aResult.begin();
359   for(; aDocIt != aResult.end(); aDocIt++) {
360     DocumentPtr anAPIDoc = *aDocIt;
361     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(anAPIDoc);
362     if (aDoc) {
363       const std::set<int> aSubs = aDoc->subDocuments();
364       std::set<int>::const_iterator aSubIter = aSubs.cbegin();
365       for(; aSubIter != aSubs.cend(); aSubIter++) {
366         aResult.push_back(Model_Application::getApplication()->document(*aSubIter));
367       }
368     }
369   }
370   return aResult;
371 }
372
373 bool Model_Session::isLoadByDemand(const std::wstring theDocID, const int theDocIndex)
374 {
375   return Model_Application::getApplication()->isLoadByDemand(theDocID, theDocIndex);
376 }
377
378 std::shared_ptr<ModelAPI_Document> Model_Session::copy(
379     std::shared_ptr<ModelAPI_Document> theSource, const int theDestID)
380 {
381   std::shared_ptr<Model_Document> aNew = Model_Application::getApplication()->document(theDestID);
382   // make a copy of all labels
383   TDF_Label aSourceRoot = std::dynamic_pointer_cast<Model_Document>(theSource)->document()->Main()
384       .Father();
385   TDF_Label aTargetRoot = aNew->document()->Main().Father();
386   Handle(TDF_DataSet) aDS = new TDF_DataSet;
387   aDS->AddLabel(aSourceRoot);
388   TDF_ClosureTool::Closure(aDS);
389   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable(Standard_True);
390   aRT->SetRelocation(aSourceRoot, aTargetRoot);
391   TDF_CopyTool::Copy(aDS, aRT);
392
393   // TODO: remove after fix in OCCT.
394   // All named shapes are stored in reversed order, so to fix this we reverse them back.
395   for(TDF_ChildIDIterator aChildIter(aTargetRoot, TNaming_NamedShape::GetID(), true);
396       aChildIter.More();
397       aChildIter.Next()) {
398     Handle(TNaming_NamedShape) aNamedShape =
399       Handle(TNaming_NamedShape)::DownCast(aChildIter.Value());
400     if (aNamedShape.IsNull()) {
401       continue;
402     }
403
404     TopoDS_Shape aShape = aNamedShape->Get();
405     if(aShape.IsNull() || aShape.ShapeType() != TopAbs_COMPOUND) {
406       continue;
407     }
408
409     TNaming_Evolution anEvol = aNamedShape->Evolution();
410     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
411     for(TNaming_Iterator anIter(aNamedShape); anIter.More(); anIter.Next()) {
412       aShapePairs.push_back(
413         std::pair<TopoDS_Shape, TopoDS_Shape>(anIter.OldShape(), anIter.NewShape()));
414     }
415
416     // Add in reverse order.
417     TDF_Label aLabel = aNamedShape->Label();
418     TNaming_Builder aBuilder(aLabel);
419     for(std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter =
420           aShapePairs.begin();
421         aPairsIter != aShapePairs.end();
422         aPairsIter++) {
423       if (anEvol == TNaming_GENERATED) {
424         aBuilder.Generated(aPairsIter->first, aPairsIter->second);
425       } else if (anEvol == TNaming_MODIFY) {
426         aBuilder.Modify(aPairsIter->first, aPairsIter->second);
427       } else if (anEvol == TNaming_DELETE) {
428         aBuilder.Delete(aPairsIter->first);
429       } else if (anEvol == TNaming_PRIMITIVE) {
430         aBuilder.Generated(aPairsIter->second);
431       } else if (anEvol == TNaming_SELECTED) {
432         aBuilder.Select(aPairsIter->second, aPairsIter->first);
433       }
434     }
435   }
436
437   TDF_LabelList anEmptyUpdated;
438   aNew->objects()->synchronizeFeatures(anEmptyUpdated, true, true, true, true);
439   return aNew;
440 }
441
442 Model_Session::Model_Session()
443 {
444   myPluginsInfoLoaded = false;
445   myCheckTransactions = true;
446   ModelAPI_Session::setSession(std::shared_ptr<ModelAPI_Session>(this));
447   // register the configuration reading listener
448   Events_Loop* aLoop = Events_Loop::loop();
449   static const Events_ID kFeatureEvent =
450     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
451   aLoop->registerListener(this, kFeatureEvent);
452   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED), 0, true);
453   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED), 0, true);
454   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED), 0, true);
455   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_VALIDATOR_LOADED));
456   aLoop->registerListener(this, Events_Loop::eventByName(Config_PluginMessage::EVENT_ID()));
457 }
458
459 void Model_Session::processEvent(const std::shared_ptr<Events_Message>& theMessage)
460 {
461   static const Events_ID kFeatureEvent =
462     Events_Loop::eventByName(Config_FeatureMessage::MODEL_EVENT());
463   static const Events_ID kValidatorEvent = Events_Loop::eventByName(EVENT_VALIDATOR_LOADED);
464   static const Events_ID kPluginEvent = Events_Loop::eventByName(Config_PluginMessage::EVENT_ID());
465   if (theMessage->eventID() == kFeatureEvent) {
466     const std::shared_ptr<Config_FeatureMessage> aMsg =
467       std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
468     if (aMsg) {
469
470       // process the plugin info, load plugin
471       if (myPlugins.find(aMsg->id()) == myPlugins.end()) {
472         myPlugins[aMsg->id()] = std::pair<std::string, std::string>(
473           aMsg->pluginLibrary(), aMsg->documentKind());
474       }
475     } else {
476       const std::shared_ptr<Config_AttributeMessage> aMsgAttr =
477         std::dynamic_pointer_cast<Config_AttributeMessage>(theMessage);
478       if (aMsgAttr) {
479
480         if (!aMsgAttr->isObligatory()) {
481           validators()->registerNotObligatory(aMsgAttr->featureId(), aMsgAttr->attributeId());
482         }
483         if(aMsgAttr->isConcealment()) {
484           validators()->registerConcealment(aMsgAttr->featureId(), aMsgAttr->attributeId());
485         }
486         if(aMsgAttr->isMainArgument()) {
487           validators()->registerMainArgument(aMsgAttr->featureId(), aMsgAttr->attributeId());
488         }
489         const std::list<std::pair<std::string, std::string> >& aCases = aMsgAttr->getCases();
490         if (!aCases.empty()) {
491           validators()->registerCase(aMsgAttr->featureId(), aMsgAttr->attributeId(), aCases);
492         }
493         if (aMsgAttr->isGeometricalSelection()) {
494           validators()->registerGeometricalSelection(aMsgAttr->featureId(),
495                                                      aMsgAttr->attributeId());
496         }
497       }
498     }
499     // plugins information was started to load, so, it will be loaded
500     myPluginsInfoLoaded = true;
501   } else if (theMessage->eventID() == kValidatorEvent) {
502     std::shared_ptr<Config_ValidatorMessage> aMsg =
503       std::dynamic_pointer_cast<Config_ValidatorMessage>(theMessage);
504     if (aMsg) {
505       if (aMsg->attributeId().empty()) {  // feature validator
506         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->parameters());
507       } else {  // attribute validator
508         validators()->assignValidator(aMsg->validatorId(), aMsg->featureId(), aMsg->attributeId(),
509                                       aMsg->parameters());
510       }
511     }
512   } else if (theMessage->eventID() == kPluginEvent) { // plugin is started to load
513     std::shared_ptr<Config_PluginMessage> aMsg =
514       std::dynamic_pointer_cast<Config_PluginMessage>(theMessage);
515     if (aMsg.get()) {
516       myCurrentPluginName = aMsg->pluginId();
517       if (!aMsg->uses().empty()) {
518         myUsePlugins[myCurrentPluginName] = aMsg->uses();
519       }
520     }
521   } else {  // create/update/delete
522     if (myCheckTransactions && !isOperation()) {
523       // check it is done in real opened document: 2958
524       bool aIsActual = true;
525       static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
526       if (theMessage->eventID() == kDeletedEvent) {
527         aIsActual = false;
528         std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
529           std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
530         std::list<std::shared_ptr<ModelAPI_Document> > allOpened =
531           Model_Session::allOpenedDocuments();
532         std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator
533           aGIter = aDeleted->groups().cbegin();
534         for (; !aIsActual && aGIter != aDeleted->groups().cend(); aGIter++) {
535           std::list<std::shared_ptr<ModelAPI_Document> >::iterator anOpened = allOpened.begin();
536           for(; anOpened != allOpened.end(); anOpened++) {
537             if (aGIter->first == *anOpened) {
538               aIsActual = true;
539               break;
540             }
541           }
542         }
543       }
544
545       if (aIsActual)
546         Events_InfoMessage("Model_Session",
547           "Modification of data structure outside of the transaction").send();
548     }
549     // if part is deleted, make the root as the current document (on undo of Parts creations)
550     static const Events_ID kDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
551     if (theMessage->eventID() == kDeletedEvent) {
552       std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleted =
553         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
554
555       std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator
556         aGIter = aDeleted->groups().cbegin();
557       for (; aGIter != aDeleted->groups().cend(); aGIter++) {
558         if (aGIter->second == ModelAPI_ResultPart::group())
559           break;
560       }
561       if (aGIter != aDeleted->groups().cend())
562       {
563          // check that the current feature of the session is still the active Part (even disabled)
564         bool aFound = false;
565         FeaturePtr aCurrentPart = moduleDocument()->currentFeature(true);
566         if (aCurrentPart.get()) {
567           const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aCurrentPart->results();
568           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
569           for(; !aFound && aRes != aResList.end(); aRes++) {
570             ResultPartPtr aPRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
571             if (aPRes.get() && aPRes->isActivated() && aPRes->partDoc() == activeDocument()) {
572               aFound = true;
573
574             }
575           }
576         }
577         if (!aFound) { // if not, the part was removed, so activate the module document
578           if (myCurrentDoc.get())
579             setActiveDocument(moduleDocument());
580         }
581       }
582     }
583   }
584 }
585
586 void Model_Session::LoadPluginsInfo()
587 {
588   if (myPluginsInfoLoaded)  // nothing to do
589     return;
590   // Read plugins information from XML files
591   Config_ModuleReader aModuleReader(Config_FeatureMessage::MODEL_EVENT());
592   aModuleReader.readAll();
593   std::set<std::string> aFiles = aModuleReader.modulePluginFiles();
594   std::set<std::string>::iterator it = aFiles.begin();
595   for ( ; it != aFiles.end(); it++ ) {
596     Config_ValidatorReader aValidatorReader (*it);
597     aValidatorReader.readAll();
598   };
599
600 }
601
602 void Model_Session::registerPlugin(ModelAPI_Plugin* thePlugin)
603 {
604   myPluginObjs[myCurrentPluginName] = thePlugin;
605   static Events_ID EVENT_LOAD = Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED);
606   ModelAPI_EventCreator::get()->sendUpdated(ObjectPtr(), EVENT_LOAD, false);
607   // If the plugin has an ability to process GUI events, register it
608   Events_Listener* aListener = dynamic_cast<Events_Listener*>(thePlugin);
609   if (aListener) {
610     Events_Loop* aLoop = Events_Loop::loop();
611     static Events_ID aStateRequestEventId =
612         Events_Loop::loop()->eventByName(EVENT_FEATURE_STATE_REQUEST);
613     aLoop->registerListener(aListener, aStateRequestEventId);
614   }
615 }
616
617 ModelAPI_ValidatorsFactory* Model_Session::validators()
618 {
619   static Model_ValidatorsFactory* aFactory = new Model_ValidatorsFactory;
620   return aFactory;
621 }
622
623 ModelAPI_FiltersFactory* Model_Session::filters()
624 {
625   static Model_FiltersFactory* aFactory = new Model_FiltersFactory;
626   return aFactory;
627 }
628
629 int Model_Session::transactionID()
630 {
631   return ROOT_DOC->transactionID();
632 }
633
634 bool Model_Session::isAutoUpdateBlocked()
635 {
636   Handle(Model_Application) anApp = Model_Application::getApplication();
637   if (!anApp->hasRoot()) // when document is not yet created, do not create it by such simple call
638     return false;
639   return !ROOT_DOC->autoRecomutationState();
640 }
641
642 void Model_Session::blockAutoUpdate(const bool theBlock)
643 {
644   bool aCurrentState = isAutoUpdateBlocked();
645   if (aCurrentState != theBlock) {
646     // if there is no operation, start it to avoid modifications outside of transaction
647     bool isOperation = this->isOperation();
648     if (!isOperation)
649       startOperation("Auto update");
650     ROOT_DOC->setAutoRecomutationState(!theBlock);
651     static Events_Loop* aLoop = Events_Loop::loop();
652     if (theBlock) {
653       static const Events_ID kAutoOff = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_DISABLE);
654       std::shared_ptr<Events_Message> aMsg(new Events_Message(kAutoOff));
655       aLoop->send(aMsg);
656     } else {
657       // if there is no operation, start it to avoid modifications outside of transaction
658       isOperation = this->isOperation();
659       if (!isOperation)
660         startOperation("Auto update enabling");
661       static const Events_ID kAutoOn = aLoop->eventByName(EVENT_AUTOMATIC_RECOMPUTATION_ENABLE);
662       std::shared_ptr<Events_Message> aMsg(new Events_Message(kAutoOn));
663       aLoop->send(aMsg);
664     }
665     if (!isOperation) {
666       finishOperation();
667       // append this transaction to the previous one: don't need this separated operation in list
668       ROOT_DOC->appendTransactionToPrevious();
669     }
670   }
671 }