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