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