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