Salome HOME
Improve multi-selector control to provide "Delete" key processing.
[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
19 #include <ModelAPI_Data.h>
20 #include <ModelAPI_Object.h>
21 #include <ModelAPI_AttributeSelectionList.h>
22 #include <ModelAPI_AttributeRefList.h>
23
24 #include <Config_WidgetAPI.h>
25
26 #include <QGridLayout>
27 #include <QLabel>
28 #include <QListWidget>
29 #include <QObject>
30 #include <QString>
31 #include <QComboBox>
32 #include <QEvent>
33 #include <QAction>
34 #include <QApplication>
35 #include <QClipboard>
36 #include <QTimer>
37
38 #include <memory>
39 #include <string>
40
41 const int ATTRIBUTE_SELECTION_INDEX_ROLE = Qt::UserRole + 1;
42
43 /**
44 * Customization of a List Widget to make it to be placed on full width of container
45 */
46 class CustomListWidget : public QListWidget
47 {
48 public:
49   /// Constructor
50   /// \param theParent a parent widget
51   CustomListWidget( QWidget* theParent )
52     : QListWidget( theParent )
53   {
54   }
55
56   /// Redefinition of virtual method
57   virtual QSize sizeHint() const
58   {
59     int aHeight = 2*QFontMetrics( font() ).height();
60     QSize aSize = QListWidget::sizeHint();
61     return QSize( aSize.width(), aHeight );
62   }
63
64   /// Redefinition of virtual method
65   virtual QSize minimumSizeHint() const
66   {
67     int aHeight = 4/*2*/*QFontMetrics( font() ).height();
68     QSize aSize = QListWidget::minimumSizeHint();
69     return QSize( aSize.width(), aHeight );
70   }
71
72 #ifndef WIN32
73 // The code is necessary only for Linux because
74 //it can not update viewport on widget resize
75 protected:
76   void resizeEvent(QResizeEvent* theEvent)
77   {
78     QListWidget::resizeEvent(theEvent);
79     QTimer::singleShot(5, viewport(), SLOT(repaint()));
80   }
81 #endif
82 };
83
84 ModuleBase_WidgetMultiSelector::ModuleBase_WidgetMultiSelector(QWidget* theParent,
85                                                                ModuleBase_IWorkshop* theWorkshop,
86                                                                const Config_WidgetAPI* theData,
87                                                                const std::string& theParentId)
88  : ModuleBase_WidgetSelector(theParent, theWorkshop, theData, theParentId),
89    mySelectionCount(0)
90 {
91   QGridLayout* aMainLay = new QGridLayout(this);
92   ModuleBase_Tools::adjustMargins(aMainLay);
93
94   QLabel* aTypeLabel = new QLabel(tr("Type"), this);
95   aMainLay->addWidget(aTypeLabel, 0, 0);
96
97   myTypeCombo = new QComboBox(this);
98   // There is no sense to parameterize list of types while we can not parameterize selection mode
99
100   std::string aPropertyTypes = theData->getProperty("type_choice");
101   QString aTypesStr = aPropertyTypes.c_str();
102   QStringList aShapeTypes = aTypesStr.split(' ', QString::SkipEmptyParts);
103
104   myIsUseChoice = theData->getBooleanAttribute("use_choice", true);
105
106   if (!aShapeTypes.empty())
107     myTypeCombo->addItems(aShapeTypes);
108   aMainLay->addWidget(myTypeCombo, 0, 1);
109   // if the xml definition contains one type, the controls to select a type should not be shown
110   if (aShapeTypes.size() <= 1 || !myIsUseChoice) {
111     aTypeLabel->setVisible(false);
112     myTypeCombo->setVisible(false);
113   }
114
115   std::string aLabelText = theData->getProperty("label");
116   QLabel* aListLabel = new QLabel(!aLabelText.empty() ? aLabelText.c_str()
117                                                       : tr("Selected objects:"), this);
118   aMainLay->addWidget(aListLabel, 1, 0);
119   // if the xml definition contains one type, an information label should be shown near to the latest
120   if (aShapeTypes.size() <= 1) {
121     QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
122     if (!aLabelIcon.isEmpty()) {
123       QLabel* aSelectedLabel = new QLabel("", this);
124       aSelectedLabel->setPixmap(QPixmap(aLabelIcon));
125       aMainLay->addWidget(aSelectedLabel, 1, 1);
126     }
127     aMainLay->setColumnStretch(2, 1);
128   }
129
130   QString aToolTip = QString::fromStdString(theData->widgetTooltip());
131   myListControl = new CustomListWidget(this);
132   QString anObjName = QString::fromStdString(attributeID());
133   myListControl->setObjectName(anObjName);
134   myListControl->setToolTip(aToolTip);
135   myListControl->setSelectionMode(QAbstractItemView::ExtendedSelection);
136
137   aMainLay->addWidget(myListControl, 2, 0, 1, -1);
138   aMainLay->setRowStretch(2, 1);
139   //aMainLay->addWidget(new QLabel(this)); //FIXME(sbh)???
140   //aMainLay->setRowMinimumHeight(3, 20);
141   //this->setLayout(aMainLay);
142   connect(myTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSelectionTypeChanged()));
143
144   myCopyAction = new QAction(QIcon(":pictures/copy.png"), tr("Copy"), this);
145   myCopyAction->setShortcut(QKeySequence::Copy);
146   myCopyAction->setEnabled(false);
147   connect(myCopyAction, SIGNAL(triggered(bool)), SLOT(onCopyItem()));
148   myListControl->addAction(myCopyAction);
149
150   myDeleteAction = new QAction(QIcon(":pictures/delete.png"), tr("Delete"), this);
151   myDeleteAction->setEnabled(false);
152   connect(myDeleteAction, SIGNAL(triggered(bool)), SLOT(onDeleteItem()));
153   myListControl->addAction(myDeleteAction);
154
155   myListControl->setContextMenuPolicy(Qt::ActionsContextMenu);
156   connect(myListControl, SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
157 }
158
159 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
160 {
161 }
162
163 //********************************************************************
164 bool ModuleBase_WidgetMultiSelector::storeValueCustom() const
165 {
166   // the value is stored on the selection changed signal processing 
167   // A rare case when plugin was not loaded. 
168   if (!myFeature)
169     return false;
170
171   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
172   if (aSelectionListAttr.get()) {
173      aSelectionListAttr->setSelectionType(myTypeCombo->currentText().toStdString());
174   }   
175    return true;
176 }
177
178 //********************************************************************
179 bool ModuleBase_WidgetMultiSelector::restoreValueCustom()
180 {
181   // A rare case when plugin was not loaded. 
182   if (!myFeature)
183     return false;
184
185   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
186   if (aSelectionListAttr.get()) {
187     // Restore shape type
188     if (!aSelectionListAttr->selectionType().empty())
189       setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionListAttr->selectionType().c_str()));
190   }
191   updateSelectionList();
192   return true;
193 }
194
195 //********************************************************************
196 void ModuleBase_WidgetMultiSelector::storeAttributeValue()
197 {
198   ModuleBase_WidgetValidated::storeAttributeValue();
199
200   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
201   if (aSelectionListAttr.get()) {
202     mySelectionType = aSelectionListAttr->selectionType();
203     mySelectionCount = aSelectionListAttr->size();
204   }
205   else {
206     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
207     mySelectionCount = aRefListAttr->size();
208   }
209 }
210
211 //********************************************************************
212 void ModuleBase_WidgetMultiSelector::restoreAttributeValue(bool theValid)
213 {
214   ModuleBase_WidgetValidated::restoreAttributeValue(theValid);
215
216   // Store shape type
217   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
218   if (aSelectionListAttr.get()) {
219     aSelectionListAttr->setSelectionType(mySelectionType);
220
221     // restore selection in the attribute. Indeed there is only one stored object
222     int aCountAppened = aSelectionListAttr->size() - mySelectionCount;
223     for (int i = 0; i < aCountAppened; i++)
224       aSelectionListAttr->removeLast();
225   }
226   else {
227     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
228     // restore objects in the attribute. Indeed there is only one stored object
229     int aCountAppened = aRefListAttr->size() - mySelectionCount;
230     for (int i = 0; i < aCountAppened; i++)
231       aRefListAttr->removeLast();
232   }
233 }
234
235 //********************************************************************
236 void ModuleBase_WidgetMultiSelector::clearAttribute()
237 {
238   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
239   if (aSelectionListAttr.get())
240     aSelectionListAttr->clear();
241   else {
242     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
243     aRefListAttr->clear();
244   }
245 }
246
247 //********************************************************************
248 void ModuleBase_WidgetMultiSelector::setObject(ObjectPtr theSelectedObject,
249                                                GeomShapePtr theShape)
250 {
251   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
252   if (aSelectionListAttr.get()) {
253     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theSelectedObject);
254     aSelectionListAttr->append(aResult, theShape, myIsInValidate);
255   }
256   else {
257     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
258     aRefListAttr->append(theSelectedObject);
259   }
260 }
261
262 //********************************************************************
263 bool ModuleBase_WidgetMultiSelector::setSelection(QList<ModuleBase_ViewerPrs>& theValues,
264                                                   const bool theToValidate)
265 {
266   QList<ModuleBase_ViewerPrs> aSkippedValues;
267
268   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
269   bool isDone = false;
270   for (; anIt != aLast; anIt++) {
271     ModuleBase_ViewerPrs aValue = *anIt;
272     bool aProcessed = false;
273     if (!theToValidate || isValidInFilters(aValue)) {
274       aProcessed = setSelectionCustom(aValue);
275     }
276     else
277       aSkippedValues.append(aValue);
278     // if there is at least one set, the result is true
279     isDone = isDone || aProcessed;
280   }
281   // updateObject - to update/redisplay feature
282   // it is commented in order to perfom it outside the method
283   //if (isDone) {
284     //updateObject(myFeature);
285     // this emit is necessary to call store/restore method an restore type of selection
286     //emit valuesChanged();
287   //}
288   theValues.clear();
289   if (!aSkippedValues.empty())
290     theValues.append(aSkippedValues);
291
292   return isDone;
293 }
294
295 //********************************************************************
296 void ModuleBase_WidgetMultiSelector::getHighlighted(QList<ModuleBase_ViewerPrs>& theValues)
297 {
298   std::set<int> anAttributeIds;
299   getSelectedAttributeIndices(anAttributeIds);
300   if (!anAttributeIds.empty())
301     convertIndicesToViewerSelection(anAttributeIds, theValues);
302 }
303
304 //********************************************************************
305 bool ModuleBase_WidgetMultiSelector::isValidSelectionCustom(const ModuleBase_ViewerPrs& thePrs)
306 {
307   bool aValid = ModuleBase_WidgetSelector::isValidSelectionCustom(thePrs);
308   if (aValid) {
309     ResultPtr aResult = myWorkshop->selection()->getResult(thePrs);
310     aValid = aResult.get() != NULL;
311     if (aValid) {
312       if (myFeature) {
313         // We can not select a result of our feature
314         const std::list<ResultPtr>& aResList = myFeature->results();
315         std::list<ResultPtr>::const_iterator aIt;
316         bool isSkipSelf = false;
317         for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
318           if ((*aIt) == aResult) {
319             isSkipSelf = true;
320             break;
321           }
322         }
323         if (isSkipSelf)
324           aValid = false;
325       }
326     }
327   }
328   return aValid;
329 }
330
331 //********************************************************************
332 bool ModuleBase_WidgetMultiSelector::processDelete()
333 {
334   // find attribute indices to delete
335   std::set<int> anAttributeIds;
336   getSelectedAttributeIndices(anAttributeIds);
337
338   // refill attribute by the items which indices are not in the list of ids
339   bool aDone = false;
340   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
341   if (aSelectionListAttr.get()) {
342     aDone = !anAttributeIds.empty();
343     aSelectionListAttr->remove(anAttributeIds);
344   }
345   else {
346     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
347     if (aRefListAttr.get()) {
348       aDone = !anAttributeIds.empty();
349       aRefListAttr->remove(anAttributeIds);
350     }
351   }
352   if (aDone) {
353     // update object is necessary to flush update signal. It leads to objects references map update
354     // and the operation presentation will not contain deleted items visualized as parameters of
355     // the feature.
356     updateObject(myFeature);
357
358     restoreValue();
359     myWorkshop->setSelected(getAttributeSelection());
360     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeAllObjects, true);
361   }
362   return true; // if the delete should be processed outsize, the method should return isDone
363 }
364
365 //********************************************************************
366 QList<QWidget*> ModuleBase_WidgetMultiSelector::getControls() const
367 {
368   QList<QWidget*> result;
369   //result << myTypeCombo;
370   result << myListControl;
371   return result;
372 }
373
374 //********************************************************************
375 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
376 {
377   activateSelectionAndFilters(true);
378   QList<ModuleBase_ViewerPrs> anEmptyList;
379   // This method will call Selection changed event which will call onSelectionChanged
380   // To clear mySelection, myListControl and storeValue()
381   // So, we don't need to call it
382   myWorkshop->setSelected(anEmptyList);
383 }
384
385 void ModuleBase_WidgetMultiSelector::updateFocus()
386 {
387   // Set focus to List control in order to make possible 
388   // to use Tab key for transfer the focus to next widgets
389   myListControl->setCurrentRow(myListControl->model()->rowCount() - 1);
390   ModuleBase_Tools::setFocus(myListControl,
391                              "ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()");
392 }
393
394 //********************************************************************
395 void ModuleBase_WidgetMultiSelector::updateSelectionName()
396 {
397 }
398
399 //********************************************************************
400 QIntList ModuleBase_WidgetMultiSelector::getShapeTypes() const
401 {
402   QIntList aShapeTypes;
403
404   if (myTypeCombo->count() > 1 && myIsUseChoice) {
405     aShapeTypes.append(ModuleBase_Tools::shapeType(myTypeCombo->currentText()));
406   }
407   else {
408     for (int i = 0, aCount = myTypeCombo->count(); i < aCount; i++) {
409       TopAbs_ShapeEnum aType = ModuleBase_Tools::shapeType(myTypeCombo->itemText(i));
410       aShapeTypes.append(aType);
411       if (aType == TopAbs_SOLID)
412         aShapeTypes.append(TopAbs_COMPSOLID);
413     }
414   }
415   return aShapeTypes;
416 }
417
418 //********************************************************************
419 void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const TopAbs_ShapeEnum theShapeType)
420 {
421   QString aShapeTypeName;
422   
423   for (int idx = 0; idx < myTypeCombo->count(); ++idx) {
424     aShapeTypeName = myTypeCombo->itemText(idx);
425     TopAbs_ShapeEnum aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
426     if(aRefType == theShapeType && idx != myTypeCombo->currentIndex()) {
427       activateSelectionAndFilters(false);
428       bool isBlocked = myTypeCombo->blockSignals(true);
429       myTypeCombo->setCurrentIndex(idx);
430       myTypeCombo->blockSignals(isBlocked);
431
432       activateSelectionAndFilters(true);
433       break;
434     }
435   }
436 }
437
438 QList<ModuleBase_ViewerPrs> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
439 {
440   QList<ModuleBase_ViewerPrs> aSelected;
441   convertIndicesToViewerSelection(std::set<int>(), aSelected);
442   return aSelected;
443 }
444
445 //********************************************************************
446 void ModuleBase_WidgetMultiSelector::updateSelectionList()
447 {
448   myListControl->clear();
449
450   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
451   if (aSelectionListAttr.get()) {
452     for (int i = 0; i < aSelectionListAttr->size(); i++) {
453       AttributeSelectionPtr aAttr = aSelectionListAttr->value(i);
454       QListWidgetItem* anItem = new QListWidgetItem(aAttr->namingName().c_str(), myListControl);
455       anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
456       myListControl->addItem(anItem);
457     }
458   }
459   else {
460     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
461     for (int i = 0; i < aRefListAttr->size(); i++) {
462       ObjectPtr anObject = aRefListAttr->object(i);
463       if (anObject.get()) {
464         QListWidgetItem* anItem = new QListWidgetItem(anObject->data()->name().c_str(),
465                                                       myListControl);
466         anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
467         myListControl->addItem(anItem);
468       }
469     }
470   }
471   // We have to call repaint because sometimes the List control is not updated
472   myListControl->repaint();
473 }
474
475 //********************************************************************
476 std::string ModuleBase_WidgetMultiSelector::validatorType(const QString& theType) const
477 {
478   std::string aType;
479
480   if (theType == "Vertices")
481     aType = "vertex";
482   else if (theType == "Edges")
483     aType = "edge";
484   else if (theType == "Faces")
485     aType = "face";
486   else if (theType == "Solids")
487     aType = "solid";
488
489   return aType;
490 }
491
492 //********************************************************************
493 void ModuleBase_WidgetMultiSelector::onCopyItem()
494 {
495   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
496   QString aRes;
497   foreach(QListWidgetItem* aItem, aItems) {
498     if (!aRes.isEmpty())
499       aRes += "\n";
500     aRes += aItem->text();
501   }
502   if (!aRes.isEmpty()) {
503     QClipboard *clipboard = QApplication::clipboard();
504     clipboard->setText(aRes);
505   }
506 }
507
508 //********************************************************************
509 void ModuleBase_WidgetMultiSelector::onDeleteItem()
510 {
511   processDelete();
512 }
513
514 //********************************************************************
515 void ModuleBase_WidgetMultiSelector::onListSelection()
516 {
517   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
518   myCopyAction->setEnabled(!aItems.isEmpty());
519   myDeleteAction->setEnabled(!aItems.isEmpty());
520   
521   myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeHighlightedObjects,
522                                         true);
523 }
524
525 //********************************************************************
526 void ModuleBase_WidgetMultiSelector::getSelectedAttributeIndices(std::set<int>& theAttributeIds)
527 {
528   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
529   foreach(QListWidgetItem* anItem, aItems) {
530     int anIndex = anItem->data(ATTRIBUTE_SELECTION_INDEX_ROLE).toInt();
531     if (theAttributeIds.find(anIndex) == theAttributeIds.end())
532       theAttributeIds.insert(anIndex);
533   }
534 }
535
536 void ModuleBase_WidgetMultiSelector::convertIndicesToViewerSelection(std::set<int> theAttributeIds,
537                                                       QList<ModuleBase_ViewerPrs>& theValues) const
538 {
539   if(myFeature.get() == NULL)
540     return;
541   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
542   if (aSelectionListAttr.get()) {
543     for (int i = 0; i < aSelectionListAttr->size(); i++) {
544       // filter by attribute indices only if the container is not empty otherwise return all items
545       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
546         continue;
547       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
548       ResultPtr anObject = anAttr->context();
549       if (anObject.get()) {
550         TopoDS_Shape aShape;
551         std::shared_ptr<GeomAPI_Shape> aShapePtr = anAttr->value();
552         if (aShapePtr.get()) {
553           aShape = aShapePtr->impl<TopoDS_Shape>();
554         }
555         theValues.append(ModuleBase_ViewerPrs(anObject, aShape, NULL));
556       }
557     }
558   }
559   else {
560     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
561     if (aRefListAttr.get()) {
562       for (int i = 0; i < aRefListAttr->size(); i++) {
563         // filter by attribute indices only if the container is not empty otherwise return all items
564         if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
565           continue;
566         ObjectPtr anObject = aRefListAttr->object(i);
567         if (anObject.get()) {
568           theValues.append(ModuleBase_ViewerPrs(anObject, TopoDS_Shape(), NULL));
569         }
570       }
571     }
572   }
573 }