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