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