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