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