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