Salome HOME
Delete key regression corrections: in previous implementation sketch entities did...
[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(QKeyEvent*)),
1064           myOperationMgr,  SLOT(onKeyReleased(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
1221   // 1. find all referenced features
1222   QList<ObjectPtr> anUnusedObjects;
1223   std::set<FeaturePtr> aDirectRefFeatures;
1224   foreach (ObjectPtr anObject, anObjects) {
1225     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1226     // for parameter result, use the corresponded reature to be removed
1227     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1228       aFeature = ModelAPI_Feature::feature(anObject);
1229     }
1230     if (aFeature.get()) {
1231       std::set<FeaturePtr> alreadyProcessed;
1232       aDirectRefFeatures.clear();
1233       XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, anObjects,
1234                                                     aDirectRefFeatures, alreadyProcessed);
1235       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1236         anUnusedObjects.append(aFeature);
1237     }
1238   }
1239
1240   // 2. warn about the references remove, break the delete operation if the user chose it
1241   if (!anUnusedObjects.empty()) {
1242     QStringList aNames;
1243     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1244       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1245       aNames.append(aFeature->name().c_str());
1246     }
1247     QString anUnusedNames = aNames.join(", ");
1248
1249     QString anActionId = "CLEAN_HISTORY_CMD";
1250     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1251
1252     QMessageBox aMessageBox(desktop());
1253     aMessageBox.setWindowTitle(aDescription);
1254     aMessageBox.setIcon(QMessageBox::Warning);
1255     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1256     aMessageBox.setDefaultButton(QMessageBox::No);
1257
1258     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1259                    .arg(anUnusedNames));
1260     aMessageBox.setText(aText);
1261     if (aMessageBox.exec() == QMessageBox::No)
1262       return;
1263
1264     // 1. start operation
1265     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1266     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1267     operationMgr()->startOperation(anOpAction);
1268
1269     std::set<FeaturePtr> anIgnoredFeatures;
1270     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId)) {
1271       operationMgr()->commitOperation();
1272     }
1273     else {
1274       operationMgr()->abortOperation(operationMgr()->currentOperation());
1275     }
1276   }
1277 }
1278
1279 //**************************************************************
1280 void XGUI_Workshop::moveObjects()
1281 {
1282   if (!abortAllOperations())
1283     return;
1284
1285   SessionPtr aMgr = ModelAPI_Session::get();
1286
1287   QString anActionId = "MOVE_CMD";
1288   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1289   aMgr->startOperation(aDescription.toStdString());
1290
1291   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1292   // It is necessary to clear selection in order to avoid selection changed event during
1293   // moving and negative consequences connected with processing of already moved items
1294   mySelector->clearSelection();
1295   // check whether the object can be moved. There should not be parts which are not loaded
1296   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1297     return;
1298
1299   DocumentPtr anActiveDocument = aMgr->activeDocument();
1300   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1301   foreach (ObjectPtr aObject, anObjects) {
1302     if (!myModule->canApplyAction(aObject, anActionId))
1303       continue;
1304
1305     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1306     if (aFeature.get()) {
1307       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1308       aCurrentFeature = anActiveDocument->currentFeature(true);
1309     }
1310   }
1311   aMgr->finishOperation();
1312 }
1313
1314 //**************************************************************
1315 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1316                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1317                                    QWidget* theParent,
1318                                    const bool theAskAboutDeleteReferences)
1319 {
1320 #ifdef DEBUG_DELETE
1321   QStringList aDInfo;
1322   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1323   for (; aDIt != aDLast; ++aDIt) {
1324     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1325   }
1326   QString anInfoStr = aDInfo.join(", ");
1327   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1328 #endif
1329
1330   // 1. find all referenced features
1331   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1332   foreach (ObjectPtr aDeletedObj, theList) {
1333     std::set<FeaturePtr> alreadyProcessed;
1334     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1335                                             aIndirectRefFeatures, alreadyProcessed);
1336     std::set<FeaturePtr> aDifference;
1337     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1338                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1339                         std::inserter(aDifference, aDifference.begin()));
1340     aIndirectRefFeatures = aDifference;
1341   }
1342
1343   bool doDeleteReferences = true;
1344
1345   // 2. warn about the references remove, break the delete operation if the user chose it
1346   if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1347     QStringList aDirectRefNames;
1348     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1349       aDirectRefNames.append(aFeature->name().c_str());
1350     QString aDirectNames = aDirectRefNames.join(", ");
1351
1352     QStringList aIndirectRefNames;
1353     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1354       aIndirectRefNames.append(aFeature->name().c_str());
1355     QString aIndirectNames = aIndirectRefNames.join(", ");
1356
1357     bool canReplaceParameters = true;
1358     foreach (ObjectPtr aObj, theList) {
1359       FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1360       if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1361         canReplaceParameters = false;
1362         break;
1363       }
1364     }
1365
1366     QMessageBox aMessageBox(theParent);
1367     aMessageBox.setWindowTitle(tr("Delete features"));
1368     aMessageBox.setIcon(QMessageBox::Warning);
1369     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1370     aMessageBox.setDefaultButton(QMessageBox::No);
1371
1372     QString aText;
1373     if (canReplaceParameters) {
1374       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?"))
1375           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1376       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1377     } else {
1378       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1379           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1380     }
1381     aMessageBox.setText(aText);
1382     aMessageBox.exec();
1383     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1384
1385     if (aButtonRole == QMessageBox::NoRole)
1386       return false;
1387
1388     if (aButtonRole == QMessageBox::ActionRole) {
1389       foreach (ObjectPtr aObj, theList)
1390         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1391       doDeleteReferences = false;
1392     }
1393   }
1394
1395   // 3. remove referenced features
1396   if (doDeleteReferences) {
1397     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1398     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1399     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1400                                          aLast = aFeaturesToDelete.end();
1401 #ifdef DEBUG_DELETE
1402     QStringList anInfo;
1403 #endif
1404     for (; anIt != aLast; anIt++) {
1405       FeaturePtr aFeature = (*anIt);
1406       DocumentPtr aDoc = aFeature->document();
1407       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1408         aDoc->removeFeature(aFeature);
1409 #ifdef DEBUG_DELETE
1410         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1411 #endif
1412       }
1413     }
1414 #ifdef DEBUG_DELETE
1415     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1416     anInfo.clear();
1417 #endif
1418   }
1419
1420   QString anActionId = "DELETE_CMD";
1421   return removeFeatures(theList, theIgnoredFeatures, anActionId);
1422 }
1423
1424 //**************************************************************
1425 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1426                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1427                                    const QString& theActionId)
1428 {
1429   bool isDone = false;
1430
1431   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1432   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1433   // 4. remove the parameter features
1434   foreach (ObjectPtr aObj, theList) {
1435     // features and parameters can be removed here,
1436     // the results are removed only by a corresponded feature remove
1437     std::string aGroupName = aObj->groupName();
1438     if (!anObjectGroups.contains(aGroupName.c_str()))
1439       continue;
1440
1441     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1442     if (aFeature) {
1443       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1444       // part features are removed in the PartSet module. This condition should be moved there
1445       if (aFeature->getKind() == "Part")
1446         continue;
1447         */
1448       DocumentPtr aDoc = aObj->document();
1449       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1450 #ifdef DEBUG_DELETE
1451         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1452         anInfo.append(anInfoStr);
1453         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1454 #endif
1455         aDoc->removeFeature(aFeature);
1456         isDone = true;
1457       }
1458     }
1459   }
1460 #ifdef DEBUG_DELETE
1461   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1462 #endif
1463   return true;
1464 }
1465
1466 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1467 {
1468   bool isFoundResultType = false;
1469   foreach(ObjectPtr anObj, theObjects)
1470   {
1471     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1472     if (aResult.get() == NULL)
1473       continue;
1474
1475     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1476     if (isFoundResultType)
1477       break;
1478   }
1479   return isFoundResultType;
1480 }
1481
1482 //**************************************************************
1483 // Returns the list of all features for theDocument and all features of
1484 // all nested parts.
1485 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1486 {
1487   std::list<FeaturePtr> aResultList;
1488   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1489   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1490     // The order of appending features of the part and the part itself is important
1491
1492     // Append features from a part feature
1493     foreach (const ResultPtr& aResult, aFeature->results()) {
1494       ResultPartPtr aResultPart =
1495           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1496       if (aResultPart.get() && aResultPart->partDoc().get()) {
1497         // Recursion
1498         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1499         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1500       }
1501     }
1502
1503     aResultList.push_back(aFeature);
1504   }
1505   return aResultList;
1506 }
1507
1508 //**************************************************************
1509 // Returns the list of features placed between theObject and the current feature
1510 // in the same document. Excludes theObject, includes the current feature.
1511 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1512 {
1513   std::list<FeaturePtr> aResult;
1514   DocumentPtr aDocument = theObject->document();
1515   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1516   // find the object iterator
1517   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1518   if (aObjectIt == anAllFeatures.end())
1519     return aResult;
1520   // find the current feature iterator
1521   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1522   if (aCurrentIt == anAllFeatures.end())
1523     return aResult;
1524   // check the right order
1525   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1526     return aResult;
1527   // exclude the object
1528   std::advance(aObjectIt, 1);
1529   // include the current feature
1530   std::advance(aCurrentIt, 1);
1531   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1532 }
1533
1534 bool XGUI_Workshop::canMoveFeature()
1535 {
1536   QString anActionId = "MOVE_CMD";
1537
1538   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1539   QObjectPtrList aValidatedObjects;
1540   foreach (ObjectPtr aObject, aObjects) {
1541     if (!myModule->canApplyAction(aObject, anActionId))
1542       continue;
1543     // To be moved feature should be in active document
1544     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1545       continue;
1546     aValidatedObjects.append(aObject);
1547   }
1548   if (aValidatedObjects.size() != aObjects.size())
1549     aObjects = aValidatedObjects;
1550
1551   bool aCanMove = !aObjects.empty();
1552
1553   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1554   for (; anIt != aLast && aCanMove; anIt++) {
1555     ObjectPtr aObject = *anIt;
1556     // 1. Get features placed between selected and current in the document 
1557     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1558     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1559     if (aFeaturesBetween.empty())
1560       aCanMove = false;
1561     else {
1562       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1563       // 2. Get all reference features to the selected object in the document 
1564       std::set<FeaturePtr> aRefFeatures;
1565       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1566
1567       if (aRefFeatures.empty())
1568         continue;
1569       else {
1570         // 3. Find any placed features in all reference features
1571         std::set<FeaturePtr> aIntersectionFeatures;
1572         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1573                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1574                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1575         // 4. Return false if any reference feature is placed before current feature
1576         if (!aIntersectionFeatures.empty())
1577           aCanMove = false;
1578       }
1579     }
1580   }
1581   return aCanMove;
1582 }
1583
1584 //**************************************************************
1585 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1586 {
1587   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1588   if (!aCanBeShaded) {
1589     ResultCompSolidPtr aCompsolidResult =
1590                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1591     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1592       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1593         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1594     }
1595   }
1596   return aCanBeShaded;
1597 }
1598
1599 //**************************************************************
1600 bool XGUI_Workshop::canChangeColor() const
1601 {
1602   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1603
1604   std::set<std::string> aTypes;
1605   aTypes.insert(ModelAPI_ResultGroup::group());
1606   aTypes.insert(ModelAPI_ResultConstruction::group());
1607   aTypes.insert(ModelAPI_ResultBody::group());
1608   aTypes.insert(ModelAPI_ResultPart::group());
1609
1610   return hasResults(aObjects, aTypes);
1611 }
1612
1613 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1614 {
1615   if (!theResult.get())
1616     return;
1617
1618   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1619   if (aColorAttr.get() != NULL) {
1620     if (!aColorAttr->size()) {
1621       aColorAttr->setSize(3);
1622     }
1623     aColorAttr->setValue(0, theColor[0]);
1624     aColorAttr->setValue(1, theColor[1]);
1625     aColorAttr->setValue(2, theColor[2]);
1626   }
1627 }
1628
1629 //**************************************************************
1630 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1631 {
1632
1633   AttributeIntArrayPtr aColorAttr;
1634   // 1. find the current color of the object. This is a color of AIS presentation
1635   // The objects are iterated until a first valid color is found 
1636   std::vector<int> aColor;
1637   foreach(ObjectPtr anObject, theObjects) {
1638     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1639     if (aResult.get()) {
1640       XGUI_CustomPrs::getResultColor(aResult, aColor);
1641     }
1642     else {
1643       // TODO: remove the obtaining a color from the AIS object
1644       // this does not happen never because:
1645       // 1. The color can be changed only on results
1646       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1647       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1648       if (anAISObj.get()) {
1649         aColor.resize(3);
1650         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1651       }
1652     }
1653     if (!aColor.empty())
1654       break;
1655   }
1656   if (aColor.size() != 3)
1657     return;
1658
1659   if (!abortAllOperations())
1660   return; 
1661   // 2. show the dialog to change the value
1662   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1663   aDlg->setColor(aColor);
1664   aDlg->move(QCursor::pos());
1665   bool isDone = aDlg->exec() == QDialog::Accepted;
1666   if (!isDone)
1667     return;
1668
1669   bool isRandomColor = aDlg->isRandomColor();
1670
1671   // 3. abort the previous operation and start a new one
1672   SessionPtr aMgr = ModelAPI_Session::get();
1673   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1674   aMgr->startOperation(aDescription.toStdString());
1675
1676   // 4. set the value to all results
1677   std::vector<int> aColorResult = aDlg->getColor();
1678   foreach(ObjectPtr anObj, theObjects) {
1679     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1680     if (aResult.get() != NULL) {
1681       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1682       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1683         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1684           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1685         }
1686       }
1687       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1688     }
1689   }
1690   aMgr->finishOperation();
1691   updateCommandStatus();
1692 }
1693
1694 //**************************************************************
1695 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1696 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1697   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1698 }
1699 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1700 {
1701   foreach (ObjectPtr aObj, theList) {
1702     /*
1703     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1704     if (aPartRes) {
1705       DocumentPtr aDoc = aPartRes->partDoc();
1706       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1707       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1708       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1709     } else {
1710     */
1711       aObj->setDisplayed(isVisible);
1712     //}
1713   }
1714   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1715 }
1716
1717 //**************************************************************
1718 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1719 {
1720   // Hide all displayed objects
1721   QObjectPtrList aList = myDisplayer->displayedObjects();
1722   foreach (ObjectPtr aObj, aList) {
1723     if (module()->canEraseObject(aObj))
1724       aObj->setDisplayed(false);
1725   }
1726
1727   // Show only objects from the list
1728   foreach (ObjectPtr aObj, theList) {
1729     /*
1730     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1731     if (aPartRes) {
1732       DocumentPtr aDoc = aPartRes->partDoc();
1733       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1734       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1735       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1736     } else {
1737     */
1738       aObj->setDisplayed(true);
1739     //}
1740   }
1741   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1742
1743 }
1744
1745
1746 //**************************************************************
1747 void XGUI_Workshop::registerValidators() const
1748 {
1749   SessionPtr aMgr = ModelAPI_Session::get();
1750   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1751 }
1752
1753 //**************************************************************
1754 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1755 {
1756   if (!theDoc)
1757     return;
1758   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1759   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1760 }
1761
1762 //**************************************************************
1763 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1764 {
1765   for (int i = 0; i < theDoc->size(theGroup); i++) 
1766     theDoc->object(theGroup, i)->setDisplayed(true);
1767     //displayObject(theDoc->object(theGroup, i));
1768   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1769 }
1770
1771 //**************************************************************
1772 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1773 {
1774   foreach(ObjectPtr aObj, theList) {
1775     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1776
1777     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1778     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1779       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1780           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1781                                       (XGUI_Displayer::DisplayMode)theMode, false);
1782       }
1783     }
1784   }
1785   if (theList.size() > 0)
1786     myDisplayer->updateViewer();
1787 }
1788
1789 //**************************************************************
1790 void XGUI_Workshop::closeDocument()
1791 {
1792   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1793   while (anOperation) {
1794     anOperation->abort();
1795     anOperation = operationMgr()->currentOperation();
1796   }
1797   myDisplayer->closeLocalContexts();
1798   myDisplayer->eraseAll();
1799   objectBrowser()->clearContent();
1800
1801   module()->closeDocument();
1802
1803   SessionPtr aMgr = ModelAPI_Session::get();
1804   aMgr->closeAll();
1805 }
1806
1807 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1808 {
1809   XGUI_HistoryMenu* aMenu = NULL;
1810   if (isSalomeMode()) {
1811     QAction* anAction = qobject_cast<QAction*>(theObject);
1812     if (!anAction)
1813       return;
1814     aMenu = new XGUI_HistoryMenu(anAction);
1815   } else {
1816     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1817     aMenu = new XGUI_HistoryMenu(aButton);
1818   }
1819   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1820   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1821 }
1822
1823 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1824 {
1825   QList<ActionInfo> aResult;
1826   std::list<std::string>::const_iterator it = theList.cbegin();
1827   for (; it != theList.cend(); it++) {
1828     QString anId = QString::fromStdString(*it);
1829     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1830     if (isEditing) {
1831       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1832     }
1833     ActionInfo anInfo;
1834     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1835     if (aContextMenuAct) {
1836       anInfo.initFrom(aContextMenuAct);
1837     } else {
1838       anInfo = myActionsMgr->actionInfoById(anId);
1839     }
1840     if (isEditing) {
1841       anInfo.text = anInfo.text.prepend("Modify ");
1842     }
1843     aResult << anInfo;
1844   }
1845   return aResult;
1846 }
1847
1848 void XGUI_Workshop::synchronizeViewer()
1849 {
1850   SessionPtr aMgr = ModelAPI_Session::get();
1851   DocumentPtr aDoc = aMgr->activeDocument();
1852
1853   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1854   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1855   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1856   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1857 }
1858
1859 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1860                                              const std::string& theGroup, 
1861                                              bool theUpdateViewer)
1862 {
1863   ObjectPtr aObj;
1864   int aSize = theDoc->size(theGroup);
1865   for (int i = 0; i < aSize; i++) {
1866     aObj = theDoc->object(theGroup, i);
1867     if (aObj->isDisplayed())
1868       myDisplayer->display(aObj, false);
1869   }
1870   if (theUpdateViewer)
1871     myDisplayer->updateViewer();
1872 }