Salome HOME
3c3fb2a1b7eff5eda6f1b1acd92d89dc3b539821
[modules/shaper.git] / src / Model / Model_AttributeSelectionList.cpp
1 // Copyright (C) 2014-2023  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     myCash[theContext].push_back(theSubShape);
69   }
70
71   int aNewTag = mySize->Get() + 1;
72   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
73
74   std::shared_ptr<Model_AttributeSelection> aNewAttr =
75     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
76   if (owner()) {
77     aNewAttr->setObject(owner());
78     aNewAttr->setParent(this);
79   }
80   aNewAttr->setID(id());
81   mySize->Set(aNewTag);
82   aNewAttr->setValue(theContext, theSubShape, theTemporarily);
83   if (theTemporarily)
84     myTmpAttr = aNewAttr;
85   else
86     myTmpAttr.reset();
87   owner()->data()->sendAttributeUpdated(this);
88 }
89
90 void Model_AttributeSelectionList::append(
91   const std::wstring& theNamingName, const std::string& theType)
92 {
93   int aNewTag = mySize->Get() + 1;
94   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
95
96   std::shared_ptr<Model_AttributeSelection> aNewAttr =
97     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
98   if (owner()) {
99     aNewAttr->setObject(owner());
100     aNewAttr->setParent(this);
101   }
102   aNewAttr->setID(id());
103   mySize->Set(aNewTag);
104   aNewAttr->selectSubShape(theType.empty() ? selectionType() : theType, theNamingName);
105   owner()->data()->sendAttributeUpdated(this);
106 }
107
108 void Model_AttributeSelectionList::append(const GeomPointPtr& thePoint, const std::string& theType)
109 {
110   int aNewTag = mySize->Get() + 1;
111   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
112
113   std::shared_ptr<Model_AttributeSelection> aNewAttr =
114     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
115   if (owner()) {
116     aNewAttr->setObject(owner());
117     aNewAttr->setParent(this);
118   }
119   aNewAttr->setID(id());
120   mySize->Set(aNewTag);
121   aNewAttr->selectSubShape(theType, thePoint);
122   owner()->data()->sendAttributeUpdated(this);
123 }
124
125 void Model_AttributeSelectionList::append(const std::string& theType,
126   const std::wstring& theContextName, const int theIndex)
127 {
128   int aNewTag = mySize->Get() + 1;
129   TDF_Label aNewLab = mySize->Label().FindChild(aNewTag);
130
131   std::shared_ptr<Model_AttributeSelection> aNewAttr =
132     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aNewLab));
133   if (owner()) {
134     aNewAttr->setObject(owner());
135     aNewAttr->setParent(this);
136   }
137   aNewAttr->setID(id());
138   mySize->Set(aNewTag);
139   aNewAttr->selectSubShape(theType, theContextName, theIndex);
140   owner()->data()->sendAttributeUpdated(this);
141 }
142
143 void Model_AttributeSelectionList::removeTemporaryValues()
144 {
145   if (myTmpAttr.get()) {
146     myTmpAttr.reset();
147   }
148 }
149
150 void Model_AttributeSelectionList::removeLast()
151 {
152   int anOldSize = mySize->Get();
153   if (anOldSize != 0) {
154     mySize->Set(anOldSize - 1);
155     TDF_Label aLab = mySize->Label().FindChild(anOldSize);
156     std::shared_ptr<Model_AttributeSelection> aOldAttr =
157       std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
158     aOldAttr->setObject(owner());
159     REMOVE_BACK_REF(aOldAttr->context());
160     aLab.ForgetAllAttributes(Standard_True);
161     myTmpAttr.reset();
162     owner()->data()->sendAttributeUpdated(this);
163   }
164 }
165
166 // copies named shapes: we need the implementation of this
167 static void CopyNS(const Handle(TNaming_NamedShape)& theFrom,
168   const Handle(TDF_Attribute)& theTo)
169 {
170   TDF_Label aLab = theTo->Label();
171   TNaming_Builder B(aLab);
172
173   // TNaming_Iterator iterates in reversed way than it was put in Builder, so, keep it in container
174   // and iterate from end to begin
175   NCollection_List<TopoDS_Shape> aOlds;
176   NCollection_List<TopoDS_Shape> aNews;
177   NCollection_List<TNaming_Evolution> aStatuses;
178
179   TNaming_Iterator anIt (theFrom);
180   for ( ;anIt.More() ; anIt.Next()) {
181     aOlds.Prepend(anIt.OldShape());
182     aNews.Prepend(anIt.NewShape());
183     aStatuses.Prepend(anIt.Evolution());
184   }
185
186   NCollection_List<TopoDS_Shape>::Iterator aOldIter(aOlds);
187   NCollection_List<TopoDS_Shape>::Iterator aNewIter(aNews);
188   NCollection_List<TNaming_Evolution>::Iterator aStatIter(aStatuses);
189   for(; aOldIter.More(); aOldIter.Next(), aNewIter.Next(), aStatIter.Next()) {
190     switch (aStatIter.Value()) {
191     case TNaming_PRIMITIVE :
192       B.Generated(aNewIter.Value());
193       break;
194     case TNaming_GENERATED :
195       B.Generated(aOldIter.Value(), aNewIter.Value());
196       break;
197     case TNaming_MODIFY :
198       B.Modify(aOldIter.Value(), aNewIter.Value());
199       break;
200     case TNaming_DELETE :
201       B.Delete (aOldIter.Value());
202       break;
203     case TNaming_SELECTED :
204       B.Select(aNewIter.Value(), aOldIter.Value());
205       break;
206     default:
207       break;
208     }
209   }
210 }
211
212 /// makes copy of all attributes on the given label and all sub-labels
213 static void copyAttrs(TDF_Label theSource, TDF_Label theDestination) {
214   TDF_AttributeIterator anAttrIter(theSource);
215   for(; anAttrIter.More(); anAttrIter.Next()) {
216     Handle(TDF_Attribute) aTargetAttr;
217     if (!theDestination.FindAttribute(anAttrIter.Value()->ID(), aTargetAttr)) {
218       // create a new attribute if not yet exists in the destination
219             aTargetAttr = anAttrIter.Value()->NewEmpty();
220       if (aTargetAttr->ID() != anAttrIter.Value()->ID())
221         aTargetAttr->SetID(anAttrIter.Value()->ID());
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             FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aContext->first);
319             if ((aRes.get() && (*aShapes)->isSame(aRes->shape())) || aFeat.get())
320               return true;
321           } else {
322             // we need to call here isSame instead of isEqual to do not check shapes orientation
323             if (isIn(*aShapes, theSubShape))
324               return true;
325           }
326         }
327       }
328       return false;
329     }
330   }
331   // no-cash method
332   bool isFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext).get() != NULL;
333   ResultPtr aRes;
334   if (!isFeature)
335     aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
336   for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
337     AttributeSelectionPtr anAttr = value(anIndex);
338     if (anAttr.get()) {
339       if (isFeature && anAttr->contextFeature() == theContext)
340         return true; // for the feature value should not be compared
341       if (!isFeature && anAttr->context() == theContext) {
342         // contexts are equal, so, check that values are also
343         std::shared_ptr<GeomAPI_Shape> aValue = anAttr->value();
344         if (!theSubShape.get()) {
345           if (!aValue.get() || (aRes.get() && aValue->isSame(aRes->shape())))
346             return true;
347         } else {
348           // we need to call here isSame instead of isEqual to do not check shapes orientation
349           if (isIn(aValue, theSubShape)) // shapes are equal
350             return true;
351         }
352       }
353     }
354   }
355   return false;
356 }
357 // LCOV_EXCL_STOP
358
359 const std::string Model_AttributeSelectionList::selectionType() const
360 {
361   return TCollection_AsciiString(mySelectionType->Get()).ToCString();
362 }
363
364 void Model_AttributeSelectionList::setSelectionType(const std::string& theType)
365 {
366   mySelectionType->Set(theType.c_str());
367 }
368
369 std::shared_ptr<ModelAPI_AttributeSelection>
370   Model_AttributeSelectionList::value(const int theIndex)
371 {
372   if (myTmpAttr.get() && theIndex == size() - 1) {
373     return myTmpAttr;
374   }
375   TDF_Label aLabel = mySize->Label().FindChild(theIndex + 1);
376   // create a new attribute each time, by demand
377   // supporting of old attributes is too slow (sync each time) and buggy on redo
378   // (if attribute is deleted and created, the abort updates attribute and makes the Attr invalid)
379   std::shared_ptr<Model_AttributeSelection> aNewAttr =
380     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLabel));
381   if (owner()) {
382     aNewAttr->setObject(owner());
383     aNewAttr->setParent(this);
384   }
385   aNewAttr->setID(id());
386   return aNewAttr;
387 }
388
389 void Model_AttributeSelectionList::clear()
390 {
391   if (mySize->Get() != 0) {
392     mySize->Set(0);
393     myTmpAttr.reset();
394     TDF_ChildIterator aSubIter(mySize->Label());
395     for(; aSubIter.More(); aSubIter.Next()) {
396       TDF_Label aLab = aSubIter.Value();
397       std::shared_ptr<Model_AttributeSelection> aNewAttr =
398         std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
399       if (owner()) {
400         aNewAttr->setObject(owner());
401         aNewAttr->setParent(this);
402       }
403       REMOVE_BACK_REF(aNewAttr->context());
404
405       aLab.ForgetAllAttributes(Standard_True);
406     }
407     owner()->data()->sendAttributeUpdated(this);
408   }
409 }
410
411 bool Model_AttributeSelectionList::isInitialized()
412 {
413   if (size() == 0) { // empty list is not initialized list: sketch will be not valid after add/undo
414     return false;
415   }
416   return ModelAPI_AttributeSelectionList::isInitialized();
417 }
418
419 Model_AttributeSelectionList::Model_AttributeSelectionList(TDF_Label& theLabel)
420 : ModelAPI_AttributeSelectionList(), myLab(theLabel)
421 {
422   reinit();
423 }
424
425 void Model_AttributeSelectionList::reinit()
426 {
427   myIsInitialized = myLab.FindAttribute(TDataStd_Integer::GetID(), mySize) == Standard_True;
428   if (!myIsInitialized) {
429     mySize = TDataStd_Integer::Set(myLab, 0);
430     mySelectionType = TDataStd_Comment::Set(myLab, "");
431   } else { // recollect mySubs
432     myLab.FindAttribute(TDataStd_Comment::GetID(), mySelectionType);
433   }
434   myIsCashed = false;
435 }
436
437 // LCOV_EXCL_START
438 void Model_AttributeSelectionList::cashValues(const bool theEnabled)
439 {
440   myIsCashed = theEnabled;
441   myCash.clear(); // empty list as indicator that cash is not used
442   if (theEnabled) {
443     for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
444       AttributeSelectionPtr anAttr = value(anIndex);
445       if (anAttr.get()) {
446         myCash[anAttr->contextObject()].push_back(anAttr->value());
447       }
448     }
449   }
450 }
451 // LCOV_EXCL_STOP
452
453 bool Model_AttributeSelectionList::isGeometricalSelection() const
454 {
455   return myLab.IsAttribute(kIS_GEOMETRICAL_SELECTION);
456 }
457
458 void Model_AttributeSelectionList::setGeometricalSelection(const bool theIsGeometricalSelection)
459 {
460   if (isGeometricalSelection() == theIsGeometricalSelection)
461     return; // nothing to do
462   if (theIsGeometricalSelection) // store the state
463     TDataStd_UAttribute::Set(myLab, kIS_GEOMETRICAL_SELECTION);
464   else
465     myLab.ForgetAttribute(kIS_GEOMETRICAL_SELECTION);
466   std::set<int> anIndiciesToRemove;  // Update list according to the flag
467   if (theIsGeometricalSelection) { // all objects with same geometry must be combined into single
468     std::list<AttributeSelectionPtr> anAttributes; // collect attributes with geometrical compounds
469     for(int anIndex = 0; anIndex < size(); anIndex++) {
470       AttributeSelectionPtr anAttr = value(anIndex);
471       if (!anAttr.get() || !anAttr->context().get())
472         continue;
473       anAttr->combineGeometrical();
474       if (!anAttr->value().get() || anAttr->value()->shapeType() != GeomAPI_Shape::COMPOUND)
475         continue;
476       // check it is equal to some other attribute already presented in the list
477       std::list<AttributeSelectionPtr>::iterator anAttrIter = anAttributes.begin();
478       for(; anAttrIter != anAttributes.end(); anAttrIter++) {
479         if (anAttr->context() == (*anAttrIter)->context() &&
480             anAttr->namingName() == (*anAttrIter)->namingName()) {
481           anIndiciesToRemove.insert(anIndex);
482           break;
483         }
484       }
485       if (anAttrIter == anAttributes.end()) // not removed, so, add to the compare-list
486         anAttributes.push_back(anAttr);
487     }
488   } else { // all objects with same geometry must be divided into separated sub-attributes
489     int anInitialSize = size();
490     for(int anIndex = 0; anIndex < anInitialSize; anIndex++) {
491       AttributeSelectionPtr anAttr = value(anIndex);
492       if (!anAttr.get() || !anAttr->context().get())
493         continue;
494       GeomShapePtr aValue = anAttr->value();
495       if (!aValue.get() || aValue->shapeType() != GeomAPI_Shape::COMPOUND)
496         continue;
497       for(GeomAPI_ShapeIterator anIter(aValue); anIter.more(); anIter.next()) {
498         append(anAttr->context(), anIter.current());
499       }
500       anIndiciesToRemove.insert(anIndex);
501     }
502   }
503   remove(anIndiciesToRemove);
504   myIsCashed = false;
505   myCash.clear(); // empty list as indicator that cash is not used
506   owner()->data()->sendAttributeUpdated(this);
507 }
508
509 FiltersFeaturePtr Model_AttributeSelectionList::filters() const
510 {
511   Handle(TDataStd_ReferenceList) aRef;
512   if (myLab.FindAttribute(kSELECTION_FILTERS_REF, aRef) && !aRef->IsEmpty()) {
513     if (owner().get()) {
514       std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(
515         owner()->document());
516       if (aDoc) {
517         const TDF_Label& aRefLab = aRef->First();
518         if (!aRefLab.IsNull()) {  // it may happen with old document, issue #285
519           ObjectPtr anObj = aDoc->objects()->object(aRefLab);
520           FiltersFeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(anObj);
521           if (aFeat.get()) {
522             aFeat->setAttribute(owner()->data()->attribute(id()));
523             return aFeat;
524           }
525         }
526       }
527     }
528   }
529   return FiltersFeaturePtr(); // null pointer if nothing is defined
530 }
531
532 void Model_AttributeSelectionList::setFilters(FiltersFeaturePtr theFeature)
533 {
534   Handle(TDataStd_ReferenceList) aRef = TDataStd_ReferenceList::Set(myLab, kSELECTION_FILTERS_REF);
535   if (theFeature.get()) {
536     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theFeature->data());
537     if (aData->isValid())  {
538       TDF_Label anObjLab = aData->label().Father(); // object label
539       if (!aRef->IsEmpty())
540         aRef->Clear();
541       aRef->Append(anObjLab);
542       theFeature->setAttribute(owner()->data()->attribute(id()));
543       return;
544     }
545   }
546   // remove attribute if something is wrong
547   myLab.ForgetAttribute(TDataStd_ReferenceList::GetID());
548 }