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