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