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