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