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