]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModuleBase/ModuleBase_WidgetMultiSelector.cpp
Salome HOME
Merge branch 'task_5_2_4' into CEA_2019
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetMultiSelector.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <ModuleBase_WidgetMultiSelector.h>
21
22 #include <GeomAPI_AISObject.h>
23
24 #include <ModuleBase_ActionIntParameter.h>
25 #include <ModuleBase_Definitions.h>
26 #include <ModuleBase_Events.h>
27 #include <ModuleBase_IconFactory.h>
28 #include <ModuleBase_IModule.h>
29 #include <ModuleBase_ISelection.h>
30 #include <ModuleBase_ISelectionActivate.h>
31 #include <ModuleBase_IPropertyPanel.h>
32 #include <ModuleBase_IViewer.h>
33 #include <ModuleBase_IWorkshop.h>
34 #include <ModuleBase_ListView.h>
35 #include <ModuleBase_ResultPrs.h>
36 #include <ModuleBase_Tools.h>
37 #include <ModuleBase_ViewerPrs.h>
38 #include <ModuleBase_WidgetShapeSelector.h>
39 #include <ModuleBase_ChoiceCtrl.h>
40 #include <ModuleBase_WidgetSelectionFilter.h>
41
42 #include <ModelAPI_Data.h>
43 #include <ModelAPI_Object.h>
44 #include <ModelAPI_AttributeSelectionList.h>
45 #include <ModelAPI_AttributeRefList.h>
46 #include <ModelAPI_AttributeRefAttrList.h>
47 #include <ModelAPI_Tools.h>
48 #include <ModelAPI_Events.h>
49
50 #include <Config_WidgetAPI.h>
51
52 #include <AIS_InteractiveObject.hxx>
53
54 #include <QGridLayout>
55 #include <QLabel>
56 #include <QListWidget>
57 #include <QObject>
58 #include <QString>
59 #include <QComboBox>
60 #include <QEvent>
61 #include <QApplication>
62 #include <QClipboard>
63 #include <QTimer>
64 #include <QMainWindow>
65 #include <QCheckBox>
66 #include <QPushButton>
67
68 #include <memory>
69 #include <string>
70
71 //#define DEBUG_UNDO_REDO
72
73 #ifdef DEBUG_UNDO_REDO
74 void printHistoryInfo(const QString& theMethodName, int theCurrentHistoryIndex,
75   QList<QList<std::shared_ptr<ModuleBase_ViewerPrs> > > theSelectedHistoryValues)
76 {
77   QStringList aSizes;
78   for (int i = 0; i < theSelectedHistoryValues.size(); i++)
79     aSizes.append(QString::number(theSelectedHistoryValues[i].size()));
80
81   std::cout << theMethodName.toStdString()
82             << "  current = " << theCurrentHistoryIndex
83             << " size(history) =  " << theSelectedHistoryValues.size()
84             << " (" << aSizes.join(", ").toStdString() << ")"
85             << std::endl;
86 }
87 #endif
88
89
90 QStringList getIconsList(const QStringList& theNames)
91 {
92   QStringList aIcons;
93   foreach (QString aName, theNames) {
94     QString aUName = aName.toUpper();
95     if ((aUName == "VERTICES") || (aUName == "VERTEX"))
96       aIcons << ":pictures/vertex32.png";
97     else if ((aUName == "EDGES") || (aUName == "EDGE"))
98       aIcons << ":pictures/edge32.png";
99     else if ((aUName == "FACES") || (aUName == "FACE"))
100       aIcons << ":pictures/face32.png";
101     else if ((aUName == "SOLIDS") || (aUName == "SOLID"))
102       aIcons << ":pictures/solid32.png";
103   }
104   return aIcons;
105 }
106
107 /// Stores default values of selected option (selection mode)
108 /// It is used only in case if myTypeCtrl is used
109 static QMap<std::string, std::string> defaultValues;
110
111
112 ModuleBase_WidgetMultiSelector::ModuleBase_WidgetMultiSelector(QWidget* theParent,
113                                                                ModuleBase_IWorkshop* theWorkshop,
114                                                                const Config_WidgetAPI* theData)
115 : ModuleBase_WidgetSelector(theParent, theWorkshop, theData),
116   myIsSetSelectionBlocked(false), myCurrentHistoryIndex(-1),
117   myIsFirst(true), myFiltersWgt(0)
118 {
119   std::string aPropertyTypes = theData->getProperty("type_choice");
120   QString aTypesStr = aPropertyTypes.c_str();
121   myShapeTypes = aTypesStr.split(' ', QString::SkipEmptyParts);
122   myIsUseChoice = theData->getBooleanAttribute("use_choice", false);
123
124   QVBoxLayout* aMainLay = new QVBoxLayout(this);
125   ModuleBase_Tools::adjustMargins(aMainLay);
126
127   QStringList aIconsList = getIconsList(myShapeTypes);
128   myTypeCtrl = new ModuleBase_ChoiceCtrl(this, myShapeTypes, aIconsList);
129   myTypeCtrl->setLabel(tr("Type"));
130   myTypeCtrl->setValue(0);
131   aMainLay->addWidget(myTypeCtrl);
132   myDefMode = myShapeTypes.first().toStdString();
133
134   // There is no sense to parameterize list of types while we can not parameterize selection mode
135   // if the xml definition contains one type, the controls to select a type should not be shown
136   if (myShapeTypes.size() <= 1 || !myIsUseChoice) {
137     myTypeCtrl->setVisible(false);
138   }
139
140   QString aLabelText = translate(theData->getProperty("label"));
141   if (aLabelText.size() > 0) {
142     QWidget* aLabelWgt = new QWidget(this);
143     QHBoxLayout* aLabelLayout = new QHBoxLayout(aLabelWgt);
144     aLabelLayout->setContentsMargins(0, 0, 0, 0);
145     aMainLay->addWidget(aLabelWgt);
146
147     QLabel* aListLabel = new QLabel(aLabelText, this);
148     aLabelLayout->addWidget(aListLabel);
149     // if the xml definition contains one type, an information label
150     // should be shown near to the latest
151     if (myShapeTypes.size() <= 1) {
152       QString aLabelIcon = QString::fromStdString(theData->widgetIcon());
153       if (!aLabelIcon.isEmpty()) {
154         QLabel* aSelectedLabel = new QLabel("", this);
155         aSelectedLabel->setPixmap(ModuleBase_IconFactory::loadPixmap(aLabelIcon));
156         aLabelLayout->addWidget(aSelectedLabel);
157         aLabelLayout->addStretch(1);
158       }
159     }
160   }
161
162   QString aToolTip = QString::fromStdString(theData->widgetTooltip());
163   QString anObjName = QString::fromStdString(attributeID());
164   myListView = new ModuleBase_ListView(this, anObjName, aToolTip);
165   connect(myListView->getControl(), SIGNAL(itemSelectionChanged()), SLOT(onListSelection()));
166   connect(myListView, SIGNAL(deleteActionClicked()), SLOT(onDeleteItem()));
167   connect(myListView, SIGNAL(listActivated()), SLOT(onListActivated()));
168
169   aMainLay->addWidget(myListView->getControl());
170   connect(myTypeCtrl, SIGNAL(valueChanged(int)), this, SLOT(onSelectionTypeChanged()));
171
172   std::string aUseFilters = theData->getProperty("use_filters");
173   if (aUseFilters.length() > 0) {
174     QWidget* aFltrWgt = new QWidget(this);
175     QHBoxLayout* aFltrLayout = new QHBoxLayout(aFltrWgt);
176
177     myFiltersWgt = new ModuleBase_FilterStarter(aUseFilters.c_str(), aFltrWgt, theWorkshop);
178     aFltrLayout->addWidget(myFiltersWgt);
179
180     aFltrLayout->addStretch();
181
182     QPushButton* aShowBtn = new QPushButton(tr("Show only"), aFltrWgt);
183     aShowBtn->setCheckable(true);
184     aShowBtn->setChecked(false);
185     connect(aShowBtn, SIGNAL(toggled(bool)), SLOT(onShowOnly(bool)));
186     aFltrLayout->addWidget(aShowBtn);
187
188     aMainLay->addWidget(aFltrWgt);
189   }
190
191   bool aSameTop = theData->getBooleanAttribute("same_topology", false);
192   if (aSameTop) {
193     myGeomCheck = new QCheckBox(tr("Add elements that share the same topology"), this);
194     aMainLay->addWidget(myGeomCheck);
195     connect(myGeomCheck, SIGNAL(toggled(bool)), SLOT(onSameTopology(bool)));
196   }
197   else
198     myGeomCheck = 0;
199
200   myIsNeutralPointClear = theData->getBooleanAttribute("clear_in_neutral_point", true);
201   if (myShapeTypes.size() > 1 || myIsUseChoice) {
202     if (defaultValues.contains(myFeatureId + attributeID())) {
203       myDefMode = defaultValues[myFeatureId + attributeID()];
204       myTypeCtrl->setValue(myDefMode.c_str());
205     }
206   }
207 }
208
209 ModuleBase_WidgetMultiSelector::~ModuleBase_WidgetMultiSelector()
210 {
211 }
212
213 //********************************************************************
214 void ModuleBase_WidgetMultiSelector::activateCustom()
215 {
216   ModuleBase_WidgetSelector::activateCustom();
217
218   myWorkshop->module()->activateCustomPrs(myFeature,
219                             ModuleBase_IModule::CustomizeHighlightedObjects, true);
220   clearSelectedHistory();
221 }
222
223 //********************************************************************
224 void ModuleBase_WidgetMultiSelector::deactivate()
225 {
226   myWorkshop->module()->enableCustomModes();
227
228   ModuleBase_WidgetSelector::deactivate();
229   if (myVisibleObjects.size())
230     onShowOnly(false);
231
232   myWorkshop->module()->deactivateCustomPrs(ModuleBase_IModule::CustomizeHighlightedObjects, true);
233   clearSelectedHistory();
234 }
235
236 //********************************************************************
237 void ModuleBase_WidgetMultiSelector::updateAfterDeactivation()
238 {
239   // restore previous Undo/Redo workshop state
240   myWorkshop->updateCommandStatus();
241 }
242
243 //********************************************************************
244 void ModuleBase_WidgetMultiSelector::updateAfterActivation()
245 {
246   // fill Undo/Redo actions with current information
247   myWorkshop->updateCommandStatus();
248 }
249
250 //********************************************************************
251 bool ModuleBase_WidgetMultiSelector::storeValueCustom()
252 {
253   // the value is stored on the selection changed signal processing
254   // A rare case when plugin was not loaded.
255   if (!myFeature)
256     return false;
257
258   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
259   std::string aType = anAttribute->attributeType();
260   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
261     AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
262     std::string aMode = myTypeCtrl->textValue().toStdString();
263     if (myTypeCtrl->isVisible() && myIsFirst && (!myDefMode.empty()))
264       aMode = myDefMode;
265
266     aSelectionListAttr->setSelectionType(aMode);
267     myIsFirst = false;
268   }
269   return true;
270 }
271
272 //********************************************************************
273 bool ModuleBase_WidgetMultiSelector::restoreValueCustom()
274 {
275   // A rare case when plugin was not loaded.
276   if (!myFeature)
277     return false;
278
279   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
280   AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
281   std::string aType = anAttribute->attributeType();
282   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
283     // Restore shape type
284     std::string aSelectionType = aSelectionListAttr->selectionType().c_str();
285     if (!aSelectionType.empty()) {
286       setCurrentShapeType(ModuleBase_Tools::shapeType(aSelectionType.c_str()));
287       myDefMode = aSelectionType;
288       myIsFirst = false;
289     }
290   }
291   if (myGeomCheck)
292     myGeomCheck->setChecked(aSelectionListAttr->isGeometricalSelection());
293   updateSelectionList();
294   return true;
295 }
296
297 //********************************************************************
298 bool ModuleBase_WidgetMultiSelector::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
299                                                   const bool theToValidate)
300 {
301   if (myIsSetSelectionBlocked)
302     return false;
303
304   AttributeSelectionListPtr aSelectionListAttr;
305   if (attribute()->attributeType() == ModelAPI_AttributeSelectionList::typeId())
306     aSelectionListAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelectionList>(attribute());
307   if (aSelectionListAttr.get())
308     aSelectionListAttr->cashValues(true);
309
310   /// remove unused objects from the model attribute.
311   /// It should be performed before new attributes append.
312   bool isDone = removeUnusedAttributeObjects(theValues);
313
314   QList<ModuleBase_ViewerPrsPtr> anInvalidValues;
315   QList<ModuleBase_ViewerPrsPtr> anAttributeValues;
316   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
317   for (; anIt != aLast; anIt++) {
318     ModuleBase_ViewerPrsPtr aValue = *anIt;
319     // do not validate and append to attribute selection presentation if it exists in the attribute
320     ObjectPtr anObject;
321     GeomShapePtr aShape;
322     getGeomSelection(aValue, anObject, aShape);
323     if (ModuleBase_Tools::hasObject(attribute(), anObject, aShape, myWorkshop, myIsInValidate)) {
324       anAttributeValues.append(aValue);
325       continue;
326     }
327     if (theToValidate && !isValidInFilters(aValue))
328       anInvalidValues.append(aValue);
329   }
330   bool aHasInvalidValues = anInvalidValues.size() > 0;
331
332   for (anIt = theValues.begin(); anIt != aLast; anIt++) {
333     ModuleBase_ViewerPrsPtr aValue = *anIt;
334     bool aProcessed = false;
335     if ((aHasInvalidValues && anInvalidValues.contains(aValue)) ||
336         anAttributeValues.contains(aValue))
337       continue;
338     aProcessed = setSelectionCustom(aValue); /// it is not optimal as hasObject() is already checked
339     // if there is at least one set, the result is true
340     isDone = isDone || aProcessed;
341   }
342   // Check the selection with validators
343   QString aError = getError();
344   if (aError.length() > 0) {
345     aSelectionListAttr->clear();
346     isDone = false;
347   }
348   // updateObject - to update/redisplay feature
349   // it is commented in order to perfom it outside the method
350   //if (isDone) {
351     //updateObject(myFeature);
352     // this emit is necessary to call store/restore method an restore type of selection
353     //emit valuesChanged();
354   //}
355
356   if (aSelectionListAttr.get())
357     aSelectionListAttr->cashValues(false);
358
359   theValues.clear();
360   if (!anInvalidValues.empty())
361     theValues.append(anInvalidValues);
362
363   if (isDone) // may be the feature's result is not displayed, but attributes should be
364     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeArguments,
365                              true);/// hope that something is redisplayed by object updated
366
367   return isDone;
368 }
369
370 //********************************************************************
371 void ModuleBase_WidgetMultiSelector::getHighlighted(QList<ModuleBase_ViewerPrsPtr>& theValues)
372 {
373   std::set<int> anAttributeIds;
374   getSelectedAttributeIndices(anAttributeIds);
375   if (!anAttributeIds.empty())
376     convertIndicesToViewerSelection(anAttributeIds, theValues);
377 }
378
379 //********************************************************************
380 bool ModuleBase_WidgetMultiSelector::canProcessAction(ModuleBase_ActionType theActionType,
381                                                       bool& isActionEnabled)
382 {
383   isActionEnabled = false;
384   bool aCanProcess = false;
385   switch (theActionType) {
386     case ActionUndo:
387     case ActionRedo: {
388       aCanProcess = true;
389       isActionEnabled = theActionType == ActionUndo ? myCurrentHistoryIndex > 0
390           : (mySelectedHistoryValues.size() > 0 &&
391              myCurrentHistoryIndex < mySelectedHistoryValues.size() - 1);
392     }
393     break;
394     default:
395       aCanProcess = ModuleBase_WidgetSelector::canProcessAction(theActionType, isActionEnabled);
396     break;
397   }
398   return aCanProcess;
399 }
400
401 //********************************************************************
402 bool ModuleBase_WidgetMultiSelector::processAction(ModuleBase_ActionType theActionType,
403                                                    const ActionParamPtr& theParam)
404 {
405   switch (theActionType) {
406     case ActionUndo:
407     case ActionRedo: {
408       ActionIntParamPtr aParam =
409         std::dynamic_pointer_cast<ModuleBase_ActionIntParameter>(theParam);
410       int aNb = aParam->value();
411       if (theActionType == ActionUndo)
412         myCurrentHistoryIndex -= aNb;
413       else
414         myCurrentHistoryIndex += aNb;
415       QList<ModuleBase_ViewerPrsPtr> aSelected = mySelectedHistoryValues[myCurrentHistoryIndex];
416       // equal vertices should not be used here
417       ModuleBase_ISelection::filterSelectionOnEqualPoints(aSelected);
418       bool isDone = setSelection(aSelected,
419                                  false /*need not validate because values already was in list*/);
420       updateOnSelectionChanged(isDone);
421
422       myWorkshop->updateCommandStatus();
423 #ifdef DEBUG_UNDO_REDO
424       printHistoryInfo(QString("processAction %1").arg(theActionType == ActionUndo ? "Undo"
425         : "Redo"), myCurrentHistoryIndex, mySelectedHistoryValues);
426 #endif
427       return true;
428     }
429     default:
430       return ModuleBase_ModelWidget::processAction(theActionType, theParam);
431   }
432 }
433
434 //********************************************************************
435 bool ModuleBase_WidgetMultiSelector::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& thePrs)
436 {
437   bool aValid = ModuleBase_WidgetSelector::isValidSelectionCustom(thePrs);
438   if (aValid) {
439     ResultPtr aResult = myWorkshop->selection()->getResult(thePrs);
440     if (!aResult.get()) { // In case if a feature was selected
441       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(thePrs->object());
442       if (aFeature.get())
443         aResult = aFeature->firstResult();
444     }
445     aValid = aResult.get() != NULL;
446     if (aValid) {
447       if (myFeature) {
448         // We can not select a result of our feature
449         std::list<ResultPtr> aResults;
450         ModelAPI_Tools::allResults(myFeature, aResults);
451         std::list<ResultPtr>::const_iterator aIt;
452         bool isSkipSelf = false;
453         for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
454           if ((*aIt) == aResult) {
455             isSkipSelf = true;
456             break;
457           }
458         }
459         if (isSkipSelf)
460           aValid = false;
461       }
462     }
463   }
464   return aValid;
465 }
466
467 //********************************************************************
468 bool ModuleBase_WidgetMultiSelector::processDelete()
469 {
470   appendFirstSelectionInHistory();
471
472   // find attribute indices to delete
473   std::set<int> anAttributeIds;
474   getSelectedAttributeIndices(anAttributeIds);
475
476   QModelIndexList anIndices = myListView->getControl()->selectionModel()->selectedIndexes();
477
478   // refill attribute by the items which indices are not in the list of ids
479   bool aDone = false;
480   DataPtr aData = myFeature->data();
481   AttributePtr anAttribute = aData->attribute(attributeID());
482   std::string aType = anAttribute->attributeType();
483   aDone = !anAttributeIds.empty();
484   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
485     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
486     aSelectionListAttr->remove(anAttributeIds);
487
488   }
489   else if (aType == ModelAPI_AttributeRefList::typeId()) {
490     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
491     aRefListAttr->remove(anAttributeIds);
492   }
493   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
494     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
495     aRefAttrListAttr->remove(anAttributeIds);
496   }
497
498   if (aDone) {
499     // update object is necessary to flush update signal. It leads to objects references map update
500     // and the operation presentation will not contain deleted items visualized as parameters of
501     // the feature.
502     updateObject(myFeature);
503
504     restoreValue();
505     myWorkshop->setSelected(getAttributeSelection());
506
507     // may be the feature's result is not displayed, but attributes should be
508     myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeArguments,
509                               true); /// hope that something is redisplayed by object updated
510   }
511
512   // Restore selection
513   myListView->restoreSelection(anIndices);
514
515   appendSelectionInHistory();
516   return true/*aDone*/; // following #2438 Delete should be processed even if nothing is delete
517 }
518
519 //********************************************************************
520 QList<QWidget*> ModuleBase_WidgetMultiSelector::getControls() const
521 {
522   QList<QWidget*> result;
523   result << myListView->getControl();
524   return result;
525 }
526
527 //********************************************************************
528 void ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()
529 {
530   // Clear current selection in order to avoid updating of object browser with obsolete indexes
531   // which can appear because of results deletetion after changing a type of selection
532   QString aSelectionType = myTypeCtrl->textValue();
533   QList<ModuleBase_ViewerPrsPtr> aEmptyList;
534   myWorkshop->setSelected(aEmptyList);
535
536   updateSelectionModesAndFilters(true);
537   myWorkshop->selectionActivate()->updateSelectionModes();
538
539   if (!myFeature)
540     return;
541   /// store the selected type
542   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
543   std::string aType = anAttribute->attributeType();
544   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
545     AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
546     aSelectionListAttr->setSelectionType(aSelectionType.toStdString());
547   }
548
549   // clear attribute values
550   DataPtr aData = myFeature->data();
551   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
552     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
553     aSelectionListAttr->clear();
554   }
555   else if (aType == ModelAPI_AttributeRefList::typeId()) {
556     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
557     aRefListAttr->clear();
558   }
559   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
560     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
561     aRefAttrListAttr->clear();
562   }
563
564   // update object is necessary to flush update signal. It leads to objects references map update
565   // and the operation presentation will not contain deleted items visualized as parameters of
566   // the feature.
567   updateObject(myFeature);
568   restoreValue();
569   myWorkshop->setSelected(getAttributeSelection());
570   // may be the feature's result is not displayed, but attributes should be
571   myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeArguments,
572                             true); /// hope that something is redisplayed by object updated
573   // clear history should follow after set selected to do not increase history by setSelected
574   clearSelectedHistory();
575
576   if (myWorkshop->propertyPanel()->activeWidget() != this)
577     myWorkshop->propertyPanel()->activateWidget(this);
578 }
579
580 //********************************************************************
581 bool ModuleBase_WidgetMultiSelector::processSelection()
582 {
583   if (!myIsNeutralPointClear) {
584     QList<ModuleBase_ViewerPrsPtr> aSelected = getFilteredSelected();
585     // do not clear selected object
586     if (aSelected.size() == 0) {
587       if (!getAttributeSelection().empty()) {
588         // Restore selection in the viewer by the attribute selection list
589         // it should be postponed to exit from the selectionChanged processing
590         static Events_ID anEvent = Events_Loop::eventByName(EVENT_UPDATE_BY_WIDGET_SELECTION);
591         ModelAPI_EventCreator::get()->sendUpdated(myFeature, anEvent);
592         Events_Loop::loop()->flush(anEvent);
593         return true;
594       }
595     }
596   }
597   appendFirstSelectionInHistory();
598   bool aDone = ModuleBase_WidgetSelector::processSelection();
599   appendSelectionInHistory();
600   return aDone;
601 }
602
603 void ModuleBase_WidgetMultiSelector::appendFirstSelectionInHistory()
604 {
605   if (mySelectedHistoryValues.empty()) {
606     myCurrentHistoryIndex++;
607     mySelectedHistoryValues.append(getAttributeSelection());
608
609 #ifdef DEBUG_UNDO_REDO
610     printHistoryInfo("appendSelectionInHistory", myCurrentHistoryIndex, mySelectedHistoryValues);
611 #endif
612   }
613 }
614
615 void ModuleBase_WidgetMultiSelector::appendSelectionInHistory()
616 {
617   while (myCurrentHistoryIndex != mySelectedHistoryValues.count() - 1)
618     mySelectedHistoryValues.removeLast();
619
620   QList<ModuleBase_ViewerPrsPtr> aSelected = getFilteredSelected();
621   myCurrentHistoryIndex++;
622   mySelectedHistoryValues.append(aSelected);
623   myWorkshop->updateCommandStatus();
624
625 #ifdef DEBUG_UNDO_REDO
626   printHistoryInfo("appendSelectionInHistory", myCurrentHistoryIndex, mySelectedHistoryValues);
627 #endif
628 }
629
630 void ModuleBase_WidgetMultiSelector::clearSelectedHistory()
631 {
632   mySelectedHistoryValues.clear();
633   myCurrentHistoryIndex = -1;
634   myWorkshop->updateCommandStatus();
635
636 #ifdef DEBUG_UNDO_REDO
637   printHistoryInfo("clearSelectedHistory", myCurrentHistoryIndex, mySelectedHistoryValues);
638 #endif
639 }
640
641 void ModuleBase_WidgetMultiSelector::updateFocus()
642 {
643   // Set focus to List control in order to make possible
644   // to use Tab key for transfer the focus to next widgets
645   ModuleBase_Tools::setFocus(myListView->getControl(),
646                              "ModuleBase_WidgetMultiSelector::onSelectionTypeChanged()");
647 }
648
649 //********************************************************************
650 void ModuleBase_WidgetMultiSelector::updateSelectionName()
651 {
652 }
653
654 //********************************************************************
655 void ModuleBase_WidgetMultiSelector::updateOnSelectionChanged(const bool theDone)
656 {
657   if (myIsSetSelectionBlocked)
658     return;
659   ModuleBase_WidgetSelector::updateOnSelectionChanged(theDone);
660
661   // according to #2154 we need to update OB selection when selection in the viewer happens
662   // it is important to flush sinchronize selection signal after flush of Update/Create/Delete.
663   // because we need that Object Browser has been already updated when synchronize happens.
664
665   // Restore selection in the viewer by the attribute selection list
666   // it is possible that diring selection attribute filling, selection in Object Browser
667   // is changed(some items were removed/added) and as result, selection in the viewer
668   // differs from the selection come to this method. By next rows, we restore selection
669   // in the viewer according to content of selection attribute. Case is Edge selection in Group
670   myIsSetSelectionBlocked = true;
671   static Events_ID anEvent = Events_Loop::eventByName(EVENT_UPDATE_BY_WIDGET_SELECTION);
672   ModelAPI_EventCreator::get()->sendUpdated(myFeature, anEvent);
673   Events_Loop::loop()->flush(anEvent);
674   myIsSetSelectionBlocked = false;
675 }
676
677 //********************************************************************
678 QIntList ModuleBase_WidgetMultiSelector::shapeTypes() const
679 {
680   QIntList aShapeTypes;
681
682   if (myShapeTypes.length() > 1 && myIsUseChoice) {
683     aShapeTypes.append(ModuleBase_Tools::shapeType(myTypeCtrl->textValue()));
684   }
685   else {
686     foreach (QString aType, myShapeTypes) {
687       aShapeTypes.append(ModuleBase_Tools::shapeType(aType));
688     }
689   }
690   return aShapeTypes;
691 }
692
693 //********************************************************************
694 void ModuleBase_WidgetMultiSelector::setCurrentShapeType(const int theShapeType)
695 {
696   QString aShapeTypeName;
697
698   int idx = 0;
699   foreach (QString aShapeTypeName, myShapeTypes) {
700     int aRefType = ModuleBase_Tools::shapeType(aShapeTypeName);
701     if(aRefType == theShapeType && idx != myTypeCtrl->value()) {
702       updateSelectionModesAndFilters(false);
703       bool isBlocked = myTypeCtrl->blockSignals(true);
704       myTypeCtrl->setValue(idx);
705       myTypeCtrl->blockSignals(isBlocked);
706       updateSelectionModesAndFilters(true);
707       break;
708     }
709     idx++;
710   }
711 }
712
713 QList<ModuleBase_ViewerPrsPtr> ModuleBase_WidgetMultiSelector::getAttributeSelection() const
714 {
715   QList<ModuleBase_ViewerPrsPtr> aSelected;
716   convertIndicesToViewerSelection(std::set<int>(), aSelected);
717   return aSelected;
718 }
719
720 //********************************************************************
721 void ModuleBase_WidgetMultiSelector::updateSelectionList()
722 {
723   myListView->getControl()->clear();
724
725   DataPtr aData = myFeature->data();
726   AttributePtr anAttribute = aData->attribute(attributeID());
727   std::string aType = anAttribute->attributeType();
728   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
729     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
730     for (int i = 0; i < aSelectionListAttr->size(); i++) {
731       AttributeSelectionPtr aAttr = aSelectionListAttr->value(i);
732       myListView->addItem(aAttr->namingName().c_str(), i);
733     }
734   }
735   else if (aType == ModelAPI_AttributeRefList::typeId()) {
736     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
737     for (int i = 0; i < aRefListAttr->size(); i++) {
738       ObjectPtr anObject = aRefListAttr->object(i);
739       if (anObject.get()) {
740         myListView->addItem(anObject->data()->name().c_str(), i);
741       }
742     }
743   }
744   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
745     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
746     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
747       AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
748       QString aName;
749       if (anAttribute.get()) {
750         std::string anAttrName = ModuleBase_Tools::generateName(anAttribute, myWorkshop);
751         aName = QString::fromStdString(anAttrName);
752       }
753       else {
754         ObjectPtr anObject = aRefAttrListAttr->object(i);
755         if (anObject.get()) {
756           aName = anObject->data()->name().c_str();
757         }
758       }
759       myListView->addItem(aName, i);
760     }
761   }
762
763   // We have to call repaint because sometimes the List control is not updated
764   myListView->getControl()->update();
765 }
766
767 //********************************************************************
768 std::string ModuleBase_WidgetMultiSelector::validatorType(const QString& theType) const
769 {
770   std::string aType;
771
772   if (theType == "Vertices")
773     aType = "vertex";
774   else if (theType == "Edges")
775     aType = "edge";
776   else if (theType == "Faces")
777     aType = "face";
778   else if (theType == "Solids")
779     aType = "solid";
780
781   return aType;
782 }
783
784 //********************************************************************
785 void ModuleBase_WidgetMultiSelector::clearSelection()
786 {
787   bool isClearInNeutralPoint = myIsNeutralPointClear;
788   myIsNeutralPointClear = true;
789
790   QList<ModuleBase_ViewerPrsPtr> anEmptyList;
791   // This method will call Selection changed event which will call onSelectionChanged
792   // To clear mySelection, myListView and storeValue()
793   // So, we don't need to call it
794   myWorkshop->setSelected(anEmptyList);
795
796   myIsNeutralPointClear = isClearInNeutralPoint;
797 }
798
799 //********************************************************************
800 void ModuleBase_WidgetMultiSelector::onDeleteItem()
801 {
802   processDelete();
803 }
804
805 //********************************************************************
806 void ModuleBase_WidgetMultiSelector::onListSelection()
807 {
808   myWorkshop->module()->customizeObject(myFeature, ModuleBase_IModule::CustomizeHighlightedObjects,
809                                         true);
810 }
811
812 //********************************************************************
813 void ModuleBase_WidgetMultiSelector::getSelectedAttributeIndices(std::set<int>& theAttributeIds)
814 {
815   myListView->getSelectedIndices(theAttributeIds);
816 }
817
818 void ModuleBase_WidgetMultiSelector::convertIndicesToViewerSelection(std::set<int> theAttributeIds,
819                                                    QList<ModuleBase_ViewerPrsPtr>& theValues) const
820 {
821   if(myFeature.get() == NULL)
822     return;
823
824   DataPtr aData = myFeature->data();
825   AttributePtr anAttribute = aData->attribute(attributeID());
826   std::string aType = anAttribute->attributeType();
827   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
828     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
829     for (int i = 0; i < aSelectionListAttr->size(); i++) {
830       // filter by attribute indices only if the container is not empty otherwise return all items
831       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
832         continue;
833       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
834       ObjectPtr anObject = anAttr->contextObject();
835       if (anObject.get())
836         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
837                new ModuleBase_ViewerPrs(anObject, anAttr->value(), NULL)));
838     }
839   }
840   else if (aType == ModelAPI_AttributeRefList::typeId()) {
841     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
842     for (int i = 0; i < aRefListAttr->size(); i++) {
843       // filter by attribute indices only if the container is not empty otherwise return all items
844       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
845         continue;
846       ObjectPtr anObject = aRefListAttr->object(i);
847       if (anObject.get()) {
848         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
849                new ModuleBase_ViewerPrs(anObject, GeomShapePtr(), NULL)));
850       }
851     }
852   }
853   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
854     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
855     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
856       // filter by attribute indices only if the container is not empty otherwise return all items
857       if (!theAttributeIds.empty() && theAttributeIds.find(i) == theAttributeIds.end())
858         continue;
859       ObjectPtr anObject = aRefAttrListAttr->object(i);
860       if (!anObject.get())
861         continue;
862       TopoDS_Shape aShape;
863       AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
864       if (anAttribute.get()) {
865         GeomShapePtr aGeomShape = ModuleBase_Tools::getShape(anAttribute, myWorkshop);
866         theValues.append(std::shared_ptr<ModuleBase_ViewerPrs>(
867                new ModuleBase_ViewerPrs(anObject, aGeomShape, NULL)));
868       }
869     }
870   }
871 }
872
873 bool ModuleBase_WidgetMultiSelector::removeUnusedAttributeObjects
874                                                  (QList<ModuleBase_ViewerPrsPtr>& theValues)
875 {
876   bool isDone = false;
877
878   std::map<ObjectPtr, std::set<GeomShapePtr> > aGeomSelection = convertSelection(theValues);
879   DataPtr aData = myFeature->data();
880   AttributePtr anAttribute = aData->attribute(attributeID());
881   std::string aType = anAttribute->attributeType();
882   std::set<GeomShapePtr> aShapes;
883   std::set<int> anIndicesToBeRemoved;
884   FeaturePtr aFeature;
885   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
886     // iteration through data model to find not selected elements to remove them
887     AttributeSelectionListPtr aSelectionListAttr = aData->selectionList(attributeID());
888     for (int i = 0; i < aSelectionListAttr->size(); i++) {
889       AttributeSelectionPtr anAttr = aSelectionListAttr->value(i);
890       //aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->contextObject());
891       //if (!aFeature.get()) { // Feature can not be found as geometry selection
892         bool aFound = findInSelection(
893           anAttr->contextObject(), anAttr->value(), aGeomSelection, myWorkshop);
894         if (!aFound)
895           anIndicesToBeRemoved.insert(i);
896 //      }
897     }
898     isDone = anIndicesToBeRemoved.size() > 0;
899     if (isDone)
900       aSelectionListAttr->remove(anIndicesToBeRemoved);
901   }
902   else if (aType == ModelAPI_AttributeRefList::typeId()) {
903     AttributeRefListPtr aRefListAttr = aData->reflist(attributeID());
904     for (int i = 0; i < aRefListAttr->size(); i++) {
905       ObjectPtr anObject = aRefListAttr->object(i);
906       if (anObject.get()) {
907         bool aFound = findInSelection(anObject, GeomShapePtr(), aGeomSelection,
908                                       myWorkshop);
909         if (!aFound)
910           anIndicesToBeRemoved.insert(i);
911       }
912     }
913     isDone = anIndicesToBeRemoved.size() > 0;
914     aRefListAttr->remove(anIndicesToBeRemoved);
915   }
916   else if (aType == ModelAPI_AttributeRefAttrList::typeId()) {
917     std::set<AttributePtr> anAttributes;
918     QList<ModuleBase_ViewerPrsPtr>::const_iterator
919       anIt = theValues.begin(), aLast = theValues.end();
920     ObjectPtr anObject;
921     GeomShapePtr aShape;
922     for (; anIt != aLast; anIt++) {
923       ModuleBase_ViewerPrsPtr aPrs = *anIt;
924       getGeomSelection(aPrs, anObject, aShape);
925       AttributePtr anAttr = myWorkshop->module()->findAttribute(anObject, aShape);
926       if (anAttr.get() && anAttributes.find(anAttr) == anAttributes.end())
927         anAttributes.insert(anAttr);
928     }
929
930     AttributeRefAttrListPtr aRefAttrListAttr = aData->refattrlist(attributeID());
931     for (int i = 0; i < aRefAttrListAttr->size(); i++) {
932       bool aFound = false;
933       if (aRefAttrListAttr->isAttribute(i)) {
934         AttributePtr anAttribute = aRefAttrListAttr->attribute(i);
935         aFound = anAttributes.find(anAttribute) != anAttributes.end();
936       }
937       else {
938         aFound = findInSelection(aRefAttrListAttr->object(i), GeomShapePtr(), aGeomSelection,
939                                  myWorkshop);
940       }
941       if (!aFound)
942         anIndicesToBeRemoved.insert(i);
943     }
944     isDone = anIndicesToBeRemoved.size() > 0;
945     aRefAttrListAttr->remove(anIndicesToBeRemoved);
946   }
947
948   return isDone;
949 }
950
951 std::map<ObjectPtr, std::set<GeomShapePtr> > ModuleBase_WidgetMultiSelector::convertSelection
952                                                      (QList<ModuleBase_ViewerPrsPtr>& theValues)
953 {
954   // convert prs list to objects map
955   std::map<ObjectPtr, std::set<GeomShapePtr> > aGeomSelection;
956   std::set<GeomShapePtr> aShapes;
957   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theValues.begin(), aLast = theValues.end();
958   ObjectPtr anObject;
959   GeomShapePtr aShape;
960   GeomShapePtr anEmptyShape(new GeomAPI_Shape());
961   for (; anIt != aLast; anIt++) {
962     ModuleBase_ViewerPrsPtr aPrs = *anIt;
963     getGeomSelection(aPrs, anObject, aShape);
964     aShapes.clear();
965     if (aGeomSelection.find(anObject) != aGeomSelection.end()) // found
966       aShapes = aGeomSelection[anObject];
967     // we need to know if there was an empty shape in selection for the object
968     if (!aShape.get())
969       aShape = anEmptyShape;
970     if (aShape.get() && aShapes.find(aShape) == aShapes.end()) // not found
971       aShapes.insert(aShape);
972     aGeomSelection[anObject] = aShapes;
973   }
974   return aGeomSelection;
975 }
976
977 bool ModuleBase_WidgetMultiSelector::findInSelection(const ObjectPtr& theObject,
978                               GeomShapePtr theShape,
979                               const std::map<ObjectPtr, std::set<GeomShapePtr> >& theGeomSelection,
980                               ModuleBase_IWorkshop* theWorkshop)
981 {
982   if (!theObject.get())
983     return false;
984   // issue #2154: we should not remove from list objects hidden in the viewer if selection
985   // was done with SHIFT button
986   if (theWorkshop->hasSHIFTPressed() && !theObject->isDisplayed())
987     return true;
988
989   bool aFound = false;
990   GeomShapePtr aShape = theShape;
991   if (!aShape.get()) {
992     // #2429 (the preselection of a sketch is not taken into account)
993     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
994     if (aResult.get())
995       aShape = aResult->shape();
996   }
997   if (theGeomSelection.find(theObject) != theGeomSelection.end()) {// found
998     const std::set<GeomShapePtr>& aShapes = theGeomSelection.at(theObject);
999     std::set<GeomShapePtr>::const_iterator anIt = aShapes.begin(), aLast = aShapes.end();
1000     for (; anIt != aLast && !aFound; anIt++) {
1001       GeomShapePtr aCShape = *anIt;
1002       if (aCShape.get())
1003       {
1004         // treat shape equal to context as null: 2219, keep order of shapes in list
1005         if (aCShape->isNull()) { // in selection, shape of result is equal to selected shape
1006           // if so, here we need to check shape of result
1007           ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1008           if (aResult.get())
1009             aCShape = aResult->shape();
1010         }
1011         aFound = aCShape->isSame(aShape);
1012       }
1013     }
1014   }
1015
1016   // issue #2903: (Possibility to hide faces) - check whether given shape is a hidden sub-shape
1017   if (!aFound && theShape.get() && theWorkshop->hasSHIFTPressed() && theObject->isDisplayed()) {
1018     AISObjectPtr anAIS = theWorkshop->findPresentation(theObject);
1019     if (anAIS.get() != NULL) {
1020       Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1021
1022       Handle(ModuleBase_ResultPrs) aResultPrs = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1023       if (!aResultPrs.IsNull() && aResultPrs->isSubShapeHidden(theShape->impl<TopoDS_Shape>()))
1024         return true;
1025     }
1026   }
1027
1028   return aFound;
1029 }
1030
1031 QList<ActionInfo>
1032   ModuleBase_WidgetMultiSelector::actionsList(ModuleBase_ActionType theActionType) const
1033 {
1034   QList<ActionInfo> aList;
1035   if (myCurrentHistoryIndex > -1) {
1036     int i = 0;
1037     QString aTitle("Selection %1 items");
1038     QString aTit("Selection %1 item");
1039     QIcon aIcon(":pictures/selection.png");
1040     int aNb;
1041     switch (theActionType) {
1042     case ActionUndo:
1043       i = 1;
1044       while (i <= myCurrentHistoryIndex) {
1045         aNb = mySelectedHistoryValues.at(i).count();
1046         if (aNb == 1) {
1047           ActionInfo aInfo(aIcon, aTit.arg(aNb));
1048           aList.insert(0, aInfo);
1049         } else {
1050           ActionInfo aInfo(aIcon, aTitle.arg(aNb));
1051           aList.insert(0, aInfo);
1052         }
1053         i++;
1054       }
1055       break;
1056     case ActionRedo:
1057       i = mySelectedHistoryValues.length() - 1;
1058       while (i > myCurrentHistoryIndex) {
1059         aNb = mySelectedHistoryValues.at(i).count();
1060         if (aNb == 1) {
1061           ActionInfo aInfo(aIcon, aTit.arg(mySelectedHistoryValues.at(i).count()));
1062           aList.insert(0, aInfo);
1063         } else {
1064           ActionInfo aInfo(aIcon, aTitle.arg(mySelectedHistoryValues.at(i).count()));
1065           aList.insert(0, aInfo);
1066         }
1067         i--;
1068       }
1069       break;
1070     }
1071   }
1072   return aList;
1073 }
1074
1075
1076 void ModuleBase_WidgetMultiSelector::onFeatureAccepted()
1077 {
1078   defaultValues[myFeatureId + attributeID()] = myDefMode;
1079 }
1080
1081 void ModuleBase_WidgetMultiSelector::onListActivated()
1082 {
1083   //focusTo();
1084   emitFocusInWidget();
1085 }
1086
1087 void ModuleBase_WidgetMultiSelector::onSameTopology(bool theOn)
1088 {
1089   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
1090   std::string aType = anAttribute->attributeType();
1091   if (aType == ModelAPI_AttributeSelectionList::typeId()) {
1092     AttributeSelectionListPtr aSelectionListAttr = myFeature->data()->selectionList(attributeID());
1093     aSelectionListAttr->setGeometricalSelection(theOn);
1094     updateObject(myFeature);
1095   }
1096 }
1097
1098 void ModuleBase_WidgetMultiSelector::onShowOnly(bool theChecked)
1099 {
1100   std::list<ResultPtr> aResults = myFeature->results();
1101    std::list<ResultPtr>::const_iterator aIt;
1102   if (theChecked) {
1103     myVisibleObjects = myWorkshop->displayedObjects();
1104     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
1105       myVisibleObjects.removeAll(*aIt);
1106     }
1107     myWorkshop->module()->disableCustomMode(ModuleBase_IModule::CustomizeArguments);
1108   }
1109   else
1110     myWorkshop->module()->enableCustomModes();
1111
1112   foreach(ObjectPtr aObj, myVisibleObjects) {
1113     aObj->setDisplayed(!theChecked);
1114   }
1115
1116   if (!theChecked) {
1117     // Hide and show the group result in order to make it above all objects
1118     bool aOldState = myWorkshop->enableUpdateViewer(false);
1119     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
1120       (*aIt)->setDisplayed(false);
1121     }
1122     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1123     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
1124       (*aIt)->setDisplayed(true);
1125     }
1126     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1127     myWorkshop->enableUpdateViewer(aOldState);
1128
1129     myVisibleObjects.clear();
1130   } else
1131     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1132 }