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