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