Salome HOME
Merge remote-tracking branch 'origin/Toolbars_Management'
[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 // LCOV_EXCL_START
273
274 // returns true if theShape is same with theInList or is contained in it (a compound)
275 static bool isIn(GeomShapePtr theInList, GeomShapePtr theShape) {
276   if (theShape->isSame(theInList))
277     return true;
278   if (theInList.get() && theInList->shapeType() == GeomAPI_Shape::COMPOUND) {
279     for(GeomAPI_ShapeIterator anIter(theInList); anIter.more(); anIter.next()) {
280       if (!anIter.current()->isNull() && anIter.current()->isSame(theShape))
281         return true;
282     }
283   }
284   return false;
285 }
286
287 bool Model_AttributeSelectionList::isInList(const ObjectPtr& theContext,
288                                             const std::shared_ptr<GeomAPI_Shape>& theSubShape,
289                                             const bool theTemporarily)
290 {
291   ResultPtr aResCont = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
292   if (myIsCashed) { // the cashing is active
293     if (aResCont.get()) {
294       std::map<ResultPtr, std::list<std::shared_ptr<GeomAPI_Shape> > >::iterator aContext =
295         myCash.find(aResCont);
296       if (aContext != myCash.end()) {
297         // iterate shapes because "isSame" method must be called for each shape
298         std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aShapes = aContext->second.begin();
299         for(; aShapes != aContext->second.end(); aShapes++) {
300           if (!theSubShape.get()) {
301             if (!aShapes->get() || (*aShapes)->isSame(aContext->first->shape()))
302               return true;
303           } else {
304             // we need to call here isSame instead of isEqual to do not check shapes orientation
305             if (isIn(*aShapes, theSubShape))
306               return true;
307           }
308         }
309       }
310       return false;
311     }
312   }
313   // no-cash method
314   for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
315     AttributeSelectionPtr anAttr = value(anIndex);
316     if (anAttr.get()) {
317       if (anAttr->context() == theContext) { // contexts are equal, so, check that values are also
318         std::shared_ptr<GeomAPI_Shape> aValue = anAttr->value();
319         if (!theSubShape.get()) {
320           if (!aValue.get() || (aResCont.get() && aValue->isSame(aResCont->shape()))) {// both null
321             return true;
322           }
323         } else {
324           // we need to call here isSame instead of isEqual to do not check shapes orientation
325           if (isIn(aValue, theSubShape)) // shapes are equal
326             return true;
327         }
328       }
329     }
330   }
331   return false;
332 }
333 // LCOV_EXCL_STOP
334
335 const std::string Model_AttributeSelectionList::selectionType() const
336 {
337   return TCollection_AsciiString(mySelectionType->Get()).ToCString();
338 }
339
340 void Model_AttributeSelectionList::setSelectionType(const std::string& theType)
341 {
342   mySelectionType->Set(theType.c_str());
343 }
344
345 std::shared_ptr<ModelAPI_AttributeSelection>
346   Model_AttributeSelectionList::value(const int theIndex)
347 {
348   if (myTmpAttr.get() && theIndex == size() - 1) {
349     return myTmpAttr;
350   }
351   TDF_Label aLabel = mySize->Label().FindChild(theIndex + 1);
352   // create a new attribute each time, by demand
353   // supporting of old attributes is too slow (sync each time) and buggy on redo
354   // (if attribute is deleted and created, the abort updates attribute and makes the Attr invalid)
355   std::shared_ptr<Model_AttributeSelection> aNewAttr =
356     std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLabel));
357   if (owner()) {
358     aNewAttr->setObject(owner());
359     aNewAttr->setParent(this);
360   }
361   aNewAttr->setID(id());
362   return aNewAttr;
363 }
364
365 void Model_AttributeSelectionList::clear()
366 {
367   if (mySize->Get() != 0) {
368     mySize->Set(0);
369     myTmpAttr.reset();
370     TDF_ChildIterator aSubIter(mySize->Label());
371     for(; aSubIter.More(); aSubIter.Next()) {
372       TDF_Label aLab = aSubIter.Value();
373       std::shared_ptr<Model_AttributeSelection> aNewAttr =
374         std::shared_ptr<Model_AttributeSelection>(new Model_AttributeSelection(aLab));
375       if (owner()) {
376         aNewAttr->setObject(owner());
377         aNewAttr->setParent(this);
378       }
379       REMOVE_BACK_REF(aNewAttr->context());
380
381       aLab.ForgetAllAttributes(Standard_True);
382     }
383     owner()->data()->sendAttributeUpdated(this);
384   }
385 }
386
387 bool Model_AttributeSelectionList::isInitialized()
388 {
389   if (size() == 0) { // empty list is not initialized list: sketch will be not valid after add/undo
390     return false;
391   }
392   return ModelAPI_AttributeSelectionList::isInitialized();
393 }
394
395 Model_AttributeSelectionList::Model_AttributeSelectionList(TDF_Label& theLabel)
396 : myLab(theLabel)
397 {
398   reinit();
399 }
400
401 void Model_AttributeSelectionList::reinit()
402 {
403   myIsInitialized = myLab.FindAttribute(TDataStd_Integer::GetID(), mySize) == Standard_True;
404   if (!myIsInitialized) {
405     mySize = TDataStd_Integer::Set(myLab, 0);
406     mySelectionType = TDataStd_Comment::Set(myLab, "");
407   } else { // recollect mySubs
408     myLab.FindAttribute(TDataStd_Comment::GetID(), mySelectionType);
409   }
410   myIsCashed = false;
411 }
412
413 // LCOV_EXCL_START
414 void Model_AttributeSelectionList::cashValues(const bool theEnabled)
415 {
416   myIsCashed = theEnabled;
417   myCash.clear(); // empty list as indicator that cash is not used
418   if (theEnabled) {
419     for(int anIndex = size() - 1; anIndex >= 0; anIndex--) {
420       AttributeSelectionPtr anAttr = value(anIndex);
421       if (anAttr.get()) {
422         myCash[anAttr->context()].push_back(anAttr->value());
423       }
424     }
425   }
426 }
427 // LCOV_EXCL_STOP
428
429 bool Model_AttributeSelectionList::isGeometricalSelection() const
430 {
431   return myLab.IsAttribute(kIS_GEOMETRICAL_SELECTION);
432 }
433
434 void Model_AttributeSelectionList::setGeometricalSelection(const bool theIsGeometricalSelection)
435 {
436   if (isGeometricalSelection() == theIsGeometricalSelection)
437     return; // nothing to do
438   if (theIsGeometricalSelection) // store the state
439     TDataStd_UAttribute::Set(myLab, kIS_GEOMETRICAL_SELECTION);
440   else
441     myLab.ForgetAttribute(kIS_GEOMETRICAL_SELECTION);
442   std::set<int> anIndiciesToRemove;  // Update list according to the flag
443   if (theIsGeometricalSelection) { // all objects with same geometry must be combined into single
444     std::list<AttributeSelectionPtr> anAttributes; // collect attributes with geometrical compounds
445     for(int anIndex = 0; anIndex < size(); anIndex++) {
446       AttributeSelectionPtr anAttr = value(anIndex);
447       if (!anAttr.get() || !anAttr->context().get())
448         continue;
449       anAttr->combineGeometrical();
450       if (!anAttr->value().get() || anAttr->value()->shapeType() != GeomAPI_Shape::COMPOUND)
451         continue;
452       // check it is equal to some other attribute already presented in the list
453       std::list<AttributeSelectionPtr>::iterator anAttrIter = anAttributes.begin();
454       for(; anAttrIter != anAttributes.end(); anAttrIter++) {
455         if (anAttr->context() == (*anAttrIter)->context() &&
456             anAttr->namingName() == (*anAttrIter)->namingName()) {
457           anIndiciesToRemove.insert(anIndex);
458           break;
459         }
460       }
461       if (anAttrIter == anAttributes.end()) // not removed, so, add to the compare-list
462         anAttributes.push_back(anAttr);
463     }
464   } else { // all objects with same geometry must be divided into separated sub-attributes
465     int anInitialSize = size();
466     for(int anIndex = 0; anIndex < anInitialSize; anIndex++) {
467       AttributeSelectionPtr anAttr = value(anIndex);
468       if (!anAttr.get() || !anAttr->context().get())
469         continue;
470       GeomShapePtr aValue = anAttr->value();
471       if (!aValue.get() || aValue->shapeType() != GeomAPI_Shape::COMPOUND)
472         continue;
473       for(GeomAPI_ShapeIterator anIter(aValue); anIter.more(); anIter.next()) {
474         append(anAttr->context(), anIter.current());
475       }
476       anIndiciesToRemove.insert(anIndex);
477     }
478   }
479   remove(anIndiciesToRemove);
480   myIsCashed = false;
481   myCash.clear(); // empty list as indicator that cash is not used
482   owner()->data()->sendAttributeUpdated(this);
483 }