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