Salome HOME
Issue #1834: Fix length of lines
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetMultiSelector.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 /*
4  * ModuleBase_WidgetMultiSelector.cpp
5  *
6  *  Created on: Aug 28, 2014
7  *      Author: sbh
8  */
9
10 #include <ModuleBase_WidgetMultiSelector.h>
11 #include <ModuleBase_WidgetShapeSelector.h>
12 #include <ModuleBase_ISelection.h>
13 #include <ModuleBase_IWorkshop.h>
14 #include <ModuleBase_IViewer.h>
15 #include <ModuleBase_Tools.h>
16 #include <ModuleBase_Definitions.h>
17 #include <ModuleBase_IModule.h>
18 #include <ModuleBase_ViewerPrs.h>
19 #include <ModuleBase_IconFactory.h>
20 #include <ModuleBase_Events.h>
21
22 #include <ModelAPI_Data.h>
23 #include <ModelAPI_Object.h>
24 #include <ModelAPI_AttributeSelectionList.h>
25 #include <ModelAPI_AttributeRefList.h>
26 #include <ModelAPI_AttributeRefAttrList.h>
27 #include <ModelAPI_Tools.h>
28 #include <ModelAPI_Events.h>
29
30 #include <Config_WidgetAPI.h>
31
32 #include <QGridLayout>
33 #include <QLabel>
34 #include <QListWidget>
35 #include <QObject>
36 #include <QString>
37 #include <QComboBox>
38 #include <QEvent>
39 #include <QAction>
40 #include <QApplication>
41 #include <QClipboard>
42 #include <QTimer>
43 #include <QMainWindow>
44
45 #include <memory>
46 #include <string>
47
48 const int ATTRIBUTE_SELECTION_INDEX_ROLE = Qt::UserRole + 1;
49
50 /**
51 * Customization of a List Widget to make it to be placed on full width of container
52 */
53 class CustomListWidget : public QListWidget
54 {
55 public:
56   /// Constructor
57   /// \param theParent a parent widget
58   CustomListWidget( QWidget* theParent )
59     : QListWidget( theParent )
60   {
61   }
62
63   /// Redefinition of virtual method
64   virtual QSize sizeHint() const
65   {
66     int aHeight = 2*QFontMetrics( font() ).height();
67     QSize aSize = QListWidget::sizeHint();
68     return QSize( aSize.width(), aHeight );
69   }
70
71   /// Redefinition of virtual method
72   virtual QSize minimumSizeHint() const
73   {
74     int aHeight = 4/*2*/*QFontMetrics( font() ).height();
75     QSize aSize = QListWidget::minimumSizeHint();
76     return QSize( aSize.width(), aHeight );
77   }
78
79 #ifndef WIN32
80 // The code is necessary only for Linux because
81 //it can not update viewport on widget resize
82 protected:
83   void resizeEvent(QResizeEvent* theEvent)
84   {
85     QListWidget::resizeEvent(theEvent);
86     QTimer::singleShot(5, viewport(), SLOT(repaint()));
87   }
88 #endif
89 };
90
91 ModuleBase_WidgetMultiSelector::ModuleBase_WidgetMultiSelector(QWidget* theParent,
92                                                                ModuleBase_IWorkshop* theWorkshop,
93                                                                const Config_WidgetAPI* theData)
94 : ModuleBase_WidgetSelector(theParent, theWorkshop, theData)
95 {
96   QGridLayout* aMainLay = new QGridLayout(this);
97   ModuleBase_Tools::adjustMargins(aMainLay);
98
99   QLabel* aTypeLabel = new QLabel(tr("Type"), this);
100   aMainLay->addWidget(aTypeLabel, 0, 0);
101
102   myTypeCombo = new QComboBox(this);
103   // There is no sense to parameterize list of types while we can not parameterize selection mode
104
105   std::string aPropertyTypes = theData->getProperty("type_choice");
106   QString aTypesStr = aPropertyTypes.c_str();
107   QStringList aShapeTypes = aTypesStr.split(' ', QString::SkipEmptyParts);
108
109   myIsUseChoice = theData->getBooleanAttribute("use_choice", false);
110
111   if (!aShapeTypes.empty())
112     myTypeCombo->addItems(aShapeTypes);
113   aMainLay->addWidget(myTypeCombo, 0, 1);
114   // if the xml definition contains one type, the controls to select a type should not be shown
115   if (aShapeTypes.size() <= 1 || !myIsUseChoice) {
116     aTypeLabel->setVisible(false);
117     myTypeCombo->setVisible(false);
118   }
119
120   std::string aLabelText = theData->getProperty("label");
121   QLabel* aListLabel = new QLabel(!aLabelText.empty() ? aLabelText.c_str()
122                                                       : tr("Selected objects:"), this);
123   aMainLay->addWidget(aListLabel, 1, 0);
124   // if the xml definition contains one type, an information label 
125   // should be shown near to the latest
126   if (aShapeTypes.size() <= 1) {
127     QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
128     if (!aLabelIcon.isEmpty()) {
129       QLabel* aSelectedLabel = new QLabel("", this);
130       aSelectedLabel->setPixmap(ModuleBase_IconFactory::loadPixmap(aLabelIcon));
131       aMainLay->addWidget(aSelectedLabel, 1, 1);
132     }
133     aMainLay->setColumnStretch(2, 1);
134   }
135
136   QString aToolTip = QString::fromStdString(theData->widgetTooltip());
137   myListControl = new CustomListWidget(this);
138   QString anObjName = QString::fromStdString(attributeID());
139   myListControl->setObjectName(anObjName);
140   myListControl->setToolTip(aToolTip);
141   myListControl->setSelectionMode(QAbstractItemView::ExtendedSelection);
142
143   aMainLay->addWidget(myListControl, 2, 0, 1, -1);
144   aMainLay->setRowStretch(2, 1);
145   //aMainLay->addWidget(new QLabel(this)); //FIXME(sbh)???
146   //aMainLay->setRowMinimumHeight(3, 20);
147   //this->setLayout(aMainLay);
148   connect(myTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSelectionTypeChanged()));
149
150   myCopyAction = ModuleBase_Tools::createAction(QIcon(":pictures/copy.png"), tr("Copy"),
151                           myWorkshop->desktop(), this, SLOT(onCopyItem()));
152   myCopyAction->setShortcut(QKeySequence::Copy);
153   myCopyAction->setEnabled(false);
154   myListControl->addAction(myCopyAction);
155
156   myDeleteAction = ModuleBase_Tools::createAction(QIcon(":pictures/delete.png"), tr("Delete"),
157                           myWorkshop->desktop(), this, SLOT(onDeleteItem()));
158   myDeleteAction->setEnabled(false);
159   myListControl->addAction(myDeleteAction);
160
161   myListControl->setContextMenuPolicy(Qt::ActionsContextMenu);
162   connect(myListControl, SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
163
164   myIsNeutralPointClear = theData->getBooleanAttribute("clear_in_neutral_point", true);
165 }
166
167 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
168 {
169 }
170
171 //********************************************************************
172 void ModuleBase_WidgetMultiSelector::activateCustom()
173 {
174   ModuleBase_WidgetSelector::activateCustom();
175
176   myWorkshop->module()->activateCustomPrs(myFeature,
177                             ModuleBase_IModule::CustomizeHighlightedObjects, true);
178 }
179
180 //********************************************************************
181 void ModuleBase_WidgetMultiSelector::deactivate()
182 {
183   ModuleBase_WidgetSelector::deactivate();
184
185   myWorkshop->module()->deactivateCustomPrs(ModuleBase_IModule::CustomizeHighlightedObjects, true);
186 }
187
188 //********************************************************************
189 bool ModuleBase_WidgetMultiSelector::storeValueCustom()
190 {
191   // the value is stored on the selection changed signal processing 
192   // A rare case when plugin was not loaded. 
193   if (!myFeature)
194     return false;
195
196   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
197   std::string aType = anAttribute->attributeType();
198   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
199     AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
200     aSelectionListAttr->setSelectionType(myTypeCombo->currentText().toStdString());
201   }
202   return true;
203 }
204
205 //********************************************************************
206 bool ModuleBase_WidgetMultiSelector::restoreValueCustom()
207 {
208   // A rare case when plugin was not loaded. 
209   if (!myFeature)
210     return false;
211
212   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
213   std::string aType = anAttribute->attributeType();
214   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
215     AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
216     // Restore shape type
217     std::string aSelectionType = aSelectionListAttr->selectionType().c_str();
218     if (!aSelectionType.empty())
219       setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionType.c_str()));
220   }
221   updateSelectionList();
222   return true;
223 }
224
225 //********************************************************************
226 bool ModuleBase_WidgetMultiSelector::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
227                                                   const bool theToValidate)
228 {
229   AttributeSelectionListPtr aSelectionListAttr;
230   if (attribute()->attributeType() == ModelAPI_AttributeSelectionList::typeId())
231     aSelectionListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(attribute());
232   if (aSelectionListAttr.get())
233     aSelectionListAttr->cashValues(true);
234
235   /// remove unused objects from the model attribute.
236   /// It should be performed before new attributes append.
237   bool isDone = removeUnusedAttributeObjects(theValues);
238
239   QList<ModuleBase_ViewerPrsPtr> anInvalidValues;
240   QList<ModuleBase_ViewerPrsPtr> anAttributeValues;
241   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
242   for (; anIt != aLast; anIt++) {
243     ModuleBase_ViewerPrsPtr aValue = *anIt;
244     // do not validate and append to attribute selection presentation if it exists in the attribute
245     ObjectPtr anObject;
246     GeomShapePtr aShape;
247     getGeomSelection(aValue, anObject, aShape);
248     if (ModuleBase_Tools::hasObject(attribute(), anObject, aShape, myWorkshop, myIsInValidate)) {
249       anAttributeValues.append(aValue);
250       continue;
251     }
252     if (theToValidate && !isValidInFilters(aValue))
253       anInvalidValues.append(aValue);
254   }
255   bool aHasInvalidValues = anInvalidValues.size() > 0;
256
257   for (anIt = theValues.begin(); anIt != aLast; anIt++) {
258     ModuleBase_ViewerPrsPtr aValue = *anIt;
259     bool aProcessed = false;
260     if ((aHasInvalidValues && anInvalidValues.contains(aValue)) ||
261         anAttributeValues.contains(aValue))
262       continue;
263     aProcessed = setSelectionCustom(aValue); /// it is not optimal as hasObject() is already checked
264     // if there is at least one set, the result is true
265     isDone = isDone || aProcessed;
266   }
267   // updateObject - to update/redisplay feature
268   // it is commented in order to perfom it outside the method
269   //if (isDone) {
270     //updateObject(myFeature);
271     // this emit is necessary to call store/restore method an restore type of selection
272     //emit valuesChanged();
273   //}
274
275   if (aSelectionListAttr.get())
276     aSelectionListAttr->cashValues(false);
277
278   theValues.clear();
279   if (!anInvalidValues.empty())
280     theValues.append(anInvalidValues);
281
282   if (isDone) // may be the feature's result is not displayed, but attributes should be
283     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeArguments,
284                              true);/// hope that something is redisplayed by object updated
285
286   return isDone;
287 }
288
289 //********************************************************************
290 void ModuleBase_WidgetMultiSelector::getHighlighted(QList<ModuleBase_ViewerPrsPtr>& theValues)
291 {
292   std::set<int> anAttributeIds;
293   getSelectedAttributeIndices(anAttributeIds);
294   if (!anAttributeIds.empty())
295     convertIndicesToViewerSelection(anAttributeIds, theValues);
296 }
297
298 //********************************************************************
299 bool ModuleBase_WidgetMultiSelector::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& thePrs)
300 {
301   bool aValid = ModuleBase_WidgetSelector::isValidSelectionCustom(thePrs);
302   if (aValid) {
303     ResultPtr aResult = myWorkshop->selection()->getResult(thePrs);
304     aValid = aResult.get() != NULL;
305     if (aValid) {
306       if (myFeature) {
307         // We can not select a result of our feature
308         std::list<ResultPtr> aResults;
309         ModelAPI_Tools::allResults(myFeature, aResults);
310         std::list<ResultPtr>::const_iterator aIt;
311         bool isSkipSelf = false;
312         for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
313           if ((*aIt) == aResult) {
314             isSkipSelf = true;
315             break;
316           }
317         }
318         if (isSkipSelf)
319           aValid = false;
320       }
321     }
322   }
323   return aValid;
324 }
325
326 //********************************************************************
327 bool ModuleBase_WidgetMultiSelector::processDelete()
328 {
329   // find attribute indices to delete
330   std::set<int> anAttributeIds;
331   getSelectedAttributeIndices(anAttributeIds);
332
333   QModelIndexList aIndexes = myListControl->selectionModel()->selectedIndexes();
334
335   // refill attribute by the items which indices are not in the list of ids
336   bool aDone = false;
337   DataPtr aData = myFeature->data();
338   AttributePtr anAttribute = aData->attribute(attributeID());
339   std::string aType = anAttribute->attributeType();
340   aDone = !anAttributeIds.empty();
341   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
342     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
343     aSelectionListAttr->remove(anAttributeIds);
344
345   }
346   else if (aType == ModelAPI_AttributeRefList::typeId()) {
347     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
348     aRefListAttr->remove(anAttributeIds);
349   }
350   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
351     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
352     aRefAttrListAttr->remove(anAttributeIds);
353   }
354
355   if (aDone) {
356     // update object is necessary to flush update signal. It leads to objects references map update
357     // and the operation presentation will not contain deleted items visualized as parameters of
358     // the feature.
359     updateObject(myFeature);
360
361     restoreValue();
362     myWorkshop->setSelected(getAttributeSelection());
363
364     // may be the feature's result is not displayed, but attributes should be
365     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeArguments,
366                               true); /// hope that something is redisplayed by object updated
367   }
368
369   // Restore selection
370   int aRows = myListControl->model()->rowCount();
371   if (aRows > 0) {
372     foreach(QModelIndex aIndex, aIndexes) {
373       if (aIndex.row() < aRows)
374         myListControl->selectionModel()->select(aIndex, QItemSelectionModel::Select);
375       else {
376         QModelIndex aIdx = myListControl->model()->index(aRows - 1, 0);
377         myListControl->selectionModel()->select(aIdx, QItemSelectionModel::Select);
378       }
379     }
380   }
381   return aDone;
382 }
383
384 //********************************************************************
385 QList<QWidget*> ModuleBase_WidgetMultiSelector::getControls() const
386 {
387   QList<QWidget*> result;
388   //result << myTypeCombo;
389   result << myListControl;
390   return result;
391 }
392
393 //********************************************************************
394 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
395 {
396   activateSelectionAndFilters(true);
397   QList<ModuleBase_ViewerPrsPtr> anEmptyList;
398   // This method will call Selection changed event which will call onSelectionChanged
399   // To clear mySelection, myListControl and storeValue()
400   // So, we don't need to call it
401   myWorkshop->setSelected(anEmptyList);
402 }
403
404 //********************************************************************
405 void ModuleBase_WidgetMultiSelector::onSelectionChanged()
406 {
407   if (!myIsNeutralPointClear) {
408     QList<ModuleBase_ViewerPrsPtr> aSelected = getFilteredSelected();
409     // do not clear selected object
410     if (aSelected.size() == 0) {
411       if (!getAttributeSelection().empty()) {
412         // Restore selection in the viewer by the attribute selection list
413         // it should be postponed to exit from the selectionChanged processing
414         static Events_ID anEvent = Events_Loop::eventByName(EVENT_UPDATE_BY_WIDGET_SELECTION);
415         ModelAPI_EventCreator::get()->sendUpdated(myFeature, anEvent);
416         Events_Loop::loop()->flush(anEvent);
417         return;
418       }
419     }
420   }
421   ModuleBase_WidgetSelector::onSelectionChanged();
422 }
423
424 void ModuleBase_WidgetMultiSelector::updateFocus()
425 {
426   // Set focus to List control in order to make possible 
427   // to use Tab key for transfer the focus to next widgets
428   myListControl->setCurrentRow(myListControl->model()->rowCount() - 1);
429   ModuleBase_Tools::setFocus(myListControl,
430                              "ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()");
431 }
432
433 //********************************************************************
434 void ModuleBase_WidgetMultiSelector::updateSelectionName()
435 {
436 }
437
438 //********************************************************************
439 QIntList ModuleBase_WidgetMultiSelector::shapeTypes() const
440 {
441   QIntList aShapeTypes;
442
443   if (myTypeCombo->count() > 1 && myIsUseChoice) {
444     aShapeTypes.append(ModuleBase_Tools::shapeType(myTypeCombo->currentText()));
445   }
446   else {
447     for (int i = 0, aCount = myTypeCombo->count(); i < aCount; i++)
448       aShapeTypes.append(ModuleBase_Tools::shapeType(myTypeCombo->itemText(i)));
449   }
450   return aShapeTypes;
451 }
452
453 //********************************************************************
454 void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const int theShapeType)
455 {
456   QString aShapeTypeName;
457   
458   for (int idx = 0; idx < myTypeCombo->count(); ++idx) {
459     aShapeTypeName = myTypeCombo->itemText(idx);
460     int aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
461     if(aRefType == theShapeType && idx != myTypeCombo->currentIndex()) {
462       bool aWasActivated = activateSelectionAndFilters(false);
463       bool isBlocked = myTypeCombo->blockSignals(true);
464       myTypeCombo->setCurrentIndex(idx);
465       myTypeCombo->blockSignals(isBlocked);
466       if (aWasActivated)
467         activateSelectionAndFilters(true);
468       break;
469     }
470   }
471 }
472
473 QList<ModuleBase_ViewerPrsPtr> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
474 {
475   QList<ModuleBase_ViewerPrsPtr> aSelected;
476   convertIndicesToViewerSelection(std::set<int>(), aSelected);
477   return aSelected;
478 }
479
480 //********************************************************************
481 void ModuleBase_WidgetMultiSelector::updateSelectionList()
482 {
483   myListControl->clear();
484
485   DataPtr aData = myFeature->data();
486   AttributePtr anAttribute = aData->attribute(attributeID());
487   std::string aType = anAttribute->attributeType();
488   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
489     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
490     for (int i = 0; i < aSelectionListAttr->size(); i++) {
491       AttributeSelectionPtr aAttr = aSelectionListAttr->value(i);
492       QListWidgetItem* anItem = new QListWidgetItem(aAttr->namingName().c_str(), myListControl);
493       anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
494       myListControl->addItem(anItem);
495     }
496   }
497   else if (aType == ModelAPI_AttributeRefList::typeId()) {
498     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
499     for (int i = 0; i < aRefListAttr->size(); i++) {
500       ObjectPtr anObject = aRefListAttr->object(i);
501       if (anObject.get()) {
502         QListWidgetItem* anItem = new QListWidgetItem(anObject->data()->name().c_str(),
503                                                       myListControl);
504         anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
505         myListControl->addItem(anItem);
506       }
507     }
508   }
509   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
510     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
511     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
512       AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
513       QString aName;
514       if (anAttribute.get()) {
515         std::string anAttrName = generateName(anAttribute, myWorkshop);
516         aName = QString::fromStdString(anAttrName);
517       }
518       else {
519         ObjectPtr anObject = aRefAttrListAttr->object(i);
520         if (anObject.get()) {
521           aName = anObject->data()->name().c_str();
522         }
523       }
524       QListWidgetItem* anItem = new QListWidgetItem(aName, myListControl);
525       anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
526       myListControl->addItem(anItem);
527     }
528   }
529
530   // We have to call repaint because sometimes the List control is not updated
531   myListControl->repaint();
532 }
533
534 //********************************************************************
535 std::string ModuleBase_WidgetMultiSelector::validatorType(const QString& theType) const
536 {
537   std::string aType;
538
539   if (theType == "Vertices")
540     aType = "vertex";
541   else if (theType == "Edges")
542     aType = "edge";
543   else if (theType == "Faces")
544     aType = "face";
545   else if (theType == "Solids")
546     aType = "solid";
547
548   return aType;
549 }
550
551 //********************************************************************
552 void ModuleBase_WidgetMultiSelector::onCopyItem()
553 {
554   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
555   QString aRes;
556   foreach(QListWidgetItem* aItem, aItems) {
557     if (!aRes.isEmpty())
558       aRes += "\n";
559     aRes += aItem->text();
560   }
561   if (!aRes.isEmpty()) {
562     QClipboard *clipboard = QApplication::clipboard();
563     clipboard->setText(aRes);
564   }
565 }
566
567 //********************************************************************
568 void ModuleBase_WidgetMultiSelector::onDeleteItem()
569 {
570   processDelete();
571 }
572
573 //********************************************************************
574 void ModuleBase_WidgetMultiSelector::onListSelection()
575 {
576   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
577   myCopyAction->setEnabled(!aItems.isEmpty());
578   myDeleteAction->setEnabled(!aItems.isEmpty());
579   
580   myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeHighlightedObjects,
581                                         true);
582 }
583
584 //********************************************************************
585 void ModuleBase_WidgetMultiSelector::getSelectedAttributeIndices(std::set<int>& theAttributeIds)
586 {
587   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
588   foreach(QListWidgetItem* anItem, aItems) {
589     int anIndex = anItem->data(ATTRIBUTE_SELECTION_INDEX_ROLE).toInt();
590     if (theAttributeIds.find(anIndex) == theAttributeIds.end())
591       theAttributeIds.insert(anIndex);
592   }
593 }
594
595 void ModuleBase_WidgetMultiSelector::convertIndicesToViewerSelection(std::set<int> theAttributeIds,
596                                                    QList<ModuleBase_ViewerPrsPtr>& theValues) const
597 {
598   if(myFeature.get() == NULL)
599     return;
600
601   DataPtr aData = myFeature->data();
602   AttributePtr anAttribute = aData->attribute(attributeID());
603   std::string aType = anAttribute->attributeType();
604   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
605     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
606     for (int i = 0; i < aSelectionListAttr->size(); i++) {
607       // filter by attribute indices only if the container is not empty otherwise return all items
608       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
609         continue;
610       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
611       ResultPtr anObject = anAttr->context();
612       if (anObject.get())
613         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
614                new ModuleBase_ViewerPrs(anObject, anAttr->value(), NULL)));
615     }
616   }
617   else if (aType == ModelAPI_AttributeRefList::typeId()) {
618     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
619     for (int i = 0; i < aRefListAttr->size(); i++) {
620       // filter by attribute indices only if the container is not empty otherwise return all items
621       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
622         continue;
623       ObjectPtr anObject = aRefListAttr->object(i);
624       if (anObject.get()) {
625         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
626                new ModuleBase_ViewerPrs(anObject, GeomShapePtr(), NULL)));
627       }
628     }
629   }
630   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
631     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
632     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
633       // filter by attribute indices only if the container is not empty otherwise return all items
634       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
635         continue;
636       ObjectPtr anObject = aRefAttrListAttr->object(i);
637       if (!anObject.get())
638         continue;
639       TopoDS_Shape aShape;
640       AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
641       if (anAttribute.get()) {
642         GeomShapePtr aGeomShape = ModuleBase_Tools::getShape(anAttribute, myWorkshop);
643         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
644                new ModuleBase_ViewerPrs(anObject, aGeomShape, NULL)));
645       }
646     }
647   }
648 }
649
650 bool ModuleBase_WidgetMultiSelector::removeUnusedAttributeObjects
651                                                  (QList<ModuleBase_ViewerPrsPtr>& theValues)
652 {
653   bool isDone = false;
654
655   std::map<ObjectPtr, std::set<GeomShapePtr> > aGeomSelection = convertSelection(theValues);
656   DataPtr aData = myFeature->data();
657   AttributePtr anAttribute = aData->attribute(attributeID());
658   std::string aType = anAttribute->attributeType();
659   std::set<GeomShapePtr> aShapes;
660   std::set<int> anIndicesToBeRemoved;
661   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
662     // iteration through data model to find not selected elements to remove them
663     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
664     for (int i = 0; i < aSelectionListAttr->size(); i++) {
665       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
666       bool aFound = findInSelection(anAttr->context(), anAttr->value(), aGeomSelection);
667       if (!aFound)
668         anIndicesToBeRemoved.insert(i);
669     }
670     isDone = anIndicesToBeRemoved.size() > 0;
671     aSelectionListAttr->remove(anIndicesToBeRemoved);
672   }
673   else if (aType == ModelAPI_AttributeRefList::typeId()) {
674     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
675     for (int i = 0; i < aRefListAttr->size(); i++) {
676       ObjectPtr anObject = aRefListAttr->object(i);
677       if (anObject.get()) {
678         bool aFound = findInSelection(anObject, GeomShapePtr(), aGeomSelection);
679         if (!aFound)
680           anIndicesToBeRemoved.insert(i);
681       }
682     }
683     isDone = anIndicesToBeRemoved.size() > 0;
684     aRefListAttr->remove(anIndicesToBeRemoved);
685   }
686   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
687     std::set<AttributePtr> anAttributes;
688     QList<ModuleBase_ViewerPrsPtr>::const_iterator 
689       anIt = theValues.begin(), aLast = theValues.end();
690     ObjectPtr anObject;
691     GeomShapePtr aShape;
692     for (; anIt != aLast; anIt++) {
693       ModuleBase_ViewerPrsPtr aPrs = *anIt;
694       getGeomSelection(aPrs, anObject, aShape);
695       AttributePtr anAttr = myWorkshop->module()->findAttribute(anObject, aShape);
696       if (anAttr.get() && anAttributes.find(anAttr) == anAttributes.end())
697         anAttributes.insert(anAttr);
698     }
699
700     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
701     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
702       bool aFound = false;
703       if (aRefAttrListAttr->isAttribute(i)) {
704         AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
705         aFound = anAttributes.find(anAttribute) != anAttributes.end();
706       }
707       else {
708         aFound = findInSelection(aRefAttrListAttr->object(i), GeomShapePtr(), aGeomSelection);
709       }
710       if (!aFound)
711         anIndicesToBeRemoved.insert(i);
712     }
713     isDone = anIndicesToBeRemoved.size() > 0;
714     aRefAttrListAttr->remove(anIndicesToBeRemoved);
715   }
716
717   return isDone;
718 }
719
720 std::map<ObjectPtr, std::set<GeomShapePtr> > ModuleBase_WidgetMultiSelector::convertSelection
721                                                      (QList<ModuleBase_ViewerPrsPtr>& theValues)
722 {
723   // convert prs list to objects map
724   std::map<ObjectPtr, std::set<GeomShapePtr> > aGeomSelection;
725   std::set<GeomShapePtr> aShapes;
726   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
727   ObjectPtr anObject;
728   GeomShapePtr aShape;
729   GeomShapePtr anEmptyShape(new GeomAPI_Shape());
730   for (; anIt != aLast; anIt++) {
731     ModuleBase_ViewerPrsPtr aPrs = *anIt;
732     getGeomSelection(aPrs, anObject, aShape);
733     aShapes.clear();
734     if (aGeomSelection.find(anObject) != aGeomSelection.end()) // found
735       aShapes = aGeomSelection[anObject];
736     // we need to know if there was an empty shape in selection for the object
737     if (!aShape.get())
738       aShape = anEmptyShape;
739     if (aShape.get() && aShapes.find(aShape) == aShapes.end()) // not found
740       aShapes.insert(aShape);
741     aGeomSelection[anObject] = aShapes;
742   }
743   return aGeomSelection;
744 }
745
746 bool ModuleBase_WidgetMultiSelector::findInSelection(const ObjectPtr& theObject,
747                               const GeomShapePtr& theShape,
748                               const std::map<ObjectPtr, std::set<GeomShapePtr> >& theGeomSelection)
749 {
750   bool aFound = false;
751   GeomShapePtr anEmptyShape(new GeomAPI_Shape());
752   GeomShapePtr aShape = theShape.get() ? theShape : anEmptyShape;
753   if (theGeomSelection.find(theObject) != theGeomSelection.end()) {// found
754     const std::set<GeomShapePtr>& aShapes = theGeomSelection.at(theObject);
755     std::set<GeomShapePtr>::const_iterator anIt = aShapes.begin(), aLast = aShapes.end();
756     for (; anIt != aLast && !aFound; anIt++) {
757       GeomShapePtr aCShape = *anIt;
758       if (aCShape.get())
759         aFound = aCShape->isEqual(aShape);
760     }
761   }
762   return aFound;
763 }