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