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