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