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