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