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