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