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