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