Salome HOME
Issue #1407: Provide selection of feature from result
[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   } else if (theId == "SHOW_FEATURE_CMD") {
1237     highlightFeature(aObjects);
1238   }
1239 }
1240
1241 //**************************************************************
1242 void XGUI_Workshop::setViewerSelectionMode(int theMode)
1243 {
1244   myViewerSelMode = theMode;
1245   activateObjectsSelection(myDisplayer->displayedObjects());
1246 }
1247
1248 //**************************************************************
1249 void XGUI_Workshop::activateObjectsSelection(const QObjectPtrList& theList)
1250 {
1251   QIntList aModes;
1252   module()->activeSelectionModes(aModes);
1253   if (aModes.isEmpty() && (myViewerSelMode != -1))
1254     aModes.append(myViewerSelMode);
1255   myDisplayer->activateObjects(aModes, theList);
1256 }
1257
1258
1259 //**************************************************************
1260 void XGUI_Workshop::deleteObjects()
1261 {
1262   ModuleBase_IModule* aModule = module();
1263   // 1. allow the module to delete objects, do nothing if it has succeed
1264   if (aModule->deleteObjects()) {
1265     updateCommandStatus();
1266     return;
1267   }
1268
1269   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1270   if (!abortAllOperations())
1271     return;
1272   // check whether the object can be deleted. There should not be parts which are not loaded
1273   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1274     return;
1275
1276   bool hasResult = false;
1277   bool hasFeature = false;
1278   bool hasParameter = false;
1279   bool hasCompositeOwner = false;
1280   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasCompositeOwner);
1281   if (!(hasFeature || hasParameter))
1282     return;
1283
1284   // 3. delete objects
1285   std::set<FeaturePtr> anIgnoredFeatures;
1286   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1287   ModuleBase_Tools::findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1288
1289   bool doDeleteReferences = true;
1290   if (ModuleBase_Tools::isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, 
1291       aIndirectRefFeatures, desktop(), doDeleteReferences)) {
1292     // start operation
1293     QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1294     aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1295     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1296     operationMgr()->startOperation(anOpAction);
1297
1298     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1299     // It is necessary to clear selection in order to avoid selection changed event during
1300     // deletion and negative consequences connected with processing of already deleted items
1301     mySelector->clearSelection();
1302
1303     // delete and commit/abort operation in model
1304     if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1305                                anIgnoredFeatures, doDeleteReferences))
1306       operationMgr()->commitOperation();
1307     else
1308       operationMgr()->abortOperation(operationMgr()->currentOperation());
1309   }
1310 }
1311
1312 //**************************************************************
1313 void XGUI_Workshop::cleanHistory()
1314 {
1315   if (!abortAllOperations())
1316     return;
1317
1318   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1319   QObjectPtrList aFeatures;
1320   foreach (ObjectPtr anObject, anObjects) {
1321     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1322     // for parameter result, use the corresponded reature to be removed
1323     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1324       aFeature = ModelAPI_Feature::feature(anObject);
1325     }
1326     aFeatures.append(aFeature);
1327   }
1328
1329   // 1. find all referenced features
1330   QList<ObjectPtr> anUnusedObjects;
1331   std::set<FeaturePtr> aDirectRefFeatures;
1332   //foreach (ObjectPtr anObject, anObjects) {
1333   foreach (ObjectPtr anObject, aFeatures) {
1334     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1335     // for parameter result, use the corresponded reature to be removed
1336     //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1337     //  aFeature = ModelAPI_Feature::feature(anObject);
1338     //}
1339     if (aFeature.get()) {
1340       std::set<FeaturePtr> alreadyProcessed;
1341       aDirectRefFeatures.clear();
1342       ModuleBase_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1343                                                     aDirectRefFeatures, alreadyProcessed);
1344       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1345         anUnusedObjects.append(aFeature);
1346     }
1347   }
1348
1349   // 2. warn about the references remove, break the delete operation if the user chose it
1350   if (!anUnusedObjects.empty()) {
1351     QStringList aNames;
1352     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1353       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1354       aNames.append(aFeature->name().c_str());
1355     }
1356     QString anUnusedNames = aNames.join(", ");
1357
1358     QString anActionId = "CLEAN_HISTORY_CMD";
1359     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1360
1361     QMessageBox aMessageBox(desktop());
1362     aMessageBox.setWindowTitle(aDescription);
1363     aMessageBox.setIcon(QMessageBox::Warning);
1364     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1365     aMessageBox.setDefaultButton(QMessageBox::No);
1366
1367     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1368                    .arg(anUnusedNames));
1369     /*QString aText;
1370     if (anUnusedNames.isEmpty()) {
1371       aMessageBox.setStandardButtons(QMessageBox::Ok);
1372       aMessageBox.setDefaultButton(QMessageBox::Ok);
1373
1374       aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1375     }
1376     else {
1377       aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1378       aMessageBox.setDefaultButton(QMessageBox::No);
1379
1380       aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1381         .arg(anUnusedNames));
1382     }*/
1383
1384     aMessageBox.setText(aText);
1385     if (aMessageBox.exec() == QMessageBox::No)
1386       return;
1387
1388     // 1. start operation
1389     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1390     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1391     operationMgr()->startOperation(anOpAction);
1392
1393     // WORKAROUND, should be done before each object remove, if it presents in XGUI_DataModel tree
1394     // It is necessary to clear selection in order to avoid selection changed event during
1395     // deletion and negative consequences connected with processing of already deleted items
1396     mySelector->clearSelection();
1397
1398     std::set<FeaturePtr> anIgnoredFeatures;
1399     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId, true)) {
1400       operationMgr()->commitOperation();
1401     }
1402     else {
1403       operationMgr()->abortOperation(operationMgr()->currentOperation());
1404     }
1405   }
1406   else {
1407     QString anActionId = "CLEAN_HISTORY_CMD";
1408     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1409
1410     QMessageBox aMessageBox(desktop());
1411     aMessageBox.setWindowTitle(aDescription);
1412     aMessageBox.setIcon(QMessageBox::Warning);
1413     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1414     aMessageBox.setDefaultButton(QMessageBox::No);
1415
1416     QString aText;
1417     aMessageBox.setStandardButtons(QMessageBox::Ok);
1418     aMessageBox.setDefaultButton(QMessageBox::Ok);
1419
1420     aText = QString(tr("All features are relevant, there is nothing to be deleted"));
1421     aMessageBox.setText(aText);
1422
1423     if (aMessageBox.exec() == QMessageBox::No)
1424       return;
1425   }
1426 }
1427
1428 //**************************************************************
1429 void XGUI_Workshop::moveObjects()
1430 {
1431   if (!abortAllOperations())
1432     return;
1433
1434   SessionPtr aMgr = ModelAPI_Session::get();
1435
1436   QString anActionId = "MOVE_CMD";
1437   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1438   aMgr->startOperation(aDescription.toStdString());
1439
1440   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1441   // It is necessary to clear selection in order to avoid selection changed event during
1442   // moving and negative consequences connected with processing of already moved items
1443   mySelector->clearSelection();
1444   // check whether the object can be moved. There should not be parts which are not loaded
1445   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1446     return;
1447
1448   DocumentPtr anActiveDocument = aMgr->activeDocument();
1449   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1450   foreach (ObjectPtr aObject, anObjects) {
1451     if (!myModule->canApplyAction(aObject, anActionId))
1452       continue;
1453
1454     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1455     if (aFeature.get()) {
1456       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1457       aCurrentFeature = anActiveDocument->currentFeature(true);
1458     }
1459   }
1460   aMgr->finishOperation();
1461 }
1462
1463 //**************************************************************
1464 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1465                                    const std::set<FeaturePtr>& theIgnoredFeatures)
1466 {
1467   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1468   ModuleBase_Tools::findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1469   return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1470                                 theIgnoredFeatures);
1471 }
1472
1473 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1474                                            const std::set<FeaturePtr>& aDirectRefFeatures,
1475                                            const std::set<FeaturePtr>& aIndirectRefFeatures,
1476                                            const std::set<FeaturePtr>& theIgnoredFeatures,
1477                                            const bool doDeleteReferences)
1478 {
1479   bool isDone = false;
1480   if (doDeleteReferences) {
1481     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1482     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1483     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1484                                          aLast = aFeaturesToDelete.end();
1485 #ifdef DEBUG_DELETE
1486     QStringList anInfo;
1487 #endif
1488     for (; anIt != aLast; anIt++) {
1489       FeaturePtr aFeature = (*anIt);
1490       DocumentPtr aDoc = aFeature->document();
1491       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1492         // flush REDISPLAY signal after remove feature
1493         aDoc->removeFeature(aFeature);
1494         isDone = true;
1495 #ifdef DEBUG_DELETE
1496         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1497 #endif
1498       }
1499     }
1500 #ifdef DEBUG_DELETE
1501     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1502     anInfo.clear();
1503 #endif
1504   }
1505
1506   QString anActionId = "DELETE_CMD";
1507   isDone = removeFeatures(theList, theIgnoredFeatures, anActionId, false) || isDone;
1508
1509   if (isDone) {
1510     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1511     // if should be done after removeFeature() of document
1512     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1513   }
1514   return isDone;
1515 }
1516
1517 //**************************************************************
1518 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1519                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1520                                    const QString& theActionId,
1521                                    const bool theFlushRedisplay)
1522 {
1523   bool isDone = false;
1524
1525   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1526   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1527   // 4. remove the parameter features
1528   foreach (ObjectPtr aObj, theList) {
1529     // features and parameters can be removed here,
1530     // the results are removed only by a corresponded feature remove
1531     std::string aGroupName = aObj->groupName();
1532     if (!anObjectGroups.contains(aGroupName.c_str()))
1533       continue;
1534
1535     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1536     if (aFeature) {
1537       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1538       // part features are removed in the PartSet module. This condition should be moved there
1539       if (aFeature->getKind() == "Part")
1540         continue;
1541         */
1542       DocumentPtr aDoc = aObj->document();
1543       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1544 #ifdef DEBUG_DELETE
1545         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1546         anInfo.append(anInfoStr);
1547         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1548 #endif
1549         // flush REDISPLAY signal after remove feature
1550         aDoc->removeFeature(aFeature);
1551         isDone = true;
1552       }
1553     }
1554   }
1555   if (isDone && theFlushRedisplay) {
1556     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
1557     // if should be done after removeFeature() of document
1558     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
1559   }
1560
1561 #ifdef DEBUG_DELETE
1562   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1563 #endif
1564   return true;
1565 }
1566
1567 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1568 {
1569   bool isFoundResultType = false;
1570   foreach(ObjectPtr anObj, theObjects)
1571   {
1572     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1573     if (aResult.get() == NULL)
1574       continue;
1575
1576     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1577     if (isFoundResultType)
1578       break;
1579   }
1580   return isFoundResultType;
1581 }
1582
1583 //**************************************************************
1584 // Returns the list of all features for theDocument and all features of
1585 // all nested parts.
1586 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1587 {
1588   std::list<FeaturePtr> aResultList;
1589   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1590   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1591     // The order of appending features of the part and the part itself is important
1592
1593     // Append features from a part feature
1594     foreach (const ResultPtr& aResult, aFeature->results()) {
1595       ResultPartPtr aResultPart =
1596           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1597       if (aResultPart.get() && aResultPart->partDoc().get()) {
1598         // Recursion
1599         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1600         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1601       }
1602     }
1603
1604     aResultList.push_back(aFeature);
1605   }
1606   return aResultList;
1607 }
1608
1609 //**************************************************************
1610 // Returns the list of features placed between theObject and the current feature
1611 // in the same document. Excludes theObject, includes the current feature.
1612 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1613 {
1614   std::list<FeaturePtr> aResult;
1615   DocumentPtr aDocument = theObject->document();
1616   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1617   // find the object iterator
1618   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1619   if (aObjectIt == anAllFeatures.end())
1620     return aResult;
1621   // find the current feature iterator
1622   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1623   if (aCurrentIt == anAllFeatures.end())
1624     return aResult;
1625   // check the right order
1626   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1627     return aResult;
1628   // exclude the object
1629   std::advance(aObjectIt, 1);
1630   // include the current feature
1631   std::advance(aCurrentIt, 1);
1632   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1633 }
1634
1635 bool XGUI_Workshop::canMoveFeature()
1636 {
1637   QString anActionId = "MOVE_CMD";
1638
1639   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1640   QObjectPtrList aValidatedObjects;
1641   foreach (ObjectPtr aObject, aObjects) {
1642     if (!myModule->canApplyAction(aObject, anActionId))
1643       continue;
1644     // To be moved feature should be in active document
1645     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1646       continue;
1647     aValidatedObjects.append(aObject);
1648   }
1649   if (aValidatedObjects.size() != aObjects.size())
1650     aObjects = aValidatedObjects;
1651
1652   bool aCanMove = !aObjects.empty();
1653
1654   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1655   for (; anIt != aLast && aCanMove; anIt++) {
1656     ObjectPtr aObject = *anIt;
1657     // 1. Get features placed between selected and current in the document 
1658     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1659     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1660     if (aFeaturesBetween.empty())
1661       aCanMove = false;
1662     else {
1663       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1664       // 2. Get all reference features to the selected object in the document 
1665       std::set<FeaturePtr> aRefFeatures;
1666       ModuleBase_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1667
1668       if (aRefFeatures.empty())
1669         continue;
1670       else {
1671         // 3. Find any placed features in all reference features
1672         std::set<FeaturePtr> aIntersectionFeatures;
1673         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1674                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1675                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1676         // 4. Return false if any reference feature is placed before current feature
1677         if (!aIntersectionFeatures.empty())
1678           aCanMove = false;
1679       }
1680     }
1681   }
1682   return aCanMove;
1683 }
1684
1685 //**************************************************************
1686 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1687 {
1688   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1689   if (!aCanBeShaded) {
1690     ResultCompSolidPtr aCompsolidResult =
1691                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1692     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1693       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1694         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1695     }
1696   }
1697   return aCanBeShaded;
1698 }
1699
1700 //**************************************************************
1701 bool XGUI_Workshop::canChangeColor() const
1702 {
1703   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1704
1705   std::set<std::string> aTypes;
1706   aTypes.insert(ModelAPI_ResultGroup::group());
1707   aTypes.insert(ModelAPI_ResultConstruction::group());
1708   aTypes.insert(ModelAPI_ResultBody::group());
1709   aTypes.insert(ModelAPI_ResultPart::group());
1710
1711   return hasResults(aObjects, aTypes);
1712 }
1713
1714 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1715 {
1716   if (!theResult.get())
1717     return;
1718
1719   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1720   if (aColorAttr.get() != NULL) {
1721     if (!aColorAttr->size()) {
1722       aColorAttr->setSize(3);
1723     }
1724     aColorAttr->setValue(0, theColor[0]);
1725     aColorAttr->setValue(1, theColor[1]);
1726     aColorAttr->setValue(2, theColor[2]);
1727   }
1728 }
1729
1730 //**************************************************************
1731 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1732 {
1733
1734   AttributeIntArrayPtr aColorAttr;
1735   // 1. find the current color of the object. This is a color of AIS presentation
1736   // The objects are iterated until a first valid color is found 
1737   std::vector<int> aColor;
1738   foreach(ObjectPtr anObject, theObjects) {
1739     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1740     if (aResult.get()) {
1741       XGUI_CustomPrs::getResultColor(aResult, aColor);
1742     }
1743     else {
1744       // TODO: remove the obtaining a color from the AIS object
1745       // this does not happen never because:
1746       // 1. The color can be changed only on results
1747       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1748       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1749       if (anAISObj.get()) {
1750         aColor.resize(3);
1751         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1752       }
1753     }
1754     if (!aColor.empty())
1755       break;
1756   }
1757   if (aColor.size() != 3)
1758     return;
1759
1760   if (!abortAllOperations())
1761   return; 
1762   // 2. show the dialog to change the value
1763   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1764   aDlg->setColor(aColor);
1765   aDlg->move(QCursor::pos());
1766   bool isDone = aDlg->exec() == QDialog::Accepted;
1767   if (!isDone)
1768     return;
1769
1770   bool isRandomColor = aDlg->isRandomColor();
1771
1772   // 3. abort the previous operation and start a new one
1773   SessionPtr aMgr = ModelAPI_Session::get();
1774   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1775   aMgr->startOperation(aDescription.toStdString());
1776
1777   // 4. set the value to all results
1778   std::vector<int> aColorResult = aDlg->getColor();
1779   foreach(ObjectPtr anObj, theObjects) {
1780     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1781     if (aResult.get() != NULL) {
1782       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1783       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1784         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1785           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1786         }
1787       }
1788       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1789     }
1790   }
1791   aMgr->finishOperation();
1792   updateCommandStatus();
1793 }
1794
1795 //**************************************************************
1796 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1797 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1798   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1799 }
1800 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1801 {
1802   foreach (ObjectPtr aObj, theList) {
1803     /*
1804     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1805     if (aPartRes) {
1806       DocumentPtr aDoc = aPartRes->partDoc();
1807       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1808       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1809       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1810     } else {
1811     */
1812       aObj->setDisplayed(isVisible);
1813     //}
1814   }
1815   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1816 }
1817
1818 //**************************************************************
1819 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1820 {
1821   // Hide all displayed objects
1822   QObjectPtrList aList = myDisplayer->displayedObjects();
1823   foreach (ObjectPtr aObj, aList) {
1824     if (module()->canEraseObject(aObj))
1825       aObj->setDisplayed(false);
1826   }
1827
1828   // Show only objects from the list
1829   foreach (ObjectPtr aObj, theList) {
1830     /*
1831     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1832     if (aPartRes) {
1833       DocumentPtr aDoc = aPartRes->partDoc();
1834       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1835       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1836       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1837     } else {
1838     */
1839       aObj->setDisplayed(true);
1840     //}
1841   }
1842   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1843
1844 }
1845
1846
1847 //**************************************************************
1848 void XGUI_Workshop::registerValidators() const
1849 {
1850   SessionPtr aMgr = ModelAPI_Session::get();
1851   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1852 }
1853
1854 //**************************************************************
1855 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1856 {
1857   if (!theDoc)
1858     return;
1859   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1860   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1861 }
1862
1863 //**************************************************************
1864 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1865 {
1866   for (int i = 0; i < theDoc->size(theGroup); i++) 
1867     theDoc->object(theGroup, i)->setDisplayed(true);
1868     //displayObject(theDoc->object(theGroup, i));
1869   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1870 }
1871
1872 //**************************************************************
1873 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1874 {
1875   foreach(ObjectPtr aObj, theList) {
1876     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1877
1878     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1879     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1880       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1881           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1882                                       (XGUI_Displayer::DisplayMode)theMode, false);
1883       }
1884     }
1885   }
1886   if (theList.size() > 0)
1887     myDisplayer->updateViewer();
1888 }
1889
1890 //**************************************************************
1891 void XGUI_Workshop::closeDocument()
1892 {
1893   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1894   while (anOperation) {
1895     anOperation->abort();
1896     anOperation = operationMgr()->currentOperation();
1897   }
1898   myDisplayer->closeLocalContexts();
1899   myDisplayer->eraseAll();
1900   objectBrowser()->clearContent();
1901
1902   module()->closeDocument();
1903
1904   SessionPtr aMgr = ModelAPI_Session::get();
1905   aMgr->closeAll();
1906 }
1907
1908 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1909 {
1910   XGUI_HistoryMenu* aMenu = NULL;
1911   if (isSalomeMode()) {
1912     QAction* anAction = qobject_cast<QAction*>(theObject);
1913     if (!anAction)
1914       return;
1915     aMenu = new XGUI_HistoryMenu(anAction);
1916   } else {
1917     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1918     aMenu = new XGUI_HistoryMenu(aButton);
1919   }
1920   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1921   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1922 }
1923
1924 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1925 {
1926   QList<ActionInfo> aResult;
1927   std::list<std::string>::const_iterator it = theList.cbegin();
1928   for (; it != theList.cend(); it++) {
1929     QString anId = QString::fromStdString(*it);
1930     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1931     if (isEditing) {
1932       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1933     }
1934     ActionInfo anInfo;
1935     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1936     if (aContextMenuAct) {
1937       anInfo.initFrom(aContextMenuAct);
1938     } else {
1939       anInfo = myActionsMgr->actionInfoById(anId);
1940     }
1941     if (isEditing) {
1942       anInfo.text = anInfo.text.prepend("Modify ");
1943     }
1944     aResult << anInfo;
1945   }
1946   return aResult;
1947 }
1948
1949 void XGUI_Workshop::synchronizeViewer()
1950 {
1951   SessionPtr aMgr = ModelAPI_Session::get();
1952   DocumentPtr aDoc = aMgr->activeDocument();
1953
1954   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1955   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1956   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1957   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1958 }
1959
1960 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1961                                              const std::string& theGroup, 
1962                                              bool theUpdateViewer)
1963 {
1964   ObjectPtr aObj;
1965   int aSize = theDoc->size(theGroup);
1966   for (int i = 0; i < aSize; i++) {
1967     aObj = theDoc->object(theGroup, i);
1968     if (aObj->isDisplayed()) {
1969       // Hide the presentation with an empty shape. But isDisplayed state of the object should not
1970       // be changed to the object becomes visible when the shape becomes not empty
1971       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1972       if (aRes.get() && (!aRes->shape().get() || aRes->shape()->isNull()))
1973         continue;
1974       myDisplayer->display(aObj, false);
1975     }
1976   }
1977   if (theUpdateViewer)
1978     myDisplayer->updateViewer();
1979 }
1980
1981 void XGUI_Workshop::highlightResults(const QObjectPtrList& theObjects)
1982 {
1983   FeaturePtr aFeature;
1984   QObjectPtrList aSelList = theObjects;
1985   std::list<ResultPtr> aResList;
1986   foreach(ObjectPtr aObj, theObjects) {
1987     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1988     if (aFeature.get()) {
1989       aResList = aFeature->results();
1990       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aIt;
1991       for(aIt = aResList.cbegin(); aIt != aResList.cend(); aIt++) {
1992         aSelList.append(*aIt);
1993       }
1994     }
1995   }
1996   if (aSelList.count() > theObjects.count()) {
1997     // if something was found
1998     bool aBlocked = objectBrowser()->blockSignals(true);
1999     objectBrowser()->setObjectsSelected(aSelList);
2000     objectBrowser()->blockSignals(aBlocked);
2001   }
2002 }
2003
2004 void XGUI_Workshop::highlightFeature(const QObjectPtrList& theObjects)
2005 {
2006   ResultPtr aResult;
2007   QObjectPtrList aSelList = theObjects;
2008   FeaturePtr aFeature;
2009   foreach(ObjectPtr aObj, theObjects) {
2010     aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
2011     if (aResult.get()) {
2012       aFeature = ModelAPI_Feature::feature(aResult);
2013       if (aFeature.get()) {
2014         aSelList.append(aFeature);
2015       }
2016     }
2017   }
2018   if (aSelList.count() > theObjects.count()) {
2019     // if something was found
2020     bool aBlocked = objectBrowser()->blockSignals(true);
2021     objectBrowser()->setObjectsSelected(aSelList);
2022     objectBrowser()->blockSignals(aBlocked);
2023   }
2024 }