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