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