Salome HOME
Fix pyconfig redefined declarations for _XOPEN_SOURCE and _POSIX_C_SOURCE
[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
18 #include <GeomValidators_ShapeType.h>
19
20 #include <ModelAPI_Data.h>
21 #include <ModelAPI_Object.h>
22
23 #include <Config_WidgetAPI.h>
24
25 #include <QGridLayout>
26 #include <QLabel>
27 #include <QListWidget>
28 #include <QObject>
29 #include <QString>
30 #include <QComboBox>
31 #include <QEvent>
32 #include <QAction>
33 #include <QApplication>
34 #include <QClipboard>
35
36 #include <memory>
37 #include <string>
38
39 ModuleBase_WidgetMultiSelector::ModuleBase_WidgetMultiSelector(QWidget* theParent,
40                                                                ModuleBase_IWorkshop* theWorkshop,
41                                                                const Config_WidgetAPI* theData,
42                                                                const std::string& theParentId)
43     : ModuleBase_WidgetValidated(theParent, theData, theParentId),
44       myWorkshop(theWorkshop)
45 {
46   QGridLayout* aMainLay = new QGridLayout(this);
47   ModuleBase_Tools::adjustMargins(aMainLay);
48
49   QLabel* aTypeLabel = new QLabel(tr("Type"), this);
50   aMainLay->addWidget(aTypeLabel, 0, 0);
51
52   myTypeCombo = new QComboBox(this);
53   // There is no sence to paramerize list of types while we can not parametrize selection mode
54
55   myShapeValidator = new GeomValidators_ShapeType();
56
57   std::string aPropertyTypes = theData->getProperty("type_choice");
58   QString aTypesStr = aPropertyTypes.c_str();
59   QStringList aShapeTypes = aTypesStr.split(' ');
60
61   //myIsUseChoice = theData->getBooleanAttribute("use_choice", true);
62
63   myTypeCombo->addItems(aShapeTypes);
64   aMainLay->addWidget(myTypeCombo, 0, 1);
65   // if the xml definition contains one type, the controls to select a type should not be shown
66   if (aShapeTypes.size() == 1/* || !myIsUseChoice*/) {
67     aTypeLabel->setVisible(false);
68     myTypeCombo->setVisible(false);
69   }
70
71   std::string aLabelText = theData->getProperty("label");
72   QLabel* aListLabel = new QLabel(!aLabelText.empty() ? aLabelText.c_str()
73                                                       : tr("Selected objects:"), this);
74   aMainLay->addWidget(aListLabel, 1, 0);
75   // if the xml definition contains one type, an information label should be shown near to the latest
76   if (aShapeTypes.size() == 1) {
77     QString aLabelText = QString::fromStdString(theData->widgetLabel());
78     QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
79     QLabel* aSelectedLabel = new QLabel(aLabelText, this);
80     if (!aLabelIcon.isEmpty())
81       aSelectedLabel->setPixmap(QPixmap(aLabelIcon));
82     aMainLay->addWidget(aSelectedLabel, 1, 1);
83     aMainLay->setColumnStretch(2, 1);
84   }
85
86   myListControl = new QListWidget(this);
87   aMainLay->addWidget(myListControl, 2, 0, 2, -1);
88   aMainLay->setRowStretch(2, 1);
89   aMainLay->addWidget(new QLabel(this)); //FIXME(sbh)???
90   aMainLay->setRowMinimumHeight(3, 20);
91   this->setLayout(aMainLay);
92   connect(myTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSelectionTypeChanged()));
93
94   myCopyAction = new QAction(QIcon(":pictures/copy.png"), tr("Copy"), this);
95   myCopyAction->setShortcut(QKeySequence::Copy);
96   myCopyAction->setEnabled(false);
97   connect(myCopyAction, SIGNAL(triggered(bool)), SLOT(onCopyItem()));
98   myListControl->addAction(myCopyAction);
99   myListControl->setContextMenuPolicy(Qt::ActionsContextMenu);
100   connect(myListControl, SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
101 }
102
103 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
104 {
105   delete myShapeValidator;
106 }
107
108 //TODO: nds stabilization hotfix
109 void ModuleBase_WidgetMultiSelector::disconnectSignals()
110 {
111   disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
112 }
113
114 //********************************************************************
115 void ModuleBase_WidgetMultiSelector::activateCustom()
116 {
117   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
118   connect(myWorkshop, SIGNAL(selectionChanged()), 
119           this,       SLOT(onSelectionChanged()), 
120           Qt::UniqueConnection);
121
122   activateShapeSelection(true);
123
124   // Restore selection in the viewer by the attribute selection list
125   myWorkshop->setSelected(getAttributeSelection());
126
127   activateFilters(myWorkshop, true);
128 }
129
130 //********************************************************************
131 void ModuleBase_WidgetMultiSelector::deactivate()
132 {
133   disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
134   activateShapeSelection(false);
135   activateFilters(myWorkshop, false);
136 }
137
138 //********************************************************************
139 bool ModuleBase_WidgetMultiSelector::storeValueCustom() const
140 {
141   // the value is stored on the selection changed signal processing 
142   // A rare case when plugin was not loaded. 
143   if(!myFeature)
144     return false;
145   DataPtr aData = myFeature->data();
146   AttributeSelectionListPtr aSelectionListAttr = 
147     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
148
149   if (aSelectionListAttr) {
150     // Store shapes type
151      TopAbs_ShapeEnum aCurrentType =
152            ModuleBase_Tools::shapeType(myTypeCombo->currentText());
153      aSelectionListAttr->setSelectionType(myTypeCombo->currentText().toStdString());
154   }   
155    return true;
156 }
157
158 //********************************************************************
159 bool ModuleBase_WidgetMultiSelector::restoreValue()
160 {
161   // A rare case when plugin was not loaded. 
162   if(!myFeature)
163     return false;
164   DataPtr aData = myFeature->data();
165   AttributeSelectionListPtr aSelectionListAttr = 
166     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
167
168   if (aSelectionListAttr) {
169     // Restore shape type
170     if (!aSelectionListAttr->selectionType().empty())
171       setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionListAttr->selectionType().c_str()));
172     updateSelectionList(aSelectionListAttr);
173     return true;
174   }
175   return false;
176 }
177
178 //********************************************************************
179 void ModuleBase_WidgetMultiSelector::storeAttributeValue()
180 {
181   DataPtr aData = myFeature->data();
182   AttributeSelectionListPtr aSelectionListAttr = 
183     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
184   if (aSelectionListAttr.get() == NULL)
185     return;
186
187   mySelectionType = aSelectionListAttr->selectionType();
188   mySelection.clear();
189   int aSize = aSelectionListAttr->size();
190   for (int i = 0; i < aSelectionListAttr->size(); i++) {
191     AttributeSelectionPtr aSelectAttr = aSelectionListAttr->value(i);
192     mySelection.append(GeomSelection(aSelectAttr->context(), aSelectAttr->value()));
193   }
194 }
195
196 //********************************************************************
197 void ModuleBase_WidgetMultiSelector::restoreAttributeValue(bool/* theValid*/)
198 {
199   DataPtr aData = myFeature->data();
200   AttributeSelectionListPtr aSelectionListAttr = 
201     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
202   if (aSelectionListAttr.get() == NULL)
203     return;
204   aSelectionListAttr->clear();
205
206   // Store shapes type
207   aSelectionListAttr->setSelectionType(mySelectionType);
208
209   // Store selection in the attribute
210   int aSize = mySelection.size();
211   foreach (GeomSelection aSelec, mySelection) {
212     aSelectionListAttr->append(aSelec.first, aSelec.second);
213   }
214 }
215
216 //********************************************************************
217 void ModuleBase_WidgetMultiSelector::customValidators(
218                                         std::list<ModelAPI_Validator*>& theValidators,
219                                         std::list<std::list<std::string> >& theArguments) const
220 {
221   return;
222   std::list<std::string> anArguments;
223
224   theValidators.push_back(myShapeValidator);
225   if (true/*myIsUseChoice*/) {
226     QString aType = myTypeCombo->currentText();
227     anArguments.push_back(validatorType(aType));
228   }
229   else {
230     for(int i = 0, aCount = myTypeCombo->count(); i < aCount; i++) {
231       anArguments.push_back(validatorType(myTypeCombo->itemText(i)));
232     }
233   }
234   theArguments.push_back(anArguments);
235 }
236
237 //********************************************************************
238 bool ModuleBase_WidgetMultiSelector::acceptSubShape(const TopoDS_Shape& theShape) const
239 {
240   bool aValid = true;
241   if (theShape.IsNull()) {
242     aValid = true; // do not check the shape type if the shape is empty
243     // extrusion uses a sketch object selectected in Object browser
244   }
245   else {
246     aValid = false;
247     TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
248     if (myTypeCombo->count() > 1) {
249       TopAbs_ShapeEnum aType = ModuleBase_Tools::shapeType(myTypeCombo->currentText());
250       aValid = aShapeType == aType;
251     }
252     else {
253       for(int i = 0, aCount = myTypeCombo->count(); i < aCount && !aValid; i++) {
254         TopAbs_ShapeEnum aType = ModuleBase_Tools::shapeType(myTypeCombo->itemText(i));
255         aValid = aShapeType == aType;
256       }
257     }
258   }
259   return aValid;
260 }
261
262 //********************************************************************
263 bool ModuleBase_WidgetMultiSelector::setSelection(const QList<ModuleBase_ViewerPrs>& theValues,
264                                                   int& thePosition)
265 {
266   if (thePosition < 0)
267     return false;
268
269   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
270   bool isDone = false;
271   for (int i = thePosition; i < theValues.size(); i++) {
272     ModuleBase_ViewerPrs aValue = theValues[i];
273     bool aProcessed = false;
274     if (isValidSelection(aValue)) {
275       aProcessed = setSelectionCustom(aValue);
276     }
277     // if there is at least one set, the result is true
278     isDone = isDone || aProcessed;
279     // when an object, which do not satisfy the validating process, stop set selection
280     if (!aProcessed)
281       break;
282     else
283       thePosition++;
284   }
285   if (isDone) {
286     updateObject(myFeature);
287     // this emit is necessary to call store/restore method an restore type of selection
288     emit valuesChanged();
289   }
290   return isDone;
291 }
292
293 //********************************************************************
294 bool ModuleBase_WidgetMultiSelector::setSelectionCustom(const ModuleBase_ViewerPrs& thePrs)
295 {
296   TopoDS_Shape aShape = thePrs.shape();
297   if (!acceptSubShape(aShape))
298     return false;
299
300   ResultPtr aResult;
301   if (!thePrs.owner().IsNull()) {
302     ObjectPtr anObject = myWorkshop->selection()->getSelectableObject(thePrs.owner());
303     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
304   }
305   else {
306     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(thePrs.object());
307   }
308
309
310   if (myFeature) {
311     // We can not select a result of our feature
312     const std::list<ResultPtr>& aResList = myFeature->results();
313     std::list<ResultPtr>::const_iterator aIt;
314     bool isSkipSelf = false;
315     for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
316       if ((*aIt) == aResult) {
317         isSkipSelf = true;
318         break;
319       }
320     }
321     if(isSkipSelf)
322       return false;
323   }
324
325   // if the result has the similar shap as the parameter shape, just the context is set to the
326   // selection list attribute.
327   DataPtr aData = myFeature->data();
328   AttributeSelectionListPtr aSelectionListAttr = 
329     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
330
331   const TopoDS_Shape& aTDSShape = thePrs.shape();
332   // if only result is selected, an empty shape is set to the model
333   if (aTDSShape.IsNull()) {
334     aSelectionListAttr->append(aResult, GeomShapePtr());
335   }
336   else {
337     GeomShapePtr aShape(new GeomAPI_Shape());
338     aShape->setImpl(new TopoDS_Shape(aTDSShape));
339     // We can not select a result of our feature
340     if (aShape->isEqual(aResult->shape()))
341       aSelectionListAttr->append(aResult, GeomShapePtr());
342     else
343       aSelectionListAttr->append(aResult, aShape);
344   }
345   return true;
346 }
347
348 //********************************************************************
349 QList<QWidget*> ModuleBase_WidgetMultiSelector::getControls() const
350 {
351   QList<QWidget*> result;
352   //result << myTypeCombo;
353   result << myListControl;
354   return result;
355 }
356
357 //********************************************************************
358 bool ModuleBase_WidgetMultiSelector::eventFilter(QObject* theObj, QEvent* theEvent)
359 {
360   //TODO: Remove maybe?
361   return ModuleBase_ModelWidget::eventFilter(theObj, theEvent);
362 }
363
364 //********************************************************************
365 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
366 {
367   activateShapeSelection(true);
368   activateFilters(myWorkshop, true);
369   QList<ModuleBase_ViewerPrs> anEmptyList;
370   // This method will call Selection changed event which will call onSelectionChanged
371   // To clear mySelection, myListControl and storeValue()
372   // So, we don't need to call it
373   myWorkshop->setSelected(anEmptyList);
374 }
375
376 //********************************************************************
377 void ModuleBase_WidgetMultiSelector::onSelectionChanged()
378 {
379   QList<ModuleBase_ViewerPrs> aSelected = getSelectedEntitiesOrObjects(myWorkshop->selection());
380
381   DataPtr aData = myFeature->data();
382   AttributeSelectionListPtr aSelectionListAttr = 
383     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
384
385   aSelectionListAttr->clear();
386   if (aSelected.size() > 0) {
387     foreach (ModuleBase_ViewerPrs aPrs, aSelected) {
388       if (isValidSelection(aPrs)) {
389         setSelectionCustom(aPrs);
390       }
391     }
392   }
393   emit valuesChanged();
394   // the updateObject method should be called to flush the updated sigal. The workshop listens it,
395   // calls validators for the feature and, as a result, updates the Apply button state.
396   updateObject(myFeature);
397
398   // Set focus to List control in order to make possible 
399   // to use Tab key for transfer the focus to next widgets
400   myListControl->setCurrentRow(myListControl->model()->rowCount() - 1);
401   myListControl->setFocus();
402 }
403
404 //********************************************************************
405 void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const TopAbs_ShapeEnum theShapeType)
406 {
407   QString aShapeTypeName;
408   
409   for (int idx = 0; idx < myTypeCombo->count(); ++idx) {
410     aShapeTypeName = myTypeCombo->itemText(idx);
411     TopAbs_ShapeEnum aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
412     if(aRefType == theShapeType && idx != myTypeCombo->currentIndex()) {
413       activateShapeSelection(false);
414       activateFilters(myWorkshop, false);
415       bool isBlocked = myTypeCombo->blockSignals(true);
416       myTypeCombo->setCurrentIndex(idx);
417       myTypeCombo->blockSignals(isBlocked);
418
419       activateShapeSelection(true);
420       activateFilters(myWorkshop, true);
421       break;
422     }
423   }
424 }
425
426 void ModuleBase_WidgetMultiSelector::activateShapeSelection(const bool isActivated)
427 {
428   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
429
430   if (isActivated) {
431     QString aNewType = myTypeCombo->currentText();
432     QIntList aList;
433     if (true /*myIsUseChoice*/) {
434       aList.append(ModuleBase_Tools::shapeType(aNewType));
435     }
436     else {
437       for(int i = 0, aCount = myTypeCombo->count(); i < aCount; i++)
438         aList.append(ModuleBase_Tools::shapeType(myTypeCombo->itemText(i)));
439     }
440     myWorkshop->activateSubShapesSelection(aList);
441   } else {
442     myWorkshop->deactivateSubShapesSelection();
443   }
444 }
445
446 QList<ModuleBase_ViewerPrs> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
447 {
448   QList<ModuleBase_ViewerPrs> aSelected;
449   // Restore selection in the viewer by the attribute selection list
450   if(myFeature) {
451     DataPtr aData = myFeature->data();
452     AttributeSelectionListPtr aListAttr = 
453       std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
454     if (aListAttr) {
455       for (int i = 0; i < aListAttr->size(); i++) {
456         AttributeSelectionPtr anAttr = aListAttr->value(i);
457         ResultPtr anObject = anAttr->context();
458         if (anObject.get()) {
459           TopoDS_Shape aShape;
460           std::shared_ptr<GeomAPI_Shape> aShapePtr = anAttr->value();
461           if (aShapePtr.get()) {
462             aShape = aShapePtr->impl<TopoDS_Shape>();
463           }
464           aSelected.append(ModuleBase_ViewerPrs(anObject, aShape, NULL));
465         }
466       }
467     }
468   }
469   return aSelected;
470 }
471
472 //********************************************************************
473 void ModuleBase_WidgetMultiSelector::updateSelectionList(AttributeSelectionListPtr theList)
474 {
475   myListControl->clear();
476   for (int i = 0; i < theList->size(); i++) {
477     AttributeSelectionPtr aAttr = theList->value(i);
478     myListControl->addItem(aAttr->namingName().c_str());
479   }
480   // We have to call repaint because sometimes the List control is not updated
481   myListControl->repaint();
482 }
483
484 //********************************************************************
485 std::string ModuleBase_WidgetMultiSelector::validatorType(const QString& theType) const
486 {
487   std::string aType;
488
489   if (theType == "Vertices")
490     aType = "vertex";
491   else if (theType == "Edges")
492     aType = "edge";
493   else if (theType == "Faces")
494     aType = "face";
495   else if (theType == "Solids")
496     aType = "solid";
497
498   return aType;
499 }
500
501 //********************************************************************
502 void ModuleBase_WidgetMultiSelector::onCopyItem()
503 {
504   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
505   QString aRes;
506   foreach(QListWidgetItem* aItem, aItems) {
507     if (!aRes.isEmpty())
508       aRes += "\n";
509     aRes += aItem->text();
510   }
511   if (!aRes.isEmpty()) {
512     QClipboard *clipboard = QApplication::clipboard();
513     clipboard->setText(aRes);
514   }
515 }
516
517 //********************************************************************
518 void ModuleBase_WidgetMultiSelector::onListSelection()
519 {
520   QList<QListWidgetItem*> aItems = myListControl->selectedItems();
521   myCopyAction->setEnabled(!aItems.isEmpty());
522 }
523