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