Salome HOME
Fix for import/export features
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Document.cxx
4 // Created:     28 Feb 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Objects.h>
10 #include <Model_Application.h>
11 #include <Model_Session.h>
12 #include <Model_Events.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_Validator.h>
15 #include <ModelAPI_CompositeFeature.h>
16
17 #include <Events_Loop.h>
18 #include <Events_Error.h>
19
20 #include <TDataStd_Integer.hxx>
21 #include <TDataStd_Comment.hxx>
22 #include <TDF_ChildIDIterator.hxx>
23 #include <TDataStd_ReferenceArray.hxx>
24 #include <TDataStd_HLabelArray1.hxx>
25 #include <TDataStd_Name.hxx>
26 #include <TDF_Reference.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDF_LabelMapHasher.hxx>
29 #include <OSD_File.hxx>
30 #include <OSD_Path.hxx>
31
32 #include <climits>
33 #ifndef WIN32
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef WIN32
38 # define _separator_ '\\'
39 #else
40 # define _separator_ '/'
41 #endif
42
43 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
44
45 static const int TAG_GENERAL = 1;  // general properties tag
46
47 // general sub-labels
48 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
49 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
50
51 Model_Document::Model_Document(const std::string theID, const std::string theKind)
52     : myID(theID), myKind(theKind), myIsActive(false),
53       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
54 {
55   myObjs = new Model_Objects(myDoc->Main());
56   myDoc->SetUndoLimit(UNDO_LIMIT);  
57   myTransactionSave = 0;
58   myExecuteFeatures = true;
59   // to have something in the document and avoid empty doc open/save problem
60   // in transaction for nesting correct working
61   myDoc->NewCommand();
62   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
63   myDoc->CommitCommand();
64 }
65
66 void Model_Document::setThis(DocumentPtr theDoc)
67 {
68   myObjs->setOwner(theDoc);
69 }
70
71 /// Returns the file name of this document by the nameof directory and identifuer of a document
72 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
73 {
74   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
75   // remove end-separators
76   while(aPath.Length() && 
77         (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
78     aPath.Remove(aPath.Length());
79   aPath += _separator_;
80   aPath += theID.c_str();
81   aPath += ".cbf";  // standard binary file extension
82   return aPath;
83 }
84
85 bool Model_Document::isRoot() const
86 {
87   return this == Model_Session::get()->moduleDocument().get();
88 }
89
90 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
91 {
92   Handle(Model_Application) anApp = Model_Application::getApplication();
93   if (isRoot()) {
94     anApp->setLoadPath(theFileName);
95   }
96   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
97   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
98   try {
99     aStatus = anApp->Open(aPath, myDoc);
100   } catch (Standard_Failure) {
101     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
102     Events_Error::send(
103         std::string("Exception in opening of document: ") + aFail->GetMessageString());
104     return false;
105   }
106   bool isError = aStatus != PCDM_RS_OK;
107   if (isError) {
108     switch (aStatus) {
109       case PCDM_RS_UnknownDocument:
110         Events_Error::send(std::string("Can not open document"));
111         break;
112       case PCDM_RS_AlreadyRetrieved:
113         Events_Error::send(std::string("Can not open document: already opened"));
114         break;
115       case PCDM_RS_AlreadyRetrievedAndModified:
116         Events_Error::send(
117             std::string("Can not open document: already opened and modified"));
118         break;
119       case PCDM_RS_NoDriver:
120         Events_Error::send(std::string("Can not open document: driver library is not found"));
121         break;
122       case PCDM_RS_UnknownFileDriver:
123         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
124         break;
125       case PCDM_RS_OpenError:
126         Events_Error::send(std::string("Can not open document: file open error"));
127         break;
128       case PCDM_RS_NoVersion:
129         Events_Error::send(std::string("Can not open document: invalid version"));
130         break;
131       case PCDM_RS_NoModel:
132         Events_Error::send(std::string("Can not open document: no data model"));
133         break;
134       case PCDM_RS_NoDocument:
135         Events_Error::send(std::string("Can not open document: no document inside"));
136         break;
137       case PCDM_RS_FormatFailure:
138         Events_Error::send(std::string("Can not open document: format failure"));
139         break;
140       case PCDM_RS_TypeNotFoundInSchema:
141         Events_Error::send(std::string("Can not open document: invalid object"));
142         break;
143       case PCDM_RS_UnrecognizedFileFormat:
144         Events_Error::send(std::string("Can not open document: unrecognized file format"));
145         break;
146       case PCDM_RS_MakeFailure:
147         Events_Error::send(std::string("Can not open document: make failure"));
148         break;
149       case PCDM_RS_PermissionDenied:
150         Events_Error::send(std::string("Can not open document: permission denied"));
151         break;
152       case PCDM_RS_DriverFailure:
153         Events_Error::send(std::string("Can not open document: driver failure"));
154         break;
155       default:
156         Events_Error::send(std::string("Can not open document: unknown error"));
157         break;
158     }
159   }
160   if (!isError) {
161     myDoc->SetUndoLimit(UNDO_LIMIT);
162     // to avoid the problem that feature is created in the current, not this, document
163     std::shared_ptr<Model_Session> aSession = 
164       std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
165     aSession->setActiveDocument(anApp->getDocument(myID), false);
166     aSession->setCheckTransactions(false);
167     if (myObjs)
168       delete myObjs;
169     myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
170     myObjs->setOwner(theThis);
171     // update the current features status
172     setCurrentFeature(currentFeature(false), false);
173     aSession->setCheckTransactions(true);
174     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
175     // this is done in Part result "activate", so no needed here. Causes not-blue active part.
176     // aSession->setActiveDocument(anApp->getDocument(myID), true);
177   }
178   return !isError;
179 }
180
181 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
182 {
183   // create a directory in the root document if it is not yet exist
184   Handle(Model_Application) anApp = Model_Application::getApplication();
185   if (isRoot()) {
186 #ifdef WIN32
187     CreateDirectory(theFileName, NULL);
188 #else
189     mkdir(theFileName, 0x1ff);
190 #endif
191   }
192   // filename in the dir is id of document inside of the given directory
193   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
194   PCDM_StoreStatus aStatus;
195   try {
196     aStatus = anApp->SaveAs(myDoc, aPath);
197   } catch (Standard_Failure) {
198     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
199     Events_Error::send(
200         std::string("Exception in saving of document: ") + aFail->GetMessageString());
201     return false;
202   }
203   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
204   if (!isDone) {
205     switch (aStatus) {
206       case PCDM_SS_DriverFailure:
207         Events_Error::send(std::string("Can not save document: save driver-library failure"));
208         break;
209       case PCDM_SS_WriteFailure:
210         Events_Error::send(std::string("Can not save document: file writing failure"));
211         break;
212       case PCDM_SS_Failure:
213       default:
214         Events_Error::send(std::string("Can not save document"));
215         break;
216     }
217   }
218   myTransactionSave = myTransactions.size();
219   if (isDone) {  // save also sub-documents if any
220     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
221     const std::set<std::string> aSubs = subDocuments(false);
222     std::set<std::string>::iterator aSubIter = aSubs.begin();
223     for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
224       if (anApp->isLoadByDemand(*aSubIter)) { 
225         // copy not-activated document that is not in the memory
226         std::string aDocName = *aSubIter;
227         if (!aDocName.empty()) {
228           // just copy file
229           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
230           OSD_Path aPath(aSubPath);
231           OSD_File aFile(aPath);
232           if (aFile.Exists()) {
233             TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
234             OSD_Path aDestination(aDestinationDir);
235             aFile.Copy(aDestination);
236             theResults.push_back(aDestinationDir.ToCString());
237           } else {
238             Events_Error::send(
239               std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
240           }
241         }
242       } else { // simply save opened document
243         isDone = subDoc(*aSubIter)->save(theFileName, theResults);
244       }
245     }
246   }
247   return isDone;
248 }
249
250 void Model_Document::close(const bool theForever)
251 {
252   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
253   if (!isRoot() && this == aPM->activeDocument().get()) {
254     aPM->setActiveDocument(aPM->moduleDocument());
255   } else if (isRoot()) {
256     // erase the active document if root is closed
257     aPM->setActiveDocument(DocumentPtr());
258   }
259   // close all subs
260   const std::set<std::string> aSubs = subDocuments(true);
261   std::set<std::string>::iterator aSubIter = aSubs.begin();
262   for (; aSubIter != aSubs.end(); aSubIter++) {
263     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
264     if (aSub->myObjs) // if it was not closed before
265       aSub->close(theForever);
266   }
267
268   // close for thid document needs no transaction in this document
269   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
270
271   // close all only if it is really asked, otherwise it can be undoed/redoed
272   if (theForever) {
273     delete myObjs;
274     myObjs = 0;
275     if (myDoc->CanClose() == CDM_CCS_OK)
276       myDoc->Close();
277   } else {
278     setCurrentFeature(FeaturePtr(), false); // disables all features
279   }
280
281   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
282 }
283
284 void Model_Document::startOperation()
285 {
286   if (myDoc->HasOpenCommand()) {  // start of nested command
287     if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
288       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
289     }
290     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
291     myDoc->OpenCommand();
292   } else {  // start the simple command
293     myDoc->NewCommand();
294   }
295   // starts a new operation
296   incrementTransactionID();
297   myTransactions.push_back(Transaction());
298   if (!myNestedNum.empty())
299     (*myNestedNum.rbegin())++;
300   myRedos.clear();
301   // new command for all subs
302   const std::set<std::string> aSubs = subDocuments(true);
303   std::set<std::string>::iterator aSubIter = aSubs.begin();
304   for (; aSubIter != aSubs.end(); aSubIter++)
305     subDoc(*aSubIter)->startOperation();
306 }
307
308 void Model_Document::compactNested()
309 {
310   if (!myNestedNum.empty()) {
311     int aNumToCompact = *(myNestedNum.rbegin());
312     int aSumOfTransaction = 0;
313     for(int a = 0; a < aNumToCompact; a++) {
314       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
315       myTransactions.pop_back();
316     }
317     // the latest transaction is the start of lower-level operation which startes the nested
318     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
319     myNestedNum.pop_back();
320   }
321 }
322
323 bool Model_Document::finishOperation()
324 {
325   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
326   static std::shared_ptr<Model_Session> aSession = 
327     std::static_pointer_cast<Model_Session>(Model_Session::get());
328   myObjs->synchronizeBackRefs();
329   Events_Loop* aLoop = Events_Loop::loop();
330   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
331   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
332   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
333   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
334   // this must be here just after everything is finished but before real transaction stop
335   // to avoid messages about modifications outside of the transaction
336   // and to rebuild everything after all updates and creates
337   if (isRoot()) { // once for root document
338     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
339     static std::shared_ptr<Events_Message> aFinishMsg
340       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
341     Events_Loop::loop()->send(aFinishMsg);
342     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
343   }
344   // to avoid "updated" message appearance by updater
345   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
346
347   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
348   bool aResult = false;
349   const std::set<std::string> aSubs = subDocuments(true);
350   std::set<std::string>::iterator aSubIter = aSubs.begin();
351   for (; aSubIter != aSubs.end(); aSubIter++)
352     if (subDoc(*aSubIter)->finishOperation())
353       aResult = true;
354
355   // transaction may be empty if this document was created during this transaction (create part)
356   if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
357     myTransactions.rbegin()->myOCAFNum++;
358     aResult = true;
359   }
360
361   if (isNestedClosed) {
362     compactNested();
363   }
364   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
365     aResult = myTransactions.rbegin()->myOCAFNum != 0;
366
367   if (!aResult && isRoot()) {
368     // nothing inside in all documents, so remove this transaction from the transactions list
369     undoInternal(true, false);
370   }
371   // on finish clear redos in any case (issue 446) and for all subs (issue 408)
372   myDoc->ClearRedos();
373   myRedos.clear();
374   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
375     subDoc(*aSubIter)->myDoc->ClearRedos();
376     subDoc(*aSubIter)->myRedos.clear();
377   }
378
379   return aResult;
380 }
381
382 void Model_Document::abortOperation()
383 {
384   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
385     compactNested();
386     undoInternal(false, false);
387     myDoc->ClearRedos();
388     myRedos.clear();
389   } else { // abort the current
390     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
391     myTransactions.pop_back();
392     if (!myNestedNum.empty())
393       (*myNestedNum.rbegin())--;
394     // roll back the needed number of transactions
395     myDoc->AbortCommand();
396     for(int a = 0; a < aNumTransactions; a++)
397       myDoc->Undo();
398     myDoc->ClearRedos();
399   }
400   // abort for all subs, flushes will be later, in the end of root abort
401   const std::set<std::string> aSubs = subDocuments(true);
402   std::set<std::string>::iterator aSubIter = aSubs.begin();
403   for (; aSubIter != aSubs.end(); aSubIter++)
404     subDoc(*aSubIter)->abortOperation();
405   // references may be changed because they are set in attributes on the fly
406   myObjs->synchronizeFeatures(true, true, isRoot());
407 }
408
409 bool Model_Document::isOperation() const
410 {
411   // operation is opened for all documents: no need to check subs
412   return myDoc->HasOpenCommand() == Standard_True ;
413 }
414
415 bool Model_Document::isModified()
416 {
417   // is modified if at least one operation was commited and not undoed
418   return myTransactions.size() != myTransactionSave || isOperation();
419 }
420
421 bool Model_Document::canUndo()
422 {
423   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
424   int aCurrentNum = isOperation() ? 1 : 0;
425   if (myDoc->GetAvailableUndos() > 0 && 
426       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
427       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
428     return true;
429   // check other subs contains operation that can be undoed
430   const std::set<std::string> aSubs = subDocuments(true);
431   std::set<std::string>::iterator aSubIter = aSubs.begin();
432   for (; aSubIter != aSubs.end(); aSubIter++) {
433     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
434     if (aSub->myObjs) {// if it was not closed before
435       if (aSub->canUndo())
436         return true;
437     }
438   }
439
440   return false;
441 }
442
443 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
444 {
445   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
446   myRedos.push_back(*myTransactions.rbegin());
447   myTransactions.pop_back();
448   if (!myNestedNum.empty())
449     (*myNestedNum.rbegin())--;
450   // roll back the needed number of transactions
451   for(int a = 0; a < aNumTransactions; a++)
452     myDoc->Undo();
453
454   if (theWithSubs) {
455     // undo for all subs
456     const std::set<std::string> aSubs = subDocuments(true);
457     std::set<std::string>::iterator aSubIter = aSubs.begin();
458     for (; aSubIter != aSubs.end(); aSubIter++) {
459       if (!subDoc(*aSubIter)->myObjs)
460         continue;
461       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
462     }
463   }
464   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
465   if (theSynchronize) {
466     myObjs->synchronizeFeatures(true, true, isRoot());
467     // update the current features status
468     setCurrentFeature(currentFeature(false), false);
469   }
470 }
471
472 void Model_Document::undo()
473 {
474   undoInternal(true, true);
475 }
476
477 bool Model_Document::canRedo()
478 {
479   if (!myRedos.empty())
480     return true;
481   // check other subs contains operation that can be redoed
482   const std::set<std::string> aSubs = subDocuments(true);
483   std::set<std::string>::iterator aSubIter = aSubs.begin();
484   for (; aSubIter != aSubs.end(); aSubIter++) {
485     if (!subDoc(*aSubIter)->myObjs)
486       continue;
487     if (subDoc(*aSubIter)->canRedo())
488       return true;
489   }
490   return false;
491 }
492
493 void Model_Document::redo()
494 {
495   if (!myNestedNum.empty())
496     (*myNestedNum.rbegin())++;
497   int aNumRedos = myRedos.rbegin()->myOCAFNum;
498   myTransactions.push_back(*myRedos.rbegin());
499   myRedos.pop_back();
500   for(int a = 0; a < aNumRedos; a++)
501     myDoc->Redo();
502
503   // redo for all subs
504   const std::set<std::string> aSubs = subDocuments(true);
505   std::set<std::string>::iterator aSubIter = aSubs.begin();
506   for (; aSubIter != aSubs.end(); aSubIter++)
507     subDoc(*aSubIter)->redo();
508
509   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
510   myObjs->synchronizeFeatures(true, true, isRoot());
511   // update the current features status
512   setCurrentFeature(currentFeature(false), false);
513 }
514
515 std::list<std::string> Model_Document::undoList() const
516 {
517   std::list<std::string> aResult;
518   // the number of skipped current operations (on undo they will be aborted)
519   int aSkipCurrent = isOperation() ? 1 : 0;
520   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
521   int aNumUndo = myTransactions.size();
522   if (!myNestedNum.empty())
523     aNumUndo = *myNestedNum.rbegin();
524   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
525     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
526     else aSkipCurrent--;
527   }
528   return aResult;
529 }
530
531 std::list<std::string> Model_Document::redoList() const
532 {
533   std::list<std::string> aResult;
534   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
535   for( ; aTrIter != myRedos.crend(); aTrIter++) {
536     aResult.push_back(aTrIter->myId);
537   }
538   return aResult;
539 }
540
541 void Model_Document::operationId(const std::string& theId)
542 {
543   myTransactions.rbegin()->myId = theId;
544 }
545
546 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
547 {
548   std::shared_ptr<Model_Session> aSession = 
549     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
550   FeaturePtr aFeature = aSession->createFeature(theID, this);
551   if (!aFeature)
552     return aFeature;
553   Model_Document* aDocToAdd;
554   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
555     if (aFeature->documentToAdd() != kind()) { // the root document by default
556       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
557     } else {
558       aDocToAdd = this;
559     }
560   } else { // if customized is not presented, add to "this" document
561     aDocToAdd = this;
562   }
563   if (aFeature) {
564     aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
565     if (!aFeature->isAction()) {  // do not add action to the data model
566       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
567         aDocToAdd->setCurrentFeature(aFeature, false);
568     } else { // feature must be executed
569        // no creation event => updater not working, problem with remove part
570       aFeature->execute();
571     }
572   }
573   return aFeature;
574 }
575
576
577 void Model_Document::refsToFeature(FeaturePtr theFeature,
578   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
579 {
580   myObjs->refsToFeature(theFeature, theRefs, isSendError);
581 }
582
583 void Model_Document::removeFeature(FeaturePtr theFeature)
584 {
585   myObjs->removeFeature(theFeature);
586 }
587
588 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
589 {
590   myObjs->updateHistory(theObject);
591 }
592
593 void Model_Document::updateHistory(const std::string theGroup)
594 {
595   myObjs->updateHistory(theGroup);
596 }
597
598 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
599 {
600   return Model_Application::getApplication()->getDocument(theDocID);
601 }
602
603 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
604 {
605   std::set<std::string> aResult;
606   std::list<ResultPtr> aPartResults;
607   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
608   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
609   for(; aPartRes != aPartResults.end(); aPartRes++) {
610     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
611     if (aPart && (!theActivatedOnly || aPart->isActivated()))
612       aResult.insert(aPart->data()->name());
613   }
614   return aResult;
615 }
616
617 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
618 {
619   // just store sub-document identifier here to manage it later
620   return std::dynamic_pointer_cast<Model_Document>(
621     Model_Application::getApplication()->getDocument(theDocID));
622 }
623
624 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
625 {
626   return myObjs->object(theGroupID, theIndex);
627 }
628
629 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
630     const std::string& theGroupID, const std::string& theName)
631 {
632   return myObjs->objectByName(theGroupID, theName);
633 }
634
635 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
636 {
637   return myObjs->index(theObject);
638 }
639
640 int Model_Document::size(const std::string& theGroupID)
641 {
642   return myObjs->size(theGroupID);
643 }
644
645 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
646 {
647   if (!myObjs) // on close document feature destruction it may call this method
648     return std::shared_ptr<ModelAPI_Feature>();
649   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
650   Handle(TDF_Reference) aRef;
651   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
652     TDF_Label aLab = aRef->Get();
653     FeaturePtr aResult = myObjs->feature(aLab);
654     if (theVisible) { // get nearest visible (in history) going up
655       while(aResult.get() && !aResult->isInHistory()) {
656         aResult = myObjs->nextFeature(aResult, true);
657       }
658     }
659     return aResult;
660   }
661   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
662 }
663
664 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
665   const bool theVisible)
666 {
667   // blocks the flush signals to avoid each objects visualization in the viewer
668   // they should not be shown once after all modifications are performed
669   Events_Loop* aLoop = Events_Loop::loop();
670   bool isActive = aLoop->activateFlushes(false);
671
672   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
673   CompositeFeaturePtr aMain; // main feature that may nest the new current
674   if (theCurrent.get()) {
675     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
676     if (!aMain.get()) {
677       // if feature nests into compisite feature, make the composite feature as current
678       const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
679       std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
680       for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
681         CompositeFeaturePtr aComposite = 
682           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
683         if (aComposite.get() && aComposite->isSub(theCurrent)) {
684           aMain = aComposite;
685           break;
686         }
687       }
688     }
689   }
690
691   if (theVisible) { // make features below which are not in history also enabled: sketch subs
692     FeaturePtr aNext = 
693       theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
694     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
695       if (aNext->isInHistory()) {
696         break; // next in history is not needed
697       } else { // next not in history is good for making current
698         theCurrent = aNext;
699       }
700     }
701   }
702   if (theCurrent.get()) {
703     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
704     if (!aData.get() || !aData->isValid()) {
705       aLoop->activateFlushes(isActive);
706       return;
707     }
708     TDF_Label aFeatureLabel = aData->label().Father();
709
710     Handle(TDF_Reference) aRef;
711     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
712       aRef->Set(aFeatureLabel);
713     } else {
714       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
715     }
716   } else { // remove reference for the null feature
717     aRefLab.ForgetAttribute(TDF_Reference::GetID());
718   }
719   // make all features after this feature disabled in reversed order (to remove results without deps)
720   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
721   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
722   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
723
724   bool aPassed = false; // flag that the current object is already passed in cycle
725   FeaturePtr anIter = myObjs->lastFeature();
726   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
727     // check this before passed become enabled: the current feature is enabled!
728     if (anIter == theCurrent) aPassed = true;
729
730     bool aDisabledFlag = !aPassed;
731     if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
732       aDisabledFlag = false;
733     if (anIter->getKind() == "Parameter") // parameters are always out of the history
734       aDisabledFlag = false;
735     if (anIter->setDisabled(aDisabledFlag)) {
736       // state of feature is changed => so feature become updated
737       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
738       ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
739       // flush is in the end of this method
740       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
741     }
742   }
743   // unblock  the flush signals and up them after this
744   aLoop->activateFlushes(isActive);
745
746   aLoop->flush(aCreateEvent);
747   aLoop->flush(aRedispEvent);
748   aLoop->flush(aDeleteEvent);
749 }
750
751 void Model_Document::setCurrentFeatureUp()
752 {
753   // on remove just go up for minimum step: highlight external objects in sketch causes 
754   // problems if it is true: here and in "setCurrentFeature"
755   FeaturePtr aCurrent = currentFeature(false);
756   if (aCurrent.get()) { // if not, do nothing because null is the upper
757     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
758     setCurrentFeature(aPrev, false);
759   }
760 }
761
762 TDF_Label Model_Document::generalLabel() const
763 {
764   return myDoc->Main().FindChild(TAG_GENERAL);
765 }
766
767 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
768     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
769 {
770   return myObjs->createConstruction(theFeatureData, theIndex);
771 }
772
773 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
774     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
775 {
776   return myObjs->createBody(theFeatureData, theIndex);
777 }
778
779 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
780     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
781 {
782   return myObjs->createPart(theFeatureData, theIndex);
783 }
784
785 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
786     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
787 {
788   return myObjs->createGroup(theFeatureData, theIndex);
789 }
790
791 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
792       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
793 {
794   return myObjs->createParameter(theFeatureData, theIndex);
795 }
796
797 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
798     const std::shared_ptr<ModelAPI_Result>& theResult)
799 {
800   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
801   if (aData) {
802     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
803     return myObjs->feature(aFeatureLab);
804   }
805   return FeaturePtr();
806 }
807
808 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
809 {
810   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
811
812 }
813 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
814 {
815   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
816 }
817
818 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
819 {
820   myNamingNames[theName] = theLabel;
821 }
822
823 TDF_Label Model_Document::findNamingName(std::string theName)
824 {
825   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
826   if (aFind == myNamingNames.end())
827     return TDF_Label(); // not found
828   return aFind->second;
829 }
830
831 ResultPtr Model_Document::findByName(const std::string theName)
832 {
833   return myObjs->findByName(theName);
834 }
835
836 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
837 {
838   return myObjs->allFeatures();
839 }
840
841 void Model_Document::setActive(const bool theFlag)
842 {
843   if (theFlag != myIsActive) {
844     myIsActive = theFlag;
845     // redisplay all the objects of this part
846     static Events_Loop* aLoop = Events_Loop::loop();
847     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
848
849     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
850       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
851         object(ModelAPI_Feature::group(), a));
852       if (aFeature.get() && aFeature->data()->isValid()) {
853         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
854         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
855         for(; aRes != aResList.end(); aRes++) {
856           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
857         }
858       }
859     }
860   }
861 }
862
863 bool Model_Document::isActive() const
864 {
865   return myIsActive;
866 }
867
868 int Model_Document::transactionID()
869 {
870   Handle(TDataStd_Integer) anIndex;
871   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
872       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
873     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
874   }
875   return anIndex->Get();
876 }
877
878 void Model_Document::incrementTransactionID()
879 {
880   int aNewVal = transactionID() + 1;
881   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
882 }
883 void Model_Document::decrementTransactionID()
884 {
885   int aNewVal = transactionID() - 1;
886   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
887 }