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