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