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