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