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