Salome HOME
a8a82e1af680f5f0dfbfc2c1897a32eed5e30013
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Document.h>
22 #include <Model_Data.h>
23 #include <Model_Objects.h>
24 #include <Model_Application.h>
25 #include <Model_Session.h>
26 #include <Model_Events.h>
27 #include <ModelAPI_ResultPart.h>
28 #include <ModelAPI_Validator.h>
29 #include <ModelAPI_CompositeFeature.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <Events_Loop.h>
34 #include <Events_InfoMessage.h>
35 #include <GeomAPI_Tools.h>
36
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_Comment.hxx>
39 #include <TDF_ChildIDIterator.hxx>
40 #include <TDataStd_ReferenceArray.hxx>
41 #include <TDataStd_ReferenceList.hxx>
42 #include <TDataStd_IntegerArray.hxx>
43 #include <TDataStd_HLabelArray1.hxx>
44 #include <TDataStd_Name.hxx>
45 #include <TDataStd_AsciiString.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_Delta.hxx>
49 #include <TDF_AttributeDelta.hxx>
50 #include <TDF_AttributeDeltaList.hxx>
51 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
52 #include <TDF_ListIteratorOfLabelList.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_Tool.hxx>
55 #include <TDF_DeltaOnAddition.hxx>
56 #include <TDataStd_ExtStringList.hxx>
57 #include <TDataStd_UAttribute.hxx>
58 #include <TNaming_Builder.hxx>
59 #include <TNaming_SameShapeIterator.hxx>
60 #include <TNaming_Iterator.hxx>
61 #include <TNaming_NamedShape.hxx>
62 #include <TNaming_Tool.hxx>
63 #include<TNaming_OldShapeIterator.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_ListOfShape.hxx>
66
67 #include <TopExp_Explorer.hxx>
68 #include <TopoDS_Shape.hxx>
69
70 #include <OSD_File.hxx>
71 #include <OSD_Path.hxx>
72 #include <CDF_Session.hxx>
73 #include <CDF_Directory.hxx>
74
75 #include <climits>
76 #ifndef WIN32
77 #include <sys/stat.h>
78 #endif
79
80 #ifdef WIN32
81 # define _separator_ '\\'
82 #else
83 # define _separator_ '/'
84 #endif
85
86 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
87
88 static const int TAG_GENERAL = 1;  // general properties tag
89
90 // general sub-labels
91 /// where the reference to the current feature label is located (or no attribute if null feature)
92 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
93 /// integer, index of the transaction + GUID for auto recomputation blocking
94 static const int TAG_CURRENT_TRANSACTION = 2;
95 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
96 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
97 ///< naming structures constructions selected from other document
98 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
99
100 /// reference to the shape in external document: sting list attribute identifier
101 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
102
103 Model_Document::Model_Document(const int theID, const std::string theKind)
104     : myID(theID), myKind(theKind), myIsActive(false), myIsSetCurrentFeature(false),
105       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
106 {
107 #ifdef TINSPECTOR
108   CDF_Session::CurrentSession()->Directory()->Add(myDoc);
109 #endif
110   myObjs = new Model_Objects(myDoc->Main());
111   myDoc->SetUndoLimit(UNDO_LIMIT);
112   myTransactionSave = 0;
113   myExecuteFeatures = true;
114   // to have something in the document and avoid empty doc open/save problem
115   // in transaction for nesting correct working
116   myDoc->NewCommand();
117   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
118   // this to avoid creation of integer attribute outside the transaction after undo
119   transactionID();
120   myDoc->CommitCommand();
121 }
122
123 void Model_Document::setThis(DocumentPtr theDoc)
124 {
125   myObjs->setOwner(theDoc);
126 }
127
128 /// Returns the file name of this document by the name of directory and identifier of a document
129 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
130 {
131   TCollection_ExtendedString aPath((const Standard_CString) theDirName);
132   // remove end-separators
133   while(aPath.Length() &&
134         (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
135     aPath.Remove(aPath.Length());
136   aPath += _separator_;
137   aPath += theID.c_str();
138   aPath += ".cbf";  // standard binary file extension
139   return aPath;
140 }
141
142 bool Model_Document::isRoot() const
143 {
144   return this == Model_Session::get()->moduleDocument().get();
145 }
146
147 // LCOV_EXCL_START
148 /// Makes all modification and generation naming shapes that have old shapes corresponding to
149 /// shapes in a root document be equal to this root document
150 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
151 {
152   TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
153   TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
154   for(; aThisIter.More(); aThisIter.Next()) {
155     aCurrentToRoot.Clear();
156     Handle(TNaming_NamedShape) aNS;
157     if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
158       continue;
159     if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
160       continue;
161     for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
162       const TopoDS_Shape& anOld = aNSIter.OldShape();
163       if (anOld.IsNull())
164         continue;
165       TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
166       for (; aNewIter.More(); aNewIter.Next()) {
167         TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
168         if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
169           break;
170       }
171       if (aNewIter.More())
172         continue;
173       GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
174       anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
175       anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
176
177       // search the same shape in the root document
178       Handle(TDataStd_ExtStringList) anEntries =
179         Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
180       TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
181       for (; anIter.More(); anIter.Next()) {
182         TDF_Label aRootLab;
183         TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
184         if (aRootLab.IsNull())
185           continue;
186         Handle(TNaming_NamedShape) aRootNS;
187         if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
188           continue;
189         TNaming_Iterator aRootShapes(aRootNS);
190         for (; aRootShapes.More(); aRootShapes.Next()) {
191           if (aRootShapes.NewShape().IsNull())
192             continue;
193           aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
194           aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
195           if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
196             continue;
197           // found a good corresponded shape
198           if (!anOld.IsEqual(aRootShapes.NewShape()))
199             aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
200         }
201       }
202     }
203     if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
204       TopTools_ListOfShape anOld, aNew;
205       TNaming_Evolution anEvol = aNS->Evolution();
206       for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
207         anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
208           aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
209         aNew.Prepend(aNSIter.NewShape());
210       }
211       TNaming_Builder aBuilder(aNS->Label());
212       TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
213       for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
214         if (anEvol == TNaming_GENERATED) {
215           aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
216         } else if (anEvol == TNaming_MODIFY) {
217           aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
218         }
219       }
220     }
221   }
222 }
223 // LCOV_EXCL_STOP
224
225 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
226 {
227   Handle(Model_Application) anApp = Model_Application::getApplication();
228   if (isRoot()) {
229     anApp->setLoadPath(theDirName);
230   }
231   TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
232   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
233   Handle(TDocStd_Document) aLoaded;
234   try {
235     aStatus = anApp->Open(aPath, aLoaded);
236   } catch (Standard_Failure const& anException) {
237     Events_InfoMessage("Model_Document",
238         "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
239     return false;
240   }
241   bool isError = aStatus != PCDM_RS_OK;
242   if (isError) {
243     // LCOV_EXCL_START
244     switch (aStatus) {
245       case PCDM_RS_UnknownDocument:
246         Events_InfoMessage("Model_Document", "Can not open document").send();
247         break;
248       case PCDM_RS_AlreadyRetrieved:
249         Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
250         break;
251       case PCDM_RS_AlreadyRetrievedAndModified:
252         Events_InfoMessage("Model_Document",
253             "Can not open document: already opened and modified").send();
254         break;
255       case PCDM_RS_NoDriver:
256         Events_InfoMessage("Model_Document",
257                            "Can not open document: driver library is not found").send();
258         break;
259       case PCDM_RS_UnknownFileDriver:
260         Events_InfoMessage("Model_Document",
261                            "Can not open document: unknown driver for opening").send();
262         break;
263       case PCDM_RS_OpenError:
264         Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
265         break;
266       case PCDM_RS_NoVersion:
267         Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
268         break;
269       case PCDM_RS_NoModel:
270         Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
271         break;
272       case PCDM_RS_NoDocument:
273         Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
274         break;
275       case PCDM_RS_FormatFailure:
276         Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
277         break;
278       case PCDM_RS_TypeNotFoundInSchema:
279         Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
280         break;
281       case PCDM_RS_UnrecognizedFileFormat:
282         Events_InfoMessage("Model_Document",
283                            "Can not open document: unrecognized file format").send();
284         break;
285       case PCDM_RS_MakeFailure:
286         Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
287         break;
288       case PCDM_RS_PermissionDenied:
289         Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
290         break;
291       case PCDM_RS_DriverFailure:
292         Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
293         break;
294       default:
295         Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
296         break;
297     }
298     // LCOV_EXCL_STOP
299   }
300   std::shared_ptr<Model_Session> aSession =
301     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
302   if (!isError) {
303     myDoc = aLoaded;
304     myDoc->SetUndoLimit(UNDO_LIMIT);
305
306     // to avoid the problem that feature is created in the current, not this, document
307     aSession->setActiveDocument(anApp->document(myID), false);
308     aSession->setCheckTransactions(false);
309     if (myObjs)
310       delete myObjs;
311     myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
312     myObjs->setOwner(theThis);
313     // update the current features status
314     setCurrentFeature(currentFeature(false), false);
315     aSession->setCheckTransactions(true);
316     aSession->setActiveDocument(aSession->moduleDocument(), false);
317     // this is done in Part result "activate", so no needed here. Causes not-blue active part.
318     // aSession->setActiveDocument(anApp->getDocument(myID), true);
319
320     // make sub-parts as loaded by demand
321     std::list<ResultPtr> aPartResults;
322     myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
323     std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
324     for(; aPartRes != aPartResults.end(); aPartRes++) {
325       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
326       if (aPart.get())
327         anApp->setLoadByDemand(aPart->data()->name(),
328           aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
329     }
330     if (!isRoot()) {
331       updateShapesFromRoot(myDoc->Main(),
332         std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
333     }
334   } else { // open failed, but new document was created to work with it: inform the model
335     aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
336   }
337   return !isError;
338 }
339
340 bool Model_Document::save(
341   const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
342 {
343   // if the history line is not in the end, move it to the end before save, otherwise
344   // problems with results restore and (the most important) naming problems will appear
345   // due to change evolution to SELECTION (problems in NamedShape and Name)
346   FeaturePtr aWasCurrent;
347   std::shared_ptr<Model_Session> aSession =
348     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
349   if (currentFeature(false) != lastFeature()) {
350     aSession->setCheckTransactions(false);
351     aWasCurrent = currentFeature(false);
352     // if last is nested into something else, make this something else as last:
353     // otherwise it will look like edition of sub-element, so, the main will be disabled
354     FeaturePtr aLast = lastFeature();
355     if (aLast.get()) {
356       CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
357       while(aMain.get()) {
358         aLast = aMain;
359         aMain = ModelAPI_Tools::compositeOwner(aLast);
360       }
361     }
362     setCurrentFeature(aLast, true);
363   }
364   // create a directory in the root document if it is not yet exist
365   Handle(Model_Application) anApp = Model_Application::getApplication();
366   if (isRoot()) {
367 #ifdef WIN32
368     CreateDirectory((LPTSTR) theDirName, NULL);
369 #else
370     mkdir(theDirName, 0x1ff);
371 #endif
372   }
373   // filename in the dir is id of document inside of the given directory
374   TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
375   PCDM_StoreStatus aStatus;
376   try {
377     aStatus = anApp->SaveAs(myDoc, aPath);
378   } catch (Standard_Failure const& anException) {
379     Events_InfoMessage("Model_Document",
380         "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
381     if (aWasCurrent.get()) { // return the current feature to the initial position
382       setCurrentFeature(aWasCurrent, false);
383       aSession->setCheckTransactions(true);
384     }
385     return false;
386   }
387   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
388   if (!isDone) {
389     switch (aStatus) {
390       case PCDM_SS_DriverFailure:
391         Events_InfoMessage("Model_Document",
392                            "Can not save document: save driver-library failure").send();
393         break;
394       case PCDM_SS_WriteFailure:
395         Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
396         break;
397       case PCDM_SS_Failure:
398       default:
399         Events_InfoMessage("Model_Document", "Can not save document").send();
400         break;
401     }
402   }
403
404   if (aWasCurrent.get()) { // return the current feature to the initial position
405     setCurrentFeature(aWasCurrent, false);
406     aSession->setCheckTransactions(true);
407   }
408
409   myTransactionSave = int(myTransactions.size());
410   if (isDone) {  // save also sub-documents if any
411     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
412     // iterate all result parts to find all loaded or not yet loaded documents
413     std::list<ResultPtr> aPartResults;
414     myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
415     std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
416     for(; aPartRes != aPartResults.end(); aPartRes++) {
417       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
418       if (!aPart->isActivated()) {
419         // copy not-activated document that is not in the memory
420         std::string aDocName = aPart->data()->name();
421         if (!aDocName.empty()) {
422           // just copy file
423           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
424           OSD_Path aPath(aSubPath);
425           OSD_File aFile(aPath);
426           if (aFile.Exists()) {
427             TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
428             OSD_Path aDestination(aDestinationDir);
429             aFile.Copy(aDestination);
430             theResults.push_back(aDestinationDir.ToCString());
431           } else {
432             Events_InfoMessage("Model_Document",
433               "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
434           }
435         }
436       } else { // simply save opened document
437         isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
438           save(theDirName, aPart->data()->name().c_str(), theResults);
439       }
440     }
441   }
442   return isDone;
443 }
444
445 void Model_Document::close(const bool theForever)
446 {
447   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
448   if (!isRoot() && this == aPM->activeDocument().get()) {
449     aPM->setActiveDocument(aPM->moduleDocument());
450   } else if (isRoot()) {
451     // erase the active document if root is closed
452     aPM->setActiveDocument(DocumentPtr());
453   }
454   // close all subs
455   const std::set<int> aSubs = subDocuments();
456   std::set<int>::iterator aSubIter = aSubs.begin();
457   for (; aSubIter != aSubs.end(); aSubIter++) {
458     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
459     if (aSub->myObjs) // if it was not closed before
460       aSub->close(theForever);
461   }
462
463   // close for this document needs no transaction in this document
464   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
465
466   // close all only if it is really asked, otherwise it can be undone/redone
467   if (theForever) {
468     // flush everything to avoid messages with bad objects
469     delete myObjs;
470     myObjs = 0;
471     if (myDoc->CanClose() == CDM_CCS_OK)
472       myDoc->Close();
473     mySelectionFeature.reset();
474   } else {
475     setCurrentFeature(FeaturePtr(), false); // disables all features
476     // update the OB: features are disabled (on remove of Part)
477     Events_Loop* aLoop = Events_Loop::loop();
478     static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
479     aLoop->flush(aDeleteEvent);
480   }
481
482   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
483 }
484
485 void Model_Document::startOperation()
486 {
487   incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
488   if (myDoc->HasOpenCommand()) {  // start of nested command
489     if (myDoc->CommitCommand()) {
490       // commit the current: it will contain all nested after compactification
491       myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
492     }
493     myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
494     myDoc->OpenCommand();
495   } else {  // start the simple command
496     myDoc->NewCommand();
497   }
498   // starts a new operation
499   myTransactions.push_back(Transaction());
500   if (!myNestedNum.empty())
501     (*myNestedNum.rbegin())++;
502   myRedos.clear();
503   // new command for all subs
504   const std::set<int> aSubs = subDocuments();
505   std::set<int>::iterator aSubIter = aSubs.begin();
506   for (; aSubIter != aSubs.end(); aSubIter++)
507     subDoc(*aSubIter)->startOperation();
508 }
509
510 void Model_Document::compactNested()
511 {
512   if (!myNestedNum.empty()) {
513     int aNumToCompact = *(myNestedNum.rbegin());
514     int aSumOfTransaction = 0;
515     for(int a = 0; a < aNumToCompact; a++) {
516       aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
517       myTransactions.pop_back();
518     }
519     // the latest transaction is the start of lower-level operation which starts the nested
520     myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
521     myNestedNum.pop_back();
522   }
523 }
524
525 /// Compares the content of the given attributes, returns true if equal.
526 /// This method is used to avoid empty transactions when only "current" is changed
527 /// to some value and then comes back in this transaction, so, it compares only
528 /// references and Boolean and Integer Arrays for the current moment.
529 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
530 {
531   if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
532     Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
533     Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
534     if (aRef1.IsNull() && aRef2.IsNull())
535       return true;
536     if (aRef1.IsNull() || aRef2.IsNull())
537       return false;
538     return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
539   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
540     Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
541     Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
542     if (anArr1.IsNull() && anArr2.IsNull())
543       return true;
544     if (anArr1.IsNull() || anArr2.IsNull())
545       return false;
546     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
547       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
548         if (a == 1 && // second is for display
549             anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
550             anArr2->Label().Depth() == 6))
551           continue;
552         if (anArr1->Value(a) != anArr2->Value(a))
553           return false;
554       }
555       return true;
556     }
557   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
558     Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
559     Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
560     if (anArr1.IsNull() && anArr2.IsNull())
561       return true;
562     if (anArr1.IsNull() || anArr2.IsNull())
563       return false;
564     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
565       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
566         if (anArr1->Value(a) != anArr2->Value(a)) {
567           // avoid the transaction ID checking
568           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
569             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
570             continue;
571           return false;
572         }
573       return true;
574     }
575   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
576     Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
577     Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
578     if (anArr1.IsNull() && anArr2.IsNull())
579       return true;
580     if (anArr1.IsNull() || anArr2.IsNull())
581       return false;
582     if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
583       for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
584         if (anArr1->Value(a) != anArr2->Value(a)) {
585           // avoid the transaction ID checking
586           if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
587             (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
588             continue;
589           return false;
590         }
591       return true;
592     }
593   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
594     Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
595     Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
596     if (aList1.IsNull() && aList2.IsNull())
597       return true;
598     if (aList1.IsNull() || aList2.IsNull())
599       return false;
600     const TDF_LabelList& aLList1 = aList1->List();
601     const TDF_LabelList& aLList2 = aList2->List();
602     TDF_ListIteratorOfLabelList aLIter1(aLList1);
603     TDF_ListIteratorOfLabelList aLIter2(aLList2);
604     for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
605       if (aLIter1.Value() != aLIter2.Value())
606         return false;
607     }
608     return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
609   } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
610     return true; // it just for created and removed feature: nothing is changed
611   }
612   return false;
613 }
614
615 /// Returns true if the last transaction is actually empty: modification to the same values
616 /// were performed only
617 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
618   Handle(TDF_Delta) aDelta;
619   aDelta = theDoc->GetUndos().Last();
620   TDF_LabelList aDeltaList;
621   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
622   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
623     return false;
624   }
625   // add also label of the modified attributes
626   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
627   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
628     Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
629     Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
630     if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
631       if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
632         Handle(TDF_Attribute) aCurrentAttr;
633         if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
634           if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
635             continue; // attribute is not changed actually
636           }
637         } else
638           if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
639             continue; // error message is disappeared
640         }
641       }
642     }
643     return false;
644   }
645   return true;
646 }
647
648 bool Model_Document::finishOperation()
649 {
650   bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
651   static std::shared_ptr<Model_Session> aSession =
652     std::static_pointer_cast<Model_Session>(Model_Session::get());
653
654   // open transaction if nested is closed to fit inside
655   // all synchronizeBackRefs and flushed consequences
656   if (isNestedClosed) {
657     myDoc->OpenCommand();
658   }
659   // do it before flashes to enable and recompute nesting features correctly
660   if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
661     // if all nested operations are closed, make current the higher level objects (to perform
662     // it in the python scripts correctly): sketch become current after creation of sub-elements
663     FeaturePtr aCurrent = currentFeature(false);
664     CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
665     while(aNext.get()) {
666       aMain = aNext;
667       aNext = ModelAPI_Tools::compositeOwner(aMain);
668     }
669     if (aMain.get() && aMain != aCurrent)
670       setCurrentFeature(aMain, false);
671   }
672   myObjs->synchronizeBackRefs();
673   Events_Loop* aLoop = Events_Loop::loop();
674   static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
675   static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
676   static const Events_ID kRedispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
677   static const Events_ID kDeletedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED);
678   aLoop->flush(kCreatedEvent);
679   aLoop->flush(kUpdatedEvent);
680   aLoop->flush(kRedispEvent);
681   aLoop->flush(kDeletedEvent);
682
683   if (isNestedClosed) {
684     if (myDoc->CommitCommand())
685       myTransactions.rbegin()->myOCAFNum++;
686   }
687
688   // this must be here just after everything is finished but before real transaction stop
689   // to avoid messages about modifications outside of the transaction
690   // and to rebuild everything after all updates and creates
691   if (isRoot()) { // once for root document
692     static std::shared_ptr<Events_Message> aFinishMsg
693       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
694     Events_Loop::loop()->send(aFinishMsg);
695   }
696
697   // for open of document with primitive box inside (finish transaction in initAttributes)
698   bool aWasActivatedFlushes = aLoop->activateFlushes(true);
699   while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
700         aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
701     aLoop->flush(kCreatedEvent);
702     aLoop->flush(kUpdatedEvent);
703     aLoop->flush(kRedispEvent);
704     aLoop->flush(kDeletedEvent);
705   }
706   aLoop->activateFlushes(aWasActivatedFlushes);
707
708   // to avoid "updated" message appearance by updater
709   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
710
711   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
712   bool aResult = false;
713   const std::set<int> aSubs = subDocuments();
714   std::set<int>::iterator aSubIter = aSubs.begin();
715   for (; aSubIter != aSubs.end(); aSubIter++)
716     if (subDoc(*aSubIter)->finishOperation())
717       aResult = true;
718
719   // transaction may be empty if this document was created during this transaction (create part)
720   if (!myTransactions.empty() && myDoc->CommitCommand()) {
721     // if commit is successful, just increment counters
722     if (isEmptyTransaction(myDoc)) { // erase this transaction
723       myDoc->Undo();
724       myDoc->ClearRedos();
725     } else {
726       myTransactions.rbegin()->myOCAFNum++;
727       aResult = true;
728     }
729   }
730
731   if (isNestedClosed) {
732     compactNested();
733   }
734   if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
735     aResult = myTransactions.rbegin()->myOCAFNum != 0;
736
737   if (!aResult && isRoot()) {
738     // nothing inside in all documents, so remove this transaction from the transactions list
739     undoInternal(true, false);
740   }
741   // on finish clear redo in any case (issue 446) and for all subs (issue 408)
742   myDoc->ClearRedos();
743   myRedos.clear();
744   for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
745     subDoc(*aSubIter)->myDoc->ClearRedos();
746     subDoc(*aSubIter)->myRedos.clear();
747   }
748
749   return aResult;
750 }
751
752 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
753 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
754   const bool isRedo = false) {
755   Handle(TDF_Delta) aDelta;
756   if (isRedo)
757     aDelta = theDoc->GetRedos().First();
758   else
759     aDelta = theDoc->GetUndos().Last();
760   TDF_LabelList aDeltaList;
761   aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
762   for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
763     theDelta.Append(aListIter.Value());
764   }
765   // add also label of the modified attributes
766   const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
767   /// named shape evolution also modifies integer on this label: exclude it
768   TDF_LabelMap anExcludedInt;
769   for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
770     if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
771       // Boolean array is used for feature auxiliary attributes only, feature args are not modified
772       continue;
773     }
774     if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
775       anExcludedInt.Add(anAttr.Value()->Label());
776       // named shape evolution is changed in history update => skip them,
777       // they are not the features arguments
778       continue;
779     }
780     if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
781       if (anExcludedInt.Contains(anAttr.Value()->Label()))
782         continue;
783     }
784       theDelta.Append(anAttr.Value()->Label());
785   }
786   TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
787   for(; aDeltaIter.More(); aDeltaIter.Next()) {
788     if (anExcludedInt.Contains(aDeltaIter.Value())) {
789       theDelta.Remove(aDeltaIter);
790       if (!aDeltaIter.More())
791         break;
792     }
793   }
794 }
795
796 void Model_Document::abortOperation()
797 {
798   TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
799   if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
800     compactNested();
801     // store undo-delta here as undo actually does in the method later
802     int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
803     for(a = 0; a < aNumTransactions; a++) {
804       modifiedLabels(myDoc, aDeltaLabels);
805       myDoc->Undo();
806     }
807     for(a = 0; a < aNumTransactions; a++) {
808       myDoc->Redo();
809     }
810
811     undoInternal(false, false);
812     myDoc->ClearRedos();
813     myRedos.clear();
814   } else { // abort the current
815     int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
816     myTransactions.pop_back();
817     if (!myNestedNum.empty())
818       (*myNestedNum.rbegin())--;
819     // roll back the needed number of transactions
820     //myDoc->AbortCommand();
821     // instead of abort, do commit and undo: to get the delta of modifications
822     if (myDoc->CommitCommand())  {
823       modifiedLabels(myDoc, aDeltaLabels);
824       myDoc->Undo();
825     }
826     for(int a = 0; a < aNumTransactions; a++) {
827       modifiedLabels(myDoc, aDeltaLabels);
828       myDoc->Undo();
829     }
830     myDoc->ClearRedos();
831   }
832   // abort for all subs, flushes will be later, in the end of root abort
833   const std::set<int> aSubs = subDocuments();
834   std::set<int>::iterator aSubIter = aSubs.begin();
835   for (; aSubIter != aSubs.end(); aSubIter++)
836     subDoc(*aSubIter)->abortOperation();
837   // references may be changed because they are set in attributes on the fly
838   myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
839 }
840
841 bool Model_Document::isOperation() const
842 {
843   // operation is opened for all documents: no need to check subs
844   return myDoc->HasOpenCommand() == Standard_True ;
845 }
846
847 bool Model_Document::isModified()
848 {
849   // is modified if at least one operation was committed and not undone
850   return myTransactions.size() != myTransactionSave || isOperation();
851 }
852
853 bool Model_Document::canUndo()
854 {
855   // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
856   int aCurrentNum = isOperation() ? 1 : 0;
857   if (myDoc->GetAvailableUndos() > 0 &&
858       // there is something to undo in nested
859       (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
860       myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
861     return true;
862   // check other subs contains operation that can be undone
863   const std::set<int> aSubs = subDocuments();
864   std::set<int>::iterator aSubIter = aSubs.begin();
865   for (; aSubIter != aSubs.end(); aSubIter++) {
866     std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
867     if (aSub->myObjs) {// if it was not closed before
868       if (aSub->canUndo())
869         return true;
870     }
871   }
872
873   return false;
874 }
875
876 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
877 {
878   if (myTransactions.empty())
879     return;
880   int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
881   myRedos.push_back(*myTransactions.rbegin());
882   myTransactions.pop_back();
883   if (!myNestedNum.empty())
884     (*myNestedNum.rbegin())--;
885   // roll back the needed number of transactions
886   TDF_LabelList aDeltaLabels;
887   for(int a = 0; a < aNumTransactions; a++) {
888     if (theSynchronize)
889       modifiedLabels(myDoc, aDeltaLabels);
890     myDoc->Undo();
891   }
892
893   if (theWithSubs) {
894     // undo for all subs
895     const std::set<int> aSubs = subDocuments();
896     std::set<int>::iterator aSubIter = aSubs.begin();
897     for (; aSubIter != aSubs.end(); aSubIter++) {
898       if (!subDoc(*aSubIter)->myObjs)
899         continue;
900       subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
901     }
902   }
903   // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
904   if (theSynchronize) {
905     myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
906     // update the current features status
907     setCurrentFeature(currentFeature(false), false);
908   }
909 }
910
911 void Model_Document::undo()
912 {
913   undoInternal(true, true);
914 }
915
916 bool Model_Document::canRedo()
917 {
918   if (!myRedos.empty())
919     return true;
920   // check other subs contains operation that can be redone
921   const std::set<int> aSubs = subDocuments();
922   std::set<int>::iterator aSubIter = aSubs.begin();
923   for (; aSubIter != aSubs.end(); aSubIter++) {
924     if (!subDoc(*aSubIter)->myObjs)
925       continue;
926     if (subDoc(*aSubIter)->canRedo())
927       return true;
928   }
929   return false;
930 }
931
932 void Model_Document::redo()
933 {
934   if (!myNestedNum.empty())
935     (*myNestedNum.rbegin())++;
936   int aNumRedos = myRedos.rbegin()->myOCAFNum;
937   myTransactions.push_back(*myRedos.rbegin());
938   myRedos.pop_back();
939   TDF_LabelList aDeltaLabels;
940   for(int a = 0; a < aNumRedos; a++) {
941     modifiedLabels(myDoc, aDeltaLabels, true);
942     myDoc->Redo();
943   }
944
945   // redo for all subs
946   const std::set<int> aSubs = subDocuments();
947   std::set<int>::iterator aSubIter = aSubs.begin();
948   for (; aSubIter != aSubs.end(); aSubIter++)
949     subDoc(*aSubIter)->redo();
950
951   // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
952   myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
953   // update the current features status
954   setCurrentFeature(currentFeature(false), false);
955 }
956 // this is used for creation of undo/redo1-list by GUI
957 // LCOV_EXCL_START
958 std::list<std::string> Model_Document::undoList() const
959 {
960   std::list<std::string> aResult;
961   // the number of skipped current operations (on undo they will be aborted)
962   int aSkipCurrent = isOperation() ? 1 : 0;
963   std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
964   int aNumUndo = int(myTransactions.size());
965   if (!myNestedNum.empty())
966     aNumUndo = *myNestedNum.rbegin();
967   for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
968     if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
969     else aSkipCurrent--;
970   }
971   return aResult;
972 }
973
974 std::list<std::string> Model_Document::redoList() const
975 {
976   std::list<std::string> aResult;
977   std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
978   for( ; aTrIter != myRedos.crend(); aTrIter++) {
979     aResult.push_back(aTrIter->myId);
980   }
981   return aResult;
982 }
983 // LCOV_EXCL_STOP
984
985 void Model_Document::operationId(const std::string& theId)
986 {
987   myTransactions.rbegin()->myId = theId;
988 }
989
990 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
991 {
992   std::shared_ptr<Model_Session> aSession =
993     std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
994   FeaturePtr aFeature = aSession->createFeature(theID, this);
995   if (!aFeature)
996     return aFeature;
997   aFeature->init();
998   Model_Document* aDocToAdd;
999   if (!aFeature->documentToAdd().empty()) { // use the customized document to add
1000     if (aFeature->documentToAdd() != kind()) { // the root document by default
1001       aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
1002     } else {
1003       aDocToAdd = this;
1004     }
1005   } else { // if customized is not presented, add to "this" document
1006     aDocToAdd = this;
1007   }
1008   if (aFeature) {
1009     // searching for feature after which must be added the next feature: this is the current feature
1010     // but also all sub-features of this feature
1011     FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1012     bool isModified = true;
1013     for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1014         aComp.get() && isModified;
1015         aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1016       isModified =  false;
1017       int aSubs = aComp->numberOfSubs(false);
1018       for(int a = 0; a < aSubs; a++) {
1019         FeaturePtr aSub = aComp->subFeature(a, false);
1020         if (aSub && myObjs->isLater(aSub, aCurrent)) {
1021           isModified =  true;
1022           aCurrent = aSub;
1023         }
1024       }
1025     }
1026     aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1027     if (!aFeature->isAction()) {  // do not add action to the data model
1028       if (theMakeCurrent)  // after all this feature stays in the document, so make it current
1029         aDocToAdd->setCurrentFeature(aFeature, false);
1030     } else { // feature must be executed
1031        // no creation event => updater not working, problem with remove part
1032       aFeature->execute();
1033     }
1034   }
1035   return aFeature;
1036 }
1037
1038 void Model_Document::refsToFeature(FeaturePtr theFeature,
1039   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1040 {
1041   myObjs->refsToFeature(theFeature, theRefs, isSendError);
1042 }
1043
1044 void Model_Document::removeFeature(FeaturePtr theFeature)
1045 {
1046   myObjs->removeFeature(theFeature);
1047   // fix for #2723: send signal that part is updated
1048   if (!isRoot() && isOperation()) {
1049     std::shared_ptr<Model_Document> aRoot =
1050       std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1051     std::list<ResultPtr> allParts;
1052     aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1053     std::list<ResultPtr>::iterator aParts = allParts.begin();
1054     for(; aParts != allParts.end(); aParts++) {
1055       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1056       if (aPart->partDoc().get() == this) {
1057         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1058         ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1059         break;
1060       }
1061     }
1062   }
1063 }
1064
1065 // recursive function to check if theSub is a child of theMain composite feature
1066 // through all the hierarchy of parents
1067 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1068   CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1069   if (!aParent.get())
1070     return false;
1071   if (aParent == theMain)
1072     return true;
1073   return isSub(theMain, aParent);
1074 }
1075
1076 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
1077 {
1078   bool aCurrentUp = theMoved == currentFeature(false);
1079   if (aCurrentUp) {
1080     setCurrentFeatureUp();
1081   }
1082   // if user adds after high-level feature with nested,
1083   // add it after all nested (otherwise the nested will be disabled)
1084   CompositeFeaturePtr aCompositeAfter =
1085     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1086   FeaturePtr anAfterThisSub = theAfterThis;
1087   if (aCompositeAfter.get()) {
1088     FeaturePtr aSub = aCompositeAfter;
1089     int anIndex = kUNDEFINED_FEATURE_INDEX;
1090     do {
1091       FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1092       if (!isSub(aCompositeAfter, aNext)) {
1093         anAfterThisSub = aSub;
1094         break;
1095       }
1096       aSub = aNext;
1097     } while (aSub.get());
1098   }
1099
1100   myObjs->moveFeature(theMoved, anAfterThisSub);
1101   if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1102     setCurrentFeature(currentFeature(false), false);
1103   } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1104     // must be after move to make enabled all features which are before theMoved
1105     setCurrentFeature(theMoved, true);
1106   }
1107 }
1108
1109 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1110 {
1111   if (myObjs)
1112     myObjs->updateHistory(theObject);
1113 }
1114
1115 void Model_Document::updateHistory(const std::string theGroup)
1116 {
1117   if (myObjs)
1118     myObjs->updateHistory(theGroup);
1119 }
1120
1121 const std::set<int> Model_Document::subDocuments() const
1122 {
1123   std::set<int> aResult;
1124   std::list<ResultPtr> aPartResults;
1125   myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1126   std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1127   for(; aPartRes != aPartResults.end(); aPartRes++) {
1128     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1129     if (aPart && aPart->isActivated()) {
1130       aResult.insert(aPart->original()->partDoc()->id());
1131     }
1132   }
1133   return aResult;
1134 }
1135
1136 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1137 {
1138   // just store sub-document identifier here to manage it later
1139   return std::dynamic_pointer_cast<Model_Document>(
1140     Model_Application::getApplication()->document(theDocID));
1141 }
1142
1143 ObjectPtr Model_Document::object(const std::string& theGroupID,
1144                                  const int theIndex,
1145                                  const bool theAllowFolder)
1146 {
1147   return myObjs->object(theGroupID, theIndex, theAllowFolder);
1148 }
1149
1150 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1151     const std::string& theGroupID, const std::string& theName)
1152 {
1153   return myObjs->objectByName(theGroupID, theName);
1154 }
1155
1156 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1157                                 const bool theAllowFolder)
1158 {
1159   return myObjs->index(theObject, theAllowFolder);
1160 }
1161
1162 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1163 {
1164   if (myObjs == 0) // may be on close
1165     return 0;
1166   return myObjs->size(theGroupID, theAllowFolder);
1167 }
1168
1169 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1170   const std::shared_ptr<ModelAPI_Object> theChild)
1171 {
1172   if(myObjs == 0) // may be on close
1173     return ObjectPtr();
1174   return myObjs->parent(theChild);
1175 }
1176
1177 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1178 {
1179   if (!myObjs) // on close document feature destruction it may call this method
1180     return std::shared_ptr<ModelAPI_Feature>();
1181   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1182   Handle(TDF_Reference) aRef;
1183   if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1184     TDF_Label aLab = aRef->Get();
1185     FeaturePtr aResult = myObjs->feature(aLab);
1186     if (theVisible) { // get nearest visible (in history) going up
1187       int anIndex = kUNDEFINED_FEATURE_INDEX;
1188       while(aResult.get() &&  !aResult->isInHistory()) {
1189         aResult = myObjs->nextFeature(aResult, anIndex, true);
1190       }
1191     }
1192     return aResult;
1193   }
1194   return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1195 }
1196
1197 void Model_Document::setCurrentFeature(
1198   std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1199 {
1200   if (myIsSetCurrentFeature)
1201     return;
1202   myIsSetCurrentFeature = true;
1203   // blocks the flush signals to avoid each objects visualization in the viewer
1204   // they should not be shown once after all modifications are performed
1205   Events_Loop* aLoop = Events_Loop::loop();
1206   bool isActive = aLoop->activateFlushes(false);
1207
1208   TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1209   CompositeFeaturePtr aMain; // main feature that may nest the new current
1210   std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1211   if (theCurrent.get()) {
1212     aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1213     CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1214     while(anOwner.get()) {
1215       if (!aMain.get()) {
1216         aMain = anOwner;
1217       }
1218       anOwners.insert(anOwner);
1219       anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1220     }
1221   }
1222
1223   if (theVisible && !theCurrent.get()) {
1224     // needed to avoid disabling of PartSet initial constructions
1225     int anIndex = kUNDEFINED_FEATURE_INDEX;
1226     FeaturePtr aNext =
1227       theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1228     for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1229       if (aNext->isInHistory()) {
1230         break; // next in history is not needed
1231       } else { // next not in history is good for making current
1232         theCurrent = aNext;
1233       }
1234     }
1235   }
1236   if (theCurrent.get()) {
1237     std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1238     if (!aData.get() || !aData->isValid()) {
1239       aLoop->activateFlushes(isActive);
1240       myIsSetCurrentFeature = false;
1241       return;
1242     }
1243     TDF_Label aFeatureLabel = aData->label().Father();
1244
1245     Handle(TDF_Reference) aRef;
1246     if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1247       aRef->Set(aFeatureLabel);
1248     } else {
1249       aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1250     }
1251   } else { // remove reference for the null feature
1252     aRefLab.ForgetAttribute(TDF_Reference::GetID());
1253   }
1254   // make all features after this feature disabled in reversed order
1255   // (to remove results without dependencies)
1256   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1257
1258   bool aPassed = false; // flag that the current object is already passed in cycle
1259   FeaturePtr anIter = myObjs->lastFeature();
1260   bool aWasChanged = false;
1261   bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1262   int anIndex = kUNDEFINED_FEATURE_INDEX;
1263   for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1264     // check this before passed become enabled: the current feature is enabled!
1265     if (anIter == theCurrent) aPassed = true;
1266
1267     bool aDisabledFlag = !aPassed;
1268     if (aMain.get()) {
1269       if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1270         aDisabledFlag = false;
1271       else if (anOwners.find(anIter) != anOwners.end())
1272         // disable the higher-level feature if the nested is the current
1273         if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1274           aDisabledFlag = true;
1275     }
1276
1277     if (anIter->getKind() == "Parameter") {
1278       // parameters are always out of the history of features, but not parameters
1279       // due to the issue 1491 all parameters are kept enabled any time
1280       //if (!isCurrentParameter)
1281         aDisabledFlag = false;
1282     } else if (isCurrentParameter) {
1283       // if parameter is active, all other features become enabled (issue 1307)
1284       aDisabledFlag = false;
1285     }
1286
1287     if (anIter->setDisabled(aDisabledFlag)) {
1288       static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1289       // state of feature is changed => so inform that it must be updated if it has such state
1290       if (!aDisabledFlag &&
1291           (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1292            anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1293         ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1294       // flush is in the end of this method
1295       ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1296       aWasChanged = true;
1297     }
1298     // update for everyone concealment flag immediately: on edit feature in the middle of history
1299     if (aWasChanged) {
1300       std::list<ResultPtr> aResults;
1301       ModelAPI_Tools::allResults(anIter, aResults);
1302       std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1303       for(; aRes != aResults.end(); aRes++) {
1304         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1305           std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1306       }
1307       // update the concealment status for display in isConcealed of ResultBody
1308       for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1309         if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1310           (*aRes)->isConcealed();
1311       }
1312     }
1313   }
1314   myIsSetCurrentFeature = false;
1315   // unblock  the flush signals and up them after this
1316   aLoop->activateFlushes(isActive);
1317 }
1318
1319 void Model_Document::setCurrentFeatureUp()
1320 {
1321   // on remove just go up for minimum step: highlight external objects in sketch causes
1322   // problems if it is true: here and in "setCurrentFeature"
1323   FeaturePtr aCurrent = currentFeature(false);
1324   if (aCurrent.get()) { // if not, do nothing because null is the upper
1325     int anIndex = kUNDEFINED_FEATURE_INDEX;
1326     FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1327     // make the higher level composite as current (sketch becomes disabled if line is enabled)
1328     if (aPrev.get()) {
1329       FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1330       // without cycle (issue 1555): otherwise extrusion fuse
1331       // will be enabled and displayed when inside sketch
1332       if (aComp.get())
1333           aPrev = aComp;
1334     }
1335     // do not flush: it is called only on remove, it will be flushed in the end of transaction
1336     setCurrentFeature(aPrev, false);
1337   }
1338 }
1339
1340 TDF_Label Model_Document::generalLabel() const
1341 {
1342   return myDoc->Main().FindChild(TAG_GENERAL);
1343 }
1344
1345 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1346     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1347 {
1348   return myObjs->createConstruction(theFeatureData, theIndex);
1349 }
1350
1351 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1352     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1353 {
1354   return myObjs->createBody(theFeatureData, theIndex);
1355 }
1356
1357 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1358     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1359 {
1360   return myObjs->createPart(theFeatureData, theIndex);
1361 }
1362
1363 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1364       const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1365       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1366 {
1367   return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1368 }
1369
1370 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1371     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1372 {
1373   return myObjs->createGroup(theFeatureData, theIndex);
1374 }
1375
1376 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1377     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1378 {
1379   return myObjs->createField(theFeatureData, theIndex);
1380 }
1381
1382 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1383       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1384 {
1385   return myObjs->createParameter(theFeatureData, theIndex);
1386 }
1387
1388 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1389     std::shared_ptr<ModelAPI_Feature> theAddBefore)
1390 {
1391   return myObjs->createFolder(theAddBefore);
1392 }
1393
1394 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1395 {
1396   if (theFolder)
1397     myObjs->removeFolder(theFolder);
1398 }
1399
1400 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1401       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1402 {
1403   return myObjs->findFolder(theFeatures, false);
1404 }
1405
1406 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1407       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1408 {
1409   return myObjs->findFolder(theFeatures, true);
1410 }
1411
1412 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1413       const std::shared_ptr<ModelAPI_Feature>& theFeature,
1414       int& theIndexInFolder)
1415 {
1416   return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1417 }
1418
1419 bool Model_Document::moveToFolder(
1420       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1421       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1422 {
1423   return myObjs->moveToFolder(theFeatures, theFolder);
1424 }
1425
1426 bool Model_Document::removeFromFolder(
1427       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1428       const bool theBefore)
1429 {
1430   return myObjs->removeFromFolder(theFeatures, theBefore);
1431 }
1432
1433 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1434     const std::shared_ptr<ModelAPI_Result>& theResult)
1435 {
1436   if (myObjs == 0) // may be on close
1437     return std::shared_ptr<ModelAPI_Feature>();
1438   return myObjs->feature(theResult);
1439 }
1440
1441 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1442   TDF_Label aCurrentLab = theLab;
1443   while(aCurrentLab.Depth() > 3)
1444     aCurrentLab = aCurrentLab.Father();
1445   return myObjs->feature(aCurrentLab);
1446 }
1447
1448 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1449 {
1450   TDF_Label aCurrentLab = theLab;
1451   while(aCurrentLab.Depth() > 3) {
1452     ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1453     if (aResultObj.get()) {
1454       return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1455     }
1456     aCurrentLab = aCurrentLab.Father();
1457   }
1458   return ResultPtr(); // not found
1459 }
1460
1461 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1462 {
1463   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1464
1465   if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1466     // to keep correct order in spite of history line management
1467     std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1468     FeaturePtr anAddedFeature = featureByLab(theLabel);
1469     std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1470     while(aLabIter != aFind->second.end()) {
1471       if (theLabel.IsEqual(*aLabIter)) {
1472         std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1473         aLabIter++;
1474         aFind->second.erase(aTmpIter);
1475       } else {
1476         FeaturePtr aCurFeature = featureByLab(*aLabIter);
1477         if (aCurFeature.get() && anAddedFeature.get() &&
1478             myObjs->isLater(anAddedFeature, aCurFeature))
1479           anAddAfterThis = aLabIter;
1480
1481         aLabIter++;
1482       }
1483     }
1484     if (anAddAfterThis != aFind->second.end()) {
1485       anAddAfterThis++;
1486       if (anAddAfterThis != aFind->second.end()) {
1487         myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1488         return;
1489       }
1490     }
1491   }
1492   myNamingNames[theName].push_back(theLabel);
1493 }
1494
1495 void Model_Document::changeNamingName(const std::string theOldName,
1496                                       const std::string theNewName,
1497                                       const TDF_Label& theLabel)
1498 {
1499   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1500   if (aFind != myNamingNames.end()) {
1501     std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1502     for(; aLabIter != aFind->second.end(); aLabIter++) {
1503       if (theLabel.IsEqual(*aLabIter)) { // found the label
1504         myNamingNames[theNewName].push_back(theLabel);
1505         if (aFind->second.size() == 1) { // only one element, so, just change the name
1506           myNamingNames.erase(theOldName);
1507         } else { // remove from the list
1508           aFind->second.erase(aLabIter);
1509         }
1510         // check the sketch vertex name located under renamed sketch line
1511         TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1512         for(; aChild.More(); aChild.Next()) {
1513           Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1514           std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
1515           if (aName.find(theOldName) == 0) { // started from parent name
1516             std::string aNewSubName = theNewName + aName.substr(theNewName.size());
1517             changeNamingName(aName, aNewSubName, aSubName->Label());
1518             aSubName->Set(aNewSubName.c_str());
1519           }
1520         }
1521         return;
1522       }
1523     }
1524   }
1525 }
1526
1527 TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theContext)
1528 {
1529   std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1530   if (aFind != myNamingNames.end()) {
1531       std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1532       for(; aLabIter != aFind->second.rend(); aLabIter++) {
1533         if (theContext.get()) {
1534           // context is defined and not like this, so, skip
1535           if (theContext == myObjs->object(aLabIter->Father()))
1536             return *aLabIter;
1537         }
1538       }
1539       return *(aFind->second.rbegin()); // no more variants, so, return the last
1540   }
1541   // not found exact name, try to find by sub-components
1542   std::string::size_type aSlash = theName.rfind('/');
1543   if (aSlash != std::string::npos) {
1544     std::string anObjName = theName.substr(0, aSlash);
1545     aFind = myNamingNames.find(anObjName);
1546     if (aFind != myNamingNames.end()) {
1547       TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1548       // iterate all possible same-named labels starting from the last one (the recent)
1549       std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1550       for(; aLabIter != aFind->second.rend(); aLabIter++) {
1551         if (theContext.get()) {
1552           // context is defined and not like this, so, skip
1553           if (theContext != myObjs->object(aLabIter->Father()))
1554             continue;
1555         }
1556         // copy aSubName to avoid incorrect further processing after its suffix cutting
1557         TCollection_ExtendedString aSubNameCopy(aSubName);
1558         // searching sub-labels with this name
1559         TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1560         for(; aNamesIter.More(); aNamesIter.Next()) {
1561           Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1562           if (aName->Get() == aSubNameCopy)
1563             return aName->Label();
1564         }
1565         // If not found child label with the exact sub-name, then try to find compound with
1566         // such sub-name without suffix.
1567         Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1568         if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1569           TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1570           aSubNameCopy.Remove(aSuffixPos);
1571           aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1572           for(; aNamesIter.More(); aNamesIter.Next()) {
1573             Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1574             if (aName->Get() == aSubNameCopy) {
1575               return aName->Label();
1576             }
1577           }
1578           // check also "this" label
1579           Handle(TDataStd_Name) aName;
1580           if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1581             if (aName->Get() == aSubNameCopy) {
1582               return aName->Label();
1583             }
1584           }
1585         }
1586       }
1587       // verify context's name is same as sub-component's and use context's label
1588       if (aSubName.IsEqual(anObjName.c_str()))
1589         return *(aFind->second.rbegin());
1590     }
1591   }
1592   return TDF_Label(); // not found
1593 }
1594
1595 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1596   // check dependencies first: if theOther depends on theThis, theThis is not later
1597   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1598   theOther->data()->referencesToObjects(aRefs);
1599   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1600     aRefIt = aRefs.begin();
1601   for(; aRefIt != aRefs.end(); aRefIt++) {
1602     std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1603     for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1604       ObjectPtr aRefObj = *aRefObjIt;
1605       if (aRefObj.get()) {
1606         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1607         if (!aRefFeat.get()) { // take feature of the result
1608           aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1609         }
1610         if (aRefFeat.get()) {
1611           if (aRefFeat == theThis)
1612             return false; // other references to this, so other later than this
1613           //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1614           //  if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1615           //    return false;
1616           //}
1617         }
1618       }
1619     }
1620   }
1621   FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1622   if (aThisOwner.get()) {
1623     if (aThisOwner == theOther)
1624       return true; // composite owner is later that its sub
1625     if (!isLaterByDep(aThisOwner, theOther))
1626       return false;
1627   }
1628   return myObjs->isLater(theThis, theOther);
1629 }
1630
1631 int Model_Document::numberOfNameInHistory(
1632   const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1633 {
1634   std::map<std::string, std::list<TDF_Label> >::iterator aFind =
1635     myNamingNames.find(theNameObject->data()->name());
1636   if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1637     return 1; // no need to specify the name by additional identifiers
1638   }
1639   // get the feature of the object for relative compare
1640   FeaturePtr aStart = myObjs->feature(theStartFrom);
1641   if (!aStart.get()) // strange, but can not find feature by the label
1642     return 1;
1643   // feature that contain result with this name
1644   FeaturePtr aNameFeature;
1645   ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1646   if (aNameResult)
1647     aNameFeature = myObjs->feature(aNameResult);
1648   else
1649     aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1650   // iterate all labels with this name to find the nearest just before or equal relative
1651   std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1652   for(; aLabIter != aFind->second.rend(); aLabIter++) {
1653     FeaturePtr aLabFeat = featureByLab(*aLabIter);
1654     if (!aLabFeat.get())
1655       continue;
1656     if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1657       break;
1658   }
1659   int aResIndex = 1;
1660   for(; aLabIter != aFind->second.rend(); aLabIter++) {
1661     FeaturePtr aLabFeat = featureByLab(*aLabIter);
1662     if (!aLabFeat.get())
1663       continue;
1664     if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1665       return aResIndex;
1666     aResIndex++;
1667   }
1668   return aResIndex; // strange
1669 }
1670
1671 ResultPtr Model_Document::findByName(
1672   std::string& theName, std::string& theSubShapeName, bool& theUniqueContext)
1673 {
1674   int aNumInHistory = 0;
1675   std::string aName = theName;
1676   ResultPtr aRes = myObjs->findByName(aName);
1677   theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1678   while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1679     aNumInHistory++;
1680     aName = aName.substr(1);
1681     aRes = myObjs->findByName(aName);
1682   }
1683   if (aNumInHistory) {
1684     std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1685     if (aFind != myNamingNames.end() && aFind->second.size() > aNumInHistory) {
1686       std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1687       for(; aNumInHistory != 0; aNumInHistory--)
1688         aLibIt++;
1689       const TDF_Label& aResultLab = *aLibIt;
1690       aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1691       if (aRes) { // modify the incoming names
1692         if (!theSubShapeName.empty())
1693           theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1694         theName = aName;
1695       }
1696     }
1697   }
1698   return aRes;
1699 }
1700
1701 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1702 {
1703   return myObjs->allFeatures();
1704 }
1705
1706 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1707 {
1708   return myObjs->allObjects();
1709 }
1710
1711 void Model_Document::setActive(const bool theFlag)
1712 {
1713   if (theFlag != myIsActive) {
1714     myIsActive = theFlag;
1715     // redisplay all the objects of this part
1716     static Events_Loop* aLoop = Events_Loop::loop();
1717     static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1718
1719     for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1720       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1721         object(ModelAPI_Feature::group(), a));
1722       if (aFeature.get() && aFeature->data()->isValid()) {
1723         std::list<ResultPtr> aResults;
1724         ModelAPI_Tools::allResults(aFeature, aResults);
1725         for (std::list<ResultPtr>::iterator aRes = aResults.begin();
1726                                                 aRes != aResults.end(); aRes++) {
1727           ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1728         }
1729       }
1730     }
1731   }
1732 }
1733
1734 bool Model_Document::isActive() const
1735 {
1736   return myIsActive;
1737 }
1738
1739 int Model_Document::transactionID()
1740 {
1741   Handle(TDataStd_Integer) anIndex;
1742   if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1743       FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1744     anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1745   }
1746   return anIndex->Get();
1747 }
1748
1749 void Model_Document::incrementTransactionID()
1750 {
1751   int aNewVal = transactionID() + 1;
1752   TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1753 }
1754
1755 TDF_Label Model_Document::extConstructionsLabel() const
1756 {
1757   return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
1758 }
1759
1760 bool Model_Document::isOpened()
1761 {
1762   return myObjs && !myDoc.IsNull();
1763 }
1764
1765 int Model_Document::numInternalFeatures()
1766 {
1767   return myObjs->numInternalFeatures();
1768 }
1769
1770 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1771 {
1772   return myObjs->internalFeature(theIndex);
1773 }
1774
1775 void Model_Document::synchronizeTransactions()
1776 {
1777   Model_Document* aRoot =
1778     std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1779   if (aRoot == this)
1780     return; // don't need to synchronize root with root
1781
1782   std::shared_ptr<Model_Session> aSession =
1783     std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1784   while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
1785     aSession->setCheckTransactions(false);
1786     redo();
1787     aSession->setCheckTransactions(true);
1788   }
1789   /* this case can not be reproduced in any known case for the current moment, so, just comment
1790   while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
1791     undoInternal(false, true);
1792   }*/
1793 }
1794
1795 /// Feature that is used for selection in the Part document by the external request
1796 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1797 public:
1798   /// Nothing to do in constructor
1799   Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1800
1801   /// Returns the unique kind of a feature
1802   virtual const std::string& getKind() {
1803     static std::string MY_KIND("InternalSelectionInPartFeature");
1804     return MY_KIND;
1805   }
1806   /// Request for initialization of data model of the object: adding all attributes
1807   virtual void initAttributes() {
1808     data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1809   }
1810   /// Nothing to do in the execution function
1811   virtual void execute() {}
1812
1813 };
1814
1815 //! Returns the feature that is used for calculation of selection externally from the document
1816 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1817 {
1818   // return already created, otherwise create
1819   if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1820     // create a new one
1821     mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1822
1823     TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1824     std::shared_ptr<Model_Data> aData(new Model_Data);
1825     aData->setLabel(aFeatureLab.FindChild(1));
1826     aData->setObject(mySelectionFeature);
1827     mySelectionFeature->setDoc(myObjs->owner());
1828     mySelectionFeature->setData(aData);
1829     std::string aName = id() + "_Part";
1830     mySelectionFeature->data()->setName(aName);
1831     mySelectionFeature->setDoc(myObjs->owner());
1832     mySelectionFeature->initAttributes();
1833     mySelectionFeature->init(); // to make it enabled and Update correctly
1834     // this update may cause recomputation of the part after selection on it, that is not needed
1835     mySelectionFeature->data()->blockSendAttributeUpdated(true);
1836   }
1837   return mySelectionFeature->selectionList("selection");
1838 }
1839
1840 FeaturePtr Model_Document::lastFeature()
1841 {
1842   if (myObjs)
1843     return myObjs->lastFeature();
1844   return FeaturePtr();
1845 }
1846
1847 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1848   Handle(TNaming_NamedShape) aResult;
1849   while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1850     TopoDS_Shape aShape = theShape;
1851     theShape.Nullify();
1852     // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
1853     if (!TNaming_Tool::HasLabel(aMain, aShape))
1854       break;
1855     for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
1856       TDF_Label aNSLab = anIter.Label();
1857       Handle(TNaming_NamedShape) aNS;
1858       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1859         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1860           if (aShapesIter.Evolution() == TNaming_SELECTED ||
1861               aShapesIter.Evolution() == TNaming_DELETE)
1862             continue; // don't use the selection evolution
1863           if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1864             aResult = aNS;
1865             if (aResult->Evolution() == TNaming_MODIFY)
1866               theShape = aShapesIter.OldShape();
1867             // otherwise may me searching for another item of this shape with longer history
1868             if (!theShape.IsNull())
1869               break;
1870           }
1871         }
1872       }
1873     }
1874   }
1875   return aResult;
1876 }
1877
1878 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
1879     std::shared_ptr<ModelAPI_Result> theResult,
1880     const std::shared_ptr<GeomAPI_Shape>& theShape)
1881 {
1882   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1883   if (!aBody.get()) {
1884     return feature(theResult); // for not-body just returns the feature that produced this result
1885   }
1886   // otherwise get the shape and search the very initial label for it
1887   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1888   if (aShape.IsNull())
1889     return FeaturePtr();
1890
1891   // for compsolids and compounds all the naming is located in the main object, so, try to use
1892   // it first
1893   ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
1894   while (aMain.get()) { // get the top-most main
1895     ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
1896     if (aNextMain.get())
1897       aMain = aNextMain;
1898     else break;
1899   }
1900   if (aMain.get()) {
1901     FeaturePtr aMainRes = producedByFeature(aMain, theShape);
1902     if (aMainRes)
1903       return aMainRes;
1904   }
1905
1906   std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1907   if (!aBodyData.get() || !aBodyData->isValid())
1908     return FeaturePtr();
1909
1910   TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
1911   TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
1912   Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
1913   TDF_Label aBodyLab = aBodyData->shapeLab();
1914   // use child and this label (the lowest priority)
1915   TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
1916   bool aUseThis = !aNSIter.More();
1917   while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
1918     Handle(TNaming_NamedShape) aNS;
1919     if (aUseThis) {
1920       if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
1921         break;
1922     } else {
1923       aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1924     }
1925     for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1926       if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
1927         continue; // don't use the selection evolution
1928       if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1929         aCandidatInThis = aNS;
1930         if (aCandidatInThis->Evolution() == TNaming_MODIFY)
1931           anOldShape = aShapesIter.OldShape();
1932         // otherwise may me searching for another item of this shape with longer history
1933         if (!anOldShape.IsNull())
1934           break;
1935       }
1936       // check that the shape contains aShape as sub-shape to fill container
1937       if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
1938         TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
1939         for(; anExp.More(); anExp.Next()) {
1940           if (aShape.IsSame(anExp.Current())) {
1941             aCandidatContainer = aNS;
1942             aShapeContainer = aShapesIter.NewShape();
1943           }
1944         }
1945       }
1946     }
1947     // iterate to the next label or to the body label in the end
1948     if (!aUseThis)
1949       aNSIter.Next();
1950     if (!aNSIter.More()) {
1951       if (aUseThis)
1952         break;
1953       aUseThis = true;
1954     }
1955   }
1956   if (aCandidatInThis.IsNull()) {
1957     // to fix 1512: searching for original shape of this shape
1958     // if modification of it is not in this result
1959     aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
1960     if (aCandidatInThis.IsNull()) {
1961       if (aCandidatContainer.IsNull())
1962         return FeaturePtr();
1963       // with the lower priority use the higher level shape that contains aShape
1964       aCandidatInThis = aCandidatContainer;
1965       anOldShape = aShapeContainer;
1966     } else {
1967       // to stop the searching by the following searchForOriginalShape
1968       anOldShape.Nullify();
1969     }
1970   }
1971
1972   Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
1973   if (!aNS.IsNull())
1974     aCandidatInThis = aNS;
1975
1976   FeaturePtr aResult;
1977   TDF_Label aResultLab = aCandidatInThis->Label();
1978   while(aResultLab.Depth() > 3)
1979     aResultLab = aResultLab.Father();
1980   FeaturePtr aFeature = myObjs->feature(aResultLab);
1981   if (aFeature.get()) {
1982     if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
1983       aResult = aFeature;
1984     }
1985   }
1986   return aResult;
1987 }
1988
1989 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1990 {
1991   return myObjs->isLater(theLater, theCurrent);
1992 }
1993
1994 // Object Browser nodes states
1995 // LCOV_EXCL_START
1996 void Model_Document::storeNodesState(const std::list<bool>& theStates)
1997 {
1998   TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
1999   aLab.ForgetAllAttributes();
2000   if (!theStates.empty()) {
2001     Handle(TDataStd_BooleanArray) anArray =
2002       TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
2003     std::list<bool>::const_iterator aState = theStates.begin();
2004     for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2005       anArray->SetValue(anIndex, *aState);
2006     }
2007   }
2008 }
2009
2010 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2011 {
2012   TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2013   Handle(TDataStd_BooleanArray) anArray;
2014   if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2015     int anUpper = anArray->Upper();
2016     for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2017       theStates.push_back(anArray->Value(anIndex) == Standard_True);
2018     }
2019   }
2020 }
2021 // LCOV_EXCL_STOP
2022
2023 void Model_Document::eraseAllFeatures()
2024 {
2025   if (myObjs)
2026     myObjs->eraseAllFeatures();
2027 }
2028
2029 void Model_Document::setExecuteFeatures(const bool theFlag)
2030 {
2031   myExecuteFeatures = theFlag;
2032   const std::set<int> aSubs = subDocuments();
2033   std::set<int>::iterator aSubIter = aSubs.begin();
2034   for (; aSubIter != aSubs.end(); aSubIter++) {
2035     if (!subDoc(*aSubIter)->myObjs)
2036       continue;
2037     subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2038   }
2039 }
2040
2041 void Model_Document::appendTransactionToPrevious()
2042 {
2043   Transaction anAppended =  myTransactions.back();
2044   myTransactions.pop_back();
2045   if (!myTransactions.empty()) { // if it is empty, just forget the appended
2046     myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2047   }
2048   // propagate the same action to sub-documents
2049   const std::set<int> aSubs = subDocuments();
2050   for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2051     subDoc(*aSubIter)->appendTransactionToPrevious();
2052   }
2053 }
2054
2055 /// GUID for keeping information about the auto-recomputation state
2056 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2057
2058 void Model_Document::setAutoRecomutationState(const bool theState)
2059 {
2060   if (theState)
2061     generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2062   else
2063     TDataStd_UAttribute::Set(
2064       generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2065 }
2066
2067 bool Model_Document::autoRecomutationState() const
2068 {
2069   return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);
2070 }