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