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