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