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