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