Salome HOME
cb6e77a0ed0840c6f2c6e2328b11dcc24e37c69f
[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   myModule->onOperationStarted(aFOperation);
464
465   // the objects of the current operation should be deactivated
466   QObjectPtrList anObjects;
467   FeaturePtr aFeature = aFOperation->feature();
468   anObjects.append(aFeature);
469   std::list<ResultPtr> aResults = aFeature->results();
470   std::list<ResultPtr>::const_iterator aIt;
471   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
472     anObjects.append(*aIt);
473   }
474   QObjectPtrList::const_iterator anIt = anObjects.begin(), aLast = anObjects.end();
475   for (; anIt != aLast; anIt++)
476     deactivateActiveObject(*anIt, false);
477   if (anObjects.size() > 0)
478     myDisplayer->updateViewer();
479 }
480
481 //******************************************************
482 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
483 {
484   setGrantedFeatures(theOperation);
485
486   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
487     setPropertyPanel(theOperation);
488   }
489   updateCommandStatus();
490
491   myModule->onOperationResumed(theOperation);
492 }
493
494
495 //******************************************************
496 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
497 {
498   updateCommandStatus();
499
500   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
501                                                                         (theOperation);
502   if (!aFOperation)
503     return;
504
505   ModuleBase_ISelection* aSel = mySelector->selection();
506   QObjectPtrList aObj = aSel->selectedPresentations();
507   //!< No need for property panel
508   hidePropertyPanel();
509   myPropertyPanel->cleanContent();
510
511   myModule->onOperationStopped(aFOperation);
512
513   // the deactivated objects of the current operation should be activated back.
514   // They were deactivated on operation start or an object redisplay
515   QObjectPtrList anObjects;
516   FeaturePtr aFeature = aFOperation->feature();
517   if (aFeature.get()) { // feature may be not created (plugin load fail)
518     if (myDisplayer->isVisible(aFeature) && !myDisplayer->isActive(aFeature))
519       anObjects.append(aFeature);
520     std::list<ResultPtr> aResults = aFeature->results();
521     std::list<ResultPtr>::const_iterator aIt;
522     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
523       ResultPtr anObject = *aIt;
524       if (myDisplayer->isVisible(anObject) && !myDisplayer->isActive(anObject)) {
525         anObjects.append(anObject);
526       }
527     }
528   }
529   QIntList aModes;
530   module()->activeSelectionModes(aModes);
531   myDisplayer->activateObjects(aModes, anObjects);
532 }
533
534
535 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
536 {
537   myModule->onOperationCommitted(theOperation);
538 }
539
540 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
541 {
542   myModule->onOperationAborted(theOperation);
543 }
544
545 void XGUI_Workshop::setGrantedFeatures(ModuleBase_Operation* theOperation)
546 {
547   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
548   if (!aFOperation)
549     return;
550
551   QStringList aGrantedIds;
552   if (isSalomeMode())
553     aGrantedIds = mySalomeConnector->nestedActions(theOperation->id());
554   else
555     aGrantedIds = myActionsMgr->nestedCommands(theOperation->id());
556
557   ModuleBase_IModule* aModule = module();
558   if (aModule)
559     aModule->grantedOperationIds(theOperation, aGrantedIds);
560
561   aFOperation->setGrantedOperationIds(aGrantedIds);
562 }
563
564 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
565 {
566   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>(theOperation);
567   if (!aFOperation)
568     return;
569
570   showPropertyPanel();
571   QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
572   ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
573
574   myPropertyPanel->cleanContent();
575   aFactory.createWidget(myPropertyPanel->contentWidget());
576
577   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
578
579   // check compatibility of feature and widgets
580   FeaturePtr aFeature = aFOperation->feature();
581   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
582     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
583       std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
584           + aWidget->attributeID() + "' used by widget '"
585           + aWidget->metaObject()->className() + "'.";
586       Events_Error::send(anErrorMsg);
587       myPropertyPanel->cleanContent();
588       return;
589     }
590   }
591
592   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
593     bool isStoreValue = !aFOperation->isEditOperation() &&
594                         !aWidget->getDefaultValue().empty() &&
595                         !aWidget->isComputedDefault();
596     aWidget->setFeature(aFOperation->feature(), isStoreValue);
597     aWidget->enableFocusProcessing();
598   }
599
600   myPropertyPanel->setModelWidgets(aWidgets);
601   aFOperation->setPropertyPanel(myPropertyPanel);
602
603   myModule->propertyPanelDefined(theOperation);
604
605   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
606
607   myErrorMgr->setPropertyPanel(myPropertyPanel);
608 }
609
610 /*
611  * Saves document with given name.
612  */
613 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
614 {
615   QApplication::restoreOverrideCursor();
616   SessionPtr aMgr = ModelAPI_Session::get();
617   aMgr->save(theName.toLatin1().constData(), theFileNames);
618   QApplication::restoreOverrideCursor();
619 }
620
621 bool XGUI_Workshop::abortAllOperations()
622 {
623   return myOperationMgr->abortAllOperations();
624 }
625
626 //******************************************************
627 void XGUI_Workshop::onOpen()
628 {
629   if(!abortAllOperations())
630     return;
631   //save current file before close if modified
632   SessionPtr aSession = ModelAPI_Session::get();
633   if (aSession->isModified()) {
634     //TODO(sbh): re-launch the app?
635     int anAnswer = QMessageBox::question(
636         desktop(), tr("Save current file"),
637         tr("The document is modified, save before opening another?"),
638         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
639     if (anAnswer == QMessageBox::Save) {
640       onSave();
641     } else if (anAnswer == QMessageBox::Cancel) {
642       return;
643     }
644     myCurrentDir = "";
645   }
646
647   //show file dialog, check if readable and open
648   myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
649   if (myCurrentDir.isEmpty())
650     return;
651   QFileInfo aFileInfo(myCurrentDir);
652   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
653     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
654     myCurrentDir = "";
655     return;
656   }
657   QApplication::setOverrideCursor(Qt::WaitCursor);
658   aSession->closeAll();
659   aSession->load(myCurrentDir.toLatin1().constData());
660   myObjectBrowser->rebuildDataTree();
661   updateCommandStatus();
662   QApplication::restoreOverrideCursor();
663 }
664
665 //******************************************************
666 void XGUI_Workshop::onNew()
667 {
668   QApplication::setOverrideCursor(Qt::WaitCursor);
669   if (objectBrowser() == 0) {
670     createDockWidgets();
671     mySelector->connectViewers();
672   }
673   myViewerProxy->connectToViewer();
674   showObjectBrowser();
675 #ifndef HAVE_SALOME
676   myMainWindow->showPythonConsole();
677   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
678   aWnd->showMaximized();
679   updateCommandStatus();
680 #endif
681   myContextMenuMgr->connectViewer();
682   QApplication::restoreOverrideCursor();
683 }
684
685 #ifndef HAVE_SALOME
686 //******************************************************
687 void XGUI_Workshop::onExit()
688 {
689   SessionPtr aMgr = ModelAPI_Session::get();
690   if (aMgr->isModified()) {
691     int anAnswer = QMessageBox::question(
692         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
693         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
694     if (anAnswer == QMessageBox::Save) {
695       bool saved = onSave();
696       if (!saved) {
697         return;
698       }
699     } else if (anAnswer == QMessageBox::Cancel) {
700       return;
701     }
702   }
703   qApp->exit();
704 }
705
706 //******************************************************
707 void XGUI_Workshop::onPreferences()
708 {
709   ModuleBase_Prefs aModif;
710   ModuleBase_Preferences::editPreferences(aModif);
711   if (aModif.size() > 0) {
712     QString aSection;
713     foreach (ModuleBase_Pref aPref, aModif)
714     {
715       aSection = aPref.first;
716       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
717         myMainWindow->viewer()->updateFromResources();
718       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
719         myMainWindow->menuObject()->updateFromResources();
720       }
721     }
722     displayer()->redisplayObjects();
723   }
724 }
725 #endif
726
727 //******************************************************
728 bool XGUI_Workshop::onSave()
729 {
730   if(!abortAllOperations())
731     return false;
732   if (myCurrentDir.isEmpty()) {
733     return onSaveAs();
734   }
735   std::list<std::string> aFiles;
736   saveDocument(myCurrentDir, aFiles);
737   updateCommandStatus();
738 #ifndef HAVE_SALOME
739     myMainWindow->setModifiedState(false);
740 #endif
741   return true;
742 }
743
744 //******************************************************
745 bool XGUI_Workshop::onSaveAs()
746 {
747   if(!abortAllOperations())
748     return false;
749   QFileDialog dialog(desktop());
750   dialog.setWindowTitle(tr("Select directory to save files..."));
751   dialog.setFileMode(QFileDialog::Directory);
752   dialog.setFilter(tr("Directories (*)"));
753   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
754   dialog.setViewMode(QFileDialog::Detail);
755
756   if (!dialog.exec()) {
757     return false;
758   }
759
760   QString aTempDir = dialog.selectedFiles().first();
761   QDir aDir(aTempDir);
762   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
763     int answer = QMessageBox::question(
764         desktop(),
765         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
766         tr("Save"),
767         tr("The directory already contains some files, save anyway?"),
768         QMessageBox::Save | QMessageBox::Cancel);
769     if (answer == QMessageBox::Cancel) {
770       return false;
771     }
772   }
773   myCurrentDir = aTempDir;
774 #ifndef HAVE_SALOME
775     myMainWindow->setCurrentDir(myCurrentDir, false);
776     myMainWindow->setModifiedState(false);
777 #endif
778   return onSave();
779 }
780
781 //******************************************************
782 void XGUI_Workshop::onUndo(int theTimes)
783 {
784   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
785   SessionPtr aMgr = ModelAPI_Session::get();
786   if (aMgr->isOperation()) {
787     /// this is important for nested operations
788     /// when sketch operation is active, this condition is false and
789     /// the sketch operation is not aborted
790     operationMgr()->onAbortOperation();
791   }
792   for (int i = 0; i < theTimes; ++i) {
793     aMgr->undo();
794   }
795
796   operationMgr()->updateApplyOfOperations();
797   updateCommandStatus();
798 }
799
800 //******************************************************
801 void XGUI_Workshop::onRedo(int theTimes)
802 {
803   // the viewer update should be blocked in order to avoid the features blinking. For the created
804   // feature a results are created, the flush of the created signal caused the viewer redisplay for
805   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
806   // redo of all possible objects happens
807   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
808
809   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
810   SessionPtr aMgr = ModelAPI_Session::get();
811   if (aMgr->isOperation()) {
812     /// this is important for nested operations
813     /// when sketch operation is active, this condition is false and
814     /// the sketch operation is not aborted
815     operationMgr()->onAbortOperation();
816   }
817   for (int i = 0; i < theTimes; ++i) {
818     aMgr->redo();
819   }
820   operationMgr()->updateApplyOfOperations();
821   updateCommandStatus();
822
823   // unblock the viewer update functionality and make update on purpose
824   myDisplayer->enableUpdateViewer(isUpdateEnabled);
825   myDisplayer->updateViewer();
826 }
827
828 //******************************************************
829 void XGUI_Workshop::onRebuild()
830 {
831   SessionPtr aMgr = ModelAPI_Session::get();
832   bool aWasOperation = aMgr->isOperation(); // keep this value
833   if (!aWasOperation) {
834     aMgr->startOperation("Rebuild");
835   }
836   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
837   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
838     new Events_Message(aRebuildEvent, this)));
839   if (!aWasOperation) {
840     aMgr->finishOperation();
841   }
842   updateCommandStatus();
843 }
844
845 //******************************************************
846 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
847 {
848   QString libName = QString::fromStdString(library(theModule.toStdString()));
849   if (libName.isEmpty()) {
850     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
851     return 0;
852   }
853
854   QString err;
855   CREATE_FUNC crtInst = 0;
856
857 #ifdef WIN32
858   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
859   if (!modLib) {
860     LPVOID lpMsgBuf;
861     ::FormatMessage(
862         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
863         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
864     QString aMsg((char*) &lpMsgBuf);
865     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
866     ::LocalFree(lpMsgBuf);
867   } else {
868     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
869     if (!crtInst) {
870       LPVOID lpMsgBuf;
871       ::FormatMessage(
872           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
873               | FORMAT_MESSAGE_IGNORE_INSERTS,
874           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
875       QString aMsg((char*) &lpMsgBuf);
876       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
877       ::LocalFree(lpMsgBuf);
878     }
879   }
880 #else
881   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
882   if ( !modLib ) {
883     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
884   } else {
885     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
886     if ( !crtInst ) {
887       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
888     }
889   }
890 #endif
891
892   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
893
894   if (!err.isEmpty()) {
895     if (desktop()) {
896       Events_Error::send(err.toStdString());
897     } else {
898       qWarning(qPrintable(err));
899     }
900   }
901   return aModule;
902 }
903
904 //******************************************************
905 bool XGUI_Workshop::createModule()
906 {
907   Config_ModuleReader aModuleReader;
908   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
909   myModule = loadModule(moduleName);
910   if (!myModule)
911     return false;
912
913   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
914   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
915   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
916   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
917
918   myModule->createFeatures();
919   //myActionsMgr->update();
920   return true;
921 }
922
923 //******************************************************
924 void XGUI_Workshop::updateCommandStatus()
925 {
926   QList<QAction*> aCommands;
927 #ifdef HAVE_SALOME
928     aCommands = salomeConnector()->commandList();
929 #else
930     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
931     foreach (AppElements_Command* aCmd, aMenuBar->features())
932       aCommands.append(aCmd);
933 #endif
934   SessionPtr aMgr = ModelAPI_Session::get();
935   if (aMgr->hasModuleDocument()) {
936     foreach(QAction* aCmd, aCommands) {
937       QString aId = aCmd->data().toString();
938       if (aId == "UNDO_CMD")
939         aCmd->setEnabled(myModule->canUndo());
940       else if (aId == "REDO_CMD")
941         aCmd->setEnabled(myModule->canRedo());
942       else
943         // Enable all commands
944         aCmd->setEnabled(true);
945     }
946     updateHistory();
947   } else {
948     foreach(QAction* aCmd, aCommands) {
949       QString aId = aCmd->data().toString();
950       if (aId == "NEW_CMD")
951         aCmd->setEnabled(true);
952       else if (aId == "EXIT_CMD")
953         aCmd->setEnabled(true);
954       else
955         aCmd->setEnabled(false);
956     }
957   }
958   myActionsMgr->update();
959   emit commandStatusUpdated();
960 }
961
962 void XGUI_Workshop::updateHistory()
963 {
964   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
965   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
966   emit updateUndoHistory(aUndoRes);
967
968   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
969   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
970   emit updateRedoHistory(aRedoRes);
971 }
972
973 //******************************************************
974 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
975 {
976   QDockWidget* aObjDock = new QDockWidget(theParent);
977   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
978   aObjDock->setWindowTitle(tr("Object browser"));
979   aObjDock->setStyleSheet(
980       "::title { position: relative; padding-left: 5px; text-align: left center }");
981   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
982   myModule->customizeObjectBrowser(myObjectBrowser);
983   aObjDock->setWidget(myObjectBrowser);
984
985   myContextMenuMgr->connectObjectBrowser();
986   return aObjDock;
987 }
988
989 //******************************************************
990 /*
991  * Creates dock widgets, places them in corresponding area
992  * and tabifies if necessary.
993  */
994 void XGUI_Workshop::createDockWidgets()
995 {
996   QMainWindow* aDesktop = desktop();
997   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
998   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
999   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1000   myPropertyPanel->setupActions(myActionsMgr);
1001   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1002   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1003   hidePropertyPanel();  ///<! Invisible by default
1004   hideObjectBrowser();
1005   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1006   myPropertyPanel->installEventFilter(myOperationMgr);
1007
1008   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1009   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1010
1011   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1012   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1013   connect(myPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
1014           myModule, SLOT(onNoMoreWidgets(const std::string&)));
1015   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1016           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1017   //connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1018   //        this, SLOT(onValidationStateChanged(bool)));
1019   connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
1020           myModule, SLOT(onInternalActivateFirstWidgetSelection()));
1021 }
1022
1023 //******************************************************
1024 void XGUI_Workshop::showPropertyPanel()
1025 {
1026   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1027   ///<! Restore ability to close panel from the window's menu
1028   aViewAct->setEnabled(true);
1029   myPropertyPanel->show();
1030   myPropertyPanel->raise();
1031
1032   // The next code is necessary to made the property panel the active window
1033   // in order to operation manager could process key events of the panel.
1034   // otherwise they are ignored. It happens only if the same(activateWindow) is
1035   // not happened by property panel activation(e.g. resume operation of Sketch)
1036   myPropertyPanel->activateWindow();
1037   myPropertyPanel->setFocus();
1038 }
1039
1040 //******************************************************
1041 void XGUI_Workshop::hidePropertyPanel()
1042 {
1043   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1044   ///<! Do not allow to show empty property panel
1045   aViewAct->setEnabled(false);
1046   myPropertyPanel->hide();
1047
1048   // the property panel is active window of the desktop, when it is
1049   // hidden, it is undefined which window becomes active. By this reason
1050   // it is defined to perform the desktop as the active window.
1051   // in SALOME mode, workstack made the PyConsole the active window,
1052   // set the focus on it. As a result, shortcuts of the application, like
1053   // are processed by this console. For example Undo actions.
1054   // It is possible that this code is to be moved to NewGeom package
1055   QMainWindow* aDesktop = desktop();
1056   aDesktop->activateWindow();
1057   aDesktop->setFocus();
1058 }
1059
1060 //******************************************************
1061 void XGUI_Workshop::showObjectBrowser()
1062 {
1063   myObjectBrowser->parentWidget()->show();
1064 }
1065
1066 //******************************************************
1067 void XGUI_Workshop::hideObjectBrowser()
1068 {
1069   myObjectBrowser->parentWidget()->hide();
1070 }
1071
1072 //******************************************************
1073 void XGUI_Workshop::salomeViewerSelectionChanged()
1074 {
1075   emit salomeViewerSelection();
1076 }
1077
1078 //**************************************************************
1079 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1080 {
1081   return mySalomeConnector->viewer();
1082 }
1083
1084 //**************************************************************
1085 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1086 {
1087   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1088   if (theId == "DELETE_CMD")
1089     deleteObjects();
1090   else if (theId == "MOVE_CMD")
1091     moveObjects();
1092   else if (theId == "COLOR_CMD")
1093     changeColor(aObjects);
1094   else if (theId == "SHOW_CMD")
1095     showObjects(aObjects, true);
1096   else if (theId == "HIDE_CMD")
1097     showObjects(aObjects, false);
1098   else if (theId == "SHOW_ONLY_CMD")
1099     showOnlyObjects(aObjects);
1100   else if (theId == "SHADING_CMD")
1101     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1102   else if (theId == "WIREFRAME_CMD")
1103     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1104   else if (theId == "HIDEALL_CMD") {
1105     QObjectPtrList aList = myDisplayer->displayedObjects();
1106     foreach (ObjectPtr aObj, aList) {
1107       if (module()->canEraseObject(aObj))
1108         aObj->setDisplayed(false);
1109     }
1110     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1111   }
1112 }
1113
1114 //**************************************************************
1115 void XGUI_Workshop::deleteObjects()
1116 {
1117   ModuleBase_IModule* aModule = module();
1118   // 1. allow the module to delete objects, do nothing if it has succeed
1119   if (aModule->deleteObjects()) {
1120     updateCommandStatus();
1121     return;
1122   }
1123
1124   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1125   if (!abortAllOperations())
1126     return;
1127   // It is necessary to clear selection in order to avoid selection changed event during
1128   // deletion and negative consequences connected with processing of already deleted items
1129   mySelector->clearSelection();
1130   // check whether the object can be deleted. There should not be parts which are not loaded
1131   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1132     return;
1133
1134   bool hasResult = false;
1135   bool hasFeature = false;
1136   bool hasParameter = false;
1137   bool hasSubFeature = false;
1138   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1139   if (!(hasFeature || hasParameter))
1140     return;
1141
1142   // 1. start operation
1143   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1144   aDescription += tr(" %1");
1145   QStringList aObjectNames;
1146   foreach (ObjectPtr aObj, anObjects) {
1147     if (!aObj->data()->isValid())
1148       continue;
1149     aObjectNames << QString::fromStdString(aObj->data()->name());
1150   }
1151   aDescription = aDescription.arg(aObjectNames.join(", "));
1152   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1153
1154   operationMgr()->startOperation(anOpAction);
1155   // 3. delete objects
1156   std::set<FeaturePtr> anIgnoredFeatures;
1157   if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1158     operationMgr()->commitOperation();
1159   }
1160   else {
1161     operationMgr()->abortOperation(operationMgr()->currentOperation());
1162   }
1163 }
1164
1165 //**************************************************************
1166 void XGUI_Workshop::moveObjects()
1167 {
1168   if (!abortAllOperations())
1169     return;
1170
1171   SessionPtr aMgr = ModelAPI_Session::get();
1172
1173   QString anActionId = "MOVE_CMD";
1174   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1175   aMgr->startOperation(aDescription.toStdString());
1176
1177   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1178   // It is necessary to clear selection in order to avoid selection changed event during
1179   // moving and negative consequences connected with processing of already moved items
1180   mySelector->clearSelection();
1181   // check whether the object can be moved. There should not be parts which are not loaded
1182   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1183     return;
1184
1185   DocumentPtr anActiveDocument = aMgr->activeDocument();
1186   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1187   foreach (ObjectPtr aObject, anObjects) {
1188     if (!myModule->canApplyAction(aObject, anActionId))
1189       continue;
1190
1191     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1192     if (aFeature.get()) {
1193       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1194       aCurrentFeature = anActiveDocument->currentFeature(true);
1195     }
1196   }
1197   aMgr->finishOperation();
1198 }
1199
1200 //**************************************************************
1201 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1202                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1203                                    QWidget* theParent,
1204                                    const bool theAskAboutDeleteReferences)
1205 {
1206 #ifdef DEBUG_DELETE
1207   QStringList aDInfo;
1208   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1209   for (; aDIt != aDLast; ++aDIt) {
1210     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1211   }
1212   QString anInfoStr = aDInfo.join(", ");
1213   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1214 #endif
1215
1216   // 1. find all referenced features
1217   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1218   foreach (ObjectPtr aDeletedObj, theList) {
1219     std::set<FeaturePtr> alreadyProcessed;
1220     XGUI_Tools::refsToFeatureInAllDocuments(
1221       aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1222     std::set<FeaturePtr> aDifference;
1223     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1224                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1225                         std::inserter(aDifference, aDifference.begin()));
1226     aIndirectRefFeatures = aDifference;
1227   }
1228
1229   bool doDeleteReferences = true;
1230
1231   // 2. warn about the references remove, break the delete operation if the user chose it
1232   if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1233     QStringList aDirectRefNames;
1234     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1235       aDirectRefNames.append(aFeature->name().c_str());
1236     QString aDirectNames = aDirectRefNames.join(", ");
1237
1238     QStringList aIndirectRefNames;
1239     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1240       aIndirectRefNames.append(aFeature->name().c_str());
1241     QString aIndirectNames = aIndirectRefNames.join(", ");
1242
1243     bool canReplaceParameters = true;
1244     foreach (ObjectPtr aObj, theList) {
1245       FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1246       if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1247         canReplaceParameters = false;
1248         break;
1249       }
1250     }
1251
1252     QMessageBox aMessageBox(theParent);
1253     aMessageBox.setWindowTitle(tr("Delete features"));
1254     aMessageBox.setIcon(QMessageBox::Warning);
1255     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1256     aMessageBox.setDefaultButton(QMessageBox::No);
1257
1258     QString aText;
1259     if (canReplaceParameters) {
1260       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?"))
1261           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1262       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1263     } else {
1264       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1265           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1266     }
1267     aMessageBox.setText(aText);
1268     aMessageBox.exec();
1269     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1270
1271     if (aButtonRole == QMessageBox::NoRole)
1272       return false;
1273
1274     if (aButtonRole == QMessageBox::ActionRole) {
1275       foreach (ObjectPtr aObj, theList)
1276         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1277       doDeleteReferences = false;
1278     }
1279   }
1280
1281   // 3. remove referenced features
1282   if (doDeleteReferences) {
1283     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1284     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1285     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1286                                          aLast = aFeaturesToDelete.end();
1287 #ifdef DEBUG_DELETE
1288     QStringList anInfo;
1289 #endif
1290     for (; anIt != aLast; anIt++) {
1291       FeaturePtr aFeature = (*anIt);
1292       DocumentPtr aDoc = aFeature->document();
1293       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1294         aDoc->removeFeature(aFeature);
1295 #ifdef DEBUG_DELETE
1296         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1297 #endif
1298       }
1299     }
1300 #ifdef DEBUG_DELETE
1301     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1302     anInfo.clear();
1303 #endif
1304   }
1305
1306   QString anActionId = "DELETE_CMD";
1307   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1308   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1309   // 4. remove the parameter features
1310   foreach (ObjectPtr aObj, theList) {
1311     // features and parameters can be removed here,
1312     // the results are removed only by a corresponded feature remove
1313     std::string aGroupName = aObj->groupName();
1314     if (!anObjectGroups.contains(aGroupName.c_str()))
1315       continue;
1316
1317     if (!myModule->canApplyAction(aObj, anActionId))
1318       continue;
1319
1320     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1321     if (aFeature) {
1322       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1323       // part features are removed in the PartSet module. This condition should be moved there
1324       if (aFeature->getKind() == "Part")
1325         continue;
1326         */
1327       DocumentPtr aDoc = aObj->document();
1328       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1329 #ifdef DEBUG_DELETE
1330         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1331         anInfo.append(anInfoStr);
1332         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1333 #endif
1334         aDoc->removeFeature(aFeature);
1335       }
1336     }
1337   }
1338 #ifdef DEBUG_DELETE
1339   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1340 #endif
1341   return true;
1342 }
1343
1344 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1345 {
1346   bool isFoundResultType = false;
1347   foreach(ObjectPtr anObj, theObjects)
1348   {
1349     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1350     if (aResult.get() == NULL)
1351       continue;
1352
1353     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1354     if (isFoundResultType)
1355       break;
1356   }
1357   return isFoundResultType;
1358 }
1359
1360 //**************************************************************
1361 // Returns the list of all features for theDocument and all features of
1362 // all nested parts.
1363 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1364 {
1365   std::list<FeaturePtr> aResultList;
1366   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1367   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1368     // The order of appending features of the part and the part itself is important
1369
1370     // Append features from a part feature
1371     foreach (const ResultPtr& aResult, aFeature->results()) {
1372       ResultPartPtr aResultPart =
1373           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1374       if (aResultPart.get() && aResultPart->partDoc().get()) {
1375         // Recursion
1376         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1377         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1378       }
1379     }
1380
1381     aResultList.push_back(aFeature);
1382   }
1383   return aResultList;
1384 }
1385
1386 //**************************************************************
1387 // Returns the list of features placed between theObject and the current feature
1388 // in the same document. Excludes theObject, includes the current feature.
1389 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1390 {
1391   std::list<FeaturePtr> aResult;
1392   DocumentPtr aDocument = theObject->document();
1393   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1394   // find the object iterator
1395   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1396   if (aObjectIt == anAllFeatures.end())
1397     return aResult;
1398   // find the current feature iterator
1399   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1400   if (aCurrentIt == anAllFeatures.end())
1401     return aResult;
1402   // check the right order
1403   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1404     return aResult;
1405   // exclude the object
1406   std::advance(aObjectIt, 1);
1407   // include the current feature
1408   std::advance(aCurrentIt, 1);
1409   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1410 }
1411
1412 bool XGUI_Workshop::canMoveFeature()
1413 {
1414   QString anActionId = "MOVE_CMD";
1415
1416   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1417   QObjectPtrList aValidatedObjects;
1418   foreach (ObjectPtr aObject, aObjects) {
1419     if (!myModule->canApplyAction(aObject, anActionId))
1420       continue;
1421     // To be moved feature should be in active document
1422     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1423       continue;
1424     aValidatedObjects.append(aObject);
1425   }
1426   if (aValidatedObjects.size() != aObjects.size())
1427     aObjects = aValidatedObjects;
1428
1429   bool aCanMove = !aObjects.empty();
1430
1431   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1432   for (; anIt != aLast && aCanMove; anIt++) {
1433     ObjectPtr aObject = *anIt;
1434     // 1. Get features placed between selected and current in the document 
1435     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1436     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1437     if (aFeaturesBetween.empty())
1438       aCanMove = false;
1439     else {
1440       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1441       // 2. Get all reference features to the selected object in the document 
1442       std::set<FeaturePtr> aRefFeatures;
1443       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1444
1445       if (aRefFeatures.empty())
1446         continue;
1447       else {
1448         // 3. Find any placed features in all reference features
1449         std::set<FeaturePtr> aIntersectionFeatures;
1450         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1451                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1452                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1453         // 4. Return false if any reference feature is placed before current feature
1454         if (!aIntersectionFeatures.empty())
1455           aCanMove = false;
1456       }
1457     }
1458   }
1459   return aCanMove;
1460 }
1461
1462 //**************************************************************
1463 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1464 {
1465   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1466   if (!aCanBeShaded) {
1467     ResultCompSolidPtr aCompsolidResult =
1468                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1469     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1470       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1471         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1472     }
1473   }
1474   return aCanBeShaded;
1475 }
1476
1477 //**************************************************************
1478 bool XGUI_Workshop::canChangeColor() const
1479 {
1480   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1481
1482   std::set<std::string> aTypes;
1483   aTypes.insert(ModelAPI_ResultGroup::group());
1484   aTypes.insert(ModelAPI_ResultConstruction::group());
1485   aTypes.insert(ModelAPI_ResultBody::group());
1486   aTypes.insert(ModelAPI_ResultPart::group());
1487
1488   return hasResults(aObjects, aTypes);
1489 }
1490
1491 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1492 {
1493   if (!theResult.get())
1494     return;
1495
1496   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1497   if (aColorAttr.get() != NULL) {
1498     if (!aColorAttr->size()) {
1499       aColorAttr->setSize(3);
1500     }
1501     aColorAttr->setValue(0, theColor[0]);
1502     aColorAttr->setValue(1, theColor[1]);
1503     aColorAttr->setValue(2, theColor[2]);
1504   }
1505 }
1506
1507 //**************************************************************
1508 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1509 {
1510
1511   AttributeIntArrayPtr aColorAttr;
1512   // 1. find the current color of the object. This is a color of AIS presentation
1513   // The objects are iterated until a first valid color is found 
1514   std::vector<int> aColor;
1515   foreach(ObjectPtr anObject, theObjects) {
1516     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1517     if (aResult.get()) {
1518       XGUI_CustomPrs::getResultColor(aResult, aColor);
1519     }
1520     else {
1521       // TODO: remove the obtaining a color from the AIS object
1522       // this does not happen never because:
1523       // 1. The color can be changed only on results
1524       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1525       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1526       if (anAISObj.get()) {
1527         aColor.resize(3);
1528         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1529       }
1530     }
1531     if (!aColor.empty())
1532       break;
1533   }
1534   if (aColor.size() != 3)
1535     return;
1536
1537   if (!abortAllOperations())
1538   return; 
1539   // 2. show the dialog to change the value
1540   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1541   aDlg->setColor(aColor);
1542   aDlg->move(QCursor::pos());
1543   bool isDone = aDlg->exec() == QDialog::Accepted;
1544   if (!isDone)
1545     return;
1546
1547   bool isRandomColor = aDlg->isRandomColor();
1548
1549   // 3. abort the previous operation and start a new one
1550   SessionPtr aMgr = ModelAPI_Session::get();
1551   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1552   aMgr->startOperation(aDescription.toStdString());
1553
1554   // 4. set the value to all results
1555   std::vector<int> aColorResult = aDlg->getColor();
1556   foreach(ObjectPtr anObj, theObjects) {
1557     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1558     if (aResult.get() != NULL) {
1559       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1560       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1561         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1562           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1563         }
1564       }
1565       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1566     }
1567   }
1568   aMgr->finishOperation();
1569   updateCommandStatus();
1570 }
1571
1572 //**************************************************************
1573 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1574 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1575   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1576 }
1577 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1578 {
1579   foreach (ObjectPtr aObj, theList) {
1580     /*
1581     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1582     if (aPartRes) {
1583       DocumentPtr aDoc = aPartRes->partDoc();
1584       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1585       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1586       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1587     } else {
1588     */
1589       aObj->setDisplayed(isVisible);
1590     //}
1591   }
1592   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1593 }
1594
1595 //**************************************************************
1596 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1597 {
1598   // Hide all displayed objects
1599   QObjectPtrList aList = myDisplayer->displayedObjects();
1600   foreach (ObjectPtr aObj, aList) {
1601     if (module()->canEraseObject(aObj))
1602       aObj->setDisplayed(false);
1603   }
1604
1605   // Show only objects from the list
1606   foreach (ObjectPtr aObj, theList) {
1607     /*
1608     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1609     if (aPartRes) {
1610       DocumentPtr aDoc = aPartRes->partDoc();
1611       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1612       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1613       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1614     } else {
1615     */
1616       aObj->setDisplayed(true);
1617     //}
1618   }
1619   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1620
1621 }
1622
1623
1624 //**************************************************************
1625 void XGUI_Workshop::registerValidators() const
1626 {
1627   SessionPtr aMgr = ModelAPI_Session::get();
1628   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1629 }
1630
1631 //**************************************************************
1632 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1633 {
1634   if (!theDoc)
1635     return;
1636   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1637   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1638 }
1639
1640 //**************************************************************
1641 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1642 {
1643   for (int i = 0; i < theDoc->size(theGroup); i++) 
1644     theDoc->object(theGroup, i)->setDisplayed(true);
1645     //displayObject(theDoc->object(theGroup, i));
1646   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1647 }
1648
1649 //**************************************************************
1650 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1651 {
1652   foreach(ObjectPtr aObj, theList) {
1653     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1654
1655     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1656     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1657       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1658           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1659                                       (XGUI_Displayer::DisplayMode)theMode, false);
1660       }
1661     }
1662   }
1663   if (theList.size() > 0)
1664     myDisplayer->updateViewer();
1665 }
1666
1667 //**************************************************************
1668 void XGUI_Workshop::closeDocument()
1669 {
1670   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1671   while (anOperation) {
1672     anOperation->abort();
1673     anOperation = operationMgr()->currentOperation();
1674   }
1675   myDisplayer->closeLocalContexts();
1676   myDisplayer->eraseAll();
1677   objectBrowser()->clearContent();
1678
1679   module()->closeDocument();
1680
1681   SessionPtr aMgr = ModelAPI_Session::get();
1682   aMgr->closeAll();
1683 }
1684
1685 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1686 {
1687   XGUI_HistoryMenu* aMenu = NULL;
1688   if (isSalomeMode()) {
1689     QAction* anAction = qobject_cast<QAction*>(theObject);
1690     if (!anAction)
1691       return;
1692     aMenu = new XGUI_HistoryMenu(anAction);
1693   } else {
1694     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1695     aMenu = new XGUI_HistoryMenu(aButton);
1696   }
1697   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1698   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1699 }
1700
1701 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1702 {
1703   QList<ActionInfo> aResult;
1704   std::list<std::string>::const_iterator it = theList.cbegin();
1705   for (; it != theList.cend(); it++) {
1706     QString anId = QString::fromStdString(*it);
1707     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1708     if (isEditing) {
1709       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1710     }
1711     ActionInfo anInfo;
1712     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1713     if (aContextMenuAct) {
1714       anInfo.initFrom(aContextMenuAct);
1715     } else {
1716       anInfo = myActionsMgr->actionInfoById(anId);
1717     }
1718     if (isEditing) {
1719       anInfo.text = anInfo.text.prepend("Modify ");
1720     }
1721     aResult << anInfo;
1722   }
1723   return aResult;
1724 }
1725
1726 void XGUI_Workshop::synchronizeViewer()
1727 {
1728   SessionPtr aMgr = ModelAPI_Session::get();
1729   DocumentPtr aDoc = aMgr->activeDocument();
1730
1731   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1732   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1733   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1734   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1735 }
1736
1737 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1738                                              const std::string& theGroup, 
1739                                              bool theUpdateViewer)
1740 {
1741   ObjectPtr aObj;
1742   int aSize = theDoc->size(theGroup);
1743   for (int i = 0; i < aSize; i++) {
1744     aObj = theDoc->object(theGroup, i);
1745     if (aObj->isDisplayed())
1746       myDisplayer->display(aObj, false);
1747   }
1748   if (theUpdateViewer)
1749     myDisplayer->updateViewer();
1750 }