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