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