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