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