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