]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_WidgetMultiSelector.cpp
Salome HOME
714e4ef7f389c06ed7f6e55306d97cb619d0db98
[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->setShortcut(QKeySequence::Delete);
152   myDeleteAction->setEnabled(false);
153   connect(myDeleteAction, SIGNAL(triggered(bool)), SLOT(onDeleteItem()));
154   myListControl->addAction(myDeleteAction);
155
156   myListControl->setContextMenuPolicy(Qt::ActionsContextMenu);
157   connect(myListControl, SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
158 }
159
160 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
161 {
162 }
163
164 //********************************************************************
165 bool ModuleBase_WidgetMultiSelector::storeValueCustom() const
166 {
167   // the value is stored on the selection changed signal processing 
168   // A rare case when plugin was not loaded. 
169   if (!myFeature)
170     return false;
171
172   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
173   if (aSelectionListAttr.get()) {
174      aSelectionListAttr->setSelectionType(myTypeCombo->currentText().toStdString());
175   }   
176    return true;
177 }
178
179 //********************************************************************
180 bool ModuleBase_WidgetMultiSelector::restoreValueCustom()
181 {
182   // A rare case when plugin was not loaded. 
183   if (!myFeature)
184     return false;
185
186   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
187   if (aSelectionListAttr.get()) {
188     // Restore shape type
189     if (!aSelectionListAttr->selectionType().empty())
190       setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionListAttr->selectionType().c_str()));
191   }
192   updateSelectionList();
193   return true;
194 }
195
196 //********************************************************************
197 void ModuleBase_WidgetMultiSelector::storeAttributeValue()
198 {
199   ModuleBase_WidgetValidated::storeAttributeValue();
200
201   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
202   if (aSelectionListAttr.get()) {
203     mySelectionType = aSelectionListAttr->selectionType();
204     mySelectionCount = aSelectionListAttr->size();
205   }
206   else {
207     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
208     mySelectionCount = aRefListAttr->size();
209   }
210 }
211
212 //********************************************************************
213 void ModuleBase_WidgetMultiSelector::restoreAttributeValue(bool theValid)
214 {
215   ModuleBase_WidgetValidated::restoreAttributeValue(theValid);
216
217   // Store shape type
218   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
219   if (aSelectionListAttr.get()) {
220     aSelectionListAttr->setSelectionType(mySelectionType);
221
222     // restore selection in the attribute. Indeed there is only one stored object
223     int aCountAppened = aSelectionListAttr->size() - mySelectionCount;
224     for (int i = 0; i < aCountAppened; i++)
225       aSelectionListAttr->removeLast();
226   }
227   else {
228     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
229     // restore objects in the attribute. Indeed there is only one stored object
230     int aCountAppened = aRefListAttr->size() - mySelectionCount;
231     for (int i = 0; i < aCountAppened; i++)
232       aRefListAttr->removeLast();
233   }
234 }
235
236 //********************************************************************
237 void ModuleBase_WidgetMultiSelector::clearAttribute()
238 {
239   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
240   if (aSelectionListAttr.get())
241     aSelectionListAttr->clear();
242   else {
243     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
244     aRefListAttr->clear();
245   }
246 }
247
248 //********************************************************************
249 void ModuleBase_WidgetMultiSelector::setObject(ObjectPtr theSelectedObject,
250                                                GeomShapePtr theShape)
251 {
252   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
253   if (aSelectionListAttr.get()) {
254     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theSelectedObject);
255     aSelectionListAttr->append(aResult, theShape, myIsInValidate);
256   }
257   else {
258     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
259     aRefListAttr->append(theSelectedObject);
260   }
261 }
262
263 //********************************************************************
264 bool ModuleBase_WidgetMultiSelector::setSelection(QList<ModuleBase_ViewerPrs>& theValues,
265                                                   const bool theToValidate)
266 {
267   QList<ModuleBase_ViewerPrs> aSkippedValues;
268
269   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
270   bool isDone = false;
271   for (; anIt != aLast; anIt++) {
272     ModuleBase_ViewerPrs aValue = *anIt;
273     bool aProcessed = false;
274     if (!theToValidate || isValidInFilters(aValue)) {
275       aProcessed = setSelectionCustom(aValue);
276     }
277     else
278       aSkippedValues.append(aValue);
279     // if there is at least one set, the result is true
280     isDone = isDone || aProcessed;
281   }
282   // updateObject - to update/redisplay feature
283   // it is commented in order to perfom it outside the method
284   //if (isDone) {
285     //updateObject(myFeature);
286     // this emit is necessary to call store/restore method an restore type of selection
287     //emit valuesChanged();
288   //}
289   theValues.clear();
290   if (!aSkippedValues.empty())
291     theValues.append(aSkippedValues);
292
293   return isDone;
294 }
295
296 //********************************************************************
297 void ModuleBase_WidgetMultiSelector::getHighlighted(QList<ModuleBase_ViewerPrs>& theValues)
298 {
299   std::set<int> anAttributeIds;
300   getSelectedAttributeIndices(anAttributeIds);
301   if (!anAttributeIds.empty())
302     convertIndicesToViewerSelection(anAttributeIds, theValues);
303 }
304
305 //********************************************************************
306 bool ModuleBase_WidgetMultiSelector::isValidSelectionCustom(const ModuleBase_ViewerPrs& thePrs)
307 {
308   bool aValid = ModuleBase_WidgetSelector::isValidSelectionCustom(thePrs);
309   if (aValid) {
310     ResultPtr aResult = myWorkshop->selection()->getResult(thePrs);
311     aValid = aResult.get() != NULL;
312     if (aValid) {
313       if (myFeature) {
314         // We can not select a result of our feature
315         const std::list<ResultPtr>& aResList = myFeature->results();
316         std::list<ResultPtr>::const_iterator aIt;
317         bool isSkipSelf = false;
318         for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
319           if ((*aIt) == aResult) {
320             isSkipSelf = true;
321             break;
322           }
323         }
324         if (isSkipSelf)
325           aValid = false;
326       }
327     }
328   }
329   return aValid;
330 }
331
332 //********************************************************************
333 QList<QWidget*> ModuleBase_WidgetMultiSelector::getControls() const
334 {
335   QList<QWidget*> result;
336   //result << myTypeCombo;
337   result << myListControl;
338   return result;
339 }
340
341 //********************************************************************
342 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
343 {
344   activateSelectionAndFilters(true);
345   QList<ModuleBase_ViewerPrs> anEmptyList;
346   // This method will call Selection changed event which will call onSelectionChanged
347   // To clear mySelection, myListControl and storeValue()
348   // So, we don't need to call it
349   myWorkshop->setSelected(anEmptyList);
350 }
351
352 void ModuleBase_WidgetMultiSelector::updateFocus()
353 {
354   // Set focus to List control in order to make possible 
355   // to use Tab key for transfer the focus to next widgets
356   myListControl->setCurrentRow(myListControl->model()->rowCount() - 1);
357   ModuleBase_Tools::setFocus(myListControl,
358                              "ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()");
359 }
360
361 //********************************************************************
362 void ModuleBase_WidgetMultiSelector::updateSelectionName()
363 {
364 }
365
366 //********************************************************************
367 QIntList ModuleBase_WidgetMultiSelector::getShapeTypes() const
368 {
369   QIntList aShapeTypes;
370
371   if (myTypeCombo->count() > 1 && myIsUseChoice) {
372     aShapeTypes.append(ModuleBase_Tools::shapeType(myTypeCombo->currentText()));
373   }
374   else {
375     for (int i = 0, aCount = myTypeCombo->count(); i < aCount; i++) {
376       TopAbs_ShapeEnum aType = ModuleBase_Tools::shapeType(myTypeCombo->itemText(i));
377       aShapeTypes.append(aType);
378       if (aType == TopAbs_SOLID)
379         aShapeTypes.append(TopAbs_COMPSOLID);
380     }
381   }
382   return aShapeTypes;
383 }
384
385 //********************************************************************
386 void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const TopAbs_ShapeEnum theShapeType)
387 {
388   QString aShapeTypeName;
389   
390   for (int idx = 0; idx < myTypeCombo->count(); ++idx) {
391     aShapeTypeName = myTypeCombo->itemText(idx);
392     TopAbs_ShapeEnum aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
393     if(aRefType == theShapeType && idx != myTypeCombo->currentIndex()) {
394       activateSelectionAndFilters(false);
395       bool isBlocked = myTypeCombo->blockSignals(true);
396       myTypeCombo->setCurrentIndex(idx);
397       myTypeCombo->blockSignals(isBlocked);
398
399       activateSelectionAndFilters(true);
400       break;
401     }
402   }
403 }
404
405 QList<ModuleBase_ViewerPrs> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
406 {
407   QList<ModuleBase_ViewerPrs> aSelected;
408   convertIndicesToViewerSelection(std::set<int>(), aSelected);
409   return aSelected;
410 }
411
412 //********************************************************************
413 void ModuleBase_WidgetMultiSelector::updateSelectionList()
414 {
415   myListControl->clear();
416
417   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
418   if (aSelectionListAttr.get()) {
419     for (int i = 0; i < aSelectionListAttr->size(); i++) {
420       AttributeSelectionPtr aAttr = aSelectionListAttr->value(i);
421       QListWidgetItem* anItem = new QListWidgetItem(aAttr->namingName().c_str(), myListControl);
422       anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
423       myListControl->addItem(anItem);
424     }
425   }
426   else {
427     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
428     for (int i = 0; i < aRefListAttr->size(); i++) {
429       ObjectPtr anObject = aRefListAttr->object(i);
430       if (anObject.get()) {
431         QListWidgetItem* anItem = new QListWidgetItem(anObject->data()->name().c_str(),
432                                                       myListControl);
433         anItem->setData(ATTRIBUTE_SELECTION_INDEX_ROLE, i);
434         myListControl->addItem(anItem);
435       }
436     }
437   }
438   // We have to call repaint because sometimes the List control is not updated
439   myListControl->repaint();
440 }
441
442 //********************************************************************
443 std::string ModuleBase_WidgetMultiSelector::validatorType(const QString& theType) const
444 {
445   std::string aType;
446
447   if (theType == "Vertices")
448     aType = "vertex";
449   else if (theType == "Edges")
450     aType = "edge";
451   else if (theType == "Faces")
452     aType = "face";
453   else if (theType == "Solids")
454     aType = "solid";
455
456   return aType;
457 }
458
459 //********************************************************************
460 void ModuleBase_WidgetMultiSelector::onCopyItem()
461 {
462   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
463   QString aRes;
464   foreach(QListWidgetItem* aItem, aItems) {
465     if (!aRes.isEmpty())
466       aRes += "\n";
467     aRes += aItem->text();
468   }
469   if (!aRes.isEmpty()) {
470     QClipboard *clipboard = QApplication::clipboard();
471     clipboard->setText(aRes);
472   }
473 }
474
475 //********************************************************************
476 void ModuleBase_WidgetMultiSelector::onDeleteItem()
477 {
478   // find attribute indices to delete
479   std::set<int> anAttributeIds;
480   getSelectedAttributeIndices(anAttributeIds);
481
482   // refill attribute by the items which indices are not in the list of ids
483   bool aDone = false;
484   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
485   if (aSelectionListAttr.get()) {
486     aDone = !anAttributeIds.empty();
487     aSelectionListAttr->remove(anAttributeIds);
488   }
489   else {
490     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
491     if (aRefListAttr.get()) {
492       aDone = !anAttributeIds.empty();
493       aRefListAttr->remove(anAttributeIds);
494     }
495   }
496   if (aDone) {
497     restoreValue();
498     myWorkshop->setSelected(getAttributeSelection());
499
500     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeAllObjects, true);
501   }
502 }
503
504 //********************************************************************
505 void ModuleBase_WidgetMultiSelector::onListSelection()
506 {
507   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
508   myCopyAction->setEnabled(!aItems.isEmpty());
509   myDeleteAction->setEnabled(!aItems.isEmpty());
510   
511   myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeHighlightedObjects,
512                                         true);
513 }
514
515 //********************************************************************
516 void ModuleBase_WidgetMultiSelector::getSelectedAttributeIndices(std::set<int>& theAttributeIds)
517 {
518   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
519   foreach(QListWidgetItem* anItem, aItems) {
520     int anIndex = anItem->data(ATTRIBUTE_SELECTION_INDEX_ROLE).toInt();
521     if (theAttributeIds.find(anIndex) == theAttributeIds.end())
522       theAttributeIds.insert(anIndex);
523   }
524 }
525
526 void ModuleBase_WidgetMultiSelector::convertIndicesToViewerSelection(std::set<int> theAttributeIds,
527                                                       QList<ModuleBase_ViewerPrs>& theValues) const
528 {
529   if(myFeature.get() == NULL)
530     return;
531   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
532   if (aSelectionListAttr.get()) {
533     for (int i = 0; i < aSelectionListAttr->size(); i++) {
534       // filter by attribute indices only if the container is not empty otherwise return all items
535       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
536         continue;
537       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
538       ResultPtr anObject = anAttr->context();
539       if (anObject.get()) {
540         TopoDS_Shape aShape;
541         std::shared_ptr<GeomAPI_Shape> aShapePtr = anAttr->value();
542         if (aShapePtr.get()) {
543           aShape = aShapePtr->impl<TopoDS_Shape>();
544         }
545         theValues.append(ModuleBase_ViewerPrs(anObject, aShape, NULL));
546       }
547     }
548   }
549   else {
550     AttributeRefListPtr aRefListAttr = myFeature->data()->reflist(attributeID());
551     if (aRefListAttr.get()) {
552       for (int i = 0; i < aRefListAttr->size(); i++) {
553         // filter by attribute indices only if the container is not empty otherwise return all items
554         if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
555           continue;
556         ObjectPtr anObject = aRefListAttr->object(i);
557         if (anObject.get()) {
558           theValues.append(ModuleBase_ViewerPrs(anObject, TopoDS_Shape(), NULL));
559         }
560       }
561     }
562   }
563 }