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