Salome HOME
Fix for the issue #2903 : Crash when creating a group on all faces
[modules/shaper.git] / src / Model / Model_AttributeSelectionList.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "Model_AttributeSelectionList.h"
21 #include "Model_AttributeSelection.h"
22 #include "Model_Application.h"
23 #include "Model_Events.h"
24 #include "Model_Data.h"
25
26 #include <GeomAPI_Pnt.h>
27 #include <GeomAPI_Shape.h>
28 #include <GeomAPI_ShapeIterator.h>
29
30 #include <TDF_AttributeIterator.hxx>
31 #include <TDF_ChildIterator.hxx>
32 #include <TDF_RelocationTable.hxx>
33 #include <TDF_DeltaOnAddition.hxx>
34 #include <TDataStd_UAttribute.hxx>
35 #include <TopAbs_ShapeEnum.hxx>
36 #include <TopoDS.hxx>
37 #include <TopoDS_Shape.hxx>
38 #include <TopoDS_Edge.hxx>
39 #include <BRep_Tool.hxx>
40 #include <TNaming_Builder.hxx>
41 #include <TNaming_Iterator.hxx>
42 #include <TNaming_NamedShape.hxx>
43 #include <NCollection_List.hxx>
44
45 /// GUID for UAttribute that indicates the list has "To add all elements that share the same
46 /// topology" flag enabled
47 static const Standard_GUID kIS_GEOMETRICAL_SELECTION("f16987b6-e6c8-435c-99fa-03a7e0b06e83");
48
49 void Model_AttributeSelectionList::append(
50     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
51     const bool theTemporarily)
52 {
53   // do not use the degenerated edge as a shape, a list is not incremented in this case
54   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
55     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
56     if (aSubShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
57       return;
58     }
59   }
60
61   if (myIsCashed && !theTemporarily) {
62     ResultPtr aResContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
63     if (aResContext.get())
64       myCash[aResContext].push_back(theSubShape);
65   }
66
67   int aNewTag = mySize->Get() + 1;
68   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
69
70   std::shared_ptr<Model_AttributeSelection> aNewAttr =
71     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
72   if (owner()) {
73     aNewAttr->setObject(owner());
74     aNewAttr->setParent(this);
75   }
76   aNewAttr->setID(id());
77   mySize->Set(aNewTag);
78   aNewAttr->setValue(theContext, theSubShape, theTemporarily);
79   if (theTemporarily)
80     myTmpAttr = aNewAttr;
81   else
82     myTmpAttr.reset();
83   owner()->data()->sendAttributeUpdated(this);
84 }
85
86 void Model_AttributeSelectionList::append(
87   const std::string& theNamingName, const std::string& theType)
88 {
89   int aNewTag = mySize->Get() + 1;
90   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
91
92   std::shared_ptr<Model_AttributeSelection> aNewAttr =
93     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
94   if (owner()) {
95     aNewAttr->setObject(owner());
96     aNewAttr->setParent(this);
97   }
98   aNewAttr->setID(id());
99   mySize->Set(aNewTag);
100   aNewAttr->selectSubShape(theType.empty() ? selectionType() : theType, theNamingName);
101   owner()->data()->sendAttributeUpdated(this);
102 }
103
104 void Model_AttributeSelectionList::append(const GeomPointPtr& thePoint, const std::string& theType)
105 {
106   int aNewTag = mySize->Get() + 1;
107   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
108
109   std::shared_ptr<Model_AttributeSelection> aNewAttr =
110     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
111   if (owner()) {
112     aNewAttr->setObject(owner());
113     aNewAttr->setParent(this);
114   }
115   aNewAttr->setID(id());
116   mySize->Set(aNewTag);
117   aNewAttr->selectSubShape(theType, thePoint);
118   owner()->data()->sendAttributeUpdated(this);
119 }
120
121 void Model_AttributeSelectionList::append(const std::string& theType,
122   const std::string& theContextName, const int theIndex)
123 {
124   int aNewTag = mySize->Get() + 1;
125   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
126
127   std::shared_ptr<Model_AttributeSelection> aNewAttr =
128     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
129   if (owner()) {
130     aNewAttr->setObject(owner());
131     aNewAttr->setParent(this);
132   }
133   aNewAttr->setID(id());
134   mySize->Set(aNewTag);
135   aNewAttr->selectSubShape(theType, theContextName, theIndex);
136   owner()->data()->sendAttributeUpdated(this);
137 }
138
139 void Model_AttributeSelectionList::removeTemporaryValues()
140 {
141   if (myTmpAttr.get()) {
142     myTmpAttr.reset();
143   }
144 }
145
146 void Model_AttributeSelectionList::removeLast()
147 {
148   int anOldSize = mySize->Get();
149   if (anOldSize != 0) {
150     mySize->Set(anOldSize - 1);
151     TDF_Label aLab = mySize->Label().FindChild(anOldSize);
152     std::shared_ptr<Model_AttributeSelection> aOldAttr =
153       std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
154     aOldAttr->setObject(owner());
155     REMOVE_BACK_REF(aOldAttr->context());
156     aLab.ForgetAllAttributes(Standard_True);
157     myTmpAttr.reset();
158     owner()->data()->sendAttributeUpdated(this);
159   }
160 }
161
162 // copies named shapes: we need the implementation of this
163 static void CopyNS(const Handle(TNaming_NamedShape)& theFrom,
164   const Handle(TDF_Attribute)& theTo)
165 {
166   TDF_Label aLab = theTo->Label();
167   TNaming_Builder B(aLab);
168
169   // TNaming_Iterator iterates in reversed way than it was put in Builder, so, keep it in container
170   // and iterate from end to begin
171   NCollection_List<TopoDS_Shape> aOlds;
172   NCollection_List<TopoDS_Shape> aNews;
173   NCollection_List<TNaming_Evolution> aStatuses;
174
175   TNaming_Iterator anIt (theFrom);
176   for ( ;anIt.More() ; anIt.Next()) {
177     aOlds.Prepend(anIt.OldShape());
178     aNews.Prepend(anIt.NewShape());
179     aStatuses.Prepend(anIt.Evolution());
180   }
181
182   NCollection_List<TopoDS_Shape>::Iterator aOldIter(aOlds);
183   NCollection_List<TopoDS_Shape>::Iterator aNewIter(aNews);
184   NCollection_List<TNaming_Evolution>::Iterator aStatIter(aStatuses);
185   for(; aOldIter.More(); aOldIter.Next(), aNewIter.Next(), aStatIter.Next()) {
186     switch (aStatIter.Value()) {
187     case TNaming_PRIMITIVE :
188       B.Generated(aNewIter.Value());
189       break;
190     case TNaming_GENERATED :
191       B.Generated(aOldIter.Value(), aNewIter.Value());
192       break;
193     case TNaming_MODIFY :
194       B.Modify(aOldIter.Value(), aNewIter.Value());
195       break;
196     case TNaming_DELETE :
197       B.Delete (aOldIter.Value());
198       break;
199     case TNaming_SELECTED :
200       B.Select(aNewIter.Value(), aOldIter.Value());
201       break;
202     default:
203       break;
204     }
205   }
206 }
207
208 /// makes copy of all attributes on the given label and all sub-labels
209 static void copyAttrs(TDF_Label theSource, TDF_Label theDestination) {
210   TDF_AttributeIterator anAttrIter(theSource);
211   for(; anAttrIter.More(); anAttrIter.Next()) {
212     Handle(TDF_Attribute) aTargetAttr;
213     if (!theDestination.FindAttribute(anAttrIter.Value()->ID(), aTargetAttr)) {
214       // create a new attribute if not yet exists in the destination
215             aTargetAttr = anAttrIter.Value()->NewEmpty();
216       theDestination.AddAttribute(aTargetAttr);
217     }
218     // for named shape copy exact shapes (in NamedShape Paste method the CopyTool is used)
219     Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(anAttrIter.Value());
220     if (aNS.IsNull()) {
221       // no special relocation, empty map, but self-relocation is on: copy references w/o changes
222       Handle(TDF_RelocationTable) aRelocTable = new TDF_RelocationTable(Standard_True);
223       anAttrIter.Value()->Paste(aTargetAttr, aRelocTable);
224     } else {
225       CopyNS(aNS, aTargetAttr);
226     }
227   }
228   // copy the sub-labels content
229   TDF_ChildIterator aSubLabsIter(theSource);
230   for(; aSubLabsIter.More(); aSubLabsIter.Next()) {
231     copyAttrs(aSubLabsIter.Value(), theDestination.FindChild(aSubLabsIter.Value().Tag()));
232   }
233 }
234
235 void Model_AttributeSelectionList::remove(const std::set<int>& theIndices)
236 {
237   int anOldSize = mySize->Get();
238   int aRemoved = 0;
239   // iterate one by one and shifting the removed indices
240   for(int aCurrent = 0; aCurrent < anOldSize; aCurrent++) {
241     if (theIndices.find(aCurrent) == theIndices.end()) { // not removed
242       if (aRemoved) { // but must be shifted to the removed position
243         TDF_Label aSource = mySize->Label().FindChild(aCurrent + 1);
244         TDF_Label aDest = mySize->Label().FindChild(aCurrent + 1 - aRemoved);
245         copyAttrs(aSource, aDest);
246         // remove the moved source
247         aSource.ForgetAllAttributes(Standard_True);
248       }
249     } else { // this is removed, so remove everything from this label
250       TDF_Label aLab = mySize->Label().FindChild(aCurrent + 1);
251       std::shared_ptr<Model_AttributeSelection> aOldAttr =
252         std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
253       aOldAttr->setObject(owner());
254       REMOVE_BACK_REF(aOldAttr->context());
255       aLab.ForgetAllAttributes(Standard_True);
256       myTmpAttr.reset();
257       aRemoved++;
258     }
259   }
260   if (aRemoved) { // remove was performed, so, update the size and this attribute
261     mySize->Set(anOldSize - aRemoved);
262     owner()->data()->sendAttributeUpdated(this);
263   }
264 }
265
266 int Model_AttributeSelectionList::size()
267 {
268   return mySize->Get();
269 }
270
271 // LCOV_EXCL_START
272
273 // returns true if theShape is same with theInList or is contained in it (a compound)
274 static bool isIn(GeomShapePtr theInList, GeomShapePtr theShape) {
275   if (theShape->isSame(theInList))
276     return true;
277   if (theInList.get() && theInList->shapeType() == GeomAPI_Shape::COMPOUND) {
278     for(GeomAPI_ShapeIterator anIter(theInList); anIter.more(); anIter.next()) {
279       if (!anIter.current()->isNull() && anIter.current()->isSame(theShape))
280         return true;
281     }
282   }
283   return false;
284 }
285
286 bool Model_AttributeSelectionList::isInList(const ObjectPtr& theContext,
287                                             const std::shared_ptr<GeomAPI_Shape>& theSubShape,
288                                             const bool theTemporarily)
289 {
290   ResultPtr aResCont = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
291   if (myIsCashed) { // the cashing is active
292     if (aResCont.get()) {
293       std::map<ResultPtr, std::list<std::shared_ptr<GeomAPI_Shape> > >::iterator aContext =
294         myCash.find(aResCont);
295       if (aContext != myCash.end()) {
296         // iterate shapes because "isSame" method must be called for each shape
297         std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aShapes = aContext->second.begin();
298         for(; aShapes != aContext->second.end(); aShapes++) {
299           if (!theSubShape.get()) {
300             if (!aShapes->get() || (*aShapes)->isSame(aContext->first->shape()))
301               return true;
302           } else {
303             // we need to call here isSame instead of isEqual to do not check shapes orientation
304             if (isIn(*aShapes, theSubShape))
305               return true;
306           }
307         }
308       }
309       return false;
310     }
311   }
312   // no-cash method
313   for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
314     AttributeSelectionPtr anAttr = value(anIndex);
315     if (anAttr.get()) {
316       if (anAttr->context() == theContext) { // contexts are equal, so, check that values are also
317         std::shared_ptr<GeomAPI_Shape> aValue = anAttr->value();
318         if (!theSubShape.get()) {
319           if (!aValue.get() || (aResCont.get() && aValue->isSame(aResCont->shape()))) {// both null
320             return true;
321           }
322         } else {
323           // we need to call here isSame instead of isEqual to do not check shapes orientation
324           if (isIn(aValue, theSubShape)) // shapes are equal
325             return true;
326         }
327       }
328     }
329   }
330   return false;
331 }
332 // LCOV_EXCL_STOP
333
334 const std::string Model_AttributeSelectionList::selectionType() const
335 {
336   return TCollection_AsciiString(mySelectionType->Get()).ToCString();
337 }
338
339 void Model_AttributeSelectionList::setSelectionType(const std::string& theType)
340 {
341   mySelectionType->Set(theType.c_str());
342 }
343
344 std::shared_ptr<ModelAPI_AttributeSelection>
345   Model_AttributeSelectionList::value(const int theIndex)
346 {
347   if (myTmpAttr.get() && theIndex == size() - 1) {
348     return myTmpAttr;
349   }
350   TDF_Label aLabel = mySize->Label().FindChild(theIndex + 1);
351   // create a new attribute each time, by demand
352   // supporting of old attributes is too slow (sync each time) and buggy on redo
353   // (if attribute is deleted and created, the abort updates attribute and makes the Attr invalid)
354   std::shared_ptr<Model_AttributeSelection> aNewAttr =
355     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLabel));
356   if (owner()) {
357     aNewAttr->setObject(owner());
358     aNewAttr->setParent(this);
359   }
360   aNewAttr->setID(id());
361   return aNewAttr;
362 }
363
364 void Model_AttributeSelectionList::clear()
365 {
366   if (mySize->Get() != 0) {
367     mySize->Set(0);
368     myTmpAttr.reset();
369     TDF_ChildIterator aSubIter(mySize->Label());
370     for(; aSubIter.More(); aSubIter.Next()) {
371       TDF_Label aLab = aSubIter.Value();
372       std::shared_ptr<Model_AttributeSelection> aNewAttr =
373         std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
374       if (owner()) {
375         aNewAttr->setObject(owner());
376         aNewAttr->setParent(this);
377       }
378       REMOVE_BACK_REF(aNewAttr->context());
379
380       aLab.ForgetAllAttributes(Standard_True);
381     }
382     owner()->data()->sendAttributeUpdated(this);
383   }
384 }
385
386 bool Model_AttributeSelectionList::isInitialized()
387 {
388   if (size() == 0) { // empty list is not initialized list: sketch will be not valid after add/undo
389     return false;
390   }
391   return ModelAPI_AttributeSelectionList::isInitialized();
392 }
393
394 Model_AttributeSelectionList::Model_AttributeSelectionList(TDF_Label& theLabel)
395 : myLab(theLabel)
396 {
397   reinit();
398 }
399
400 void Model_AttributeSelectionList::reinit()
401 {
402   myIsInitialized = myLab.FindAttribute(TDataStd_Integer::GetID(), mySize) == Standard_True;
403   if (!myIsInitialized) {
404     mySize = TDataStd_Integer::Set(myLab, 0);
405     mySelectionType = TDataStd_Comment::Set(myLab, "");
406   } else { // recollect mySubs
407     myLab.FindAttribute(TDataStd_Comment::GetID(), mySelectionType);
408   }
409   myIsCashed = false;
410 }
411
412 // LCOV_EXCL_START
413 void Model_AttributeSelectionList::cashValues(const bool theEnabled)
414 {
415   myIsCashed = theEnabled;
416   myCash.clear(); // empty list as indicator that cash is not used
417   if (theEnabled) {
418     for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
419       AttributeSelectionPtr anAttr = value(anIndex);
420       if (anAttr.get()) {
421         myCash[anAttr->context()].push_back(anAttr->value());
422       }
423     }
424   }
425 }
426 // LCOV_EXCL_STOP
427
428 bool Model_AttributeSelectionList::isGeometricalSelection() const
429 {
430   return myLab.IsAttribute(kIS_GEOMETRICAL_SELECTION);
431 }
432
433 void Model_AttributeSelectionList::setGeometricalSelection(const bool theIsGeometricalSelection)
434 {
435   if (isGeometricalSelection() == theIsGeometricalSelection)
436     return; // nothing to do
437   if (theIsGeometricalSelection) // store the state
438     TDataStd_UAttribute::Set(myLab, kIS_GEOMETRICAL_SELECTION);
439   else
440     myLab.ForgetAttribute(kIS_GEOMETRICAL_SELECTION);
441   std::set<int> anIndiciesToRemove;  // Update list according to the flag
442   if (theIsGeometricalSelection) { // all objects with same geometry must be combined into single
443     std::list<AttributeSelectionPtr> anAttributes; // collect attributes with geometrical compounds
444     for(int anIndex = 0; anIndex < size(); anIndex++) {
445       AttributeSelectionPtr anAttr = value(anIndex);
446       if (!anAttr.get() || !anAttr->context().get())
447         continue;
448       anAttr->combineGeometrical();
449       if (!anAttr->value().get() || anAttr->value()->shapeType() != GeomAPI_Shape::COMPOUND)
450         continue;
451       // check it is equal to some other attribute already presented in the list
452       std::list<AttributeSelectionPtr>::iterator anAttrIter = anAttributes.begin();
453       for(; anAttrIter != anAttributes.end(); anAttrIter++) {
454         if (anAttr->context() == (*anAttrIter)->context() &&
455             anAttr->namingName() == (*anAttrIter)->namingName()) {
456           anIndiciesToRemove.insert(anIndex);
457           break;
458         }
459       }
460       if (anAttrIter == anAttributes.end()) // not removed, so, add to the compare-list
461         anAttributes.push_back(anAttr);
462     }
463   } else { // all objects with same geometry must be divided into separated sub-attributes
464     int anInitialSize = size();
465     for(int anIndex = 0; anIndex < anInitialSize; anIndex++) {
466       AttributeSelectionPtr anAttr = value(anIndex);
467       if (!anAttr.get() || !anAttr->context().get())
468         continue;
469       GeomShapePtr aValue = anAttr->value();
470       if (!aValue.get() || aValue->shapeType() != GeomAPI_Shape::COMPOUND)
471         continue;
472       for(GeomAPI_ShapeIterator anIter(aValue); anIter.more(); anIter.next()) {
473         append(anAttr->context(), anIter.current());
474       }
475       anIndiciesToRemove.insert(anIndex);
476     }
477   }
478   remove(anIndiciesToRemove);
479   myIsCashed = false;
480   myCash.clear(); // empty list as indicator that cash is not used
481   owner()->data()->sendAttributeUpdated(this);
482 }