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