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