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