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