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