Salome HOME
Using validator in multi selector control for the "type_choice" key.
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetMultiSelector.cpp
index 74249c28018571309de1d4a1bb0e231d9902e0c6..976972a6077f72bfa81309459694cb10864464e7 100644 (file)
@@ -1,3 +1,5 @@
+// Copyright (C) 2014-20xx CEA/DEN, EDF R&D
+
 /*
  * ModuleBase_WidgetMultiSelector.cpp
  *
 #include <ModuleBase_WidgetShapeSelector.h>
 #include <ModuleBase_ISelection.h>
 #include <ModuleBase_IWorkshop.h>
+#include <ModuleBase_IViewer.h>
 #include <ModuleBase_Tools.h>
+#include <ModuleBase_Definitions.h>
+
+#include <GeomValidators_ShapeType.h>
 
 #include <ModelAPI_Data.h>
 #include <ModelAPI_Object.h>
-#include <ModelAPI_AttributeSelectionList.h>
 
 #include <Config_WidgetAPI.h>
 
@@ -24,6 +29,9 @@
 #include <QString>
 #include <QComboBox>
 #include <QEvent>
+#include <QAction>
+#include <QApplication>
+#include <QClipboard>
 
 #include <memory>
 #include <string>
@@ -32,47 +40,98 @@ ModuleBase_WidgetMultiSelector::ModuleBase_WidgetMultiSelector(QWidget* theParen
                                                                ModuleBase_IWorkshop* theWorkshop,
                                                                const Config_WidgetAPI* theData,
                                                                const std::string& theParentId)
-    : ModuleBase_ModelWidget(theParent, theData, theParentId),
-      myWorkshop(theWorkshop), myIsActive(false), myUseSubShapes(false)
+    : ModuleBase_WidgetValidated(theParent, theData, theParentId),
+      myWorkshop(theWorkshop)
 {
-  myMainWidget = new QWidget(theParent);
-  QGridLayout* aMainLay = new QGridLayout(myMainWidget);
+  QGridLayout* aMainLay = new QGridLayout(this);
   ModuleBase_Tools::adjustMargins(aMainLay);
 
-  QLabel* aTypeLabel = new QLabel(tr("Type"), myMainWidget);
+  QLabel* aTypeLabel = new QLabel(tr("Type"), this);
   aMainLay->addWidget(aTypeLabel, 0, 0);
 
-  myTypeCombo = new QComboBox(myMainWidget);
+  myTypeCombo = new QComboBox(this);
   // There is no sence to paramerize list of types while we can not parametrize selection mode
-  QString aTypesStr("Vertices Edges Faces Solids");
+
+  myShapeValidator = new GeomValidators_ShapeType();
+
+  std::string aPropertyTypes = theData->getProperty("type_choice");
+  QString aTypesStr = aPropertyTypes.c_str();
   QStringList aShapeTypes = aTypesStr.split(' ');
+
   myTypeCombo->addItems(aShapeTypes);
   aMainLay->addWidget(myTypeCombo, 0, 1);
+  // if the xml definition contains one type, the controls to select a type should not be shown
+  if (aShapeTypes.size() == 1) {
+    aTypeLabel->setVisible(false);
+    myTypeCombo->setVisible(false);
+  }
 
-  QLabel* aListLabel = new QLabel(tr("Selected objects:"), myMainWidget);
-  aMainLay->addWidget(aListLabel, 1, 0, 1, -1);
+  QLabel* aListLabel = new QLabel(tr("Selected objects:"), this);
+  aMainLay->addWidget(aListLabel, 1, 0);
+  // if the xml definition contains one type, an information label should be shown near to the latest
+  if (aShapeTypes.size() == 1) {
+    QString aLabelText = QString::fromStdString(theData->widgetLabel());
+    QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
+    QLabel* aSelectedLabel = new QLabel(aLabelText, this);
+    if (!aLabelIcon.isEmpty())
+      aSelectedLabel->setPixmap(QPixmap(aLabelIcon));
+    aMainLay->addWidget(aSelectedLabel, 1, 1);
+    aMainLay->setColumnStretch(2, 1);
+  }
 
-  myListControl = new QListWidget(myMainWidget);
+  myListControl = new QListWidget(this);
   aMainLay->addWidget(myListControl, 2, 0, 2, -1);
-  aMainLay->setColumnStretch(1, 1);
-  myMainWidget->setLayout(aMainLay);
-
-  //TODO: Move into the base class
-  myUseSubShapes = theData->getBooleanAttribute("use_subshapes", false);
-  //TODO_END
+  aMainLay->setRowStretch(2, 1);
+  aMainLay->addWidget(new QLabel(this)); //FIXME(sbh)???
+  aMainLay->setRowMinimumHeight(3, 20);
+  this->setLayout(aMainLay);
   connect(myTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSelectionTypeChanged()));
 
-  activateSelection(true);
+  myCopyAction = new QAction(QIcon(":pictures/copy.png"), tr("Copy"), this);
+  myCopyAction->setShortcut(QKeySequence::Copy);
+  myCopyAction->setEnabled(false);
+  connect(myCopyAction, SIGNAL(triggered(bool)), SLOT(onCopyItem()));
+  myListControl->addAction(myCopyAction);
+  myListControl->setContextMenuPolicy(Qt::ActionsContextMenu);
+  connect(myListControl, SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
 }
 
 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
 {
-  activateSelection(false);
+  activateShapeSelection(false);
+  activateFilters(myWorkshop, false);
+
+  delete myShapeValidator;
+}
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::activateCustom()
+{
+  ModuleBase_IViewer* aViewer = myWorkshop->viewer();
+  connect(myWorkshop, SIGNAL(selectionChanged()), 
+          this,       SLOT(onSelectionChanged()), 
+          Qt::UniqueConnection);
+
+  activateShapeSelection(true);
+
+  // Restore selection in the viewer by the attribute selection list
+  myWorkshop->setSelected(getAttributeSelection());
+
+  activateFilters(myWorkshop, true);
+}
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::deactivate()
+{
+  disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
+  activateShapeSelection(false);
+  activateFilters(myWorkshop, false);
 }
 
 //********************************************************************
-bool ModuleBase_WidgetMultiSelector::storeValue() const
+bool ModuleBase_WidgetMultiSelector::storeValueCustom() const
 {
+  // the value is stored on the selection changed signal processing 
   // A rare case when plugin was not loaded. 
   if(!myFeature)
     return false;
@@ -81,19 +140,12 @@ bool ModuleBase_WidgetMultiSelector::storeValue() const
     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
 
   if (aSelectionListAttr) {
-    aSelectionListAttr->clear();
     // Store shapes type
-    TopAbs_ShapeEnum aCurrentType =
-          ModuleBase_WidgetShapeSelector::shapeType(myTypeCombo->currentText());
-    aSelectionListAttr->setSelectionType((int) aCurrentType);
-    // Store selection in the attribute
-    foreach (GeomSelection aSelec, mySelection) {
-      aSelectionListAttr->append(aSelec.first, aSelec.second);
-    }
-    updateObject(myFeature);
-    return true;
-  }
-  return false;
+     TopAbs_ShapeEnum aCurrentType =
+           ModuleBase_Tools::shapeType(myTypeCombo->currentText());
+     aSelectionListAttr->setSelectionType(myTypeCombo->currentText().toStdString());
+  }   
+   return true;
 }
 
 //********************************************************************
@@ -107,25 +159,151 @@ bool ModuleBase_WidgetMultiSelector::restoreValue()
     std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
 
   if (aSelectionListAttr) {
-    mySelection.clear();
     // Restore shape type
-    TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum) aSelectionListAttr->selectionType();
-    setCurrentShapeType(aShapeType);
-    // Restore selection in the list
-    for (int i = 0; i < aSelectionListAttr->size(); i++) {
-      AttributeSelectionPtr aSelectAttr = aSelectionListAttr->value(i);
-      mySelection.append(GeomSelection(aSelectAttr->context(), aSelectAttr->value()));
-    }
-    updateSelectionList();
+    if (!aSelectionListAttr->selectionType().empty())
+      setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionListAttr->selectionType().c_str()));
+    updateSelectionList(aSelectionListAttr);
     return true;
   }
   return false;
 }
 
 //********************************************************************
-QWidget* ModuleBase_WidgetMultiSelector::getControl() const
+void ModuleBase_WidgetMultiSelector::storeAttributeValue()
+{
+  DataPtr aData = myFeature->data();
+  AttributeSelectionListPtr aSelectionListAttr = 
+    std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
+  if (aSelectionListAttr.get() == NULL)
+    return;
+
+  mySelectionType = aSelectionListAttr->selectionType();
+  mySelection.clear();
+  int aSize = aSelectionListAttr->size();
+  for (int i = 0; i < aSelectionListAttr->size(); i++) {
+    AttributeSelectionPtr aSelectAttr = aSelectionListAttr->value(i);
+    mySelection.append(GeomSelection(aSelectAttr->context(), aSelectAttr->value()));
+  }
+}
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::restoreAttributeValue(bool/* theValid*/)
+{
+  DataPtr aData = myFeature->data();
+  AttributeSelectionListPtr aSelectionListAttr = 
+    std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
+  if (aSelectionListAttr.get() == NULL)
+    return;
+  aSelectionListAttr->clear();
+
+  // Store shapes type
+  aSelectionListAttr->setSelectionType(mySelectionType);
+
+  // Store selection in the attribute
+  int aSize = mySelection.size();
+  foreach (GeomSelection aSelec, mySelection) {
+    aSelectionListAttr->append(aSelec.first, aSelec.second);
+  }
+}
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::customValidators(
+                                        std::list<ModelAPI_Validator*>& theValidators,
+                                        std::list<std::list<std::string> >& theArguments) const
+{
+  std::list<std::string> anArguments;
+
+  theValidators.push_back(myShapeValidator);
+  QString aType = myTypeCombo->currentText();
+  anArguments.push_back(aType.toStdString().c_str());
+  theArguments.push_back(anArguments);
+}
+
+//********************************************************************
+bool ModuleBase_WidgetMultiSelector::setSelection(const QList<ModuleBase_ViewerPrs>& theValues,
+                                                  int& thePosition)
+{
+  if (thePosition < 0)
+    return false;
+
+  QList<ModuleBase_ViewerPrs>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
+  bool isDone = false;
+  for (int i = thePosition; i < theValues.size(); i++) {
+    ModuleBase_ViewerPrs aValue = theValues[i];
+    thePosition++;
+    bool aProcessed = false;
+    if (isValidSelection(aValue)) {
+      aProcessed = setSelectionCustom(aValue);
+    }
+    // if there is at least one set, the result is true
+    isDone = isDone || aProcessed;
+    // when an object, which do not satisfy the validating process, stop set selection
+    if (!aProcessed)
+      break;
+  }
+  if (isDone) {
+    updateObject(myFeature);
+    // this emit is necessary to call store/restore method an restore type of selection
+    emit valuesChanged();
+  }
+  return isDone;
+}
+
+//********************************************************************
+bool ModuleBase_WidgetMultiSelector::setSelectionCustom(const ModuleBase_ViewerPrs& thePrs)
 {
-  return myMainWidget;
+  TopoDS_Shape aShape = thePrs.shape();
+  if ((myTypeCombo->count() > 1) && (!aShape.IsNull())) {
+    TopAbs_ShapeEnum aType = ModuleBase_Tools::shapeType(myTypeCombo->currentText());
+    if (aShape.ShapeType() != aType)
+      return false;
+  }
+  ResultPtr aResult;
+  if (!thePrs.owner().IsNull()) {
+    ObjectPtr anObject = myWorkshop->selection()->getSelectableObject(thePrs.owner());
+    aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
+  }
+  else {
+    aResult = std::dynamic_pointer_cast<ModelAPI_Result>(thePrs.object());
+  }
+
+
+  if (myFeature) {
+    // We can not select a result of our feature
+    const std::list<ResultPtr>& aResList = myFeature->results();
+    std::list<ResultPtr>::const_iterator aIt;
+    bool isSkipSelf = false;
+    for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
+      if ((*aIt) == aResult) {
+        isSkipSelf = true;
+        break;
+      }
+    }
+    if(isSkipSelf)
+      return false;
+  }
+
+  // if the result has the similar shap as the parameter shape, just the context is set to the
+  // selection list attribute.
+  DataPtr aData = myFeature->data();
+  AttributeSelectionListPtr aSelectionListAttr = 
+    std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
+
+  const TopoDS_Shape& aTDSShape = thePrs.shape();
+  // if only result is selected, an empty shape is set to the model
+  if (aTDSShape.IsNull()) {
+    aSelectionListAttr->append(aResult, GeomShapePtr());
+  }
+  else {
+    GeomShapePtr aShape(new GeomAPI_Shape());
+    aShape->setImpl(new TopoDS_Shape(aTDSShape));
+    // We can not select a result of our feature
+    if (aShape->isEqual(aResult->shape()))
+      aSelectionListAttr->append(aResult, GeomShapePtr());
+    else
+      aSelectionListAttr->append(aResult, aShape);
+  }
+  return true;
 }
 
 //********************************************************************
@@ -144,82 +322,44 @@ bool ModuleBase_WidgetMultiSelector::eventFilter(QObject* theObj, QEvent* theEve
   return ModuleBase_ModelWidget::eventFilter(theObj, theEvent);
 }
 
-//********************************************************************
-void ModuleBase_WidgetMultiSelector::activateSelection(bool toActivate)
-{
-  myIsActive = toActivate;
-  if (myIsActive) {
-    connect(myWorkshop, SIGNAL(selectionChanged()), 
-            this,       SLOT(onSelectionChanged()), 
-            Qt::UniqueConnection);
-    activateShapeSelection();
-  } else {
-    disconnect(myWorkshop, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
-    myWorkshop->deactivateSubShapesSelection();
-  }
-}
-
 //********************************************************************
 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
 {
-  activateShapeSelection();
-  QObjectPtrList anEmptyList;
+  activateShapeSelection(true);
+  activateFilters(myWorkshop, true);
+  QList<ModuleBase_ViewerPrs> anEmptyList;
+  // This method will call Selection changed event which will call onSelectionChanged
+  // To clear mySelection, myListControl and storeValue()
+  // So, we don't need to call it
   myWorkshop->setSelected(anEmptyList);
-  // Clear mySelection, myListControl and storeValue()
-  onSelectionChanged();
 }
 
 //********************************************************************
 void ModuleBase_WidgetMultiSelector::onSelectionChanged()
 {
-  ModuleBase_ISelection* aSelection = myWorkshop->selection();
-  NCollection_List<TopoDS_Shape> aSelectedShapes; //, aFilteredShapes;
-  std::list<ObjectPtr> aOwnersList;
-  aSelection->selectedShapes(aSelectedShapes, aOwnersList);
+  QList<ModuleBase_ViewerPrs> aSelected = getSelectedEntitiesOrObjects(myWorkshop->selection());
 
-  mySelection.clear();
-  std::list<ObjectPtr>::const_iterator aIt;
-  NCollection_List<TopoDS_Shape>::Iterator aShpIt(aSelectedShapes);
-  GeomShapePtr aShape;
-  for (aIt = aOwnersList.cbegin(); aIt != aOwnersList.cend(); aShpIt.Next(), aIt++) {
-    ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*aIt);
-    if (myFeature) {
-      // We can not select a result of our feature
-      const std::list<ResultPtr>& aResList = myFeature->results();
-      std::list<ResultPtr>::const_iterator aIt;
-      bool isSkipSelf = false;
-      for (aIt = aResList.cbegin(); aIt != aResList.cend(); ++aIt) {
-        if ((*aIt) == aResult) {
-          isSkipSelf = true;
-          break;
-        }
+  DataPtr aData = myFeature->data();
+  AttributeSelectionListPtr aSelectionListAttr = 
+    std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
+
+  aSelectionListAttr->clear();
+  if (aSelected.size() > 0) {
+    foreach (ModuleBase_ViewerPrs aPrs, aSelected) {
+      if (isValidSelection(aPrs)) {
+        setSelectionCustom(aPrs);
       }
-      if(isSkipSelf)
-        continue;
     }
-    aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape());
-    aShape->setImpl(new TopoDS_Shape(aShpIt.Value()));
-    mySelection.append(GeomSelection(aResult, aShape));
   }
-  updateSelectionList();
   emit valuesChanged();
-}
+  // the updateObject method should be called to flush the updated sigal. The workshop listens it,
+  // calls validators for the feature and, as a result, updates the Apply button state.
+  updateObject(myFeature);
 
-//********************************************************************
-void ModuleBase_WidgetMultiSelector::filterShapes(const NCollection_List<TopoDS_Shape>& theShapesToFilter,
-                                                  NCollection_List<TopoDS_Shape>& theResult)
-{
-  if(myTypeCombo->count() == 0 || theShapesToFilter.IsEmpty())
-    return;
-  TopAbs_ShapeEnum aReferenceType =
-      ModuleBase_WidgetShapeSelector::shapeType(myTypeCombo->currentText());
-  NCollection_List<TopoDS_Shape>::Iterator anIter(theShapesToFilter);
-  for (; anIter.More(); anIter.Next()) {
-    TopoDS_Shape aShape = anIter.Value();
-    if (aShape.IsNull() || aShape.ShapeType() != aReferenceType)
-      continue;
-    theResult.Append(aShape);
-  }
+  // Set focus to List control in order to make possible 
+  // to use Tab key for transfer the focus to next widgets
+  myListControl->setCurrentRow(myListControl->model()->rowCount() - 1);
+  myListControl->setFocus();
 }
 
 //********************************************************************
@@ -229,46 +369,93 @@ void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const TopAbs_ShapeEnum
   
   for (int idx = 0; idx < myTypeCombo->count(); ++idx) {
     aShapeTypeName = myTypeCombo->itemText(idx);
-    TopAbs_ShapeEnum aRefType = ModuleBase_WidgetShapeSelector::shapeType(aShapeTypeName);
+    TopAbs_ShapeEnum aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
     if(aRefType == theShapeType && idx != myTypeCombo->currentIndex()) {
-      activateSelection(false);
+      activateShapeSelection(false);
+      activateFilters(myWorkshop, false);
       bool isBlocked = myTypeCombo->blockSignals(true);
       myTypeCombo->setCurrentIndex(idx);
       myTypeCombo->blockSignals(isBlocked);
-      activateSelection(true);
+
+      activateShapeSelection(true);
+      activateFilters(myWorkshop, true);
       break;
     }
   }
 }
 
-void ModuleBase_WidgetMultiSelector::activateShapeSelection()
+void ModuleBase_WidgetMultiSelector::activateShapeSelection(const bool isActivated)
+{
+  ModuleBase_IViewer* aViewer = myWorkshop->viewer();
+
+  if (isActivated) {
+    QString aNewType = myTypeCombo->currentText();
+    QIntList aList;
+    aList.append(ModuleBase_Tools::shapeType(aNewType));
+    myWorkshop->activateSubShapesSelection(aList);
+  } else {
+    myWorkshop->deactivateSubShapesSelection();
+  }
+}
+
+QList<ModuleBase_ViewerPrs> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
 {
-  QString aNewType = myTypeCombo->currentText();
-  QIntList aList;
-  aList.append(ModuleBase_WidgetShapeSelector::shapeType(aNewType));
-  myWorkshop->activateSubShapesSelection(aList);
+  QList<ModuleBase_ViewerPrs> aSelected;
+  // Restore selection in the viewer by the attribute selection list
+  if(myFeature) {
+    DataPtr aData = myFeature->data();
+    AttributeSelectionListPtr aListAttr = 
+      std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(aData->attribute(attributeID()));
+    if (aListAttr) {
+      for (int i = 0; i < aListAttr->size(); i++) {
+        AttributeSelectionPtr anAttr = aListAttr->value(i);
+        ResultPtr anObject = anAttr->context();
+        if (anObject.get()) {
+          TopoDS_Shape aShape;
+          std::shared_ptr<GeomAPI_Shape> aShapePtr = anAttr->value();
+          if (aShapePtr.get()) {
+            aShape = aShapePtr->impl<TopoDS_Shape>();
+          }
+          aSelected.append(ModuleBase_ViewerPrs(anObject, aShape, NULL));
+        }
+      }
+    }
+  }
+  return aSelected;
 }
 
 //********************************************************************
-void ModuleBase_WidgetMultiSelector::updateSelectionList()
+void ModuleBase_WidgetMultiSelector::updateSelectionList(AttributeSelectionListPtr theList)
 {
-  QString aType;
-  if (myTypeCombo->currentText().toLower() == "vertices")
-    aType = "vertex";
-  else if (myTypeCombo->currentText().toLower() == "edges")
-    aType = "edge";
-  else if (myTypeCombo->currentText().toLower() == "faces")
-    aType = "face";
-  else if (myTypeCombo->currentText().toLower() == "solids")
-    aType = "solid";
   myListControl->clear();
-  int i = 1;
-  foreach (GeomSelection aSel, mySelection) {
-    QString aName(aSel.first->data()->name().c_str());
-    aName += ":" + aType + QString("_%1").arg(i);
-    myListControl->addItem(aName);
-    i++;
+  for (int i = 0; i < theList->size(); i++) {
+    AttributeSelectionPtr aAttr = theList->value(i);
+    myListControl->addItem(aAttr->namingName().c_str());
   }
+  // We have to call repaint because sometimes the List control is not updated
   myListControl->repaint();
 }
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::onCopyItem()
+{
+  QList<QListWidgetItem*> aItems = myListControl->selectedItems();
+  QString aRes;
+  foreach(QListWidgetItem* aItem, aItems) {
+    if (!aRes.isEmpty())
+      aRes += "\n";
+    aRes += aItem->text();
+  }
+  if (!aRes.isEmpty()) {
+    QClipboard *clipboard = QApplication::clipboard();
+    clipboard->setText(aRes);
+  }
+}
+
+//********************************************************************
+void ModuleBase_WidgetMultiSelector::onListSelection()
+{
+  QList<QListWidgetItem*> aItems = myListControl->selectedItems();
+  myCopyAction->setEnabled(!aItems.isEmpty());
+}
+