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