Salome HOME
f36f9353eab2fd50b598b8d988e7a64f83255cb9
[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 = aFeature->results();
631     std::list<ResultPtr>::const_iterator aIt;
632     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
633       ResultPtr anObject = *aIt;
634       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
635         anObjects.append(anObject);
636       }
637     }
638   }
639   activateObjectsSelection(anObjects);
640 }
641
642
643 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
644 {
645   myModule->operationCommitted(theOperation);
646 }
647
648 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
649 {
650   myModule->operationAborted(theOperation);
651 }
652
653 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
654 {
655   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
656   if (!aFOperation)
657     return;
658
659   QStringList aGrantedIds;
660   if (isSalomeMode()) {
661     const std::shared_ptr<Config_FeatureMessage>& anInfo =
662                          mySalomeConnector->featureInfo(theOperation->id());
663     if (anInfo.get())
664       aGrantedIds = QString::fromStdString(anInfo->nestedFeatures())
665                                    .split(" ", QString::SkipEmptyParts);
666   }
667   else
668     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
669
670   ModuleBase_IModule* aModule = module();
671   if (aModule)
672     aModule->grantedOperationIds(theOperation, aGrantedIds);
673
674   aFOperation->setGrantedOperationIds(aGrantedIds);
675 }
676
677
678 /*
679  * Saves document with given name.
680  */
681 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
682 {
683   QApplication::restoreOverrideCursor();
684   SessionPtr aMgr = ModelAPI_Session::get();
685   aMgr->save(theName.toLatin1().constData(), theFileNames);
686   QApplication::restoreOverrideCursor();
687 }
688
689 bool XGUI_Workshop::abortAllOperations()
690 {
691   return myOperationMgr->abortAllOperations();
692 }
693
694 //******************************************************
695 void XGUI_Workshop::onOpen()
696 {
697   if(!abortAllOperations())
698     return;
699   //save current file before close if modified
700   SessionPtr aSession = ModelAPI_Session::get();
701   if (aSession->isModified()) {
702     //TODO(sbh): re-launch the app?
703     int anAnswer = QMessageBox::question(
704         desktop(), tr("Save current file"),
705         tr("The document is modified, save before opening another?"),
706         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
707     if (anAnswer == QMessageBox::Save) {
708       onSave();
709     } else if (anAnswer == QMessageBox::Cancel) {
710       return;
711     }
712     myCurrentDir = "";
713   }
714
715   //show file dialog, check if readable and open
716   myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
717   if (myCurrentDir.isEmpty())
718     return;
719   QFileInfo aFileInfo(myCurrentDir);
720   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
721     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
722     myCurrentDir = "";
723     return;
724   }
725   QApplication::setOverrideCursor(Qt::WaitCursor);
726   aSession->closeAll();
727   aSession->load(myCurrentDir.toLatin1().constData());
728   myObjectBrowser->rebuildDataTree();
729   updateCommandStatus();
730   QApplication::restoreOverrideCursor();
731 }
732
733 //******************************************************
734 void XGUI_Workshop::onNew()
735 {
736   QApplication::setOverrideCursor(Qt::WaitCursor);
737   if (objectBrowser() == 0) {
738     createDockWidgets();
739     mySelector->connectViewers();
740   }
741   myViewerProxy->connectToViewer();
742   showObjectBrowser();
743 #ifndef HAVE_SALOME
744   myMainWindow->showPythonConsole();
745   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
746   aWnd->showMaximized();
747   updateCommandStatus();
748 #endif
749   myContextMenuMgr->connectViewer();
750   QApplication::restoreOverrideCursor();
751 }
752
753 #ifndef HAVE_SALOME
754 //******************************************************
755 void XGUI_Workshop::onExit()
756 {
757   SessionPtr aMgr = ModelAPI_Session::get();
758   if (aMgr->isModified()) {
759     int anAnswer = QMessageBox::question(
760         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
761         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
762     if (anAnswer == QMessageBox::Save) {
763       bool saved = onSave();
764       if (!saved) {
765         return;
766       }
767     } else if (anAnswer == QMessageBox::Cancel) {
768       return;
769     }
770   }
771   qApp->exit();
772 }
773
774 //******************************************************
775 void XGUI_Workshop::onPreferences()
776 {
777   ModuleBase_Prefs aModif;
778   ModuleBase_Preferences::editPreferences(aModif);
779   if (aModif.size() > 0) {
780     QString aSection;
781     foreach (ModuleBase_Pref aPref, aModif)
782     {
783       aSection = aPref.first;
784       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
785         myMainWindow->viewer()->updateFromResources();
786       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
787         myMainWindow->menuObject()->updateFromResources();
788       }
789     }
790     displayer()->redisplayObjects();
791   }
792 }
793 #endif
794
795 //******************************************************
796 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
797 {
798   XGUI_Displayer* aDisplayer = displayer();
799   if (aDisplayer)
800     aDisplayer->displayTrihedron(theState);
801 }
802
803 //******************************************************
804 bool XGUI_Workshop::onSave()
805 {
806   if(!abortAllOperations())
807     return false;
808   if (myCurrentDir.isEmpty()) {
809     return onSaveAs();
810   }
811   std::list<std::string> aFiles;
812   saveDocument(myCurrentDir, aFiles);
813   updateCommandStatus();
814 #ifndef HAVE_SALOME
815     myMainWindow->setModifiedState(false);
816 #endif
817   return true;
818 }
819
820 //******************************************************
821 bool XGUI_Workshop::onSaveAs()
822 {
823   if(!abortAllOperations())
824     return false;
825   QFileDialog dialog(desktop());
826   dialog.setWindowTitle(tr("Select directory to save files..."));
827   dialog.setFileMode(QFileDialog::Directory);
828   dialog.setFilter(tr("Directories (*)"));
829   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
830   dialog.setViewMode(QFileDialog::Detail);
831
832   if (!dialog.exec()) {
833     return false;
834   }
835
836   QString aTempDir = dialog.selectedFiles().first();
837   QDir aDir(aTempDir);
838   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
839     int answer = QMessageBox::question(
840         desktop(),
841         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
842         tr("Save"),
843         tr("The directory already contains some files, save anyway?"),
844         QMessageBox::Save | QMessageBox::Cancel);
845     if (answer == QMessageBox::Cancel) {
846       return false;
847     }
848   }
849   myCurrentDir = aTempDir;
850 #ifndef HAVE_SALOME
851     myMainWindow->setCurrentDir(myCurrentDir, false);
852     myMainWindow->setModifiedState(false);
853 #endif
854   return onSave();
855 }
856
857 //******************************************************
858 void XGUI_Workshop::onUndo(int theTimes)
859 {
860   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
861   SessionPtr aMgr = ModelAPI_Session::get();
862   std::list<std::string> aUndoList = aMgr->undoList();
863   if (aMgr->isOperation()) {
864     /// this is important for nested operations
865     /// when sketch operation is active, this condition is false and
866     /// the sketch operation is not aborted
867     operationMgr()->onAbortOperation();
868   }
869   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
870   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
871     aMgr->undo();
872     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
873       myObjectBrowser->rebuildDataTree();
874   }
875
876   operationMgr()->updateApplyOfOperations();
877   updateCommandStatus();
878 }
879
880 //******************************************************
881 void XGUI_Workshop::onRedo(int theTimes)
882 {
883   // the viewer update should be blocked in order to avoid the features blinking. For the created
884   // feature a results are created, the flush of the created signal caused the viewer redisplay for
885   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
886   // redo of all possible objects happens
887   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
888
889   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
890   SessionPtr aMgr = ModelAPI_Session::get();
891   std::list<std::string> aRedoList = aMgr->redoList();
892   if (aMgr->isOperation()) {
893     /// this is important for nested operations
894     /// when sketch operation is active, this condition is false and
895     /// the sketch operation is not aborted
896     operationMgr()->onAbortOperation();
897   }
898   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
899   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
900     aMgr->redo();
901     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
902       myObjectBrowser->rebuildDataTree();
903   }
904   operationMgr()->updateApplyOfOperations();
905   updateCommandStatus();
906
907   // unblock the viewer update functionality and make update on purpose
908   myDisplayer->enableUpdateViewer(isUpdateEnabled);
909   myDisplayer->updateViewer();
910 }
911
912 //******************************************************
913 //void XGUI_Workshop::onRebuild()
914 //{
915 //  SessionPtr aMgr = ModelAPI_Session::get();
916 //  bool aWasOperation = aMgr->isOperation(); // keep this value
917 //  if (!aWasOperation) {
918 //    aMgr->startOperation("Rebuild");
919 //  }
920 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
921 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
922 //    new Events_Message(aRebuildEvent, this)));
923 //  if (!aWasOperation) {
924 //    aMgr->finishOperation();
925 //  }
926 //  updateCommandStatus();
927 //}
928
929 //******************************************************
930 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
931 {
932   ModuleBase_ModelWidget* anActiveWidget = 0;
933   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
934   if (anOperation) {
935     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
936     if (aPanel)
937       anActiveWidget = aPanel->activeWidget();
938   }
939   if (anActiveWidget)
940     operationMgr()->onValidateOperation();
941
942   myModule->widgetStateChanged(thePreviousState);
943 }
944
945 //******************************************************
946 void XGUI_Workshop::onValuesChanged()
947 {
948   ModuleBase_ModelWidget* aSenderWidget = (ModuleBase_ModelWidget*)(sender());
949   if (!aSenderWidget || aSenderWidget->canAcceptFocus())
950     return;
951
952   ModuleBase_ModelWidget* anActiveWidget = 0;
953   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
954   if (anOperation) {
955     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
956     if (aPanel)
957       anActiveWidget = aPanel->activeWidget();
958   }
959   if (anActiveWidget) {
960     ModuleBase_WidgetValidated* aWidgetValidated = dynamic_cast<ModuleBase_WidgetValidated*>
961                                                                            (anActiveWidget);
962     if (aWidgetValidated)
963       aWidgetValidated->clearValidatedCash();
964   }
965 }
966
967 void XGUI_Workshop::onWidgetObjectUpdated()
968 {
969   operationMgr()->onValidateOperation();
970 }
971
972 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
973 {
974   QString libName = QString::fromStdString(library(theModule.toStdString()));
975   if (libName.isEmpty()) {
976     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
977     return 0;
978   }
979
980   QString err;
981   CREATE_FUNC crtInst = 0;
982
983 #ifdef WIN32
984   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
985   if (!modLib) {
986     LPVOID lpMsgBuf;
987     ::FormatMessage(
988         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
989         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
990     QString aMsg((char*) &lpMsgBuf);
991     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
992     ::LocalFree(lpMsgBuf);
993   } else {
994     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
995     if (!crtInst) {
996       LPVOID lpMsgBuf;
997       ::FormatMessage(
998           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
999               | FORMAT_MESSAGE_IGNORE_INSERTS,
1000           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1001       QString aMsg((char*) &lpMsgBuf);
1002       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1003       ::LocalFree(lpMsgBuf);
1004     }
1005   }
1006 #else
1007   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1008   if ( !modLib ) {
1009     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1010   } else {
1011     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1012     if ( !crtInst ) {
1013       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1014     }
1015   }
1016 #endif
1017
1018   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1019
1020   if (!err.isEmpty()) {
1021     if (desktop()) {
1022       Events_InfoMessage("XGUI_Workshop", err.toStdString()).send();
1023     } else {
1024       qWarning(qPrintable(err));
1025     }
1026   }
1027   return aModule;
1028 }
1029
1030 //******************************************************
1031 bool XGUI_Workshop::createModule()
1032 {
1033   Config_ModuleReader aModuleReader;
1034   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1035   myModule = loadModule(moduleName);
1036   if (!myModule)
1037     return false;
1038
1039   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1040   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1041   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1042   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1043
1044   myModule->createFeatures();
1045 #ifdef HAVE_SALOME
1046   salomeConnector()->createFeatureActions();
1047 #endif
1048   //myActionsMgr->update();
1049   return true;
1050 }
1051
1052 //******************************************************
1053 void XGUI_Workshop::updateCommandStatus()
1054 {
1055   QList<QAction*> aCommands;
1056 #ifdef HAVE_SALOME
1057     aCommands = salomeConnector()->commandList();
1058 #else
1059     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1060     foreach (AppElements_Command* aCmd, aMenuBar->features())
1061       aCommands.append(aCmd);
1062 #endif
1063   SessionPtr aMgr = ModelAPI_Session::get();
1064   if (aMgr->hasModuleDocument()) {
1065     foreach(QAction* aCmd, aCommands) {
1066       QString aId = aCmd->data().toString();
1067       if (aId == "UNDO_CMD")
1068         aCmd->setEnabled(myModule->canUndo());
1069       else if (aId == "REDO_CMD")
1070         aCmd->setEnabled(myModule->canRedo());
1071       else
1072         // Enable all commands
1073         aCmd->setEnabled(true);
1074     }
1075     updateHistory();
1076   } else {
1077     foreach(QAction* aCmd, aCommands) {
1078       QString aId = aCmd->data().toString();
1079       if (aId == "NEW_CMD")
1080         aCmd->setEnabled(true);
1081       else if (aId == "EXIT_CMD")
1082         aCmd->setEnabled(true);
1083       else
1084         aCmd->setEnabled(false);
1085     }
1086   }
1087   myActionsMgr->updateCommandsStatus();
1088   emit commandStatusUpdated();
1089 }
1090
1091 void XGUI_Workshop::updateHistory()
1092 {
1093   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1094   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1095   emit updateUndoHistory(aUndoRes);
1096
1097   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1098   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1099   emit updateRedoHistory(aRedoRes);
1100 }
1101
1102 //******************************************************
1103 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1104 {
1105   QDockWidget* aObjDock = new QDockWidget(theParent);
1106   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1107   aObjDock->setWindowTitle(tr("Object browser"));
1108   aObjDock->setStyleSheet(
1109       "::title { position: relative; padding-left: 5px; text-align: left center }");
1110   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1111   myObjectBrowser->setXMLReader(myDataModelXMLReader);
1112   myModule->customizeObjectBrowser(myObjectBrowser);
1113   aObjDock->setWidget(myObjectBrowser);
1114
1115   myContextMenuMgr->connectObjectBrowser();
1116   return aObjDock;
1117 }
1118
1119 //******************************************************
1120 /*
1121  * Creates dock widgets, places them in corresponding area
1122  * and tabifies if necessary.
1123  */
1124 void XGUI_Workshop::createDockWidgets()
1125 {
1126   QMainWindow* aDesktop = desktop();
1127   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1128   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1129   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1130   myPropertyPanel->setupActions(myActionsMgr);
1131   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1132   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1133   hidePropertyPanel();  ///<! Invisible by default
1134   hideObjectBrowser();
1135   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1136   myPropertyPanel->installEventFilter(myOperationMgr);
1137
1138   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1139   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1140
1141   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1142   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1143
1144   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1145   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1146
1147   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1148           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1149   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1150           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1151 }
1152
1153 //******************************************************
1154 void XGUI_Workshop::showPropertyPanel()
1155 {
1156   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1157   ///<! Restore ability to close panel from the window's menu
1158   aViewAct->setEnabled(true);
1159   myPropertyPanel->show();
1160   myPropertyPanel->raise();
1161
1162   // The next code is necessary to made the property panel the active window
1163   // in order to operation manager could process key events of the panel.
1164   // otherwise they are ignored. It happens only if the same(activateWindow) is
1165   // not happened by property panel activation(e.g. resume operation of Sketch)
1166   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1167   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1168 }
1169
1170 //******************************************************
1171 void XGUI_Workshop::hidePropertyPanel()
1172 {
1173   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1174   ///<! Do not allow to show empty property panel
1175   aViewAct->setEnabled(false);
1176   myPropertyPanel->hide();
1177
1178   // the property panel is active window of the desktop, when it is
1179   // hidden, it is undefined which window becomes active. By this reason
1180   // it is defined to perform the desktop as the active window.
1181   // in SALOME mode, workstack made the PyConsole the active window,
1182   // set the focus on it. As a result, shortcuts of the application, like
1183   // are processed by this console. For example Undo actions.
1184   // It is possible that this code is to be moved to SHAPER package
1185   QMainWindow* aDesktop = desktop();
1186   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1187   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1188 }
1189
1190 //******************************************************
1191 void XGUI_Workshop::showObjectBrowser()
1192 {
1193   if (!isSalomeMode())
1194     myObjectBrowser->parentWidget()->show();
1195 }
1196
1197 //******************************************************
1198 void XGUI_Workshop::hideObjectBrowser()
1199 {
1200   if (!isSalomeMode())
1201     myObjectBrowser->parentWidget()->hide();
1202 }
1203
1204 //******************************************************
1205 void XGUI_Workshop::salomeViewerSelectionChanged()
1206 {
1207   emit salomeViewerSelection();
1208 }
1209
1210 //**************************************************************
1211 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1212 {
1213   return mySalomeConnector->viewer();
1214 }
1215
1216 //**************************************************************
1217 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1218 {
1219   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1220   if (theId == "DELETE_CMD")
1221     deleteObjects();
1222   else if (theId == "CLEAN_HISTORY_CMD")
1223     cleanHistory();
1224   else if (theId == "MOVE_CMD")
1225     moveObjects();
1226   else if (theId == "COLOR_CMD")
1227     changeColor(aObjects);
1228   else if (theId == "SHOW_CMD") {
1229     showObjects(aObjects, true);
1230     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1231   }
1232   else if (theId == "HIDE_CMD")
1233     showObjects(aObjects, false);
1234   else if (theId == "SHOW_ONLY_CMD") {
1235     showOnlyObjects(aObjects);
1236     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1237   }
1238   else if (theId == "SHADING_CMD")
1239     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1240   else if (theId == "WIREFRAME_CMD")
1241     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1242   else if (theId == "HIDEALL_CMD") {
1243     QObjectPtrList aList = myDisplayer->displayedObjects();
1244     foreach (ObjectPtr aObj, aList) {
1245       if (module()->canEraseObject(aObj))
1246         aObj->setDisplayed(false);
1247     }
1248     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1249   } else if (theId == "SELECT_VERTEX_CMD") {
1250     setViewerSelectionMode(TopAbs_VERTEX);
1251   } else if (theId == "SELECT_EDGE_CMD") {
1252     setViewerSelectionMode(TopAbs_EDGE);
1253   } else if (theId == "SELECT_FACE_CMD") {
1254     setViewerSelectionMode(TopAbs_FACE);
1255   } else if (theId == "SELECT_RESULT_CMD") {
1256     setViewerSelectionMode(-1);
1257   } else if (theId == "SHOW_RESULTS_CMD") {
1258     highlightResults(aObjects);
1259   } else if (theId == "SHOW_FEATURE_CMD") {
1260     highlightFeature(aObjects);
1261   }
1262 }
1263
1264 //**************************************************************
1265 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1266 {
1267   if (theMode == -1)
1268     myViewerSelMode.clear();
1269   else {
1270     if (myViewerSelMode.contains(theMode))
1271       myViewerSelMode.removeAll(theMode);
1272     else
1273       myViewerSelMode.append(theMode);
1274   }
1275   activateObjectsSelection(myDisplayer->displayedObjects());
1276 }
1277
1278 //**************************************************************
1279 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1280 {
1281   QIntList aModes;
1282   module()->activeSelectionModes(aModes);
1283   if (aModes.isEmpty() && (myViewerSelMode.length() > 0))
1284     aModes.append(myViewerSelMode);
1285   myDisplayer->activateObjects(aModes, theList);
1286 }
1287
1288 //**************************************************************
1289 void XGUI_Workshop::deleteObjects()
1290 {
1291   ModuleBase_IModule* aModule = module();
1292   // allow the module to delete objects, do nothing if it has succeed
1293   if (aModule->deleteObjects()) {
1294     updateCommandStatus();
1295     return;
1296   }
1297
1298   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1299   if (!abortAllOperations())
1300     return;
1301
1302   bool hasResult = false;
1303   bool hasFeature = false;
1304   bool hasParameter = false;
1305   bool hasCompositeOwner = false;
1306   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1307   if (!(hasFeature || hasParameter))
1308     return;
1309
1310   // delete objects
1311   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1312   std::set<FeaturePtr> aFeatures;
1313   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1314   ModelAPI_Tools::findAllReferences(aFeatures, aReferences);
1315
1316   bool aDone = false;
1317   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text() + " %1";
1318   aDescription = aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1319   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1320
1321   operationMgr()->startOperation(anOpAction);
1322
1323   std::set<FeaturePtr> aFeatureRefsToDelete;
1324   if (ModuleBase_Tools::askToDelete(aFeatures, aReferences, desktop(), aFeatureRefsToDelete)) {
1325     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1326     // It is necessary to clear selection in order to avoid selection changed event during
1327     // deletion and negative consequences connected with processing of already deleted items
1328     mySelector->clearSelection();
1329
1330     if (!aFeatureRefsToDelete.empty())
1331       aFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1332     aDone = ModelAPI_Tools::removeFeatures(aFeatures, false);
1333   }
1334   if (aDone)
1335     operationMgr()->commitOperation();
1336   else
1337     operationMgr()->abortOperation(operationMgr()->currentOperation());
1338 }
1339
1340 //**************************************************************
1341 void addRefsToFeature(const FeaturePtr& theFeature,
1342                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
1343                       std::set<FeaturePtr>& theReferences)
1344 {
1345   //if (theReferences.find(theFeature) != theReferences.end())
1346   //  return;
1347   if (theMainList.find(theFeature) == theMainList.end())
1348     return; // this feature is not in the selection list, so exists without references to it
1349   std::set<FeaturePtr> aMainReferences = theMainList.at(theFeature);
1350
1351   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
1352                                        aLast = aMainReferences.end();
1353   for (; anIt != aLast; anIt++) {
1354     FeaturePtr aRefFeature = *anIt;
1355     if (theReferences.find(aRefFeature) == theReferences.end())
1356       theReferences.insert(aRefFeature);
1357     addRefsToFeature(aRefFeature, theMainList, theReferences);
1358   }
1359 }
1360
1361 //**************************************************************
1362 void XGUI_Workshop::cleanHistory()
1363 {
1364   if (!abortAllOperations())
1365     return;
1366
1367   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1368   std::set<FeaturePtr> aFeatures;
1369   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1370
1371 #ifdef DEBUG_CLEAN_HISTORY
1372   QStringList anInfo;
1373   std::set<FeaturePtr>::const_iterator aFIt;
1374   for (aFIt = aFeatures.begin(); aFIt != aFeatures.end(); ++aFIt) {
1375     FeaturePtr aFeature = ModelAPI_Feature::feature(*aFIt);
1376     anInfo.append(aFeature->name().c_str());
1377   }
1378   QString anInfoStr = anInfo.join(";\t");
1379   qDebug(QString("cleanHistory for: [%1] - %2").arg(aFeatures.size()).arg(anInfoStr).toStdString().c_str());
1380 #endif
1381
1382   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1383   ModelAPI_Tools::findAllReferences(aFeatures, aReferences, true, false);
1384   // find for each object whether all reference values are in the map as key, that means that there is
1385   // no other reference in the model to this object, so it might be removed by cleaning history
1386   // sk_1(ext_1, vertex_1) + (sk_3, bool_1) - cann't be deleted, dependency to bool_1
1387   // ext_1(bool_1, sk_3)  - cann't be deleted, dependency to bool_1
1388   // vertex_1()
1389   // sk_2(ext_2) + (bool_1)  - cann't be deleted, dependency to bool_1
1390   // ext_2(bool_1)  - cann't be deleted, dependency to bool_1
1391   // sk_3()
1392   // Information: bool_1 is not selected
1393   std::set<FeaturePtr> anUnusedObjects;
1394   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aReferences.begin(),
1395                                                               aMainLast = aReferences.end();
1396   for (; aMainIt != aMainLast; aMainIt++) {
1397     FeaturePtr aMainListFeature = aMainIt->first;
1398     std::set<FeaturePtr> aMainRefList = aMainIt->second;
1399     std::set<FeaturePtr>::const_iterator aRefIt = aMainRefList.begin(), aRefLast = aMainRefList.end();
1400     bool aFeatureOutOfTheList = false;
1401     for (; aRefIt != aRefLast && !aFeatureOutOfTheList; aRefIt++) {
1402       FeaturePtr aRefFeature = *aRefIt;
1403       aFeatureOutOfTheList = aReferences.find(aRefFeature) == aReferences.end();
1404     }
1405     if (!aFeatureOutOfTheList)
1406       anUnusedObjects.insert(aMainListFeature);
1407   }
1408
1409 #ifdef DEBUG_CLEAN_HISTORY
1410   anInfo.clear();
1411   for (aFIt = anUnusedObjects.begin(); aFIt != anUnusedObjects.end(); ++aFIt) {
1412     FeaturePtr aFeature = *aFIt;
1413     anInfo.append(aFeature->name().c_str());
1414   }
1415   qDebug(QString("unused objects: [%1] - %2").arg(anInfo.size()).arg(anInfo.join(";\t")).toStdString().c_str());
1416 #endif
1417
1418   // warn about the references remove, break the delete operation if the user chose it
1419   if (!anUnusedObjects.empty()) {
1420     QStringList aNames;
1421     foreach (const FeaturePtr& aFeature, anUnusedObjects) {
1422       aNames.append(aFeature->name().c_str());
1423     }
1424     aNames.sort();
1425     QString anUnusedNames = aNames.join(", ");
1426
1427     QString anActionId = "CLEAN_HISTORY_CMD";
1428     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1429
1430     QMessageBox aMessageBox(desktop());
1431     aMessageBox.setWindowTitle(aDescription);
1432     aMessageBox.setIcon(QMessageBox::Warning);
1433     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1434     aMessageBox.setDefaultButton(QMessageBox::No);
1435
1436     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1437                    .arg(anUnusedNames));
1438     aMessageBox.setText(aText);
1439     if (aMessageBox.exec() == QMessageBox::No)
1440       return;
1441
1442     // 1. start operation
1443     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1444     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1445     operationMgr()->startOperation(anOpAction);
1446
1447     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1448     // It is necessary to clear selection in order to avoid selection changed event during
1449     // deletion and negative consequences connected with processing of already deleted items
1450     mySelector->clearSelection();
1451
1452     std::set<FeaturePtr> anIgnoredFeatures;
1453     if (ModelAPI_Tools::removeFeatures(anUnusedObjects, true)) {
1454       operationMgr()->commitOperation();
1455     }
1456     else {
1457       operationMgr()->abortOperation(operationMgr()->currentOperation());
1458     }
1459   }
1460   else {
1461     QString anActionId = "CLEAN_HISTORY_CMD";
1462     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1463
1464     QMessageBox aMessageBox(desktop());
1465     aMessageBox.setWindowTitle(aDescription);
1466     aMessageBox.setIcon(QMessageBox::Warning);
1467     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1468     aMessageBox.setDefaultButton(QMessageBox::No);
1469
1470     QString aText;
1471     aMessageBox.setStandardButtons(QMessageBox::Ok);
1472     aMessageBox.setDefaultButton(QMessageBox::Ok);
1473
1474     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1475     aMessageBox.setText(aText);
1476
1477     if (aMessageBox.exec() == QMessageBox::No)
1478       return;
1479   }
1480 }
1481
1482 //**************************************************************
1483 void XGUI_Workshop::moveObjects()
1484 {
1485   if (!abortAllOperations())
1486     return;
1487
1488   SessionPtr aMgr = ModelAPI_Session::get();
1489
1490   QString anActionId = "MOVE_CMD";
1491   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1492   aMgr->startOperation(aDescription.toStdString());
1493
1494   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1495   // It is necessary to clear selection in order to avoid selection changed event during
1496   // moving and negative consequences connected with processing of already moved items
1497   mySelector->clearSelection();
1498   // check whether the object can be moved. There should not be parts which are not loaded
1499   std::set<FeaturePtr> aFeatures;
1500   ModuleBase_Tools::convertToFeatures(anObjects, aFeatures);
1501   if (!XGUI_Tools::canRemoveOrRename(desktop(), aFeatures))
1502     return;
1503
1504   DocumentPtr anActiveDocument = aMgr->activeDocument();
1505   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1506   std::set<FeaturePtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1507   for (; anIt != aLast; anIt++) {
1508     FeaturePtr aFeature = *anIt;
1509     if (!aFeature.get() || !myModule->canApplyAction(aFeature, anActionId))
1510       continue;
1511
1512     anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1513     aCurrentFeature = anActiveDocument->currentFeature(true);
1514   }
1515   aMgr->finishOperation();
1516 }
1517
1518 //**************************************************************
1519 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theObjects)
1520 {
1521   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1522   std::set<FeaturePtr> aFeatures;
1523   ModuleBase_Tools::convertToFeatures(theObjects, aFeatures);
1524
1525   return ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
1526 }
1527
1528 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1529 {
1530   bool isFoundResultType = false;
1531   foreach(ObjectPtr anObj, theObjects)
1532   {
1533     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1534     if (aResult.get() == NULL)
1535       continue;
1536
1537     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1538     if (isFoundResultType)
1539       break;
1540   }
1541   return isFoundResultType;
1542 }
1543
1544 //**************************************************************
1545 // Returns the list of all features for theDocument and all features of
1546 // all nested parts.
1547 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1548 {
1549   std::list<FeaturePtr> aResultList;
1550   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1551   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1552     // The order of appending features of the part and the part itself is important
1553
1554     // Append features from a part feature
1555     foreach (const ResultPtr& aResult, aFeature->results()) {
1556       ResultPartPtr aResultPart =
1557           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1558       if (aResultPart.get() && aResultPart->partDoc().get()) {
1559         // Recursion
1560         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1561         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1562       }
1563     }
1564
1565     aResultList.push_back(aFeature);
1566   }
1567   return aResultList;
1568 }
1569
1570 //**************************************************************
1571 // Returns the list of features placed between theObject and the current feature
1572 // in the same document. Excludes theObject, includes the current feature.
1573 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1574 {
1575   std::list<FeaturePtr> aResult;
1576   DocumentPtr aDocument = theObject->document();
1577   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1578   // find the object iterator
1579   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1580   if (aObjectIt == anAllFeatures.end())
1581     return aResult;
1582   // find the current feature iterator
1583   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1584   if (aCurrentIt == anAllFeatures.end())
1585     return aResult;
1586   // check the right order
1587   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1588     return aResult;
1589   // exclude the object
1590   std::advance(aObjectIt, 1);
1591   // include the current feature
1592   std::advance(aCurrentIt, 1);
1593   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1594 }
1595
1596 bool XGUI_Workshop::canMoveFeature()
1597 {
1598   QString anActionId = "MOVE_CMD";
1599
1600   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1601   QObjectPtrList aValidatedObjects;
1602   foreach (ObjectPtr aObject, aObjects) {
1603     if (!myModule->canApplyAction(aObject, anActionId))
1604       continue;
1605     // To be moved feature should be in active document
1606     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1607       continue;
1608     aValidatedObjects.append(aObject);
1609   }
1610   if (aValidatedObjects.size() != aObjects.size())
1611     aObjects = aValidatedObjects;
1612
1613   bool aCanMove = !aObjects.empty();
1614
1615   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1616   for (; anIt != aLast && aCanMove; anIt++) {
1617     ObjectPtr aObject = *anIt;
1618     // 1. Get features placed between selected and current in the document 
1619     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1620     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1621     if (aFeaturesBetween.empty())
1622       aCanMove = false;
1623     else {
1624       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1625       // 2. Get all reference features to the selected object in the document 
1626       std::set<FeaturePtr> aRefFeatures;
1627       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1628
1629       if (aRefFeatures.empty())
1630         continue;
1631       else {
1632         // 3. Find any placed features in all reference features
1633         std::set<FeaturePtr> aIntersectionFeatures;
1634         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1635                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1636                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1637         // 4. Return false if any reference feature is placed before current feature
1638         if (!aIntersectionFeatures.empty())
1639           aCanMove = false;
1640       }
1641     }
1642   }
1643   return aCanMove;
1644 }
1645
1646 //**************************************************************
1647 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1648 {
1649   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1650   if (!aCanBeShaded) {
1651     ResultCompSolidPtr aCompsolidResult =
1652                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1653     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1654       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1655         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1656     }
1657   }
1658   return aCanBeShaded;
1659 }
1660
1661 //**************************************************************
1662 bool XGUI_Workshop::canChangeColor() const
1663 {
1664   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1665
1666   std::set<std::string> aTypes;
1667   aTypes.insert(ModelAPI_ResultGroup::group());
1668   aTypes.insert(ModelAPI_ResultConstruction::group());
1669   aTypes.insert(ModelAPI_ResultBody::group());
1670   aTypes.insert(ModelAPI_ResultPart::group());
1671
1672   return hasResults(aObjects, aTypes);
1673 }
1674
1675 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1676 {
1677   if (!theResult.get())
1678     return;
1679
1680   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1681   if (aColorAttr.get() != NULL) {
1682     if (!aColorAttr->size()) {
1683       aColorAttr->setSize(3);
1684     }
1685     aColorAttr->setValue(0, theColor[0]);
1686     aColorAttr->setValue(1, theColor[1]);
1687     aColorAttr->setValue(2, theColor[2]);
1688   }
1689 }
1690
1691 //**************************************************************
1692 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1693 {
1694
1695   AttributeIntArrayPtr aColorAttr;
1696   // 1. find the current color of the object. This is a color of AIS presentation
1697   // The objects are iterated until a first valid color is found 
1698   std::vector<int> aColor;
1699   foreach(ObjectPtr anObject, theObjects) {
1700     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1701     if (aResult.get()) {
1702       XGUI_CustomPrs::getResultColor(aResult, aColor);
1703     }
1704     else {
1705       // TODO: remove the obtaining a color from the AIS object
1706       // this does not happen never because:
1707       // 1. The color can be changed only on results
1708       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1709       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1710       if (anAISObj.get()) {
1711         aColor.resize(3);
1712         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1713       }
1714     }
1715     if (!aColor.empty())
1716       break;
1717   }
1718   if (aColor.size() != 3)
1719     return;
1720
1721   if (!abortAllOperations())
1722   return; 
1723   // 2. show the dialog to change the value
1724   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1725   aDlg->setColor(aColor);
1726   aDlg->move(QCursor::pos());
1727   bool isDone = aDlg->exec() == QDialog::Accepted;
1728   if (!isDone)
1729     return;
1730
1731   bool isRandomColor = aDlg->isRandomColor();
1732
1733   // 3. abort the previous operation and start a new one
1734   SessionPtr aMgr = ModelAPI_Session::get();
1735   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1736   aMgr->startOperation(aDescription.toStdString());
1737
1738   // 4. set the value to all results
1739   std::vector<int> aColorResult = aDlg->getColor();
1740   foreach(ObjectPtr anObj, theObjects) {
1741     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1742     if (aResult.get() != NULL) {
1743       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1744       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1745         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1746           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1747         }
1748       }
1749       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1750     }
1751   }
1752   aMgr->finishOperation();
1753   updateCommandStatus();
1754 }
1755
1756 //**************************************************************
1757 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1758 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1759   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1760 }
1761 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1762 {
1763   foreach (ObjectPtr aObj, theList) {
1764     /*
1765     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1766     if (aPartRes) {
1767       DocumentPtr aDoc = aPartRes->partDoc();
1768       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1769       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1770       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1771     } else {
1772     */
1773       aObj->setDisplayed(isVisible);
1774     //}
1775   }
1776   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1777 }
1778
1779 //**************************************************************
1780 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1781 {
1782   // Hide all displayed objects
1783   QObjectPtrList aList = myDisplayer->displayedObjects();
1784   foreach (ObjectPtr aObj, aList) {
1785     if (module()->canEraseObject(aObj))
1786       aObj->setDisplayed(false);
1787   }
1788
1789   // Show only objects from the list
1790   foreach (ObjectPtr aObj, theList) {
1791     /*
1792     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1793     if (aPartRes) {
1794       DocumentPtr aDoc = aPartRes->partDoc();
1795       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1796       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1797       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1798     } else {
1799     */
1800       aObj->setDisplayed(true);
1801     //}
1802   }
1803   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1804
1805 }
1806
1807
1808 //**************************************************************
1809 void XGUI_Workshop::registerValidators() const
1810 {
1811   SessionPtr aMgr = ModelAPI_Session::get();
1812   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1813 }
1814
1815 //**************************************************************
1816 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1817 {
1818   if (!theDoc)
1819     return;
1820   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1821   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1822 }
1823
1824 //**************************************************************
1825 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1826 {
1827   for (int i = 0; i < theDoc->size(theGroup); i++) 
1828     theDoc->object(theGroup, i)->setDisplayed(true);
1829     //displayObject(theDoc->object(theGroup, i));
1830   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1831 }
1832
1833 //**************************************************************
1834 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1835 {
1836   foreach(ObjectPtr aObj, theList) {
1837     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1838
1839     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1840     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1841       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1842           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1843                                       (XGUI_Displayer::DisplayMode)theMode, false);
1844       }
1845     }
1846   }
1847   if (theList.size() > 0)
1848     myDisplayer->updateViewer();
1849 }
1850
1851 //**************************************************************
1852 void XGUI_Workshop::closeDocument()
1853 {
1854   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1855   while (anOperation) {
1856     anOperation->abort();
1857     anOperation = operationMgr()->currentOperation();
1858   }
1859   myDisplayer->closeLocalContexts();
1860   myDisplayer->eraseAll();
1861   objectBrowser()->clearContent();
1862
1863   module()->closeDocument();
1864
1865   SessionPtr aMgr = ModelAPI_Session::get();
1866   aMgr->closeAll();
1867 }
1868
1869 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1870 {
1871   XGUI_HistoryMenu* aMenu = NULL;
1872   if (isSalomeMode()) {
1873     QAction* anAction = qobject_cast<QAction*>(theObject);
1874     if (!anAction)
1875       return;
1876     aMenu = new XGUI_HistoryMenu(anAction);
1877   } else {
1878     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1879     aMenu = new XGUI_HistoryMenu(aButton);
1880   }
1881   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1882   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1883 }
1884
1885 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1886 {
1887   QList<ActionInfo> aResult;
1888   std::list<std::string>::const_iterator it = theList.cbegin();
1889   for (; it != theList.cend(); it++) {
1890     QString anId = QString::fromStdString(*it);
1891     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1892     if (isEditing) {
1893       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1894     }
1895     ActionInfo anInfo;
1896     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1897     if (aContextMenuAct) {
1898       anInfo.initFrom(aContextMenuAct);
1899     } else {
1900       anInfo = myActionsMgr->actionInfoById(anId);
1901     }
1902     if (isEditing) {
1903       anInfo.text = anInfo.text.prepend("Modify ");
1904     }
1905     aResult << anInfo;
1906   }
1907   return aResult;
1908 }
1909
1910 void XGUI_Workshop::setStatusBarMessage(const QString& theMessage)
1911 {
1912 #ifdef HAVE_SALOME
1913   salomeConnector()->putInfo(theMessage, -1);
1914 #else
1915   myMainWindow->putInfo(theMessage, -1);
1916 #endif
1917 }
1918
1919 void XGUI_Workshop::synchronizeViewer()
1920 {
1921   SessionPtr aMgr = ModelAPI_Session::get();
1922   DocumentPtr aDoc = aMgr->activeDocument();
1923
1924   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1925   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1926   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1927   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1928 }
1929
1930 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1931                                              const std::string& theGroup, 
1932                                              bool theUpdateViewer)
1933 {
1934   ObjectPtr aObj;
1935   int aSize = theDoc->size(theGroup);
1936   for (int i = 0; i < aSize; i++) {
1937     aObj = theDoc->object(theGroup, i);
1938     if (aObj->isDisplayed()) {
1939       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
1940       // be changed to the object becomes visible when the shape becomes not empty
1941       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1942       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
1943         continue;
1944       myDisplayer->display(aObj, false);
1945     }
1946   }
1947   if (theUpdateViewer)
1948     myDisplayer->updateViewer();
1949 }
1950
1951 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
1952 {
1953   FeaturePtr aFeature;
1954   QObjectPtrList aSelList = theObjects;
1955   std::list<ResultPtr> aResList;
1956   bool aHasHidden = false;
1957   foreach(ObjectPtr aObj, theObjects) {
1958     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1959     if (aFeature.get()) {
1960       aResList = aFeature->results();
1961       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
1962       for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
1963         aHasHidden |= (*aIt)->isConcealed();
1964         aSelList.append(*aIt);
1965       }
1966     }
1967   }
1968   if (aSelList.count() > theObjects.count()) {
1969     // if something was found
1970     bool aBlocked = objectBrowser()->blockSignals(true);
1971     objectBrowser()->setObjectsSelected(aSelList);
1972     objectBrowser()->blockSignals(aBlocked);
1973   }
1974   if (aHasHidden) 
1975     QMessageBox::information(desktop(), tr("Find results"), 
1976                              tr("Results not found"), QMessageBox::Ok);
1977 }
1978
1979 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
1980 {
1981   ResultPtr aResult;
1982   QObjectPtrList aSelList = theObjects;
1983   FeaturePtr aFeature;
1984   foreach(ObjectPtr aObj, theObjects) {
1985     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1986     if (aResult.get()) {
1987       aFeature = ModelAPI_Feature::feature(aResult);
1988       if (aFeature.get()) {
1989         aSelList.append(aFeature);
1990       }
1991     }
1992   }
1993   if (aSelList.count() > theObjects.count()) {
1994     // if something was found
1995     bool aBlocked = objectBrowser()->blockSignals(true);
1996     objectBrowser()->setObjectsSelected(aSelList);
1997     objectBrowser()->blockSignals(aBlocked);
1998   }
1999 }