Salome HOME
d28a944b2a7a13526d3455314ab70fac1f21fe1c
[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   //myActionsMgr->update();
1006   return true;
1007 }
1008
1009 //******************************************************
1010 void XGUI_Workshop::updateCommandStatus()
1011 {
1012   QList<QAction*> aCommands;
1013 #ifdef HAVE_SALOME
1014     aCommands = salomeConnector()->commandList();
1015 #else
1016     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1017     foreach (AppElements_Command* aCmd, aMenuBar->features())
1018       aCommands.append(aCmd);
1019 #endif
1020   SessionPtr aMgr = ModelAPI_Session::get();
1021   if (aMgr->hasModuleDocument()) {
1022     foreach(QAction* aCmd, aCommands) {
1023       QString aId = aCmd->data().toString();
1024       if (aId == "UNDO_CMD")
1025         aCmd->setEnabled(myModule->canUndo());
1026       else if (aId == "REDO_CMD")
1027         aCmd->setEnabled(myModule->canRedo());
1028       else
1029         // Enable all commands
1030         aCmd->setEnabled(true);
1031     }
1032     updateHistory();
1033   } else {
1034     foreach(QAction* aCmd, aCommands) {
1035       QString aId = aCmd->data().toString();
1036       if (aId == "NEW_CMD")
1037         aCmd->setEnabled(true);
1038       else if (aId == "EXIT_CMD")
1039         aCmd->setEnabled(true);
1040       else
1041         aCmd->setEnabled(false);
1042     }
1043   }
1044   myActionsMgr->updateCommandsStatus();
1045   emit commandStatusUpdated();
1046 }
1047
1048 void XGUI_Workshop::updateHistory()
1049 {
1050   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1051   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1052   emit updateUndoHistory(aUndoRes);
1053
1054   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1055   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1056   emit updateRedoHistory(aRedoRes);
1057 }
1058
1059 //******************************************************
1060 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1061 {
1062   QDockWidget* aObjDock = new QDockWidget(theParent);
1063   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1064   aObjDock->setWindowTitle(tr("Object browser"));
1065   aObjDock->setStyleSheet(
1066       "::title { position: relative; padding-left: 5px; text-align: left center }");
1067   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1068   myModule->customizeObjectBrowser(myObjectBrowser);
1069   aObjDock->setWidget(myObjectBrowser);
1070
1071   myContextMenuMgr->connectObjectBrowser();
1072   return aObjDock;
1073 }
1074
1075 //******************************************************
1076 /*
1077  * Creates dock widgets, places them in corresponding area
1078  * and tabifies if necessary.
1079  */
1080 void XGUI_Workshop::createDockWidgets()
1081 {
1082   QMainWindow* aDesktop = desktop();
1083   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1084   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1085   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1086   myPropertyPanel->setupActions(myActionsMgr);
1087   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1088   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1089   hidePropertyPanel();  ///<! Invisible by default
1090   hideObjectBrowser();
1091   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1092   myPropertyPanel->installEventFilter(myOperationMgr);
1093
1094   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1095   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1096
1097   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1098   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1099
1100   QAction* aPreviewAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Preview);
1101   connect(aPreviewAct, SIGNAL(triggered()), this, SLOT(onPreviewActionClicked()));
1102
1103   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1104           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1105   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1106           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1107 }
1108
1109 //******************************************************
1110 void XGUI_Workshop::showPropertyPanel()
1111 {
1112   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1113   ///<! Restore ability to close panel from the window's menu
1114   aViewAct->setEnabled(true);
1115   myPropertyPanel->show();
1116   myPropertyPanel->raise();
1117
1118   // The next code is necessary to made the property panel the active window
1119   // in order to operation manager could process key events of the panel.
1120   // otherwise they are ignored. It happens only if the same(activateWindow) is
1121   // not happened by property panel activation(e.g. resume operation of Sketch)
1122   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1123   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1124 }
1125
1126 //******************************************************
1127 void XGUI_Workshop::hidePropertyPanel()
1128 {
1129   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1130   ///<! Do not allow to show empty property panel
1131   aViewAct->setEnabled(false);
1132   myPropertyPanel->hide();
1133
1134   // the property panel is active window of the desktop, when it is
1135   // hidden, it is undefined which window becomes active. By this reason
1136   // it is defined to perform the desktop as the active window.
1137   // in SALOME mode, workstack made the PyConsole the active window,
1138   // set the focus on it. As a result, shortcuts of the application, like
1139   // are processed by this console. For example Undo actions.
1140   // It is possible that this code is to be moved to SHAPER package
1141   QMainWindow* aDesktop = desktop();
1142   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1143   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1144 }
1145
1146 //******************************************************
1147 void XGUI_Workshop::showObjectBrowser()
1148 {
1149   if (!isSalomeMode())
1150     myObjectBrowser->parentWidget()->show();
1151 }
1152
1153 //******************************************************
1154 void XGUI_Workshop::hideObjectBrowser()
1155 {
1156   if (!isSalomeMode())
1157     myObjectBrowser->parentWidget()->hide();
1158 }
1159
1160 //******************************************************
1161 void XGUI_Workshop::salomeViewerSelectionChanged()
1162 {
1163   emit salomeViewerSelection();
1164 }
1165
1166 //**************************************************************
1167 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1168 {
1169   return mySalomeConnector->viewer();
1170 }
1171
1172 //**************************************************************
1173 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1174 {
1175   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1176   if (theId == "DELETE_CMD")
1177     deleteObjects();
1178   else if (theId == "CLEAN_HISTORY_CMD")
1179     cleanHistory();
1180   else if (theId == "MOVE_CMD")
1181     moveObjects();
1182   else if (theId == "COLOR_CMD")
1183     changeColor(aObjects);
1184   else if (theId == "SHOW_CMD") {
1185     showObjects(aObjects, true);
1186     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1187   }
1188   else if (theId == "HIDE_CMD")
1189     showObjects(aObjects, false);
1190   else if (theId == "SHOW_ONLY_CMD") {
1191     showOnlyObjects(aObjects);
1192     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1193   }
1194   else if (theId == "SHADING_CMD")
1195     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1196   else if (theId == "WIREFRAME_CMD")
1197     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1198   else if (theId == "HIDEALL_CMD") {
1199     QObjectPtrList aList = myDisplayer->displayedObjects();
1200     foreach (ObjectPtr aObj, aList) {
1201       if (module()->canEraseObject(aObj))
1202         aObj->setDisplayed(false);
1203     }
1204     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1205   } else if (theId == "SELECT_VERTEX_CMD") {
1206     setViewerSelectionMode(TopAbs_VERTEX);
1207   } else if (theId == "SELECT_EDGE_CMD") {
1208     setViewerSelectionMode(TopAbs_EDGE);
1209   } else if (theId == "SELECT_FACE_CMD") {
1210     setViewerSelectionMode(TopAbs_FACE);
1211   } else if (theId == "SELECT_RESULT_CMD") {
1212     setViewerSelectionMode(-1);
1213   } else if (theId == "SHOW_RESULTS_CMD") {
1214     highlightResults(aObjects);
1215   }
1216 }
1217
1218 //**************************************************************
1219 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1220 {
1221   myViewerSelMode = theMode;
1222   activateObjectsSelection(myDisplayer->displayedObjects());
1223 }
1224
1225 //**************************************************************
1226 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1227 {
1228   QIntList aModes;
1229   module()->activeSelectionModes(aModes);
1230   if (aModes.isEmpty() && (myViewerSelMode != -1))
1231     aModes.append(myViewerSelMode);
1232   myDisplayer->activateObjects(aModes, theList);
1233 }
1234
1235
1236 //**************************************************************
1237 void XGUI_Workshop::deleteObjects()
1238 {
1239   ModuleBase_IModule* aModule = module();
1240   // 1. allow the module to delete objects, do nothing if it has succeed
1241   if (aModule->deleteObjects()) {
1242     updateCommandStatus();
1243     return;
1244   }
1245
1246   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1247   if (!abortAllOperations())
1248     return;
1249   // check whether the object can be deleted. There should not be parts which are not loaded
1250   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1251     return;
1252
1253   bool hasResult = false;
1254   bool hasFeature = false;
1255   bool hasParameter = false;
1256   bool hasCompositeOwner = false;
1257   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1258   if (!(hasFeature || hasParameter))
1259     return;
1260
1261   // 3. delete objects
1262   std::set<FeaturePtr> anIgnoredFeatures;
1263   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1264   findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1265
1266   bool doDeleteReferences = true;
1267   if (isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1268                                     desktop(), doDeleteReferences)) {
1269     // start operation
1270     QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1271     aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1272     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1273     operationMgr()->startOperation(anOpAction);
1274
1275     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1276     // It is necessary to clear selection in order to avoid selection changed event during
1277     // deletion and negative consequences connected with processing of already deleted items
1278     mySelector->clearSelection();
1279
1280     // delete and commit/abort operation in model
1281     if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1282                                anIgnoredFeatures, doDeleteReferences))
1283       operationMgr()->commitOperation();
1284     else
1285       operationMgr()->abortOperation(operationMgr()->currentOperation());
1286   }
1287 }
1288
1289 //**************************************************************
1290 void XGUI_Workshop::cleanHistory()
1291 {
1292   if (!abortAllOperations())
1293     return;
1294
1295   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1296   QObjectPtrList aFeatures;
1297   foreach (ObjectPtr anObject, anObjects) {
1298     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1299     // for parameter result, use the corresponded reature to be removed
1300     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1301       aFeature = ModelAPI_Feature::feature(anObject);
1302     }
1303     aFeatures.append(aFeature);
1304   }
1305
1306   // 1. find all referenced features
1307   QList<ObjectPtr> anUnusedObjects;
1308   std::set<FeaturePtr> aDirectRefFeatures;
1309   //foreach (ObjectPtr anObject, anObjects) {
1310   foreach (ObjectPtr anObject, aFeatures) {
1311     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1312     // for parameter result, use the corresponded reature to be removed
1313     //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1314     //  aFeature = ModelAPI_Feature::feature(anObject);
1315     //}
1316     if (aFeature.get()) {
1317       std::set<FeaturePtr> alreadyProcessed;
1318       aDirectRefFeatures.clear();
1319       XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1320                                                     aDirectRefFeatures, alreadyProcessed);
1321       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1322         anUnusedObjects.append(aFeature);
1323     }
1324   }
1325
1326   // 2. warn about the references remove, break the delete operation if the user chose it
1327   if (!anUnusedObjects.empty()) {
1328     QStringList aNames;
1329     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1330       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1331       aNames.append(aFeature->name().c_str());
1332     }
1333     QString anUnusedNames = aNames.join(", ");
1334
1335     QString anActionId = "CLEAN_HISTORY_CMD";
1336     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1337
1338     QMessageBox aMessageBox(desktop());
1339     aMessageBox.setWindowTitle(aDescription);
1340     aMessageBox.setIcon(QMessageBox::Warning);
1341     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1342     aMessageBox.setDefaultButton(QMessageBox::No);
1343
1344     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1345                    .arg(anUnusedNames));
1346     /*QString aText;
1347     if (anUnusedNames.isEmpty()) {
1348       aMessageBox.setStandardButtons(QMessageBox::Ok);
1349       aMessageBox.setDefaultButton(QMessageBox::Ok);
1350
1351       aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1352     }
1353     else {
1354       aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1355       aMessageBox.setDefaultButton(QMessageBox::No);
1356
1357       aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1358         .arg(anUnusedNames));
1359     }*/
1360
1361     aMessageBox.setText(aText);
1362     if (aMessageBox.exec() == QMessageBox::No)
1363       return;
1364
1365     // 1. start operation
1366     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1367     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1368     operationMgr()->startOperation(anOpAction);
1369
1370     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1371     // It is necessary to clear selection in order to avoid selection changed event during
1372     // deletion and negative consequences connected with processing of already deleted items
1373     mySelector->clearSelection();
1374
1375     std::set<FeaturePtr> anIgnoredFeatures;
1376     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId)) {
1377       operationMgr()->commitOperation();
1378     }
1379     else {
1380       operationMgr()->abortOperation(operationMgr()->currentOperation());
1381     }
1382   }
1383   else {
1384     QString anActionId = "CLEAN_HISTORY_CMD";
1385     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1386
1387     QMessageBox aMessageBox(desktop());
1388     aMessageBox.setWindowTitle(aDescription);
1389     aMessageBox.setIcon(QMessageBox::Warning);
1390     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1391     aMessageBox.setDefaultButton(QMessageBox::No);
1392
1393     QString aText;
1394     aMessageBox.setStandardButtons(QMessageBox::Ok);
1395     aMessageBox.setDefaultButton(QMessageBox::Ok);
1396
1397     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1398     aMessageBox.setText(aText);
1399
1400     if (aMessageBox.exec() == QMessageBox::No)
1401       return;
1402   }
1403 }
1404
1405 //**************************************************************
1406 void XGUI_Workshop::moveObjects()
1407 {
1408   if (!abortAllOperations())
1409     return;
1410
1411   SessionPtr aMgr = ModelAPI_Session::get();
1412
1413   QString anActionId = "MOVE_CMD";
1414   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1415   aMgr->startOperation(aDescription.toStdString());
1416
1417   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1418   // It is necessary to clear selection in order to avoid selection changed event during
1419   // moving and negative consequences connected with processing of already moved items
1420   mySelector->clearSelection();
1421   // check whether the object can be moved. There should not be parts which are not loaded
1422   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1423     return;
1424
1425   DocumentPtr anActiveDocument = aMgr->activeDocument();
1426   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1427   foreach (ObjectPtr aObject, anObjects) {
1428     if (!myModule->canApplyAction(aObject, anActionId))
1429       continue;
1430
1431     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1432     if (aFeature.get()) {
1433       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1434       aCurrentFeature = anActiveDocument->currentFeature(true);
1435     }
1436   }
1437   aMgr->finishOperation();
1438 }
1439
1440 //**************************************************************
1441 void XGUI_Workshop::findReferences(const QObjectPtrList& theList,
1442                                    std::set<FeaturePtr>& aDirectRefFeatures,
1443                                    std::set<FeaturePtr>& aIndirectRefFeatures)
1444 {
1445   foreach (ObjectPtr aDeletedObj, theList) {
1446     std::set<FeaturePtr> alreadyProcessed;
1447     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1448                                             aIndirectRefFeatures, alreadyProcessed);
1449     std::set<FeaturePtr> aDifference;
1450     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1451                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1452                         std::inserter(aDifference, aDifference.begin()));
1453     aIndirectRefFeatures = aDifference;
1454   }
1455 }
1456
1457 bool XGUI_Workshop::isDeleteFeatureWithReferences(const QObjectPtrList& theList,
1458                                    const std::set<FeaturePtr>& aDirectRefFeatures,
1459                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
1460                                    QWidget* theParent,
1461                                    bool& doDeleteReferences)
1462 {
1463   doDeleteReferences = true;
1464
1465   QString aDirectNames, aIndirectNames;
1466   if (!aDirectRefFeatures.empty()) {
1467     QStringList aDirectRefNames;
1468     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1469       aDirectRefNames.append(aFeature->name().c_str());
1470     aDirectNames = aDirectRefNames.join(", ");
1471
1472     QStringList aIndirectRefNames;
1473     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1474       aIndirectRefNames.append(aFeature->name().c_str());
1475     aIndirectNames = aIndirectRefNames.join(", ");
1476   }
1477
1478   bool aCanReplaceParameters = !aDirectRefFeatures.empty();
1479   QStringList aPartFeatureNames;
1480   foreach (ObjectPtr aObj, theList) {
1481     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1482     // invalid feature data means that the feature is already removed in model,
1483     // we needn't process it. E.g. delete of feature from create operation. The operation abort
1484     // will delete the operation
1485     if (!aFeature->data()->isValid())
1486       continue;
1487     ResultPtr aFirstResult = aFeature->firstResult();
1488     if (!aFirstResult.get())
1489       continue;
1490     std::string aResultGroupName = aFirstResult->groupName();
1491     if (aResultGroupName == ModelAPI_ResultPart::group())
1492       aPartFeatureNames.append(aFeature->name().c_str());
1493
1494     if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
1495       aCanReplaceParameters = false;
1496   }
1497   QString aPartNames = aPartFeatureNames.join(", ");
1498
1499   QMessageBox aMessageBox(theParent);
1500   aMessageBox.setWindowTitle(tr("Delete features"));
1501   aMessageBox.setIcon(QMessageBox::Warning);
1502   aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1503   aMessageBox.setDefaultButton(QMessageBox::No);
1504
1505   QString aText;
1506   if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
1507     if (aCanReplaceParameters) {
1508       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")
1509                       .arg(aDirectNames));
1510       if (!aIndirectNames.isEmpty())
1511         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1512       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1513     } else {
1514       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
1515       if (!aIndirectNames.isEmpty())
1516         aText += QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
1517     }
1518   }
1519   if (!aPartNames.isEmpty())
1520     aText += QString(tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
1521
1522   if (!aText.isEmpty()) {
1523     aText += "Would you like to continue?";
1524     aMessageBox.setText(aText);
1525     aMessageBox.exec();
1526     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1527
1528     if (aButtonRole == QMessageBox::NoRole)
1529       return false;
1530
1531     if (aButtonRole == QMessageBox::ActionRole) {
1532       foreach (ObjectPtr aObj, theList)
1533         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1534       doDeleteReferences = false;
1535     }
1536   }
1537   return true;
1538 }
1539
1540 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1541                                    const std::set<FeaturePtr>& theIgnoredFeatures)
1542 {
1543   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1544   findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1545   return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1546                                 theIgnoredFeatures);
1547 }
1548
1549 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1550                                            const std::set<FeaturePtr>& aDirectRefFeatures,
1551                                            const std::set<FeaturePtr>& aIndirectRefFeatures,
1552                                            const std::set<FeaturePtr>& theIgnoredFeatures,
1553                                            const bool doDeleteReferences)
1554 {
1555   if (doDeleteReferences) {
1556     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1557     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1558     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1559                                          aLast = aFeaturesToDelete.end();
1560 #ifdef DEBUG_DELETE
1561     QStringList anInfo;
1562 #endif
1563     for (; anIt != aLast; anIt++) {
1564       FeaturePtr aFeature = (*anIt);
1565       DocumentPtr aDoc = aFeature->document();
1566       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1567         aDoc->removeFeature(aFeature);
1568 #ifdef DEBUG_DELETE
1569         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1570 #endif
1571       }
1572     }
1573 #ifdef DEBUG_DELETE
1574     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1575     anInfo.clear();
1576 #endif
1577   }
1578
1579   QString anActionId = "DELETE_CMD";
1580   return removeFeatures(theList, theIgnoredFeatures, anActionId);
1581 }
1582
1583 //**************************************************************
1584 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1585                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1586                                    const QString& theActionId)
1587 {
1588   bool isDone = false;
1589
1590   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1591   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1592   // 4. remove the parameter features
1593   foreach (ObjectPtr aObj, theList) {
1594     // features and parameters can be removed here,
1595     // the results are removed only by a corresponded feature remove
1596     std::string aGroupName = aObj->groupName();
1597     if (!anObjectGroups.contains(aGroupName.c_str()))
1598       continue;
1599
1600     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1601     if (aFeature) {
1602       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1603       // part features are removed in the PartSet module. This condition should be moved there
1604       if (aFeature->getKind() == "Part")
1605         continue;
1606         */
1607       DocumentPtr aDoc = aObj->document();
1608       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1609 #ifdef DEBUG_DELETE
1610         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1611         anInfo.append(anInfoStr);
1612         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1613 #endif
1614         aDoc->removeFeature(aFeature);
1615         isDone = true;
1616       }
1617     }
1618   }
1619 #ifdef DEBUG_DELETE
1620   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1621 #endif
1622   return true;
1623 }
1624
1625 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1626 {
1627   bool isFoundResultType = false;
1628   foreach(ObjectPtr anObj, theObjects)
1629   {
1630     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1631     if (aResult.get() == NULL)
1632       continue;
1633
1634     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1635     if (isFoundResultType)
1636       break;
1637   }
1638   return isFoundResultType;
1639 }
1640
1641 //**************************************************************
1642 // Returns the list of all features for theDocument and all features of
1643 // all nested parts.
1644 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1645 {
1646   std::list<FeaturePtr> aResultList;
1647   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1648   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1649     // The order of appending features of the part and the part itself is important
1650
1651     // Append features from a part feature
1652     foreach (const ResultPtr& aResult, aFeature->results()) {
1653       ResultPartPtr aResultPart =
1654           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1655       if (aResultPart.get() && aResultPart->partDoc().get()) {
1656         // Recursion
1657         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1658         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1659       }
1660     }
1661
1662     aResultList.push_back(aFeature);
1663   }
1664   return aResultList;
1665 }
1666
1667 //**************************************************************
1668 // Returns the list of features placed between theObject and the current feature
1669 // in the same document. Excludes theObject, includes the current feature.
1670 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1671 {
1672   std::list<FeaturePtr> aResult;
1673   DocumentPtr aDocument = theObject->document();
1674   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1675   // find the object iterator
1676   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1677   if (aObjectIt == anAllFeatures.end())
1678     return aResult;
1679   // find the current feature iterator
1680   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1681   if (aCurrentIt == anAllFeatures.end())
1682     return aResult;
1683   // check the right order
1684   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1685     return aResult;
1686   // exclude the object
1687   std::advance(aObjectIt, 1);
1688   // include the current feature
1689   std::advance(aCurrentIt, 1);
1690   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1691 }
1692
1693 bool XGUI_Workshop::canMoveFeature()
1694 {
1695   QString anActionId = "MOVE_CMD";
1696
1697   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1698   QObjectPtrList aValidatedObjects;
1699   foreach (ObjectPtr aObject, aObjects) {
1700     if (!myModule->canApplyAction(aObject, anActionId))
1701       continue;
1702     // To be moved feature should be in active document
1703     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1704       continue;
1705     aValidatedObjects.append(aObject);
1706   }
1707   if (aValidatedObjects.size() != aObjects.size())
1708     aObjects = aValidatedObjects;
1709
1710   bool aCanMove = !aObjects.empty();
1711
1712   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1713   for (; anIt != aLast && aCanMove; anIt++) {
1714     ObjectPtr aObject = *anIt;
1715     // 1. Get features placed between selected and current in the document 
1716     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1717     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1718     if (aFeaturesBetween.empty())
1719       aCanMove = false;
1720     else {
1721       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1722       // 2. Get all reference features to the selected object in the document 
1723       std::set<FeaturePtr> aRefFeatures;
1724       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1725
1726       if (aRefFeatures.empty())
1727         continue;
1728       else {
1729         // 3. Find any placed features in all reference features
1730         std::set<FeaturePtr> aIntersectionFeatures;
1731         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1732                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1733                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1734         // 4. Return false if any reference feature is placed before current feature
1735         if (!aIntersectionFeatures.empty())
1736           aCanMove = false;
1737       }
1738     }
1739   }
1740   return aCanMove;
1741 }
1742
1743 //**************************************************************
1744 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1745 {
1746   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1747   if (!aCanBeShaded) {
1748     ResultCompSolidPtr aCompsolidResult =
1749                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1750     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1751       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1752         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1753     }
1754   }
1755   return aCanBeShaded;
1756 }
1757
1758 //**************************************************************
1759 bool XGUI_Workshop::canChangeColor() const
1760 {
1761   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1762
1763   std::set<std::string> aTypes;
1764   aTypes.insert(ModelAPI_ResultGroup::group());
1765   aTypes.insert(ModelAPI_ResultConstruction::group());
1766   aTypes.insert(ModelAPI_ResultBody::group());
1767   aTypes.insert(ModelAPI_ResultPart::group());
1768
1769   return hasResults(aObjects, aTypes);
1770 }
1771
1772 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1773 {
1774   if (!theResult.get())
1775     return;
1776
1777   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1778   if (aColorAttr.get() != NULL) {
1779     if (!aColorAttr->size()) {
1780       aColorAttr->setSize(3);
1781     }
1782     aColorAttr->setValue(0, theColor[0]);
1783     aColorAttr->setValue(1, theColor[1]);
1784     aColorAttr->setValue(2, theColor[2]);
1785   }
1786 }
1787
1788 //**************************************************************
1789 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1790 {
1791
1792   AttributeIntArrayPtr aColorAttr;
1793   // 1. find the current color of the object. This is a color of AIS presentation
1794   // The objects are iterated until a first valid color is found 
1795   std::vector<int> aColor;
1796   foreach(ObjectPtr anObject, theObjects) {
1797     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1798     if (aResult.get()) {
1799       XGUI_CustomPrs::getResultColor(aResult, aColor);
1800     }
1801     else {
1802       // TODO: remove the obtaining a color from the AIS object
1803       // this does not happen never because:
1804       // 1. The color can be changed only on results
1805       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1806       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1807       if (anAISObj.get()) {
1808         aColor.resize(3);
1809         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1810       }
1811     }
1812     if (!aColor.empty())
1813       break;
1814   }
1815   if (aColor.size() != 3)
1816     return;
1817
1818   if (!abortAllOperations())
1819   return; 
1820   // 2. show the dialog to change the value
1821   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1822   aDlg->setColor(aColor);
1823   aDlg->move(QCursor::pos());
1824   bool isDone = aDlg->exec() == QDialog::Accepted;
1825   if (!isDone)
1826     return;
1827
1828   bool isRandomColor = aDlg->isRandomColor();
1829
1830   // 3. abort the previous operation and start a new one
1831   SessionPtr aMgr = ModelAPI_Session::get();
1832   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1833   aMgr->startOperation(aDescription.toStdString());
1834
1835   // 4. set the value to all results
1836   std::vector<int> aColorResult = aDlg->getColor();
1837   foreach(ObjectPtr anObj, theObjects) {
1838     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1839     if (aResult.get() != NULL) {
1840       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1841       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1842         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1843           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1844         }
1845       }
1846       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1847     }
1848   }
1849   aMgr->finishOperation();
1850   updateCommandStatus();
1851 }
1852
1853 //**************************************************************
1854 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1855 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1856   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1857 }
1858 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1859 {
1860   foreach (ObjectPtr aObj, theList) {
1861     /*
1862     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1863     if (aPartRes) {
1864       DocumentPtr aDoc = aPartRes->partDoc();
1865       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1866       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1867       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1868     } else {
1869     */
1870       aObj->setDisplayed(isVisible);
1871     //}
1872   }
1873   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1874 }
1875
1876 //**************************************************************
1877 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1878 {
1879   // Hide all displayed objects
1880   QObjectPtrList aList = myDisplayer->displayedObjects();
1881   foreach (ObjectPtr aObj, aList) {
1882     if (module()->canEraseObject(aObj))
1883       aObj->setDisplayed(false);
1884   }
1885
1886   // Show only objects from the list
1887   foreach (ObjectPtr aObj, theList) {
1888     /*
1889     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1890     if (aPartRes) {
1891       DocumentPtr aDoc = aPartRes->partDoc();
1892       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1893       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1894       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1895     } else {
1896     */
1897       aObj->setDisplayed(true);
1898     //}
1899   }
1900   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1901
1902 }
1903
1904
1905 //**************************************************************
1906 void XGUI_Workshop::registerValidators() const
1907 {
1908   SessionPtr aMgr = ModelAPI_Session::get();
1909   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1910 }
1911
1912 //**************************************************************
1913 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1914 {
1915   if (!theDoc)
1916     return;
1917   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1918   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1919 }
1920
1921 //**************************************************************
1922 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1923 {
1924   for (int i = 0; i < theDoc->size(theGroup); i++) 
1925     theDoc->object(theGroup, i)->setDisplayed(true);
1926     //displayObject(theDoc->object(theGroup, i));
1927   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1928 }
1929
1930 //**************************************************************
1931 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1932 {
1933   foreach(ObjectPtr aObj, theList) {
1934     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1935
1936     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1937     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1938       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1939           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1940                                       (XGUI_Displayer::DisplayMode)theMode, false);
1941       }
1942     }
1943   }
1944   if (theList.size() > 0)
1945     myDisplayer->updateViewer();
1946 }
1947
1948 //**************************************************************
1949 void XGUI_Workshop::closeDocument()
1950 {
1951   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1952   while (anOperation) {
1953     anOperation->abort();
1954     anOperation = operationMgr()->currentOperation();
1955   }
1956   myDisplayer->closeLocalContexts();
1957   myDisplayer->eraseAll();
1958   objectBrowser()->clearContent();
1959
1960   module()->closeDocument();
1961
1962   SessionPtr aMgr = ModelAPI_Session::get();
1963   aMgr->closeAll();
1964 }
1965
1966 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1967 {
1968   XGUI_HistoryMenu* aMenu = NULL;
1969   if (isSalomeMode()) {
1970     QAction* anAction = qobject_cast<QAction*>(theObject);
1971     if (!anAction)
1972       return;
1973     aMenu = new XGUI_HistoryMenu(anAction);
1974   } else {
1975     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1976     aMenu = new XGUI_HistoryMenu(aButton);
1977   }
1978   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1979   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1980 }
1981
1982 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1983 {
1984   QList<ActionInfo> aResult;
1985   std::list<std::string>::const_iterator it = theList.cbegin();
1986   for (; it != theList.cend(); it++) {
1987     QString anId = QString::fromStdString(*it);
1988     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1989     if (isEditing) {
1990       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1991     }
1992     ActionInfo anInfo;
1993     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1994     if (aContextMenuAct) {
1995       anInfo.initFrom(aContextMenuAct);
1996     } else {
1997       anInfo = myActionsMgr->actionInfoById(anId);
1998     }
1999     if (isEditing) {
2000       anInfo.text = anInfo.text.prepend("Modify ");
2001     }
2002     aResult << anInfo;
2003   }
2004   return aResult;
2005 }
2006
2007 void XGUI_Workshop::synchronizeViewer()
2008 {
2009   SessionPtr aMgr = ModelAPI_Session::get();
2010   DocumentPtr aDoc = aMgr->activeDocument();
2011
2012   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
2013   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
2014   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
2015   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
2016 }
2017
2018 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
2019                                              const std::string& theGroup, 
2020                                              bool theUpdateViewer)
2021 {
2022   ObjectPtr aObj;
2023   int aSize = theDoc->size(theGroup);
2024   for (int i = 0; i < aSize; i++) {
2025     aObj = theDoc->object(theGroup, i);
2026     if (aObj->isDisplayed()) {
2027       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
2028       // be changed to the object becomes visible when the shape becomes not empty
2029       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2030       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
2031         continue;
2032       myDisplayer->display(aObj, false);
2033     }
2034   }
2035   if (theUpdateViewer)
2036     myDisplayer->updateViewer();
2037 }
2038
2039 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
2040 {
2041   FeaturePtr aFeature;
2042   QObjectPtrList aSelList = theObjects;
2043   std::list<ResultPtr> aResList;
2044   foreach(ObjectPtr aObj, theObjects) {
2045     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
2046     if (aFeature.get()) {
2047       aResList = aFeature->results();
2048       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
2049       for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
2050         aSelList.append(*aIt);
2051       }
2052     }
2053   }
2054   if (aSelList.count() > theObjects.count()) {
2055     // if something was found
2056     bool aBlocked = objectBrowser()->blockSignals(true);
2057     objectBrowser()->setObjectsSelected(aSelList);
2058     objectBrowser()->blockSignals(aBlocked);
2059   }
2060 }