Salome HOME
4f5e03c28dac1759a55079d49c98c5ee27f83c4d
[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 }
1020
1021 //******************************************************
1022 void XGUI_Workshop::showPropertyPanel()
1023 {
1024   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1025   ///<! Restore ability to close panel from the window's menu
1026   aViewAct->setEnabled(true);
1027   myPropertyPanel->show();
1028   myPropertyPanel->raise();
1029
1030   // The next code is necessary to made the property panel the active window
1031   // in order to operation manager could process key events of the panel.
1032   // otherwise they are ignored. It happens only if the same(activateWindow) is
1033   // not happened by property panel activation(e.g. resume operation of Sketch)
1034   myPropertyPanel->activateWindow();
1035   myPropertyPanel->setFocus();
1036 }
1037
1038 //******************************************************
1039 void XGUI_Workshop::hidePropertyPanel()
1040 {
1041   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1042   ///<! Do not allow to show empty property panel
1043   aViewAct->setEnabled(false);
1044   myPropertyPanel->hide();
1045
1046   // the property panel is active window of the desktop, when it is
1047   // hidden, it is undefined which window becomes active. By this reason
1048   // it is defined to perform the desktop as the active window.
1049   // in SALOME mode, workstack made the PyConsole the active window,
1050   // set the focus on it. As a result, shortcuts of the application, like
1051   // are processed by this console. For example Undo actions.
1052   // It is possible that this code is to be moved to NewGeom package
1053   QMainWindow* aDesktop = desktop();
1054   aDesktop->activateWindow();
1055   aDesktop->setFocus();
1056 }
1057
1058 //******************************************************
1059 void XGUI_Workshop::showObjectBrowser()
1060 {
1061   myObjectBrowser->parentWidget()->show();
1062 }
1063
1064 //******************************************************
1065 void XGUI_Workshop::hideObjectBrowser()
1066 {
1067   myObjectBrowser->parentWidget()->hide();
1068 }
1069
1070 //******************************************************
1071 void XGUI_Workshop::salomeViewerSelectionChanged()
1072 {
1073   emit salomeViewerSelection();
1074 }
1075
1076 //**************************************************************
1077 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1078 {
1079   return mySalomeConnector->viewer();
1080 }
1081
1082 //**************************************************************
1083 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1084 {
1085   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1086   if (theId == "DELETE_CMD")
1087     deleteObjects();
1088   else if (theId == "MOVE_CMD")
1089     moveObjects();
1090   else if (theId == "COLOR_CMD")
1091     changeColor(aObjects);
1092   else if (theId == "SHOW_CMD")
1093     showObjects(aObjects, true);
1094   else if (theId == "HIDE_CMD")
1095     showObjects(aObjects, false);
1096   else if (theId == "SHOW_ONLY_CMD")
1097     showOnlyObjects(aObjects);
1098   else if (theId == "SHADING_CMD")
1099     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1100   else if (theId == "WIREFRAME_CMD")
1101     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1102   else if (theId == "HIDEALL_CMD") {
1103     QObjectPtrList aList = myDisplayer->displayedObjects();
1104     foreach (ObjectPtr aObj, aList) {
1105       if (module()->canEraseObject(aObj))
1106         aObj->setDisplayed(false);
1107     }
1108     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1109   }
1110 }
1111
1112 //**************************************************************
1113 void XGUI_Workshop::deleteObjects()
1114 {
1115   ModuleBase_IModule* aModule = module();
1116   // 1. allow the module to delete objects, do nothing if it has succeed
1117   if (aModule->deleteObjects()) {
1118     updateCommandStatus();
1119     return;
1120   }
1121
1122   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1123   if (!abortAllOperations())
1124     return;
1125   // It is necessary to clear selection in order to avoid selection changed event during
1126   // deletion and negative consequences connected with processing of already deleted items
1127   mySelector->clearSelection();
1128   // check whether the object can be deleted. There should not be parts which are not loaded
1129   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1130     return;
1131
1132   bool hasResult = false;
1133   bool hasFeature = false;
1134   bool hasParameter = false;
1135   bool hasSubFeature = false;
1136   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1137   if (!(hasFeature || hasParameter))
1138     return;
1139
1140   // 1. start operation
1141   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1142   aDescription += tr(" %1");
1143   QStringList aObjectNames;
1144   foreach (ObjectPtr aObj, anObjects) {
1145     if (!aObj->data()->isValid())
1146       continue;
1147     aObjectNames << QString::fromStdString(aObj->data()->name());
1148   }
1149   aDescription = aDescription.arg(aObjectNames.join(", "));
1150   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1151
1152   operationMgr()->startOperation(anOpAction);
1153   // 3. delete objects
1154   std::set<FeaturePtr> anIgnoredFeatures;
1155   if (deleteFeatures(anObjects, anIgnoredFeatures, desktop(), true)) {
1156     operationMgr()->commitOperation();
1157   }
1158   else {
1159     operationMgr()->abortOperation(operationMgr()->currentOperation());
1160   }
1161 }
1162
1163 //**************************************************************
1164 void XGUI_Workshop::moveObjects()
1165 {
1166   if (!abortAllOperations())
1167     return;
1168
1169   SessionPtr aMgr = ModelAPI_Session::get();
1170
1171   QString anActionId = "MOVE_CMD";
1172   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1173   aMgr->startOperation(aDescription.toStdString());
1174
1175   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1176   // It is necessary to clear selection in order to avoid selection changed event during
1177   // moving and negative consequences connected with processing of already moved items
1178   mySelector->clearSelection();
1179   // check whether the object can be moved. There should not be parts which are not loaded
1180   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1181     return;
1182
1183   DocumentPtr anActiveDocument = aMgr->activeDocument();
1184   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1185   foreach (ObjectPtr aObject, anObjects) {
1186     if (!myModule->canApplyAction(aObject, anActionId))
1187       continue;
1188
1189     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1190     if (aFeature.get()) {
1191       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1192       aCurrentFeature = anActiveDocument->currentFeature(true);
1193     }
1194   }
1195   aMgr->finishOperation();
1196 }
1197
1198 //**************************************************************
1199 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1200                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1201                                    QWidget* theParent,
1202                                    const bool theAskAboutDeleteReferences)
1203 {
1204 #ifdef DEBUG_DELETE
1205   QStringList aDInfo;
1206   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1207   for (; aDIt != aDLast; ++aDIt) {
1208     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1209   }
1210   QString anInfoStr = aDInfo.join(", ");
1211   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1212 #endif
1213
1214   // 1. find all referenced features
1215   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1216   foreach (ObjectPtr aDeletedObj, theList) {
1217     std::set<FeaturePtr> alreadyProcessed;
1218     XGUI_Tools::refsToFeatureInAllDocuments(
1219       aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures, alreadyProcessed);
1220     std::set<FeaturePtr> aDifference;
1221     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1222                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1223                         std::inserter(aDifference, aDifference.begin()));
1224     aIndirectRefFeatures = aDifference;
1225   }
1226
1227   bool doDeleteReferences = true;
1228
1229   // 2. warn about the references remove, break the delete operation if the user chose it
1230   if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1231     QStringList aDirectRefNames;
1232     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1233       aDirectRefNames.append(aFeature->name().c_str());
1234     QString aDirectNames = aDirectRefNames.join(", ");
1235
1236     QStringList aIndirectRefNames;
1237     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1238       aIndirectRefNames.append(aFeature->name().c_str());
1239     QString aIndirectNames = aIndirectRefNames.join(", ");
1240
1241     bool canReplaceParameters = true;
1242     foreach (ObjectPtr aObj, theList) {
1243       FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1244       if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1245         canReplaceParameters = false;
1246         break;
1247       }
1248     }
1249
1250     QMessageBox aMessageBox(theParent);
1251     aMessageBox.setWindowTitle(tr("Delete features"));
1252     aMessageBox.setIcon(QMessageBox::Warning);
1253     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1254     aMessageBox.setDefaultButton(QMessageBox::No);
1255
1256     QString aText;
1257     if (canReplaceParameters) {
1258       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?"))
1259           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1260       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1261     } else {
1262       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1263           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1264     }
1265     aMessageBox.setText(aText);
1266     aMessageBox.exec();
1267     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1268
1269     if (aButtonRole == QMessageBox::NoRole)
1270       return false;
1271
1272     if (aButtonRole == QMessageBox::ActionRole) {
1273       foreach (ObjectPtr aObj, theList)
1274         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1275       doDeleteReferences = false;
1276     }
1277   }
1278
1279   // 3. remove referenced features
1280   if (doDeleteReferences) {
1281     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1282     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1283     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1284                                          aLast = aFeaturesToDelete.end();
1285 #ifdef DEBUG_DELETE
1286     QStringList anInfo;
1287 #endif
1288     for (; anIt != aLast; anIt++) {
1289       FeaturePtr aFeature = (*anIt);
1290       DocumentPtr aDoc = aFeature->document();
1291       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1292         aDoc->removeFeature(aFeature);
1293 #ifdef DEBUG_DELETE
1294         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1295 #endif
1296       }
1297     }
1298 #ifdef DEBUG_DELETE
1299     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1300     anInfo.clear();
1301 #endif
1302   }
1303
1304   QString anActionId = "DELETE_CMD";
1305   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1306   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1307   // 4. remove the parameter features
1308   foreach (ObjectPtr aObj, theList) {
1309     // features and parameters can be removed here,
1310     // the results are removed only by a corresponded feature remove
1311     std::string aGroupName = aObj->groupName();
1312     if (!anObjectGroups.contains(aGroupName.c_str()))
1313       continue;
1314
1315     if (!myModule->canApplyAction(aObj, anActionId))
1316       continue;
1317
1318     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1319     if (aFeature) {
1320       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1321       // part features are removed in the PartSet module. This condition should be moved there
1322       if (aFeature->getKind() == "Part")
1323         continue;
1324         */
1325       DocumentPtr aDoc = aObj->document();
1326       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1327 #ifdef DEBUG_DELETE
1328         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1329         anInfo.append(anInfoStr);
1330         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1331 #endif
1332         aDoc->removeFeature(aFeature);
1333       }
1334     }
1335   }
1336 #ifdef DEBUG_DELETE
1337   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1338 #endif
1339   return true;
1340 }
1341
1342 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1343 {
1344   bool isFoundResultType = false;
1345   foreach(ObjectPtr anObj, theObjects)
1346   {
1347     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1348     if (aResult.get() == NULL)
1349       continue;
1350
1351     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1352     if (isFoundResultType)
1353       break;
1354   }
1355   return isFoundResultType;
1356 }
1357
1358 //**************************************************************
1359 // Returns the list of all features for theDocument and all features of
1360 // all nested parts.
1361 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1362 {
1363   std::list<FeaturePtr> aResultList;
1364   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1365   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1366     // The order of appending features of the part and the part itself is important
1367
1368     // Append features from a part feature
1369     foreach (const ResultPtr& aResult, aFeature->results()) {
1370       ResultPartPtr aResultPart =
1371           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1372       if (aResultPart.get() && aResultPart->partDoc().get()) {
1373         // Recursion
1374         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1375         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1376       }
1377     }
1378
1379     aResultList.push_back(aFeature);
1380   }
1381   return aResultList;
1382 }
1383
1384 //**************************************************************
1385 // Returns the list of features placed between theObject and the current feature
1386 // in the same document. Excludes theObject, includes the current feature.
1387 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1388 {
1389   std::list<FeaturePtr> aResult;
1390   DocumentPtr aDocument = theObject->document();
1391   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1392   // find the object iterator
1393   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1394   if (aObjectIt == anAllFeatures.end())
1395     return aResult;
1396   // find the current feature iterator
1397   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1398   if (aCurrentIt == anAllFeatures.end())
1399     return aResult;
1400   // check the right order
1401   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1402     return aResult;
1403   // exclude the object
1404   std::advance(aObjectIt, 1);
1405   // include the current feature
1406   std::advance(aCurrentIt, 1);
1407   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1408 }
1409
1410 bool XGUI_Workshop::canMoveFeature()
1411 {
1412   QString anActionId = "MOVE_CMD";
1413
1414   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1415   QObjectPtrList aValidatedObjects;
1416   foreach (ObjectPtr aObject, aObjects) {
1417     if (!myModule->canApplyAction(aObject, anActionId))
1418       continue;
1419     // To be moved feature should be in active document
1420     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1421       continue;
1422     aValidatedObjects.append(aObject);
1423   }
1424   if (aValidatedObjects.size() != aObjects.size())
1425     aObjects = aValidatedObjects;
1426
1427   bool aCanMove = !aObjects.empty();
1428
1429   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1430   for (; anIt != aLast && aCanMove; anIt++) {
1431     ObjectPtr aObject = *anIt;
1432     // 1. Get features placed between selected and current in the document 
1433     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1434     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1435     if (aFeaturesBetween.empty())
1436       aCanMove = false;
1437     else {
1438       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1439       // 2. Get all reference features to the selected object in the document 
1440       std::set<FeaturePtr> aRefFeatures;
1441       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1442
1443       if (aRefFeatures.empty())
1444         continue;
1445       else {
1446         // 3. Find any placed features in all reference features
1447         std::set<FeaturePtr> aIntersectionFeatures;
1448         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1449                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1450                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1451         // 4. Return false if any reference feature is placed before current feature
1452         if (!aIntersectionFeatures.empty())
1453           aCanMove = false;
1454       }
1455     }
1456   }
1457   return aCanMove;
1458 }
1459
1460 //**************************************************************
1461 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1462 {
1463   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1464   if (!aCanBeShaded) {
1465     ResultCompSolidPtr aCompsolidResult =
1466                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1467     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1468       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1469         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1470     }
1471   }
1472   return aCanBeShaded;
1473 }
1474
1475 //**************************************************************
1476 bool XGUI_Workshop::canChangeColor() const
1477 {
1478   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1479
1480   std::set<std::string> aTypes;
1481   aTypes.insert(ModelAPI_ResultGroup::group());
1482   aTypes.insert(ModelAPI_ResultConstruction::group());
1483   aTypes.insert(ModelAPI_ResultBody::group());
1484   aTypes.insert(ModelAPI_ResultPart::group());
1485
1486   return hasResults(aObjects, aTypes);
1487 }
1488
1489 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1490 {
1491   if (!theResult.get())
1492     return;
1493
1494   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1495   if (aColorAttr.get() != NULL) {
1496     if (!aColorAttr->size()) {
1497       aColorAttr->setSize(3);
1498     }
1499     aColorAttr->setValue(0, theColor[0]);
1500     aColorAttr->setValue(1, theColor[1]);
1501     aColorAttr->setValue(2, theColor[2]);
1502   }
1503 }
1504
1505 //**************************************************************
1506 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1507 {
1508
1509   AttributeIntArrayPtr aColorAttr;
1510   // 1. find the current color of the object. This is a color of AIS presentation
1511   // The objects are iterated until a first valid color is found 
1512   std::vector<int> aColor;
1513   foreach(ObjectPtr anObject, theObjects) {
1514     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1515     if (aResult.get()) {
1516       XGUI_CustomPrs::getResultColor(aResult, aColor);
1517     }
1518     else {
1519       // TODO: remove the obtaining a color from the AIS object
1520       // this does not happen never because:
1521       // 1. The color can be changed only on results
1522       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1523       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1524       if (anAISObj.get()) {
1525         aColor.resize(3);
1526         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1527       }
1528     }
1529     if (!aColor.empty())
1530       break;
1531   }
1532   if (aColor.size() != 3)
1533     return;
1534
1535   if (!abortAllOperations())
1536   return; 
1537   // 2. show the dialog to change the value
1538   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1539   aDlg->setColor(aColor);
1540   aDlg->move(QCursor::pos());
1541   bool isDone = aDlg->exec() == QDialog::Accepted;
1542   if (!isDone)
1543     return;
1544
1545   bool isRandomColor = aDlg->isRandomColor();
1546
1547   // 3. abort the previous operation and start a new one
1548   SessionPtr aMgr = ModelAPI_Session::get();
1549   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1550   aMgr->startOperation(aDescription.toStdString());
1551
1552   // 4. set the value to all results
1553   std::vector<int> aColorResult = aDlg->getColor();
1554   foreach(ObjectPtr anObj, theObjects) {
1555     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1556     if (aResult.get() != NULL) {
1557       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1558       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1559         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1560           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1561         }
1562       }
1563       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1564     }
1565   }
1566   aMgr->finishOperation();
1567   updateCommandStatus();
1568 }
1569
1570 //**************************************************************
1571 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1572 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1573   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1574 }
1575 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1576 {
1577   foreach (ObjectPtr aObj, theList) {
1578     /*
1579     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1580     if (aPartRes) {
1581       DocumentPtr aDoc = aPartRes->partDoc();
1582       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1583       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1584       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1585     } else {
1586     */
1587       aObj->setDisplayed(isVisible);
1588     //}
1589   }
1590   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1591 }
1592
1593 //**************************************************************
1594 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1595 {
1596   // Hide all displayed objects
1597   QObjectPtrList aList = myDisplayer->displayedObjects();
1598   foreach (ObjectPtr aObj, aList) {
1599     if (module()->canEraseObject(aObj))
1600       aObj->setDisplayed(false);
1601   }
1602
1603   // Show only objects from the list
1604   foreach (ObjectPtr aObj, theList) {
1605     /*
1606     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1607     if (aPartRes) {
1608       DocumentPtr aDoc = aPartRes->partDoc();
1609       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1610       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1611       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1612     } else {
1613     */
1614       aObj->setDisplayed(true);
1615     //}
1616   }
1617   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1618
1619 }
1620
1621
1622 //**************************************************************
1623 void XGUI_Workshop::registerValidators() const
1624 {
1625   SessionPtr aMgr = ModelAPI_Session::get();
1626   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1627 }
1628
1629 //**************************************************************
1630 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1631 {
1632   if (!theDoc)
1633     return;
1634   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1635   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1636 }
1637
1638 //**************************************************************
1639 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1640 {
1641   for (int i = 0; i < theDoc->size(theGroup); i++) 
1642     theDoc->object(theGroup, i)->setDisplayed(true);
1643     //displayObject(theDoc->object(theGroup, i));
1644   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1645 }
1646
1647 //**************************************************************
1648 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1649 {
1650   foreach(ObjectPtr aObj, theList) {
1651     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1652
1653     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1654     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1655       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1656           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1657                                       (XGUI_Displayer::DisplayMode)theMode, false);
1658       }
1659     }
1660   }
1661   if (theList.size() > 0)
1662     myDisplayer->updateViewer();
1663 }
1664
1665 //**************************************************************
1666 void XGUI_Workshop::closeDocument()
1667 {
1668   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1669   while (anOperation) {
1670     anOperation->abort();
1671     anOperation = operationMgr()->currentOperation();
1672   }
1673   myDisplayer->closeLocalContexts();
1674   myDisplayer->eraseAll();
1675   objectBrowser()->clearContent();
1676
1677   module()->closeDocument();
1678
1679   SessionPtr aMgr = ModelAPI_Session::get();
1680   aMgr->closeAll();
1681 }
1682
1683 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1684 {
1685   XGUI_HistoryMenu* aMenu = NULL;
1686   if (isSalomeMode()) {
1687     QAction* anAction = qobject_cast<QAction*>(theObject);
1688     if (!anAction)
1689       return;
1690     aMenu = new XGUI_HistoryMenu(anAction);
1691   } else {
1692     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1693     aMenu = new XGUI_HistoryMenu(aButton);
1694   }
1695   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1696   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1697 }
1698
1699 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1700 {
1701   QList<ActionInfo> aResult;
1702   std::list<std::string>::const_iterator it = theList.cbegin();
1703   for (; it != theList.cend(); it++) {
1704     QString anId = QString::fromStdString(*it);
1705     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1706     if (isEditing) {
1707       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1708     }
1709     ActionInfo anInfo;
1710     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1711     if (aContextMenuAct) {
1712       anInfo.initFrom(aContextMenuAct);
1713     } else {
1714       anInfo = myActionsMgr->actionInfoById(anId);
1715     }
1716     if (isEditing) {
1717       anInfo.text = anInfo.text.prepend("Modify ");
1718     }
1719     aResult << anInfo;
1720   }
1721   return aResult;
1722 }
1723
1724 void XGUI_Workshop::synchronizeViewer()
1725 {
1726   SessionPtr aMgr = ModelAPI_Session::get();
1727   DocumentPtr aDoc = aMgr->activeDocument();
1728
1729   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1730   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1731   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1732   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1733 }
1734
1735 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1736                                              const std::string& theGroup, 
1737                                              bool theUpdateViewer)
1738 {
1739   ObjectPtr aObj;
1740   int aSize = theDoc->size(theGroup);
1741   for (int i = 0; i < aSize; i++) {
1742     aObj = theDoc->object(theGroup, i);
1743     if (aObj->isDisplayed())
1744       myDisplayer->display(aObj, false);
1745   }
1746   if (theUpdateViewer)
1747     myDisplayer->updateViewer();
1748 }