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