]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Fix of the exception of edit field (loaded with a study)
[modules/shaper.git] / src / XGUI / XGUI_Workshop.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 //#include "XGUI_Constants.h"
4 #include "XGUI_Workshop.h"
5
6 #include "XGUI_ActionsMgr.h"
7 #include "XGUI_MenuMgr.h"
8 #include "XGUI_ColorDialog.h"
9 #include "XGUI_DeflectionDialog.h"
10 #include "XGUI_ContextMenuMgr.h"
11 #include "XGUI_Displayer.h"
12 #include "XGUI_ErrorDialog.h"
13 #include "XGUI_ErrorMgr.h"
14 #include "XGUI_ModuleConnector.h"
15 #include "XGUI_ObjectsBrowser.h"
16 #include "XGUI_OperationMgr.h"
17 #include "XGUI_PropertyPanel.h"
18 #include "XGUI_SalomeConnector.h"
19 #include "XGUI_Selection.h"
20 #include "XGUI_SelectionMgr.h"
21 #include "XGUI_Tools.h"
22 #include "XGUI_ViewerProxy.h"
23 #include "XGUI_WorkshopListener.h"
24 #include <XGUI_CustomPrs.h>
25 #include <XGUI_HistoryMenu.h>
26 #include <XGUI_QtEvents.h>
27 #include <XGUI_DataModel.h>
28
29 #ifndef HAVE_SALOME
30 #include <AppElements_Button.h>
31 #include <AppElements_Command.h>
32 #include <AppElements_MainMenu.h>
33 #include <AppElements_MainWindow.h>
34 #include <AppElements_MenuGroupPanel.h>
35 #include <AppElements_Viewer.h>
36 #include <AppElements_Workbench.h>
37 #endif
38
39 #include <ModelAPI_AttributeDocRef.h>
40 #include <ModelAPI_AttributeIntArray.h>
41 #include <ModelAPI_AttributeDouble.h>
42 #include <ModelAPI_Data.h>
43 #include <ModelAPI_Events.h>
44 #include <ModelAPI_Feature.h>
45 #include <ModelAPI_Object.h>
46 #include <ModelAPI_ResultBody.h>
47 #include <ModelAPI_ResultConstruction.h>
48 #include <ModelAPI_ResultGroup.h>
49 #include <ModelAPI_ResultParameter.h>
50 #include <ModelAPI_ResultField.h>
51 #include <ModelAPI_Session.h>
52 #include <ModelAPI_Validator.h>
53 #include <ModelAPI_ResultCompSolid.h>
54 #include <ModelAPI_Tools.h>
55
56 //#include <PartSetPlugin_Part.h>
57
58 #include <Events_Loop.h>
59 #include <Events_InfoMessage.h>
60 #include <Events_LongOp.h>
61
62 #include <ModuleBase_IModule.h>
63 #include <ModuleBase_IViewer.h>
64 #include <ModuleBase_Operation.h>
65 #include <ModuleBase_OperationDescription.h>
66 #include <ModuleBase_PageBase.h>
67 #include <ModuleBase_Preferences.h>
68 #include <ModuleBase_SelectionValidator.h>
69 #include <ModuleBase_Tools.h>
70 #include <ModuleBase_WidgetFactory.h>
71 #include <ModuleBase_OperationFeature.h>
72 #include <ModuleBase_OperationAction.h>
73 #include <ModuleBase_PagedContainer.h>
74 #include <ModuleBase_WidgetValidated.h>
75 #include <ModuleBase_ModelWidget.h>
76 #include <ModuleBase_ResultPrs.h>
77
78 #include <Config_Common.h>
79 #include <Config_FeatureMessage.h>
80 #include <Config_ModuleReader.h>
81 #include <Config_PointerMessage.h>
82 #include <Config_PropManager.h>
83 #include <Config_DataModelReader.h>
84 #include <Config_Translator.h>
85 #include <Config_WidgetAPI.h>
86 #include <Config_Keywords.h>
87
88 #include <SUIT_ResourceMgr.h>
89
90 #include <AIS_Trihedron.hxx>
91 #ifdef BEFORE_TRIHEDRON_PATCH
92 #include <AIS_Point.hxx>
93 #include <AIS_Axis.hxx>
94 #endif
95
96 #include <QApplication>
97 #include <QFileDialog>
98 #include <QMessageBox>
99 #include <QMdiSubWindow>
100 #include <QMainWindow>
101 #include <QPushButton>
102 #include <QDockWidget>
103 #include <QLayout>
104 #include <QThread>
105 #include <QObject>
106 #include <QMenu>
107 #include <QToolButton>
108 #include <QAction>
109 #include <QDesktopWidget>
110
111 #include <iterator>
112
113 #ifdef TINSPECTOR
114 #include <CDF_Session.hxx>
115 #include <CDF_Application.hxx>
116 #include <TInspector_Communicator.hxx>
117 #include <VInspector_CallBack.hxx>
118 static TInspector_Communicator* MyTCommunicator;
119 static Handle(VInspector_CallBack) MyVCallBack;
120
121 #endif
122
123 #ifdef _DEBUG
124 #include <QDebug>
125 #include <iostream>
126 #endif
127
128 #ifdef WIN32
129 #include <windows.h>
130 #else
131 #include <dlfcn.h>
132 #endif
133
134 QString XGUI_Workshop::MOVE_TO_END_COMMAND = QObject::tr("Move to the end");
135
136 //#define DEBUG_DELETE
137 //#define DEBUG_FEATURE_NAME
138 //#define DEBUG_CLEAN_HISTORY
139
140 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
141     : QObject(),
142       myCurrentDir(QString()),
143       myModule(NULL),
144       mySalomeConnector(theConnector),
145       myPropertyPanel(0),
146       myObjectBrowser(0),
147       myDisplayer(0)
148       //myViewerSelMode(TopAbs_FACE)
149 {
150   mySelector = new XGUI_SelectionMgr(this);
151   myModuleConnector = new XGUI_ModuleConnector(this);
152   myOperationMgr = new XGUI_OperationMgr(this, 0);
153   ModuleBase_IWorkshop* aWorkshop = moduleConnector();
154   // Has to be defined first in order to get errors and messages from other components
155   myEventsListener = new XGUI_WorkshopListener(aWorkshop);
156
157   SUIT_ResourceMgr* aResMgr = ModuleBase_Preferences::resourceMgr();
158 #ifndef HAVE_SALOME
159   myMainWindow = new AppElements_MainWindow();
160
161   bool aCloc = aResMgr->booleanValue("language", "locale", true);
162   if (aCloc)
163     QLocale::setDefault( QLocale::c() );
164   else
165     QLocale::setDefault( QLocale::system() );
166 #endif
167   QString aPath = Config_XMLReader::pluginConfigFile().c_str();
168   QDir aDir(aPath);
169
170   // Load translations
171   QStringList aLangs;
172   aLangs << "*_en.ts"; // load by default eng translations
173   QString aCurrLang = aResMgr->stringValue("language", "language", "en");
174   if(aCurrLang != "en") {
175     aLangs << "*_" + aCurrLang + ".ts"; // then replace with translated files
176   }
177
178   foreach(QString aLang, aLangs) {
179     QStringList aFilters;
180     aFilters << aLang;
181     QStringList aTsFiles = aDir.entryList(aFilters, QDir::Files);
182     foreach(QString aFileName, aTsFiles) {
183       Config_Translator::load(aFileName.toStdString());
184     }
185   }
186
187   myDataModelXMLReader = new Config_DataModelReader();
188   //myDataModelXMLReader->readAll();
189
190   myDisplayer = new XGUI_Displayer(this);
191
192   connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateCommandStatus()));
193
194   myActionsMgr = new XGUI_ActionsMgr(this);
195   myMenuMgr = new XGUI_MenuMgr(this);
196   myErrorDlg = new XGUI_ErrorDialog(QApplication::desktop());
197   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
198   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
199           SLOT(onContextMenuCommand(const QString&, bool)));
200
201   myViewerProxy = new XGUI_ViewerProxy(this);
202   //connect(myViewerProxy, SIGNAL(selectionChanged()),
203   //        myActionsMgr,  SLOT(updateOnViewSelection()));
204
205   myOperationMgr->setWorkshop(aWorkshop);
206
207   myErrorMgr = new XGUI_ErrorMgr(this, aWorkshop);
208
209   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
210           SLOT(onOperationResumed(ModuleBase_Operation*)));
211   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
212           SLOT(onOperationStopped(ModuleBase_Operation*)));
213   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)),
214           SLOT(onOperationCommitted(ModuleBase_Operation*)));
215   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)),
216           SLOT(onOperationAborted(ModuleBase_Operation*)));
217
218 #ifndef HAVE_SALOME
219   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
220   onTrihedronVisibilityChanged(true);
221 #endif
222
223   connect(myEventsListener, SIGNAL(errorOccurred(std::shared_ptr<Events_InfoMessage>)),
224           myErrorDlg, SLOT(addError(std::shared_ptr<Events_InfoMessage>)));
225
226   //Config_PropManager::registerProp("Visualization", "object_default_color", "Object color",
227   //                                 Config_Prop::Color, "225,225,225");
228
229   Config_PropManager::registerProp("Visualization", "result_body_color", "Result color",
230                                    Config_Prop::Color, ModelAPI_ResultBody::DEFAULT_COLOR());
231   Config_PropManager::registerProp("Visualization", "result_group_color", "Group color",
232                                    Config_Prop::Color, ModelAPI_ResultGroup::DEFAULT_COLOR());
233   Config_PropManager::registerProp("Visualization", "result_construction_color",
234                                    "Construction color",
235                                    Config_Prop::Color,
236                                    ModelAPI_ResultConstruction::DEFAULT_COLOR());
237   Config_PropManager::registerProp("Visualization", "result_part_color", "Part color",
238                                    Config_Prop::Color, ModelAPI_ResultPart::DEFAULT_COLOR());
239   Config_PropManager::registerProp("Visualization", "result_field_color", "Field color",
240                                    Config_Prop::Color, ModelAPI_ResultField::DEFAULT_COLOR());
241
242   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "face-selection", true))
243     myViewerSelMode.append(TopAbs_FACE);
244   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "edge-selection", true))
245     myViewerSelMode.append(TopAbs_EDGE);
246   if (ModuleBase_Preferences::resourceMgr()->booleanValue("Viewer", "vertex-selection", true))
247     myViewerSelMode.append(TopAbs_VERTEX);
248   //IMP: an attempt to use result selection with other selection modes
249   myViewerSelMode.append(ModuleBase_ResultPrs::Sel_Result);//TopAbs_VERTEX);
250   myViewerSelMode.append(TopAbs_COMPSOLID);
251 }
252
253 //******************************************************
254 XGUI_Workshop::~XGUI_Workshop(void)
255 {
256 #ifdef _DEBUG
257 #ifdef MISSED_TRANSLATION
258   // Save Missed translations
259   Config_Translator::saveMissedTranslations();
260 #endif
261 #endif
262
263   delete myDisplayer;
264   delete myDataModelXMLReader;
265 }
266
267 //******************************************************
268 void XGUI_Workshop::startApplication()
269 {
270   //Initialize event listening
271   myEventsListener->initializeEventListening();
272
273   myDataModelXMLReader->readAll();
274   initMenu();
275
276   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
277                                    Config_Prop::Directory, "");
278
279
280   registerValidators();
281
282   // Calling of  loadCustomProps before activating module is required
283   // by Config_PropManger to restore user-defined path to plugins
284   ModuleBase_Preferences::loadCustomProps();
285   createModule();
286
287 #ifndef HAVE_SALOME
288   myMainWindow->show();
289   updateCommandStatus();
290 #endif
291
292   onNew();
293
294   myViewerProxy->connectViewProxy();
295   connect(myViewerProxy, SIGNAL(trihedronVisibilityChanged(bool)),
296           SLOT(onTrihedronVisibilityChanged(bool)));
297
298   emit applicationStarted();
299 }
300
301 void XGUI_Workshop::activateModule()
302 {
303   myModule->activateSelectionFilters();
304
305   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
306     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
307   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
308     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
309
310   updateCommandStatus();
311
312   // TODO: get default selection mode
313
314   // activate visualized objects in the viewer
315   activateObjectsSelection(displayer()->displayedObjects());
316   myOperationMgr->activate();
317 }
318
319 void XGUI_Workshop::deactivateModule()
320 {
321   myModule->deactivateSelectionFilters();
322
323   // remove internal displayer filter
324   displayer()->deactivateSelectionFilters();
325
326   disconnect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
327     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
328   disconnect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
329     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
330
331   XGUI_Displayer* aDisplayer = displayer();
332   QObjectPtrList aDisplayed = aDisplayer->displayedObjects();
333   aDisplayer->deactivateObjects(aDisplayed, true);
334   Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
335   Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aDisplayer->getTrihedron());
336   /// deactivate trihedron in selection modes
337   TColStd_ListOfInteger aTColModes;
338   aContext->ActivatedModes(aTrihedron, aTColModes);
339   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
340   for (; itr.More(); itr.Next() ) {
341     Standard_Integer aMode = itr.Value();
342     aContext->Deactivate(aTrihedron, aMode);
343   }
344 #ifdef BEFORE_TRIHEDRON_PATCH
345   /// Trihedron problem: objects stayed in the viewer, should be removed manually
346   /// otherwise in SALOME happens crash by HideAll in the viewer
347   aContext->Remove(aTrihedron->Position(), true);
348   aContext->Remove(aTrihedron->Axis(), true);
349   aContext->Remove(aTrihedron->XAxis(), true);
350   aContext->Remove(aTrihedron->YAxis(), true);
351 #endif
352
353   myOperationMgr->deactivate();
354 }
355
356 //******************************************************
357 void XGUI_Workshop::initMenu()
358 {
359   myContextMenuMgr->createActions();
360
361 #ifdef HAVE_SALOME
362   // Create only Undo, Redo commands
363   QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
364                                                         tr("Undo last command"),
365                                                         QIcon(":pictures/undo.png"),
366                                                         QKeySequence::Undo, false,
367                                                         "MEN_DESK_EDIT");
368   QString aToolBarTitle = tr( "INF_DESK_TOOLBAR_STANDARD" );
369   salomeConnector()->addActionInToolbar( aAction,aToolBarTitle  );
370
371   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
372   addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
373
374   aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
375                                               QIcon(":pictures/redo.png"), QKeySequence::Redo,
376                                               false, "MEN_DESK_EDIT");
377   salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
378
379   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
380   addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
381
382   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
383   //aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"),
384   //                                            tr("Rebuild data objects"),
385   //                                            QIcon(":pictures/rebuild.png"), QKeySequence(),
386   //                                            false, "MEN_DESK_EDIT");
387   //salomeConnector()->addActionInToolbar( aAction, aToolBarTitle );
388
389   //connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
390   //salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
391
392   aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export native..."),
393                                              tr("Export the current document into a native file"),
394                                               QIcon(), QKeySequence(),
395                                               false, "MEN_DESK_FILE");
396   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
397
398   aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import native..."),
399                                               tr("Import native file"),
400                                               QIcon(), QKeySequence(),
401                                               false, "MEN_DESK_FILE");
402   connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
403   salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
404
405 #else
406   // File commands group
407   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
408
409   AppElements_Command* aCommand;
410
411   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save"), tr("Save the document"),
412                                 QIcon(":pictures/save.png"), QKeySequence::Save);
413   aCommand->connectTo(this, SLOT(onSave()));
414   //aCommand->disable();
415
416   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
417                                 QIcon(":pictures/save.png"), QKeySequence());
418   aCommand->connectTo(this, SLOT(onSaveAs()));
419
420   QString aUndoId = "UNDO_CMD";
421   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
422                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
423   aCommand->connectTo(this, SLOT(onUndo()));
424   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
425   addHistoryMenu(aUndoButton,
426                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
427                  SLOT(onUndo(int)));
428
429   QString aRedoId = "REDO_CMD";
430   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
431                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
432   aCommand->connectTo(this, SLOT(onRedo()));
433   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
434   addHistoryMenu(aRedoButton,
435                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
436                  SLOT(onRedo(int)));
437
438   //aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
439   //  QIcon(":pictures/rebuild.png"), QKeySequence());
440   //aCommand->connectTo(this, SLOT(onRebuild()));
441
442   //aCommand->disable();
443
444   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
445                                 QIcon(":pictures/open.png"), QKeySequence::Open);
446   aCommand->connectTo(this, SLOT(onOpen()));
447
448   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
449                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
450   aCommand->connectTo(this, SLOT(onPreferences()));
451
452   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
453                                 QIcon(":pictures/close.png"), QKeySequence::Close);
454   aCommand->connectTo(this, SLOT(onExit()));
455 #endif
456 }
457
458 #ifndef HAVE_SALOME
459 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
460 {
461   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
462   return aMenuBar->addWorkbench(theName);
463 }
464 #endif
465
466 //******************************************************
467 QMainWindow* XGUI_Workshop::desktop() const
468 {
469 #ifdef HAVE_SALOME
470   return salomeConnector()->desktop();
471 #else
472   return myMainWindow;
473 #endif
474 }
475
476 //******************************************************
477 void XGUI_Workshop::onStartWaiting()
478 {
479   if (Events_LongOp::isPerformed()) {
480     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
481   }
482 }
483
484 //******************************************************
485 void XGUI_Workshop::onAcceptActionClicked()
486 {
487   QAction* anAction = dynamic_cast<QAction*>(sender());
488   XGUI_OperationMgr* anOperationMgr = operationMgr();
489   if (anOperationMgr) {
490     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
491                                                     (anOperationMgr->currentOperation());
492     if (aFOperation) {
493       //if (errorMgr()->canProcessClick(anAction, aFOperation->feature()))
494       myOperationMgr->onCommitOperation();
495     }
496   }
497 }
498
499 //******************************************************
500 void XGUI_Workshop::onPreviewActionClicked()
501 {
502   ModuleBase_IPropertyPanel* aPanel = propertyPanel();
503   if (aPanel) {
504     ModuleBase_ModelWidget* anActiveWidget = aPanel->activeWidget();
505     if (anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::ModifiedInPP) {
506       anActiveWidget->storeValue();
507     }
508   }
509   std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
510                 new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_REQUESTED)));
511   Events_Loop::loop()->send(aMsg);
512 }
513
514 //******************************************************
515 void XGUI_Workshop::deactivateActiveObject(const ObjectPtr& theObject, const bool theUpdateViewer)
516 {
517   if (!myModule->canActivateSelection(theObject)) {
518     if (myDisplayer->isActive(theObject)) {
519       QObjectPtrList anObjects;
520       anObjects.append(theObject);
521       myDisplayer->deactivateObjects(anObjects, theUpdateViewer);
522     }
523   }
524 }
525
526 //******************************************************
527 bool XGUI_Workshop::isFeatureOfNested(const FeaturePtr& theFeature)
528 {
529   bool aHasNested = false;
530   std::string aFeatureKind = theFeature->getKind();
531 #ifdef HAVE_SALOME
532     XGUI_SalomeConnector* aSalomeConnector = salomeConnector();
533     if (aSalomeConnector->isFeatureOfNested(actionsMgr()->action(aFeatureKind.c_str())))
534       aHasNested = true;
535 #else
536     AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
537     AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
538     if (aCommand && aCommand->button()->additionalButtonWidget())
539       aHasNested = true;
540 #endif
541   return aHasNested;
542 }
543
544 void XGUI_Workshop::fillPropertyPanel(ModuleBase_Operation* theOperation)
545 {
546   ModuleBase_OperationFeature* aFOperation =
547     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
548   if (!aFOperation)
549     return;
550
551   showPropertyPanel();
552   myPropertyPanel->cleanContent();
553
554   QList<ModuleBase_ModelWidget*> aWidgets;
555   if (!module()->createWidgets(theOperation, aWidgets)) {
556     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
557     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
558     aFactory.createWidget(myPropertyPanel->contentWidget());
559     aWidgets = aFactory.getModelWidgets();
560   }
561
562   // check compatibility of feature and widgets
563   FeaturePtr aFeature = aFOperation->feature();
564   std::string aFeatureKind = aFeature->getKind();
565   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
566     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
567       std::string anErrorMsg = "The feature '%1' has no attribute '%2' used by widget '%3'.";
568       Events_InfoMessage("XGUI_Workshop", anErrorMsg)
569         .arg(aFeatureKind).arg(aWidget->attributeID())
570         .arg(aWidget->metaObject()->className()).send();
571       myPropertyPanel->cleanContent();
572       return;
573     }
574   }
575   // for performance purpose, flush should be done after all controls are filled
576   bool isUpdateFlushed = false;
577   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
578     bool isStoreValue = !aFOperation->isEditOperation() &&
579                         !aWidget->getDefaultValue().empty() &&
580                         !aWidget->isComputedDefault();
581     aWidget->setFeature(aFeature, isStoreValue, isUpdateFlushed);
582     if (!isStoreValue)
583       aWidget->restoreValue();
584     aWidget->enableFocusProcessing();
585   }
586   ModuleBase_Tools::flushUpdated(aFeature);
587
588   // update visible state of Preview button
589 #ifdef HAVE_SALOME
590   bool anIsAutoPreview =
591     mySalomeConnector->featureInfo(aFeatureKind.c_str())->isAutoPreview();
592 #else
593   AppElements_MainMenu* aMenuBar = mainWindow()->menuObject();
594   AppElements_Command* aCommand = aMenuBar->feature(aFeatureKind.c_str());
595   bool anIsAutoPreview = true;
596   if (aCommand)
597     anIsAutoPreview = aCommand->featureMessage()->isAutoPreview();
598   else {
599     std::string aXmlCfg, aDescription;
600     module()->getXMLRepresentation(aFeatureKind, aXmlCfg, aDescription);
601     ModuleBase_WidgetFactory aFactory(aXmlCfg, moduleConnector());
602     anIsAutoPreview = aFactory.widgetAPI()->getBooleanAttribute(FEATURE_AUTO_PREVIEW, true);
603   }
604 #endif
605   if (!anIsAutoPreview) {
606     myPropertyPanel->findButton(PROP_PANEL_PREVIEW)->setVisible(true);
607     // send signal about preview should not be computed automatically, click on preview
608     // button should initiate it
609     std::shared_ptr<Events_Message> aMsg = std::shared_ptr<Events_Message>(
610                   new Events_Message(Events_Loop::eventByName(EVENT_PREVIEW_BLOCKED)));
611     Events_Loop::loop()->send(aMsg);
612   }
613   myPropertyPanel->setModelWidgets(aWidgets);
614   aFOperation->setPropertyPanel(myPropertyPanel);
615
616   myModule->propertyPanelDefined(theOperation);
617
618 #ifndef DEBUG_FEATURE_NAME
619   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
620 #else
621   std::string aFeatureName = aFeature->name();
622   myPropertyPanel->setWindowTitle(QString("%1: %2")
623     .arg(theOperation->getDescription()->description())
624     .arg(aFeatureName.c_str()));
625 #endif
626
627   myErrorMgr->setPropertyPanel(myPropertyPanel);
628 }
629
630 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
631 {
632   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
633   if (aPropertyPanel) {
634     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
635     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
636        myModule->connectToPropertyPanel(aWidget, isToConnect);
637        if (isToConnect) {
638         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
639         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
640         connect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
641        }
642       else {
643         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
644         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChanged()));
645         disconnect(aWidget, SIGNAL(objectUpdated()), this, SLOT(onWidgetObjectUpdated()));
646       }
647     }
648   }
649 }
650
651 //******************************************************
652 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
653 {
654   setGrantedFeatures(theOperation);
655
656   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
657     fillPropertyPanel(theOperation);
658     connectToPropertyPanel(true);
659   }
660   updateCommandStatus();
661
662   myModule->operationResumed(theOperation);
663 }
664
665
666 //******************************************************
667 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
668 {
669   updateCommandStatus();
670
671   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
672                                                                         (theOperation);
673   if (!aFOperation)
674     return;
675
676   ModuleBase_ISelection* aSel = mySelector->selection();
677   QObjectPtrList aObj = aSel->selectedPresentations();
678   //!< No need for property panel
679   hidePropertyPanel();
680   myPropertyPanel->cleanContent();
681
682   connectToPropertyPanel(false);
683   myModule->operationStopped(aFOperation);
684
685   // the deactivated objects of the current operation should be activated back.
686   // They were deactivated on operation start or an object redisplay
687   QObjectPtrList anObjects;
688   FeaturePtr aFeature = aFOperation->feature();
689   if (aFeature.get()) { // feature may be not created (plugin load fail)
690     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
691       anObjects.append(aFeature);
692     std::list<ResultPtr> aResults;
693     ModelAPI_Tools::allResults(aFeature, aResults);
694     std::list<ResultPtr>::const_iterator aIt;
695     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
696       ResultPtr anObject = *aIt;
697       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
698         anObjects.append(anObject);
699       }
700     }
701   }
702   activateObjectsSelection(anObjects);
703 }
704
705
706 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
707 {
708   myModule->operationCommitted(theOperation);
709 }
710
711 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
712 {
713   myModule->operationAborted(theOperation);
714 }
715
716 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
717 {
718   ModuleBase_OperationFeature* aFOperation =
719     dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
720   if (!aFOperation)
721     return;
722
723   QStringList aGrantedIds;
724   if (isSalomeMode()) {
725     const std::shared_ptr<Config_FeatureMessage>& anInfo =
726                          mySalomeConnector->featureInfo(theOperation->id());
727     if (anInfo.get())
728       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
729                                    .split(" ", QString::SkipEmptyParts);
730   }
731   else
732     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
733
734   ModuleBase_IModule* aModule = module();
735   if (aModule)
736     aModule->grantedOperationIds(theOperation, aGrantedIds);
737
738   aFOperation->setGrantedOperationIds(aGrantedIds);
739 }
740
741 //******************************************************
742 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
743 {
744   QApplication::restoreOverrideCursor();
745   SessionPtr aMgr = ModelAPI_Session::get();
746
747   std::list<DocumentPtr> aDocList = aMgr->allOpenedDocuments();
748   std::list<DocumentPtr>::const_iterator aIt;
749   for (aIt = aDocList.cbegin(); aIt != aDocList.cend(); aIt++) {
750     std::list<bool> aState = myObjectBrowser->getStateForDoc(*aIt);
751     (*aIt)->storeNodesState(aState);
752   }
753
754   aMgr->save(theName.toLatin1().constData(), theFileNames);
755
756   QApplication::restoreOverrideCursor();
757 }
758
759 //******************************************************
760 bool XGUI_Workshop::abortAllOperations()
761 {
762   return myOperationMgr->abortAllOperations();
763 }
764
765 //******************************************************
766 void XGUI_Workshop::operationStarted(ModuleBase_Operation* theOperation)
767 {
768   setGrantedFeatures(theOperation);
769   if (!theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
770     updateCommandStatus();
771   }
772   else {
773     myModule->operationStarted(theOperation);
774   }
775 }
776
777 //******************************************************
778 void XGUI_Workshop::onOpen()
779 {
780   if(!abortAllOperations())
781     return;
782   //save current file before close if modified
783   SessionPtr aSession = ModelAPI_Session::get();
784   if (aSession->isModified()) {
785     //TODO(sbh): re-launch the app?
786     int anAnswer = QMessageBox::question(
787         desktop(), tr("Save current file"),
788         tr("The document is modified, save before opening another?"),
789         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
790     if (anAnswer == QMessageBox::Save) {
791       onSave();
792     } else if (anAnswer == QMessageBox::Cancel) {
793       return;
794     }
795     myCurrentDir = "";
796   }
797
798   //show file dialog, check if readable and open
799   QString aDirectory = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
800   openDirectory(aDirectory);
801 }
802
803 //******************************************************
804 void XGUI_Workshop::openDirectory(const QString& theDirectory)
805 {
806   myCurrentDir = theDirectory;
807   if (myCurrentDir.isEmpty())
808     return;
809
810   QFileInfo aFileInfo(myCurrentDir);
811   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
812     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
813     myCurrentDir = "";
814     return;
815   }
816
817   QApplication::setOverrideCursor(Qt::WaitCursor);
818   module()->closeDocument();
819   SessionPtr aSession = ModelAPI_Session::get();
820   aSession->closeAll();
821   aSession->load(myCurrentDir.toLatin1().constData());
822   myObjectBrowser->rebuildDataTree();
823
824   // Open first level of data tree
825   DocumentPtr aRootDoc = aSession->moduleDocument();
826   std::list<bool> aStates;
827   aRootDoc->restoreNodesState(aStates);
828   myObjectBrowser->setStateForDoc(aRootDoc, aStates);
829
830   updateCommandStatus();
831 #ifndef HAVE_SALOME
832   myMainWindow->setCurrentDir(myCurrentDir, true);
833 #endif
834   QApplication::restoreOverrideCursor();
835 }
836
837 //******************************************************
838 void XGUI_Workshop::onNew()
839 {
840   QApplication::setOverrideCursor(Qt::WaitCursor);
841   if (objectBrowser() == 0) {
842     createDockWidgets();
843     mySelector->connectViewers();
844   }
845   myViewerProxy->connectToViewer();
846   showObjectBrowser();
847 #ifndef HAVE_SALOME
848   myMainWindow->showPythonConsole();
849   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
850   aWnd->showMaximized();
851   updateCommandStatus();
852 #endif
853   myContextMenuMgr->connectViewer();
854   QApplication::restoreOverrideCursor();
855 }
856
857 #ifndef HAVE_SALOME
858 //******************************************************
859 void XGUI_Workshop::onExit()
860 {
861   SessionPtr aMgr = ModelAPI_Session::get();
862   if (aMgr->isModified()) {
863     int anAnswer = QMessageBox::question(
864         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
865         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
866     if (anAnswer == QMessageBox::Save) {
867       bool saved = onSave();
868       if (!saved) {
869         return;
870       }
871     } else if (anAnswer == QMessageBox::Cancel) {
872       return;
873     }
874   }
875   qApp->exit();
876 }
877
878 //******************************************************
879 void XGUI_Workshop::onPreferences()
880 {
881   ModuleBase_Prefs aModif;
882   ModuleBase_Preferences::editPreferences(aModif);
883   if (aModif.size() > 0) {
884     QString aSection;
885     foreach (ModuleBase_Pref aPref, aModif)
886     {
887       aSection = aPref.first;
888       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
889         myMainWindow->viewer()->updateFromResources();
890       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
891         myMainWindow->menuObject()->updateFromResources();
892       }
893     }
894     displayer()->redisplayObjects();
895   }
896 }
897 #endif
898
899 //******************************************************
900 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
901 {
902   XGUI_Displayer* aDisplayer = displayer();
903   if (aDisplayer)
904     aDisplayer->displayTrihedron(theState);
905 }
906
907 //******************************************************
908 bool XGUI_Workshop::onSave()
909 {
910   if(!abortAllOperations())
911     return false;
912   if (myCurrentDir.isEmpty()) {
913     return onSaveAs();
914   }
915   std::list<std::string> aFiles;
916   saveDocument(myCurrentDir, aFiles);
917   updateCommandStatus();
918 #ifndef HAVE_SALOME
919     myMainWindow->setModifiedState(false);
920 #endif
921   return true;
922 }
923
924 //******************************************************
925 bool XGUI_Workshop::onSaveAs()
926 {
927   if(!abortAllOperations())
928     return false;
929   QFileDialog dialog(desktop());
930   dialog.setWindowTitle(tr("Select directory to save files..."));
931   dialog.setFileMode(QFileDialog::Directory);
932   dialog.setFilter(QDir::AllDirs);
933   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
934   dialog.setViewMode(QFileDialog::Detail);
935
936   if (!dialog.exec()) {
937     return false;
938   }
939
940   QString aTempDir = dialog.selectedFiles().first();
941   QDir aDir(aTempDir);
942   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
943     int answer = QMessageBox::question(
944         desktop(),
945         // Title of the dialog which asks user if he wants to save study
946         // in existing non-empty folder
947         tr("Save"),
948         tr("The directory already contains some files, save anyway?"),
949         QMessageBox::Save | QMessageBox::Cancel);
950     if (answer == QMessageBox::Cancel) {
951       return false;
952     }
953   }
954   myCurrentDir = aTempDir;
955 #ifndef HAVE_SALOME
956     myMainWindow->setCurrentDir(myCurrentDir, false);
957     myMainWindow->setModifiedState(false);
958 #endif
959   return onSave();
960 }
961
962 //******************************************************
963 void XGUI_Workshop::onUndo(int theTimes)
964 {
965   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
966   SessionPtr aMgr = ModelAPI_Session::get();
967   std::list<std::string> aUndoList = aMgr->undoList();
968   if (aMgr->isOperation()) {
969     /// this is important for nested operations
970     /// when sketch operation is active, this condition is false and
971     /// the sketch operation is not aborted
972     operationMgr()->onAbortOperation();
973   }
974   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
975   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
976     aMgr->undo();
977     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
978       myObjectBrowser->rebuildDataTree();
979   }
980
981   operationMgr()->updateApplyOfOperations();
982   updateCommandStatus();
983 }
984
985 //******************************************************
986 void XGUI_Workshop::onRedo(int theTimes)
987 {
988   // the viewer update should be blocked in order to avoid the features blinking. For the created
989   // feature a results are created, the flush of the created signal caused the viewer redisplay for
990   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked
991   // until redo of all possible objects happens
992   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
993
994   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
995   SessionPtr aMgr = ModelAPI_Session::get();
996   std::list<std::string> aRedoList = aMgr->redoList();
997   if (aMgr->isOperation()) {
998     /// this is important for nested operations
999     /// when sketch operation is active, this condition is false and
1000     /// the sketch operation is not aborted
1001     operationMgr()->onAbortOperation();
1002   }
1003   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
1004   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
1005     aMgr->redo();
1006     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
1007       myObjectBrowser->rebuildDataTree();
1008   }
1009   operationMgr()->updateApplyOfOperations();
1010   updateCommandStatus();
1011
1012   // unblock the viewer update functionality and make update on purpose
1013   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1014   myDisplayer->updateViewer();
1015 }
1016
1017 //******************************************************
1018 //void XGUI_Workshop::onRebuild()
1019 //{
1020 //  SessionPtr aMgr = ModelAPI_Session::get();
1021 //  bool aWasOperation = aMgr->isOperation(); // keep this value
1022 //  if (!aWasOperation) {
1023 //    aMgr->startOperation("Rebuild");
1024 //  }
1025 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1026 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1027 //    new Events_Message(aRebuildEvent, this)));
1028 //  if (!aWasOperation) {
1029 //    aMgr->finishOperation();
1030 //  }
1031 //  updateCommandStatus();
1032 //}
1033
1034 //******************************************************
1035 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
1036 {
1037   ModuleBase_ModelWidget* anActiveWidget = 0;
1038   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1039   if (anOperation) {
1040     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1041     if (aPanel)
1042       anActiveWidget = aPanel->activeWidget();
1043   }
1044   if (anActiveWidget)
1045     operationMgr()->onValidateOperation();
1046
1047   myModule->widgetStateChanged(thePreviousState);
1048 }
1049
1050 //******************************************************
1051 void XGUI_Workshop::onValuesChanged()
1052 {
1053   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
1054   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
1055     return;
1056
1057   ModuleBase_ModelWidget* anActiveWidget = 0;
1058   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1059   if (anOperation) {
1060     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1061     if (aPanel)
1062       anActiveWidget = aPanel->activeWidget();
1063   }
1064   if (anActiveWidget) {
1065     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
1066                                                                            (anActiveWidget);
1067     if (aWidgetValidated)
1068       aWidgetValidated->clearValidatedCash();
1069   }
1070 }
1071
1072 void XGUI_Workshop::onWidgetObjectUpdated()
1073 {
1074   operationMgr()->onValidateOperation();
1075 }
1076
1077 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1078 {
1079   QString libName = QString::fromStdString(library(theModule.toStdString()));
1080   if (libName.isEmpty()) {
1081     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1082     return 0;
1083   }
1084
1085   QString err;
1086   CREATE_FUNC crtInst = 0;
1087
1088 #ifdef WIN32
1089   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1090   if (!modLib) {
1091     LPVOID lpMsgBuf;
1092     ::FormatMessage(
1093         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1094         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1095     QString aMsg((char*) &lpMsgBuf);
1096     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1097     ::LocalFree(lpMsgBuf);
1098   } else {
1099     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1100     if (!crtInst) {
1101       LPVOID lpMsgBuf;
1102       ::FormatMessage(
1103           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1104               | FORMAT_MESSAGE_IGNORE_INSERTS,
1105           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1106       QString aMsg((char*) &lpMsgBuf);
1107       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1108       ::LocalFree(lpMsgBuf);
1109     }
1110   }
1111 #else
1112   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1113   if ( !modLib ) {
1114     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1115   } else {
1116     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1117     if ( !crtInst ) {
1118       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1119     }
1120   }
1121 #endif
1122
1123   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1124
1125   if (!err.isEmpty()) {
1126     if (desktop()) {
1127       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1128     } else {
1129       qWarning(qPrintable(err));
1130     }
1131   }
1132   return aModule;
1133 }
1134
1135 //******************************************************
1136 bool XGUI_Workshop::createModule()
1137 {
1138   Config_ModuleReader aModuleReader;
1139   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1140   myModule = loadModule(moduleName);
1141   if (!myModule)
1142     return false;
1143
1144   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1145   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1146   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1147   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1148
1149   myModule->createFeatures();
1150 #ifdef HAVE_SALOME
1151   salomeConnector()->createFeatureActions();
1152 #endif
1153   //myActionsMgr->update();
1154   return true;
1155 }
1156
1157 //******************************************************
1158 void XGUI_Workshop::updateCommandStatus()
1159 {
1160   QList<QAction*> aCommands;
1161 #ifdef HAVE_SALOME
1162     aCommands = salomeConnector()->commandList();
1163 #else
1164     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1165     foreach (AppElements_Command* aCmd, aMenuBar->features())
1166       aCommands.append(aCmd);
1167 #endif
1168   SessionPtr aMgr = ModelAPI_Session::get();
1169   if (aMgr->hasModuleDocument()) {
1170     foreach(QAction* aCmd, aCommands) {
1171       QString aId = aCmd->data().toString();
1172       if (aId == "UNDO_CMD")
1173         aCmd->setEnabled(myModule->canUndo());
1174       else if (aId == "REDO_CMD")
1175         aCmd->setEnabled(myModule->canRedo());
1176       else
1177         // Enable all commands
1178         aCmd->setEnabled(true);
1179     }
1180     updateHistory();
1181   } else {
1182     foreach(QAction* aCmd, aCommands) {
1183       QString aId = aCmd->data().toString();
1184       if (aId == "NEW_CMD")
1185         aCmd->setEnabled(true);
1186       else if (aId == "EXIT_CMD")
1187         aCmd->setEnabled(true);
1188       else
1189         aCmd->setEnabled(false);
1190     }
1191   }
1192   myActionsMgr->updateCommandsStatus();
1193   emit commandStatusUpdated();
1194 }
1195
1196 void XGUI_Workshop::updateHistory()
1197 {
1198   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1199   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1200   emit updateUndoHistory(aUndoRes);
1201
1202   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1203   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1204   emit updateRedoHistory(aRedoRes);
1205 }
1206
1207 //******************************************************
1208 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1209 {
1210   QDockWidget* aObjDock = new QDockWidget(theParent);
1211   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea |
1212                             Qt::RightDockWidgetArea |
1213                             Qt::BottomDockWidgetArea);
1214   aObjDock->setWindowTitle(tr("Object browser"));
1215   aObjDock->setStyleSheet(
1216       "::title { position: relative; padding-left: 5px; text-align: left center }");
1217   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1218   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1219   myModule->customizeObjectBrowser(myObjectBrowser);
1220   aObjDock->setWidget(myObjectBrowser);
1221
1222   myContextMenuMgr->connectObjectBrowser();
1223   return aObjDock;
1224 }
1225
1226 //******************************************************
1227 /*
1228  * Creates dock widgets, places them in corresponding area
1229  * and tabifies if necessary.
1230  */
1231 void XGUI_Workshop::createDockWidgets()
1232 {
1233   QMainWindow* aDesktop = desktop();
1234   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1235   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1236   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1237   myPropertyPanel->setupActions(myActionsMgr);
1238   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea |
1239                                    Qt::RightDockWidgetArea |
1240                                    Qt::BottomDockWidgetArea);
1241   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1242   hidePropertyPanel();  ///<! Invisible by default
1243   hideObjectBrowser();
1244   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1245   myPropertyPanel->installEventFilter(myOperationMgr);
1246
1247   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1248   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1249
1250   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1251   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1252
1253   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1254   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1255
1256   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1257           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1258   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1259           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1260 }
1261
1262 //******************************************************
1263 void XGUI_Workshop::showPropertyPanel()
1264 {
1265   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1266   ///<! Restore ability to close panel from the window's menu
1267   aViewAct->setEnabled(true);
1268   myPropertyPanel->show();
1269   myPropertyPanel->raise();
1270
1271   // The next code is necessary to made the property panel the active window
1272   // in order to operation manager could process key events of the panel.
1273   // otherwise they are ignored. It happens only if the same(activateWindow) is
1274   // not happened by property panel activation(e.g. resume operation of Sketch)
1275   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1276   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1277 }
1278
1279 //******************************************************
1280 void XGUI_Workshop::hidePropertyPanel()
1281 {
1282   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1283   ///<! Do not allow to show empty property panel
1284   aViewAct->setEnabled(false);
1285   myPropertyPanel->hide();
1286
1287   // the property panel is active window of the desktop, when it is
1288   // hidden, it is undefined which window becomes active. By this reason
1289   // it is defined to perform the desktop as the active window.
1290   // in SALOME mode, workstack made the PyConsole the active window,
1291   // set the focus on it. As a result, shortcuts of the application, like
1292   // are processed by this console. For example Undo actions.
1293   // It is possible that this code is to be moved to SHAPER package
1294   QMainWindow* aDesktop = desktop();
1295   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1296   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1297 }
1298
1299 //******************************************************
1300 void XGUI_Workshop::showObjectBrowser()
1301 {
1302   if (!isSalomeMode())
1303     myObjectBrowser->parentWidget()->show();
1304 }
1305
1306 //******************************************************
1307 void XGUI_Workshop::hideObjectBrowser()
1308 {
1309   if (!isSalomeMode())
1310     myObjectBrowser->parentWidget()->hide();
1311 }
1312
1313 //******************************************************
1314 void XGUI_Workshop::salomeViewerSelectionChanged()
1315 {
1316   emit salomeViewerSelection();
1317 }
1318
1319 //**************************************************************
1320 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1321 {
1322   return mySalomeConnector->viewer();
1323 }
1324
1325 //**************************************************************
1326 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1327 {
1328   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1329   if (theId == "DELETE_CMD")
1330     deleteObjects();
1331   else if (theId == "CLEAN_HISTORY_CMD")
1332     cleanHistory();
1333   else if (theId == "MOVE_CMD")
1334     moveObjects();
1335   else if (theId == "COLOR_CMD")
1336     changeColor(aObjects);
1337   else if (theId == "DEFLECTION_CMD")
1338     changeDeflection(aObjects);
1339   else if (theId == "SHOW_CMD") {
1340     showObjects(aObjects, true);
1341     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1342     updateCommandStatus();
1343   }
1344   else if (theId == "HIDE_CMD") {
1345     showObjects(aObjects, false);
1346     updateCommandStatus();
1347   }
1348   else if (theId == "SHOW_ONLY_CMD") {
1349     showOnlyObjects(aObjects);
1350     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1351     updateCommandStatus();
1352   }
1353   else if (theId == "SHADING_CMD")
1354     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1355   else if (theId == "WIREFRAME_CMD")
1356     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1357   else if (theId == "HIDEALL_CMD") {
1358     QObjectPtrList aList = myDisplayer->displayedObjects();
1359     foreach (ObjectPtr aObj, aList) {
1360       if (module()->canEraseObject(aObj))
1361         aObj->setDisplayed(false);
1362     }
1363     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1364     updateCommandStatus();
1365   } else if (theId == "SELECT_VERTEX_CMD") {
1366     setViewerSelectionMode(TopAbs_VERTEX);
1367   } else if (theId == "SELECT_EDGE_CMD") {
1368     setViewerSelectionMode(TopAbs_EDGE);
1369   } else if (theId == "SELECT_FACE_CMD") {
1370     setViewerSelectionMode(TopAbs_FACE);
1371   } else if (theId == "SELECT_RESULT_CMD") {
1372     //setViewerSelectionMode(-1);
1373     //IMP: an attempt to use result selection with other selection modes
1374     setViewerSelectionMode(ModuleBase_ResultPrs::Sel_Result);
1375     setViewerSelectionMode(TopAbs_COMPSOLID);
1376   } else if (theId == "SHOW_RESULTS_CMD") {
1377     highlightResults(aObjects);
1378   } else if (theId == "SHOW_FEATURE_CMD") {
1379     highlightFeature(aObjects);
1380   }
1381 #ifdef TINSPECTOR
1382   else if (theId == "TINSPECTOR_VIEW") {
1383     Handle(CDF_Application) anApplication = CDF_Session::CurrentSession()->CurrentApplication();
1384     if (!anApplication.IsNull())
1385     {
1386       if (!MyTCommunicator)
1387       {
1388         MyTCommunicator = new TInspector_Communicator();
1389
1390         NCollection_List<Handle(Standard_Transient)> aParameters;
1391         aParameters.Append(anApplication);
1392         Handle(AIS_InteractiveContext) aContext = viewer()->AISContext();
1393         if (!aContext.IsNull())
1394           aParameters.Append(aContext);
1395
1396         MyVCallBack = new VInspector_CallBack();
1397         myDisplayer->setCallBack(MyVCallBack);
1398         #ifndef HAVE_SALOME
1399         AppElements_Viewer* aViewer = mainWindow()->viewer();
1400         if (aViewer)
1401           aViewer->setCallBack(MyVCallBack);
1402         #endif
1403         aParameters.Append(MyVCallBack);
1404
1405         MyTCommunicator->registerPlugin("SMBrowser"); // custom plugin to view ModelAPI
1406
1407         MyTCommunicator->init(aParameters);
1408         MyTCommunicator->Activate("SMBrowser"); // to have button in TInspector
1409         MyTCommunicator->Activate("TKVInspector"); // to have filled callback by model
1410         MyTCommunicator->Activate("TKDFBrowser");
1411       }
1412       MyTCommunicator->setVisible(true);
1413     }
1414   }
1415 #endif
1416 }
1417
1418 //**************************************************************
1419 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1420 {
1421   if (theMode == -1)
1422     myViewerSelMode.clear();
1423   else {
1424     if (myViewerSelMode.contains(theMode))
1425       myViewerSelMode.removeAll(theMode);
1426     else
1427       myViewerSelMode.append(theMode);
1428   }
1429   activateObjectsSelection(myDisplayer->displayedObjects());
1430 }
1431
1432 //**************************************************************
1433 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1434 {
1435   QIntList aModes;
1436   module()->activeSelectionModes(aModes);
1437   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1438     aModes.append(myViewerSelMode);
1439   myDisplayer->activateObjects(aModes, theList);
1440 }
1441
1442 //**************************************************************
1443 void XGUI_Workshop::deleteObjects()
1444 {
1445   ModuleBase_IModule* aModule = module();
1446   // allow the module to delete objects, do nothing if it has succeed
1447   if (aModule->deleteObjects()) {
1448     updateCommandStatus();
1449     return;
1450   }
1451
1452   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1453   if (!abortAllOperations())
1454     return;
1455
1456   bool hasResult = false;
1457   bool hasFeature = false;
1458   bool hasParameter = false;
1459   bool hasCompositeOwner = false;
1460   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1461   if (!(hasFeature || hasParameter))
1462     return;
1463
1464   // delete objects
1465   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1466   std::set<FeaturePtr> aFeatures;
1467   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1468   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1469
1470   bool aDone = false;
1471   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1472   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1473   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1474
1475   operationMgr()->startOperation(anOpAction);
1476
1477   std::set<FeaturePtr> aFeatureRefsToDelete;
1478   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1479     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1480     // It is necessary to clear selection in order to avoid selection changed event during
1481     // deletion and negative consequences connected with processing of already deleted items
1482     mySelector->clearSelection();
1483
1484     if (!aFeatureRefsToDelete.empty())
1485       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1486     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1487   }
1488   if (aDone)
1489     operationMgr()->commitOperation();
1490   else
1491     operationMgr()->abortOperation(operationMgr()->currentOperation());
1492 }
1493
1494 //**************************************************************
1495 void addRefsToFeature(const FeaturePtr& theFeature,
1496                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1497                       std::set<FeaturePtr>& theReferences)
1498 {
1499   //if (theReferences.find(theFeature) != theReferences.end())
1500   //  return;
1501   if (theMainList.find(theFeature) == theMainList.end())
1502     return; // this feature is not in the selection list, so exists without references to it
1503   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1504
1505   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1506                                        aLast = aMainReferences.end();
1507   for (; anIt != aLast; anIt++) {
1508     FeaturePtr aRefFeature = *anIt;
1509     if (theReferences.find(aRefFeature) == theReferences.end())
1510       theReferences.insert(aRefFeature);
1511     addRefsToFeature(aRefFeature, theMainList, theReferences);
1512   }
1513 }
1514
1515 //**************************************************************
1516 void XGUI_Workshop::cleanHistory()
1517 {
1518   if (!abortAllOperations())
1519     return;
1520
1521   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1522   std::set<FeaturePtr> aFeatures;
1523   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1524
1525 #ifdef DEBUG_CLEAN_HISTORY
1526   QStringList anInfo;
1527   std::set<FeaturePtr>::const_iterator aFIt;
1528   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1529     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1530     anInfo.append(aFeature->name().c_str());
1531   }
1532   QString anInfoStr = anInfo.join(";\t");
1533   qDebug(QString("cleanHistory for: [%1] - %2").
1534     arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1535 #endif
1536
1537   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1538   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1539   // find for each object whether all reference values are in the map as key, that means that there
1540   // is no other reference in the model to this object, so it might be removed by cleaning history
1541   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1542   // ext_1(bool_1, sk_3)  - cann't be deleted, dependency to bool_1
1543   // vertex_1()
1544   // sk_2(ext_2) + (bool_1)  - cann't be deleted, dependency to bool_1
1545   // ext_2(bool_1)  - cann't be deleted, dependency to bool_1
1546   // sk_3()
1547   // Information: bool_1 is not selected
1548   std::set<FeaturePtr> anUnusedObjects;
1549   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1550                                                               aMainLast = aReferences.end();
1551   for (; aMainIt != aMainLast; aMainIt++) {
1552     FeaturePtr aMainListFeature = aMainIt->first;
1553     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1554     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(),
1555                                                   aRefLast = aMainRefList.end();
1556     bool aFeatureOutOfTheList = false;
1557     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1558       FeaturePtr aRefFeature = *aRefIt;
1559       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1560     }
1561     if (!aFeatureOutOfTheList)
1562       anUnusedObjects.insert(aMainListFeature);
1563   }
1564
1565 #ifdef DEBUG_CLEAN_HISTORY
1566   anInfo.clear();
1567   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1568     FeaturePtr aFeature = *aFIt;
1569     anInfo.append(aFeature->name().c_str());
1570   }
1571   qDebug(QString("unused objects: [%1] - %2").
1572     arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1573 #endif
1574
1575   // warn about the references remove, break the delete operation if the user chose it
1576   if (!anUnusedObjects.empty()) {
1577     QStringList aNames;
1578     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1579       aNames.append(aFeature->name().c_str());
1580     }
1581     aNames.sort();
1582     QString anUnusedNames = aNames.join(", ");
1583
1584     QString anActionId = "CLEAN_HISTORY_CMD";
1585     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1586
1587     QMessageBox aMessageBox(desktop());
1588     aMessageBox.setWindowTitle(aDescription);
1589     aMessageBox.setIcon(QMessageBox::Warning);
1590     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1591     aMessageBox.setDefaultButton(QMessageBox::No);
1592
1593     const char* aKeyStr = "Unused features are the following: "
1594                           "%1.\nThese features will be deleted.\nWould you like to continue?";
1595     QString aText = QString(tr(aKeyStr).arg(anUnusedNames));
1596     aMessageBox.setText(aText);
1597     if (aMessageBox.exec() == QMessageBox::No)
1598       return;
1599
1600     // 1. start operation
1601     aDescription += "by deleting of " +
1602       aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1603     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1604     operationMgr()->startOperation(anOpAction);
1605
1606     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1607     // It is necessary to clear selection in order to avoid selection changed event during
1608     // deletion and negative consequences connected with processing of already deleted items
1609     mySelector->clearSelection();
1610
1611     std::set<FeaturePtr> anIgnoredFeatures;
1612     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1613       operationMgr()->commitOperation();
1614     }
1615     else {
1616       operationMgr()->abortOperation(operationMgr()->currentOperation());
1617     }
1618   }
1619   else {
1620     QString anActionId = "CLEAN_HISTORY_CMD";
1621     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1622
1623     QMessageBox aMessageBox(desktop());
1624     aMessageBox.setWindowTitle(aDescription);
1625     aMessageBox.setIcon(QMessageBox::Warning);
1626     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1627     aMessageBox.setDefaultButton(QMessageBox::No);
1628
1629     QString aText;
1630     aMessageBox.setStandardButtons(QMessageBox::Ok);
1631     aMessageBox.setDefaultButton(QMessageBox::Ok);
1632
1633     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1634     aMessageBox.setText(aText);
1635
1636     if (aMessageBox.exec() == QMessageBox::No)
1637       return;
1638   }
1639 }
1640
1641 //**************************************************************
1642 void XGUI_Workshop::moveObjects()
1643 {
1644   if (!abortAllOperations())
1645     return;
1646
1647   SessionPtr aMgr = ModelAPI_Session::get();
1648
1649   QString anActionId = "MOVE_CMD";
1650   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1651   aMgr->startOperation(aDescription.toStdString());
1652
1653   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1654   // It is necessary to clear selection in order to avoid selection changed event during
1655   // moving and negative consequences connected with processing of already moved items
1656   mySelector->clearSelection();
1657   // check whether the object can be moved. There should not be parts which are not loaded
1658   std::set<FeaturePtr> aFeatures;
1659   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1660   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1661     return;
1662
1663   DocumentPtr anActiveDocument = aMgr->activeDocument();
1664   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1665   std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1666   for (; anIt != aLast; anIt++) {
1667     FeaturePtr aFeature = *anIt;
1668     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1669       continue;
1670
1671     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1672     aCurrentFeature = anActiveDocument->currentFeature(true);
1673   }
1674   aMgr->finishOperation();
1675 }
1676
1677 //**************************************************************
1678 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1679 {
1680   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1681   std::set<FeaturePtr> aFeatures;
1682   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1683
1684   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1685 }
1686
1687 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1688 {
1689   bool isFoundResultType = false;
1690   foreach(ObjectPtr anObj, theObjects)
1691   {
1692     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1693     if (aResult.get() == NULL)
1694       continue;
1695
1696     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1697     if (isFoundResultType)
1698       break;
1699   }
1700   return isFoundResultType;
1701 }
1702
1703 //**************************************************************
1704 // Returns the list of all features for theDocument and all features of
1705 // all nested parts.
1706 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1707 {
1708   std::list<FeaturePtr> aResultList;
1709   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1710   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1711     // The order of appending features of the part and the part itself is important
1712
1713     // Append features from a part feature
1714     std::list<ResultPtr> aResults;
1715     ModelAPI_Tools::allResults(aFeature, aResults);
1716     foreach (const ResultPtr& aResult, aResults) {
1717       ResultPartPtr aResultPart =
1718           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1719       if (aResultPart.get() && aResultPart->partDoc().get()) {
1720         // Recursion
1721         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1722         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1723       }
1724     }
1725
1726     aResultList.push_back(aFeature);
1727   }
1728   return aResultList;
1729 }
1730
1731 //**************************************************************
1732 // Returns the list of features placed between theObject and the current feature
1733 // in the same document. Excludes theObject, includes the current feature.
1734 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1735 {
1736   std::list<FeaturePtr> aResult;
1737   DocumentPtr aDocument = theObject->document();
1738   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1739   // find the object iterator
1740   std::list<FeaturePtr>::iterator aObjectIt =
1741     std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1742   if (aObjectIt == anAllFeatures.end())
1743     return aResult;
1744   // find the current feature iterator
1745   std::list<FeaturePtr>::iterator aCurrentIt =
1746     std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1747   if (aCurrentIt == anAllFeatures.end())
1748     return aResult;
1749   // check the right order
1750   if (std::distance(aObjectIt, anAllFeatures.end()) <=
1751       std::distance(aCurrentIt, anAllFeatures.end()))
1752     return aResult;
1753   // exclude the object
1754   std::advance(aObjectIt, 1);
1755   // include the current feature
1756   std::advance(aCurrentIt, 1);
1757   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1758 }
1759
1760 bool XGUI_Workshop::canMoveFeature()
1761 {
1762   QString anActionId = "MOVE_CMD";
1763
1764   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1765   QObjectPtrList aValidatedObjects;
1766   foreach (ObjectPtr aObject, aObjects) {
1767     if (!myModule->canApplyAction(aObject, anActionId))
1768       continue;
1769     // To be moved feature should be in active document
1770     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1771       continue;
1772     aValidatedObjects.append(aObject);
1773   }
1774   if (aValidatedObjects.size() != aObjects.size())
1775     aObjects = aValidatedObjects;
1776
1777   bool aCanMove = !aObjects.empty();
1778
1779   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1780   for (; anIt != aLast && aCanMove; anIt++) {
1781     ObjectPtr aObject = *anIt;
1782     // 1. Get features placed between selected and current in the document
1783     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1784     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1785     if (aFeaturesBetween.empty())
1786       aCanMove = false;
1787     else {
1788       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1789       // 2. Get all reference features to the selected object in the document
1790       std::set<FeaturePtr> aRefFeatures;
1791       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1792
1793       if (aRefFeatures.empty())
1794         continue;
1795       else {
1796         // 3. Find any placed features in all reference features
1797         std::set<FeaturePtr> aIntersectionFeatures;
1798         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1799                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1800                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1801         // 4. Return false if any reference feature is placed before current feature
1802         if (!aIntersectionFeatures.empty())
1803           aCanMove = false;
1804       }
1805     }
1806   }
1807   return aCanMove;
1808 }
1809
1810 //**************************************************************
1811 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1812 {
1813   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1814   if (!aCanBeShaded) {
1815     ResultCompSolidPtr aCompsolidResult =
1816                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1817     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1818       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1819         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1820     }
1821   }
1822   return aCanBeShaded;
1823 }
1824
1825 //**************************************************************
1826 bool XGUI_Workshop::canChangeColor() const
1827 {
1828   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1829
1830   std::set<std::string> aTypes;
1831   aTypes.insert(ModelAPI_ResultGroup::group());
1832   aTypes.insert(ModelAPI_ResultConstruction::group());
1833   aTypes.insert(ModelAPI_ResultBody::group());
1834   aTypes.insert(ModelAPI_ResultPart::group());
1835
1836   return hasResults(aObjects, aTypes);
1837 }
1838
1839 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1840 {
1841   if (!theResult.get())
1842     return;
1843
1844   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1845   if (aColorAttr.get() != NULL) {
1846     if (!aColorAttr->size()) {
1847       aColorAttr->setSize(3);
1848     }
1849     aColorAttr->setValue(0, theColor[0]);
1850     aColorAttr->setValue(1, theColor[1]);
1851     aColorAttr->setValue(2, theColor[2]);
1852   }
1853 }
1854
1855 //**************************************************************
1856 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1857 {
1858
1859   AttributeIntArrayPtr aColorAttr;
1860   // 1. find the current color of the object. This is a color of AIS presentation
1861   // The objects are iterated until a first valid color is found
1862   std::vector<int> aColor;
1863   foreach(ObjectPtr anObject, theObjects) {
1864     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1865     if (aResult.get()) {
1866       XGUI_CustomPrs::getResultColor(aResult, aColor);
1867     }
1868     else {
1869       // TODO: remove the obtaining a color from the AIS object
1870       // this does not happen never because:
1871       // 1. The color can be changed only on results
1872       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1873       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1874       if (anAISObj.get()) {
1875         aColor.resize(3);
1876         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1877       }
1878     }
1879     if (!aColor.empty())
1880       break;
1881   }
1882   if (aColor.size() != 3)
1883     return;
1884
1885   if (!abortAllOperations())
1886   return;
1887   // 2. show the dialog to change the value
1888   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1889   aDlg->setColor(aColor);
1890   aDlg->move(QCursor::pos());
1891   bool isDone = aDlg->exec() == QDialog::Accepted;
1892   if (!isDone)
1893     return;
1894
1895   bool isRandomColor = aDlg->isRandomColor();
1896
1897   // 3. abort the previous operation and start a new one
1898   SessionPtr aMgr = ModelAPI_Session::get();
1899   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1900   aMgr->startOperation(aDescription.toStdString());
1901
1902   // 4. set the value to all results
1903   std::vector<int> aColorResult = aDlg->getColor();
1904   foreach(ObjectPtr anObj, theObjects) {
1905     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1906     if (aResult.get() != NULL) {
1907       ResultCompSolidPtr aCompsolidResult =
1908         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1909       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1910         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1911           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult :
1912                                                                     aDlg->getRandomColor());
1913         }
1914       }
1915       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1916     }
1917   }
1918   aMgr->finishOperation();
1919   updateCommandStatus();
1920 }
1921
1922 //**************************************************************
1923 bool XGUI_Workshop::canChangeDeflection() const
1924 {
1925   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1926
1927   std::set<std::string> aTypes;
1928   aTypes.insert(ModelAPI_ResultGroup::group());
1929   aTypes.insert(ModelAPI_ResultConstruction::group());
1930   aTypes.insert(ModelAPI_ResultBody::group());
1931   aTypes.insert(ModelAPI_ResultPart::group());
1932
1933   return hasResults(aObjects, aTypes);
1934 }
1935
1936 void setDeflection(ResultPtr theResult, const double theDeflection)
1937 {
1938   if (!theResult.get())
1939     return;
1940
1941   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1942   if (aDeflectionAttr.get() != NULL)
1943     aDeflectionAttr->setValue(theDeflection);
1944 }
1945
1946
1947 //**************************************************************
1948 void XGUI_Workshop::changeDeflection(const QObjectPtrList& theObjects)
1949 {
1950   AttributeDoublePtr aDoubleAttr;
1951   // 1. find the current color of the object. This is a color of AIS presentation
1952   // The objects are iterated until a first valid color is found
1953   double aDeflection = -1;
1954   foreach(ObjectPtr anObject, theObjects) {
1955     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1956     if (aResult.get()) {
1957       aDeflection = XGUI_CustomPrs::getResultDeflection(aResult);
1958     }
1959     else {
1960       // TODO: remove the obtaining a color from the AIS object
1961       // this does not happen never because:
1962       // 1. The color can be changed only on results
1963       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1964       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1965       if (anAISObj.get()) {
1966         aDeflection = anAISObj->getDeflection();
1967       }
1968     }
1969     if (aDeflection > 0)
1970       break;
1971   }
1972   if (aDeflection < 0)
1973     return;
1974
1975   if (!abortAllOperations())
1976   return;
1977   // 2. show the dialog to change the value
1978   XGUI_DeflectionDialog* aDlg = new XGUI_DeflectionDialog(desktop());
1979   aDlg->setDeflection(aDeflection);
1980   aDlg->move(QCursor::pos());
1981   bool isDone = aDlg->exec() == QDialog::Accepted;
1982   if (!isDone)
1983     return;
1984
1985   // 3. abort the previous operation and start a new one
1986   SessionPtr aMgr = ModelAPI_Session::get();
1987   QString aDescription = contextMenuMgr()->action("DEFLECTION_CMD")->text();
1988   aMgr->startOperation(aDescription.toStdString());
1989
1990   // 4. set the value to all results
1991   aDeflection = aDlg->getDeflection();
1992   foreach(ObjectPtr anObj, theObjects) {
1993     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1994     if (aResult.get() != NULL) {
1995       ResultCompSolidPtr aCompsolidResult =
1996         std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1997       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1998         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1999           setDeflection(aCompsolidResult->subResult(i), aDeflection);
2000         }
2001       }
2002       setDeflection(aResult, aDeflection);
2003     }
2004   }
2005   aMgr->finishOperation();
2006   updateCommandStatus();
2007 }
2008
2009 //**************************************************************
2010 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
2011 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
2012   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
2013 }
2014 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
2015 {
2016   foreach (ObjectPtr aObj, theList) {
2017     aObj->setDisplayed(isVisible);
2018   }
2019   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2020 }
2021
2022 //**************************************************************
2023 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
2024 {
2025   // Hide all displayed objects
2026   QObjectPtrList aList = myDisplayer->displayedObjects();
2027   foreach (ObjectPtr aObj, aList) {
2028     if (module()->canEraseObject(aObj))
2029       aObj->setDisplayed(false);
2030   }
2031
2032   // Show only objects from the list
2033   foreach (ObjectPtr aObj, theList) {
2034     aObj->setDisplayed(true);
2035   }
2036   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2037 }
2038
2039
2040 //**************************************************************
2041 void XGUI_Workshop::registerValidators() const
2042 {
2043   SessionPtr aMgr = ModelAPI_Session::get();
2044   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
2045 }
2046
2047 //**************************************************************
2048 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
2049 {
2050   if (!theDoc)
2051     return;
2052   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
2053   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
2054 }
2055
2056 //**************************************************************
2057 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
2058 {
2059   for (int i = 0; i < theDoc->size(theGroup); i++)
2060     theDoc->object(theGroup, i)->setDisplayed(true);
2061     //displayObject(theDoc->object(theGroup, i));
2062   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2063 }
2064
2065 //**************************************************************
2066 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
2067 {
2068   foreach(ObjectPtr aObj, theList) {
2069     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
2070
2071     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
2072     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
2073       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
2074           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
2075                                       (XGUI_Displayer::DisplayMode)theMode, false);
2076       }
2077     }
2078   }
2079   if (theList.size() > 0)
2080     myDisplayer->updateViewer();
2081 }
2082
2083 //**************************************************************
2084 void XGUI_Workshop::closeDocument()
2085 {
2086   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
2087   while (anOperation) {
2088     anOperation->abort();
2089     anOperation = operationMgr()->currentOperation();
2090   }
2091   //myDisplayer->closeLocalContexts();
2092   myDisplayer->eraseAll();
2093   objectBrowser()->clearContent();
2094
2095   module()->closeDocument();
2096
2097   // data model need not process the document's signals about objects modifications as
2098   // the document is closed
2099   //bool isBlocked = objectBrowser()->dataModel()->blockEventsProcessing(true);
2100
2101   SessionPtr aMgr = ModelAPI_Session::get();
2102   aMgr->closeAll();
2103
2104   //objectBrowser()->dataModel()->blockEventsProcessing(isBlocked);
2105 }
2106
2107 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
2108 {
2109   XGUI_HistoryMenu* aMenu = NULL;
2110   if (isSalomeMode()) {
2111     QAction* anAction = qobject_cast<QAction*>(theObject);
2112     if (!anAction)
2113       return;
2114     aMenu = new XGUI_HistoryMenu(anAction);
2115   } else {
2116     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
2117     aMenu = new XGUI_HistoryMenu(aButton);
2118   }
2119   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
2120   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
2121 }
2122
2123 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
2124 {
2125   QList<ActionInfo> aResult;
2126   std::list<std::string>::const_iterator it = theList.cbegin();
2127   for (; it != theList.cend(); it++) {
2128     QString anId = QString::fromStdString(*it);
2129     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
2130     if (isEditing) {
2131       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
2132     }
2133     ActionInfo anInfo;
2134     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
2135     if (aContextMenuAct) {
2136       anInfo.initFrom(aContextMenuAct);
2137     } else {
2138       anInfo = myActionsMgr->actionInfoById(anId);
2139     }
2140     if (isEditing) {
2141       anInfo.text = anInfo.text.prepend("Modify ");
2142     }
2143     aResult << anInfo;
2144   }
2145   return aResult;
2146 }
2147
2148 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
2149 {
2150 #ifdef HAVE_SALOME
2151   salomeConnector()->putInfo(theMessage, -1);
2152 #else
2153   myMainWindow->putInfo(theMessage, -1);
2154 #endif
2155 }
2156
2157 void XGUI_Workshop::synchronizeViewer()
2158 {
2159   SessionPtr aMgr = ModelAPI_Session::get();
2160   DocumentPtr aDoc = aMgr->activeDocument();
2161
2162   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2163   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2164   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2165   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2166 }
2167
2168 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc,
2169                                              const std::string& theGroup,
2170                                              bool theUpdateViewer)
2171 {
2172   ObjectPtr aObj;
2173   int aSize = theDoc->size(theGroup);
2174   for (int i = 0; i < aSize; i++) {
2175     aObj = theDoc->object(theGroup, i);
2176     if (aObj->isDisplayed()) {
2177       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2178       // be changed to the object becomes visible when the shape becomes not empty
2179       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2180       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2181         continue;
2182       myDisplayer->display(aObj, false);
2183     }
2184   }
2185   if (theUpdateViewer)
2186     myDisplayer->updateViewer();
2187 }
2188
2189 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2190 {
2191   FeaturePtr aFeature;
2192   QObjectPtrList aSelList = theObjects;
2193   bool aHasHidden = false;
2194   foreach(ObjectPtr aObj, theObjects) {
2195     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2196     if (aFeature.get()) {
2197       std::list<ResultPtr> aResults;
2198       ModelAPI_Tools::allResults(aFeature, aResults);
2199       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2200       for(aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
2201         aHasHidden |= (*aIt)->isConcealed();
2202         aSelList.append(*aIt);
2203       }
2204     }
2205   }
2206   if (aSelList.count() > theObjects.count()) {
2207     // if something was found
2208     bool aBlocked = objectBrowser()->blockSignals(true);
2209     objectBrowser()->setObjectsSelected(aSelList);
2210     objectBrowser()->blockSignals(aBlocked);
2211   }
2212   if (aHasHidden)
2213     QMessageBox::information(desktop(), tr("Find results"),
2214                              tr("Results not found"), QMessageBox::Ok);
2215 }
2216
2217 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2218 {
2219   ResultPtr aResult;
2220   QObjectPtrList aSelList = theObjects;
2221   FeaturePtr aFeature;
2222   foreach(ObjectPtr aObj, theObjects) {
2223     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2224     if (aResult.get()) {
2225       aFeature = ModelAPI_Feature::feature(aResult);
2226       if (aFeature.get()) {
2227         aSelList.append(aFeature);
2228       }
2229     }
2230   }
2231   if (aSelList.count() > theObjects.count()) {
2232     // if something was found
2233     bool aBlocked = objectBrowser()->blockSignals(true);
2234     objectBrowser()->setObjectsSelected(aSelList);
2235     objectBrowser()->blockSignals(aBlocked);
2236   }
2237 }