Salome HOME
9e7b0b6ff1144cf9957a4cf6599808398844e791
[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 void Model_AttributeSelectionList::copyTo(AttributeSelectionListPtr theTarget) const
273 {
274   std::shared_ptr<Model_AttributeSelectionList> aTarget =
275     std::dynamic_pointer_cast<Model_AttributeSelectionList>(theTarget);
276   if (aTarget) {
277     copyAttrs(myLab, aTarget->myLab);
278     aTarget->reinit();
279   }
280 }
281
282 int Model_AttributeSelectionList::size()
283 {
284   return mySize->Get();
285 }
286
287 // LCOV_EXCL_START
288
289 // returns true if theShape is same with theInList or is contained in it (a compound)
290 static bool isIn(GeomShapePtr theInList, GeomShapePtr theShape) {
291   if (theShape->isSame(theInList))
292     return true;
293   if (theInList.get() && theInList->shapeType() == GeomAPI_Shape::COMPOUND) {
294     for(GeomAPI_ShapeIterator anIter(theInList); anIter.more(); anIter.next()) {
295       if (!anIter.current()->isNull() && anIter.current()->isSame(theShape))
296         return true;
297     }
298   }
299   return false;
300 }
301
302 bool Model_AttributeSelectionList::isInList(const ObjectPtr& theContext,
303                                             const std::shared_ptr<GeomAPI_Shape>& theSubShape,
304                                             const bool theTemporarily)
305 {
306   if (myIsCashed) { // the cashing is active
307     if (theContext.get()) {
308       std::map<ObjectPtr, std::list<std::shared_ptr<GeomAPI_Shape> > >::iterator aContext =
309         myCash.find(theContext);
310       if (aContext != myCash.end()) {
311         // iterate shapes because "isSame" method must be called for each shape
312         std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aShapes = aContext->second.begin();
313         for(; aShapes != aContext->second.end(); aShapes++) {
314           if (!theSubShape.get()) {
315             if (!aShapes->get())
316               return true;
317             ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aContext->first);
318             if (aRes.get() && (*aShapes)->isSame(aRes->shape()))
319               return true;
320           } else {
321             // we need to call here isSame instead of isEqual to do not check shapes orientation
322             if (isIn(*aShapes, theSubShape))
323               return true;
324           }
325         }
326       }
327       return false;
328     }
329   }
330   // no-cash method
331   bool isFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext).get() != NULL;
332   ResultPtr aRes;
333   if (!isFeature)
334     aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
335   for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
336     AttributeSelectionPtr anAttr = value(anIndex);
337     if (anAttr.get()) {
338       if (isFeature && anAttr->contextFeature() == theContext)
339         return true; // for the feature value should not be compared
340       if (!isFeature && anAttr->context() == theContext) {
341         // contexts are equal, so, check that values are also
342         std::shared_ptr<GeomAPI_Shape> aValue = anAttr->value();
343         if (!theSubShape.get()) {
344           if (!aValue.get() || (aRes.get() && aValue->isSame(aRes->shape())))
345             return true;
346         } else {
347           // we need to call here isSame instead of isEqual to do not check shapes orientation
348           if (isIn(aValue, theSubShape)) // shapes are equal
349             return true;
350         }
351       }
352     }
353   }
354   return false;
355 }
356 // LCOV_EXCL_STOP
357
358 const std::string Model_AttributeSelectionList::selectionType() const
359 {
360   return TCollection_AsciiString(mySelectionType->Get()).ToCString();
361 }
362
363 void Model_AttributeSelectionList::setSelectionType(const std::string& theType)
364 {
365   mySelectionType->Set(theType.c_str());
366 }
367
368 std::shared_ptr<ModelAPI_AttributeSelection>
369   Model_AttributeSelectionList::value(const int theIndex)
370 {
371   if (myTmpAttr.get() && theIndex == size() - 1) {
372     return myTmpAttr;
373   }
374   TDF_Label aLabel = mySize->Label().FindChild(theIndex + 1);
375   // create a new attribute each time, by demand
376   // supporting of old attributes is too slow (sync each time) and buggy on redo
377   // (if attribute is deleted and created, the abort updates attribute and makes the Attr invalid)
378   std::shared_ptr<Model_AttributeSelection> aNewAttr =
379     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLabel));
380   if (owner()) {
381     aNewAttr->setObject(owner());
382     aNewAttr->setParent(this);
383   }
384   aNewAttr->setID(id());
385   return aNewAttr;
386 }
387
388 void Model_AttributeSelectionList::clear()
389 {
390   if (mySize->Get() != 0) {
391     mySize->Set(0);
392     myTmpAttr.reset();
393     TDF_ChildIterator aSubIter(mySize->Label());
394     for(; aSubIter.More(); aSubIter.Next()) {
395       TDF_Label aLab = aSubIter.Value();
396       std::shared_ptr<Model_AttributeSelection> aNewAttr =
397         std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
398       if (owner()) {
399         aNewAttr->setObject(owner());
400         aNewAttr->setParent(this);
401       }
402       REMOVE_BACK_REF(aNewAttr->context());
403
404       aLab.ForgetAllAttributes(Standard_True);
405     }
406     owner()->data()->sendAttributeUpdated(this);
407   }
408 }
409
410 bool Model_AttributeSelectionList::isInitialized()
411 {
412   if (size() == 0) { // empty list is not initialized list: sketch will be not valid after add/undo
413     return false;
414   }
415   return ModelAPI_AttributeSelectionList::isInitialized();
416 }
417
418 Model_AttributeSelectionList::Model_AttributeSelectionList(TDF_Label& theLabel)
419 : ModelAPI_AttributeSelectionList(), myLab(theLabel)
420 {
421   reinit();
422 }
423
424 void Model_AttributeSelectionList::reinit()
425 {
426   myIsInitialized = myLab.FindAttribute(TDataStd_Integer::GetID(), mySize) == Standard_True;
427   if (!myIsInitialized) {
428     mySize = TDataStd_Integer::Set(myLab, 0);
429     mySelectionType = TDataStd_Comment::Set(myLab, "");
430   } else { // recollect mySubs
431     myLab.FindAttribute(TDataStd_Comment::GetID(), mySelectionType);
432   }
433   myIsCashed = false;
434 }
435
436 // LCOV_EXCL_START
437 void Model_AttributeSelectionList::cashValues(const bool theEnabled)
438 {
439   myIsCashed = theEnabled;
440   myCash.clear(); // empty list as indicator that cash is not used
441   if (theEnabled) {
442     for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
443       AttributeSelectionPtr anAttr = value(anIndex);
444       if (anAttr.get()) {
445         myCash[anAttr->context()].push_back(anAttr->value());
446       }
447     }
448   }
449 }
450 // LCOV_EXCL_STOP
451
452 bool Model_AttributeSelectionList::isGeometricalSelection() const
453 {
454   return myLab.IsAttribute(kIS_GEOMETRICAL_SELECTION);
455 }
456
457 void Model_AttributeSelectionList::setGeometricalSelection(const bool theIsGeometricalSelection)
458 {
459   if (isGeometricalSelection() == theIsGeometricalSelection)
460     return; // nothing to do
461   if (theIsGeometricalSelection) // store the state
462     TDataStd_UAttribute::Set(myLab, kIS_GEOMETRICAL_SELECTION);
463   else
464     myLab.ForgetAttribute(kIS_GEOMETRICAL_SELECTION);
465   std::set<int> anIndiciesToRemove;  // Update list according to the flag
466   if (theIsGeometricalSelection) { // all objects with same geometry must be combined into single
467     std::list<AttributeSelectionPtr> anAttributes; // collect attributes with geometrical compounds
468     for(int anIndex = 0; anIndex < size(); anIndex++) {
469       AttributeSelectionPtr anAttr = value(anIndex);
470       if (!anAttr.get() || !anAttr->context().get())
471         continue;
472       anAttr->combineGeometrical();
473       if (!anAttr->value().get() || anAttr->value()->shapeType() != GeomAPI_Shape::COMPOUND)
474         continue;
475       // check it is equal to some other attribute already presented in the list
476       std::list<AttributeSelectionPtr>::iterator anAttrIter = anAttributes.begin();
477       for(; anAttrIter != anAttributes.end(); anAttrIter++) {
478         if (anAttr->context() == (*anAttrIter)->context() &&
479             anAttr->namingName() == (*anAttrIter)->namingName()) {
480           anIndiciesToRemove.insert(anIndex);
481           break;
482         }
483       }
484       if (anAttrIter == anAttributes.end()) // not removed, so, add to the compare-list
485         anAttributes.push_back(anAttr);
486     }
487   } else { // all objects with same geometry must be divided into separated sub-attributes
488     int anInitialSize = size();
489     for(int anIndex = 0; anIndex < anInitialSize; anIndex++) {
490       AttributeSelectionPtr anAttr = value(anIndex);
491       if (!anAttr.get() || !anAttr->context().get())
492         continue;
493       GeomShapePtr aValue = anAttr->value();
494       if (!aValue.get() || aValue->shapeType() != GeomAPI_Shape::COMPOUND)
495         continue;
496       for(GeomAPI_ShapeIterator anIter(aValue); anIter.more(); anIter.next()) {
497         append(anAttr->context(), anIter.current());
498       }
499       anIndiciesToRemove.insert(anIndex);
500     }
501   }
502   remove(anIndiciesToRemove);
503   myIsCashed = false;
504   myCash.clear(); // empty list as indicator that cash is not used
505   owner()->data()->sendAttributeUpdated(this);
506 }
507
508 FiltersFeaturePtr Model_AttributeSelectionList::filters() const
509 {
510   Handle(TDataStd_ReferenceList) aRef;
511   if (myLab.FindAttribute(kSELECTION_FILTERS_REF, aRef) && !aRef->IsEmpty()) {
512     if (owner().get()) {
513       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(
514         owner()->document());
515       if (aDoc) {
516         const TDF_Label& aRefLab = aRef->First();
517         if (!aRefLab.IsNull()) {  // it may happen with old document, issue #285
518           ObjectPtr anObj = aDoc->objects()->object(aRefLab);
519           FiltersFeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(anObj);
520           if (aFeat.get()) {
521             aFeat->setAttribute(owner()->data()->attribute(id()));
522             return aFeat;
523           }
524         }
525       }
526     }
527   }
528   return FiltersFeaturePtr(); // null pointer if nothing is defined
529 }
530
531 void Model_AttributeSelectionList::setFilters(FiltersFeaturePtr theFeature)
532 {
533   Handle(TDataStd_ReferenceList) aRef = TDataStd_ReferenceList::Set(myLab, kSELECTION_FILTERS_REF);
534   if (theFeature.get()) {
535     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
536     if (aData->isValid())  {
537       TDF_Label anObjLab = aData->label().Father(); // object label
538       if (!aRef->IsEmpty())
539         aRef->Clear();
540       aRef->Append(anObjLab);
541       theFeature->setAttribute(owner()->data()->attribute(id()));
542       return;
543     }
544   }
545   // remove attribute if something is wrong
546   myLab.ForgetAttribute(TDataStd_ReferenceList::GetID());
547 }