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