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