]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
eebe7c38bc7354caad96142ce4e277105f1b7231
[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   myPropertyPanel->cleanContent();
571
572   QList<ModuleBase_ModelWidget*> aWidgets;
573   if (!module()->createWidgets(theOperation, aWidgets)) {
574     QString aXmlRepr = aFOperation->getDescription()->xmlRepresentation();
575     ModuleBase_WidgetFactory aFactory(aXmlRepr.toStdString(), myModuleConnector);
576     aFactory.createWidget(myPropertyPanel->contentWidget());
577     aWidgets = aFactory.getModelWidgets();
578   }
579
580   // check compatibility of feature and widgets
581   FeaturePtr aFeature = aFOperation->feature();
582   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
583     if (!aWidget->attributeID().empty() && !aFeature->attribute(aWidget->attributeID()).get()) {
584       std::string anErrorMsg = "The feature '" + aFeature->getKind() + "' has no attribute '"
585           + aWidget->attributeID() + "' used by widget '"
586           + aWidget->metaObject()->className() + "'.";
587       Events_Error::send(anErrorMsg);
588       myPropertyPanel->cleanContent();
589       return;
590     }
591   }
592
593   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
594     bool isStoreValue = !aFOperation->isEditOperation() &&
595                         !aWidget->getDefaultValue().empty() &&
596                         !aWidget->isComputedDefault();
597     aWidget->setFeature(aFOperation->feature(), isStoreValue);
598     aWidget->enableFocusProcessing();
599   }
600
601   myPropertyPanel->setModelWidgets(aWidgets);
602   aFOperation->setPropertyPanel(myPropertyPanel);
603
604   myModule->propertyPanelDefined(theOperation);
605
606 #ifndef DEBUG_FEATURE_NAME
607   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
608 #else
609   std::string aFeatureName = aFeature->name();
610   myPropertyPanel->setWindowTitle(QString("%1: %2").arg(theOperation->getDescription()->description())
611                                                   .arg(aFeatureName.c_str()));
612 #endif
613
614   myErrorMgr->setPropertyPanel(myPropertyPanel);
615 }
616
617 void XGUI_Workshop::connectToPropertyPanel(const bool isToConnect)
618 {
619   XGUI_PropertyPanel* aPropertyPanel = propertyPanel();
620   if (aPropertyPanel) {
621     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
622     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
623        myModule->connectToPropertyPanel(aWidget, isToConnect);
624       if (isToConnect) {
625         connect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
626       }
627       else {
628         disconnect(aWidget, SIGNAL(valueStateChanged(int)), this, SLOT(onWidgetStateChanged(int)));
629       }
630     }
631   }
632 }
633
634 /*
635  * Saves document with given name.
636  */
637 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
638 {
639   QApplication::restoreOverrideCursor();
640   SessionPtr aMgr = ModelAPI_Session::get();
641   aMgr->save(theName.toLatin1().constData(), theFileNames);
642   QApplication::restoreOverrideCursor();
643 }
644
645 bool XGUI_Workshop::abortAllOperations()
646 {
647   return myOperationMgr->abortAllOperations();
648 }
649
650 //******************************************************
651 void XGUI_Workshop::onOpen()
652 {
653   if(!abortAllOperations())
654     return;
655   //save current file before close if modified
656   SessionPtr aSession = ModelAPI_Session::get();
657   if (aSession->isModified()) {
658     //TODO(sbh): re-launch the app?
659     int anAnswer = QMessageBox::question(
660         desktop(), tr("Save current file"),
661         tr("The document is modified, save before opening another?"),
662         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
663     if (anAnswer == QMessageBox::Save) {
664       onSave();
665     } else if (anAnswer == QMessageBox::Cancel) {
666       return;
667     }
668     myCurrentDir = "";
669   }
670
671   //show file dialog, check if readable and open
672   myCurrentDir = QFileDialog::getExistingDirectory(desktop(), tr("Select directory"));
673   if (myCurrentDir.isEmpty())
674     return;
675   QFileInfo aFileInfo(myCurrentDir);
676   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
677     QMessageBox::critical(desktop(), tr("Warning"), tr("Unable to open the file."));
678     myCurrentDir = "";
679     return;
680   }
681   QApplication::setOverrideCursor(Qt::WaitCursor);
682   aSession->closeAll();
683   aSession->load(myCurrentDir.toLatin1().constData());
684   myObjectBrowser->rebuildDataTree();
685   updateCommandStatus();
686   QApplication::restoreOverrideCursor();
687 }
688
689 //******************************************************
690 void XGUI_Workshop::onNew()
691 {
692   QApplication::setOverrideCursor(Qt::WaitCursor);
693   if (objectBrowser() == 0) {
694     createDockWidgets();
695     mySelector->connectViewers();
696   }
697   myViewerProxy->connectToViewer();
698   showObjectBrowser();
699 #ifndef HAVE_SALOME
700   myMainWindow->showPythonConsole();
701   QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
702   aWnd->showMaximized();
703   updateCommandStatus();
704 #endif
705   myContextMenuMgr->connectViewer();
706   QApplication::restoreOverrideCursor();
707 }
708
709 #ifndef HAVE_SALOME
710 //******************************************************
711 void XGUI_Workshop::onExit()
712 {
713   SessionPtr aMgr = ModelAPI_Session::get();
714   if (aMgr->isModified()) {
715     int anAnswer = QMessageBox::question(
716         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
717         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
718     if (anAnswer == QMessageBox::Save) {
719       bool saved = onSave();
720       if (!saved) {
721         return;
722       }
723     } else if (anAnswer == QMessageBox::Cancel) {
724       return;
725     }
726   }
727   qApp->exit();
728 }
729
730 //******************************************************
731 void XGUI_Workshop::onPreferences()
732 {
733   ModuleBase_Prefs aModif;
734   ModuleBase_Preferences::editPreferences(aModif);
735   if (aModif.size() > 0) {
736     QString aSection;
737     foreach (ModuleBase_Pref aPref, aModif)
738     {
739       aSection = aPref.first;
740       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
741         myMainWindow->viewer()->updateFromResources();
742       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
743         myMainWindow->menuObject()->updateFromResources();
744       }
745     }
746     displayer()->redisplayObjects();
747   }
748 }
749 #endif
750
751 //******************************************************
752 void XGUI_Workshop::onTrihedronVisibilityChanged(bool theState)
753 {
754   XGUI_Displayer* aDisplayer = displayer();
755   if (aDisplayer)
756     aDisplayer->displayTrihedron(theState);
757 }
758
759 //******************************************************
760 bool XGUI_Workshop::onSave()
761 {
762   if(!abortAllOperations())
763     return false;
764   if (myCurrentDir.isEmpty()) {
765     return onSaveAs();
766   }
767   std::list<std::string> aFiles;
768   saveDocument(myCurrentDir, aFiles);
769   updateCommandStatus();
770 #ifndef HAVE_SALOME
771     myMainWindow->setModifiedState(false);
772 #endif
773   return true;
774 }
775
776 //******************************************************
777 bool XGUI_Workshop::onSaveAs()
778 {
779   if(!abortAllOperations())
780     return false;
781   QFileDialog dialog(desktop());
782   dialog.setWindowTitle(tr("Select directory to save files..."));
783   dialog.setFileMode(QFileDialog::Directory);
784   dialog.setFilter(tr("Directories (*)"));
785   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
786   dialog.setViewMode(QFileDialog::Detail);
787
788   if (!dialog.exec()) {
789     return false;
790   }
791
792   QString aTempDir = dialog.selectedFiles().first();
793   QDir aDir(aTempDir);
794   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
795     int answer = QMessageBox::question(
796         desktop(),
797         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
798         tr("Save"),
799         tr("The directory already contains some files, save anyway?"),
800         QMessageBox::Save | QMessageBox::Cancel);
801     if (answer == QMessageBox::Cancel) {
802       return false;
803     }
804   }
805   myCurrentDir = aTempDir;
806 #ifndef HAVE_SALOME
807     myMainWindow->setCurrentDir(myCurrentDir, false);
808     myMainWindow->setModifiedState(false);
809 #endif
810   return onSave();
811 }
812
813 //******************************************************
814 void XGUI_Workshop::onUndo(int theTimes)
815 {
816   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
817   SessionPtr aMgr = ModelAPI_Session::get();
818   std::list<std::string> aUndoList = aMgr->undoList();
819   if (aMgr->isOperation()) {
820     /// this is important for nested operations
821     /// when sketch operation is active, this condition is false and
822     /// the sketch operation is not aborted
823     operationMgr()->onAbortOperation();
824   }
825   std::list<std::string>::const_iterator aIt = aUndoList.cbegin();
826   for (int i = 0; (i < theTimes) && (aIt != aUndoList.cend()); ++i, ++aIt) {
827     aMgr->undo();
828     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
829       myObjectBrowser->rebuildDataTree();
830   }
831
832   operationMgr()->updateApplyOfOperations();
833   updateCommandStatus();
834 }
835
836 //******************************************************
837 void XGUI_Workshop::onRedo(int theTimes)
838 {
839   // the viewer update should be blocked in order to avoid the features blinking. For the created
840   // feature a results are created, the flush of the created signal caused the viewer redisplay for
841   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
842   // redo of all possible objects happens
843   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
844
845   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
846   SessionPtr aMgr = ModelAPI_Session::get();
847   std::list<std::string> aRedoList = aMgr->redoList();
848   if (aMgr->isOperation()) {
849     /// this is important for nested operations
850     /// when sketch operation is active, this condition is false and
851     /// the sketch operation is not aborted
852     operationMgr()->onAbortOperation();
853   }
854   std::list<std::string>::const_iterator aIt = aRedoList.cbegin();
855   for (int i = 0; (i < theTimes) && (aIt != aRedoList.cend()); ++i, ++aIt) {
856     aMgr->redo();
857     if (QString((*aIt).c_str()) == MOVE_TO_END_COMMAND)
858       myObjectBrowser->rebuildDataTree();
859   }
860   operationMgr()->updateApplyOfOperations();
861   updateCommandStatus();
862
863   // unblock the viewer update functionality and make update on purpose
864   myDisplayer->enableUpdateViewer(isUpdateEnabled);
865   myDisplayer->updateViewer();
866 }
867
868 //******************************************************
869 //void XGUI_Workshop::onRebuild()
870 //{
871 //  SessionPtr aMgr = ModelAPI_Session::get();
872 //  bool aWasOperation = aMgr->isOperation(); // keep this value
873 //  if (!aWasOperation) {
874 //    aMgr->startOperation("Rebuild");
875 //  }
876 //  static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
877 //  Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
878 //    new Events_Message(aRebuildEvent, this)));
879 //  if (!aWasOperation) {
880 //    aMgr->finishOperation();
881 //  }
882 //  updateCommandStatus();
883 //}
884
885 //******************************************************
886 void XGUI_Workshop::onWidgetStateChanged(int thePreviousState)
887 {
888   ModuleBase_ModelWidget* anActiveWidget = 0;
889   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
890   if (anOperation) {
891     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
892     if (aPanel)
893       anActiveWidget = aPanel->activeWidget();
894   }
895   if (anActiveWidget)
896     operationMgr()->onValidateOperation();
897
898   myModule->widgetStateChanged(thePreviousState);
899 }
900
901 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
902 {
903   QString libName = QString::fromStdString(library(theModule.toStdString()));
904   if (libName.isEmpty()) {
905     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
906     return 0;
907   }
908
909   QString err;
910   CREATE_FUNC crtInst = 0;
911
912 #ifdef WIN32
913   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
914   if (!modLib) {
915     LPVOID lpMsgBuf;
916     ::FormatMessage(
917         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
918         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
919     QString aMsg((char*) &lpMsgBuf);
920     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
921     ::LocalFree(lpMsgBuf);
922   } else {
923     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
924     if (!crtInst) {
925       LPVOID lpMsgBuf;
926       ::FormatMessage(
927           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
928               | FORMAT_MESSAGE_IGNORE_INSERTS,
929           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
930       QString aMsg((char*) &lpMsgBuf);
931       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
932       ::LocalFree(lpMsgBuf);
933     }
934   }
935 #else
936   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
937   if ( !modLib ) {
938     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
939   } else {
940     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
941     if ( !crtInst ) {
942       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
943     }
944   }
945 #endif
946
947   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
948
949   if (!err.isEmpty()) {
950     if (desktop()) {
951       Events_Error::send(err.toStdString());
952     } else {
953       qWarning(qPrintable(err));
954     }
955   }
956   return aModule;
957 }
958
959 //******************************************************
960 bool XGUI_Workshop::createModule()
961 {
962   Config_ModuleReader aModuleReader;
963   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
964   myModule = loadModule(moduleName);
965   if (!myModule)
966     return false;
967
968   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
969   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
970   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
971   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
972
973   myModule->createFeatures();
974   //myActionsMgr->update();
975   return true;
976 }
977
978 //******************************************************
979 void XGUI_Workshop::updateCommandStatus()
980 {
981   QList<QAction*> aCommands;
982 #ifdef HAVE_SALOME
983     aCommands = salomeConnector()->commandList();
984 #else
985     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
986     foreach (AppElements_Command* aCmd, aMenuBar->features())
987       aCommands.append(aCmd);
988 #endif
989   SessionPtr aMgr = ModelAPI_Session::get();
990   if (aMgr->hasModuleDocument()) {
991     foreach(QAction* aCmd, aCommands) {
992       QString aId = aCmd->data().toString();
993       if (aId == "UNDO_CMD")
994         aCmd->setEnabled(myModule->canUndo());
995       else if (aId == "REDO_CMD")
996         aCmd->setEnabled(myModule->canRedo());
997       else
998         // Enable all commands
999         aCmd->setEnabled(true);
1000     }
1001     updateHistory();
1002   } else {
1003     foreach(QAction* aCmd, aCommands) {
1004       QString aId = aCmd->data().toString();
1005       if (aId == "NEW_CMD")
1006         aCmd->setEnabled(true);
1007       else if (aId == "EXIT_CMD")
1008         aCmd->setEnabled(true);
1009       else
1010         aCmd->setEnabled(false);
1011     }
1012   }
1013   myActionsMgr->updateCommandsStatus();
1014   emit commandStatusUpdated();
1015 }
1016
1017 void XGUI_Workshop::updateHistory()
1018 {
1019   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1020   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1021   emit updateUndoHistory(aUndoRes);
1022
1023   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1024   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1025   emit updateRedoHistory(aRedoRes);
1026 }
1027
1028 //******************************************************
1029 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1030 {
1031   QDockWidget* aObjDock = new QDockWidget(theParent);
1032   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1033   aObjDock->setWindowTitle(tr("Object browser"));
1034   aObjDock->setStyleSheet(
1035       "::title { position: relative; padding-left: 5px; text-align: left center }");
1036   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1037   myModule->customizeObjectBrowser(myObjectBrowser);
1038   aObjDock->setWidget(myObjectBrowser);
1039
1040   myContextMenuMgr->connectObjectBrowser();
1041   return aObjDock;
1042 }
1043
1044 //******************************************************
1045 /*
1046  * Creates dock widgets, places them in corresponding area
1047  * and tabifies if necessary.
1048  */
1049 void XGUI_Workshop::createDockWidgets()
1050 {
1051   QMainWindow* aDesktop = desktop();
1052   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1053   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1054   myPropertyPanel = new XGUI_PropertyPanel(aDesktop, myOperationMgr);
1055   myPropertyPanel->setupActions(myActionsMgr);
1056   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1057   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1058   hidePropertyPanel();  ///<! Invisible by default
1059   hideObjectBrowser();
1060   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1061   myPropertyPanel->installEventFilter(myOperationMgr);
1062
1063   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1064   connect(aOkAct, SIGNAL(triggered()), this, SLOT(onAcceptActionClicked()));
1065
1066   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1067   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1068   connect(myPropertyPanel, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
1069           myOperationMgr,  SLOT(onKeyReleased(QObject*, QKeyEvent*)));
1070
1071   connect(myPropertyPanel, SIGNAL(enterClicked(QObject*)),
1072           myOperationMgr,  SLOT(onProcessEnter(QObject*)));
1073 }
1074
1075 //******************************************************
1076 void XGUI_Workshop::showPropertyPanel()
1077 {
1078   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1079   ///<! Restore ability to close panel from the window's menu
1080   aViewAct->setEnabled(true);
1081   myPropertyPanel->show();
1082   myPropertyPanel->raise();
1083
1084   // The next code is necessary to made the property panel the active window
1085   // in order to operation manager could process key events of the panel.
1086   // otherwise they are ignored. It happens only if the same(activateWindow) is
1087   // not happened by property panel activation(e.g. resume operation of Sketch)
1088   ModuleBase_Tools::activateWindow(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1089   ModuleBase_Tools::setFocus(myPropertyPanel, "XGUI_Workshop::showPropertyPanel()");
1090 }
1091
1092 //******************************************************
1093 void XGUI_Workshop::hidePropertyPanel()
1094 {
1095   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1096   ///<! Do not allow to show empty property panel
1097   aViewAct->setEnabled(false);
1098   myPropertyPanel->hide();
1099
1100   // the property panel is active window of the desktop, when it is
1101   // hidden, it is undefined which window becomes active. By this reason
1102   // it is defined to perform the desktop as the active window.
1103   // in SALOME mode, workstack made the PyConsole the active window,
1104   // set the focus on it. As a result, shortcuts of the application, like
1105   // are processed by this console. For example Undo actions.
1106   // It is possible that this code is to be moved to NewGeom package
1107   QMainWindow* aDesktop = desktop();
1108   ModuleBase_Tools::activateWindow(aDesktop, "XGUI_Workshop::hidePropertyPanel()");
1109   ModuleBase_Tools::setFocus(aDesktop, "XGUI_Workshop::showPropertyPanel()");
1110 }
1111
1112 //******************************************************
1113 void XGUI_Workshop::showObjectBrowser()
1114 {
1115   if (!isSalomeMode())
1116     myObjectBrowser->parentWidget()->show();
1117 }
1118
1119 //******************************************************
1120 void XGUI_Workshop::hideObjectBrowser()
1121 {
1122   if (!isSalomeMode())
1123     myObjectBrowser->parentWidget()->hide();
1124 }
1125
1126 //******************************************************
1127 void XGUI_Workshop::salomeViewerSelectionChanged()
1128 {
1129   emit salomeViewerSelection();
1130 }
1131
1132 //**************************************************************
1133 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1134 {
1135   return mySalomeConnector->viewer();
1136 }
1137
1138 //**************************************************************
1139 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1140 {
1141   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1142   if (theId == "DELETE_CMD")
1143     deleteObjects();
1144   else if (theId == "CLEAN_HISTORY_CMD")
1145     cleanHistory();
1146   else if (theId == "MOVE_CMD")
1147     moveObjects();
1148   else if (theId == "COLOR_CMD")
1149     changeColor(aObjects);
1150   else if (theId == "SHOW_CMD") {
1151     showObjects(aObjects, true);
1152     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1153   }
1154   else if (theId == "HIDE_CMD")
1155     showObjects(aObjects, false);
1156   else if (theId == "SHOW_ONLY_CMD") {
1157     showOnlyObjects(aObjects);
1158     mySelector->updateSelectionBy(ModuleBase_ISelection::Browser);
1159   }
1160   else if (theId == "SHADING_CMD")
1161     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1162   else if (theId == "WIREFRAME_CMD")
1163     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1164   else if (theId == "HIDEALL_CMD") {
1165     QObjectPtrList aList = myDisplayer->displayedObjects();
1166     foreach (ObjectPtr aObj, aList) {
1167       if (module()->canEraseObject(aObj))
1168         aObj->setDisplayed(false);
1169     }
1170     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1171   }
1172 }
1173
1174 //**************************************************************
1175 void XGUI_Workshop::deleteObjects()
1176 {
1177   ModuleBase_IModule* aModule = module();
1178   // 1. allow the module to delete objects, do nothing if it has succeed
1179   if (aModule->deleteObjects()) {
1180     updateCommandStatus();
1181     return;
1182   }
1183
1184   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1185   if (!abortAllOperations())
1186     return;
1187   // check whether the object can be deleted. There should not be parts which are not loaded
1188   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1189     return;
1190
1191   bool hasResult = false;
1192   bool hasFeature = false;
1193   bool hasParameter = false;
1194   bool hasSubFeature = false;
1195   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1196   if (!(hasFeature || hasParameter))
1197     return;
1198
1199   // 1. start operation
1200   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1201   aDescription += " " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1202   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1203   operationMgr()->startOperation(anOpAction);
1204
1205   // 3. delete objects
1206   std::set<FeaturePtr> anIgnoredFeatures;
1207   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1208   findReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures);
1209
1210   bool doDeleteReferences = true;
1211   if (isDeleteFeatureWithReferences(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1212                                     desktop(), doDeleteReferences)) {
1213     // It is necessary to clear selection in order to avoid selection changed event during
1214     // deletion and negative consequences connected with processing of already deleted items
1215     mySelector->clearSelection();
1216     if (deleteFeaturesInternal(anObjects, aDirectRefFeatures, aIndirectRefFeatures,
1217                                anIgnoredFeatures, doDeleteReferences))
1218       operationMgr()->commitOperation();
1219     else
1220       operationMgr()->abortOperation(operationMgr()->currentOperation());
1221   }
1222 }
1223
1224 //**************************************************************
1225 void XGUI_Workshop::cleanHistory()
1226 {
1227   if (!abortAllOperations())
1228     return;
1229
1230   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1231   QObjectPtrList aFeatures;
1232   foreach (ObjectPtr anObject, anObjects) {
1233     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1234     // for parameter result, use the corresponded reature to be removed
1235     if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1236       aFeature = ModelAPI_Feature::feature(anObject);
1237     }
1238     aFeatures.append(aFeature);
1239   }
1240
1241   // 1. find all referenced features
1242   QList<ObjectPtr> anUnusedObjects;
1243   std::set<FeaturePtr> aDirectRefFeatures;
1244   //foreach (ObjectPtr anObject, anObjects) {
1245   foreach (ObjectPtr anObject, aFeatures) {
1246     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1247     // for parameter result, use the corresponded reature to be removed
1248     //if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
1249     //  aFeature = ModelAPI_Feature::feature(anObject);
1250     //}
1251     if (aFeature.get()) {
1252       std::set<FeaturePtr> alreadyProcessed;
1253       aDirectRefFeatures.clear();
1254       XGUI_Tools::refsDirectToFeatureInAllDocuments(aFeature, aFeature, aFeatures,
1255                                                     aDirectRefFeatures, alreadyProcessed);
1256       if (aDirectRefFeatures.empty() && !anUnusedObjects.contains(aFeature))
1257         anUnusedObjects.append(aFeature);
1258     }
1259   }
1260
1261   // 2. warn about the references remove, break the delete operation if the user chose it
1262   if (!anUnusedObjects.empty()) {
1263     QStringList aNames;
1264     foreach (const ObjectPtr& anObject, anUnusedObjects) {
1265       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1266       aNames.append(aFeature->name().c_str());
1267     }
1268     QString anUnusedNames = aNames.join(", ");
1269
1270     QString anActionId = "CLEAN_HISTORY_CMD";
1271     QString aDescription = contextMenuMgr()->action(anActionId)->text();
1272
1273     QMessageBox aMessageBox(desktop());
1274     aMessageBox.setWindowTitle(aDescription);
1275     aMessageBox.setIcon(QMessageBox::Warning);
1276     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1277     aMessageBox.setDefaultButton(QMessageBox::No);
1278
1279     QString aText = QString(tr("Unused features are the following: %1.\nThese features will be deleted.\nWould you like to continue?")
1280                    .arg(anUnusedNames));
1281     aMessageBox.setText(aText);
1282     if (aMessageBox.exec() == QMessageBox::No)
1283       return;
1284
1285     // 1. start operation
1286     aDescription += "by deleting of " + aDescription.arg(XGUI_Tools::unionOfObjectNames(anObjects, ", "));
1287     ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1288     operationMgr()->startOperation(anOpAction);
1289
1290     std::set<FeaturePtr> anIgnoredFeatures;
1291     if (removeFeatures(anUnusedObjects, anIgnoredFeatures, anActionId)) {
1292       operationMgr()->commitOperation();
1293     }
1294     else {
1295       operationMgr()->abortOperation(operationMgr()->currentOperation());
1296     }
1297   }
1298 }
1299
1300 //**************************************************************
1301 void XGUI_Workshop::moveObjects()
1302 {
1303   if (!abortAllOperations())
1304     return;
1305
1306   SessionPtr aMgr = ModelAPI_Session::get();
1307
1308   QString anActionId = "MOVE_CMD";
1309   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1310   aMgr->startOperation(aDescription.toStdString());
1311
1312   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1313   // It is necessary to clear selection in order to avoid selection changed event during
1314   // moving and negative consequences connected with processing of already moved items
1315   mySelector->clearSelection();
1316   // check whether the object can be moved. There should not be parts which are not loaded
1317   if (!XGUI_Tools::canRemoveOrRename(desktop(), anObjects))
1318     return;
1319
1320   DocumentPtr anActiveDocument = aMgr->activeDocument();
1321   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1322   foreach (ObjectPtr aObject, anObjects) {
1323     if (!myModule->canApplyAction(aObject, anActionId))
1324       continue;
1325
1326     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1327     if (aFeature.get()) {
1328       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1329       aCurrentFeature = anActiveDocument->currentFeature(true);
1330     }
1331   }
1332   aMgr->finishOperation();
1333 }
1334
1335 //**************************************************************
1336 void XGUI_Workshop::findReferences(const QObjectPtrList& theList,
1337                                    std::set<FeaturePtr>& aDirectRefFeatures,
1338                                    std::set<FeaturePtr>& aIndirectRefFeatures)
1339 {
1340   foreach (ObjectPtr aDeletedObj, theList) {
1341     std::set<FeaturePtr> alreadyProcessed;
1342     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
1343                                             aIndirectRefFeatures, alreadyProcessed);
1344     std::set<FeaturePtr> aDifference;
1345     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1346                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1347                         std::inserter(aDifference, aDifference.begin()));
1348     aIndirectRefFeatures = aDifference;
1349   }
1350 }
1351
1352 bool XGUI_Workshop::isDeleteFeatureWithReferences(const QObjectPtrList& theList,
1353                                    const std::set<FeaturePtr>& aDirectRefFeatures,
1354                                    const std::set<FeaturePtr>& aIndirectRefFeatures,
1355                                    QWidget* theParent,
1356                                    bool& doDeleteReferences)
1357 {
1358   doDeleteReferences = true;
1359
1360   if (!aDirectRefFeatures.empty()) {
1361     QStringList aDirectRefNames;
1362     foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
1363       aDirectRefNames.append(aFeature->name().c_str());
1364     QString aDirectNames = aDirectRefNames.join(", ");
1365
1366     QStringList aIndirectRefNames;
1367     foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
1368       aIndirectRefNames.append(aFeature->name().c_str());
1369     QString aIndirectNames = aIndirectRefNames.join(", ");
1370
1371     bool canReplaceParameters = true;
1372     foreach (ObjectPtr aObj, theList) {
1373       FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1374       if (!std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aFeature->firstResult()).get()) { // the feature is not a parameter
1375         canReplaceParameters = false;
1376         break;
1377       }
1378     }
1379
1380     QMessageBox aMessageBox(theParent);
1381     aMessageBox.setWindowTitle(tr("Delete features"));
1382     aMessageBox.setIcon(QMessageBox::Warning);
1383     aMessageBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
1384     aMessageBox.setDefaultButton(QMessageBox::No);
1385
1386     QString aText;
1387     if (canReplaceParameters) {
1388       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?"))
1389           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames));
1390       QPushButton *aReplaceButton = aMessageBox.addButton(tr("Replace"), QMessageBox::ActionRole);
1391     } else {
1392       aText = QString(tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n%2Would you like to continue?"))
1393           .arg(aDirectNames).arg(aIndirectNames.isEmpty() ? QString() : QString(tr("Also these features will be deleted: %1.\n")).arg(aIndirectNames));
1394     }
1395     aMessageBox.setText(aText);
1396     aMessageBox.exec();
1397     QMessageBox::ButtonRole aButtonRole = aMessageBox.buttonRole(aMessageBox.clickedButton());
1398
1399     if (aButtonRole == QMessageBox::NoRole)
1400       return false;
1401
1402     if (aButtonRole == QMessageBox::ActionRole) {
1403       foreach (ObjectPtr aObj, theList)
1404         ModelAPI_ReplaceParameterMessage::send(aObj, this);
1405       doDeleteReferences = false;
1406     }
1407   }
1408   return true;
1409 }
1410
1411 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theFeatures,
1412                                    const std::set<FeaturePtr>& theIgnoredFeatures)
1413 {
1414   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1415   findReferences(theFeatures, aDirectRefFeatures, aIndirectRefFeatures);
1416   return deleteFeaturesInternal(theFeatures, aDirectRefFeatures, aIndirectRefFeatures,
1417                                 theIgnoredFeatures);
1418 }
1419
1420 bool XGUI_Workshop::deleteFeaturesInternal(const QObjectPtrList& theList,
1421                                            const std::set<FeaturePtr>& aDirectRefFeatures,
1422                                            const std::set<FeaturePtr>& aIndirectRefFeatures,
1423                                            const std::set<FeaturePtr>& theIgnoredFeatures,
1424                                            const bool doDeleteReferences)
1425 {
1426   if (doDeleteReferences) {
1427     std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1428     aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1429     std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1430                                          aLast = aFeaturesToDelete.end();
1431 #ifdef DEBUG_DELETE
1432     QStringList anInfo;
1433 #endif
1434     for (; anIt != aLast; anIt++) {
1435       FeaturePtr aFeature = (*anIt);
1436       DocumentPtr aDoc = aFeature->document();
1437       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1438         aDoc->removeFeature(aFeature);
1439 #ifdef DEBUG_DELETE
1440         anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1441 #endif
1442       }
1443     }
1444 #ifdef DEBUG_DELETE
1445     qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1446     anInfo.clear();
1447 #endif
1448   }
1449
1450   QString anActionId = "DELETE_CMD";
1451   return removeFeatures(theList, theIgnoredFeatures, anActionId);
1452 }
1453
1454 //**************************************************************
1455 bool XGUI_Workshop::removeFeatures(const QObjectPtrList& theList,
1456                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1457                                    const QString& theActionId)
1458 {
1459   bool isDone = false;
1460
1461   QString anId = QString::fromStdString(theActionId.toStdString().c_str());
1462   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1463   // 4. remove the parameter features
1464   foreach (ObjectPtr aObj, theList) {
1465     // features and parameters can be removed here,
1466     // the results are removed only by a corresponded feature remove
1467     std::string aGroupName = aObj->groupName();
1468     if (!anObjectGroups.contains(aGroupName.c_str()))
1469       continue;
1470
1471     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1472     if (aFeature) {
1473       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1474       // part features are removed in the PartSet module. This condition should be moved there
1475       if (aFeature->getKind() == "Part")
1476         continue;
1477         */
1478       DocumentPtr aDoc = aObj->document();
1479       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1480 #ifdef DEBUG_DELETE
1481         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1482         anInfo.append(anInfoStr);
1483         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1484 #endif
1485         aDoc->removeFeature(aFeature);
1486         isDone = true;
1487       }
1488     }
1489   }
1490 #ifdef DEBUG_DELETE
1491   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1492 #endif
1493   return true;
1494 }
1495
1496 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1497 {
1498   bool isFoundResultType = false;
1499   foreach(ObjectPtr anObj, theObjects)
1500   {
1501     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1502     if (aResult.get() == NULL)
1503       continue;
1504
1505     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1506     if (isFoundResultType)
1507       break;
1508   }
1509   return isFoundResultType;
1510 }
1511
1512 //**************************************************************
1513 // Returns the list of all features for theDocument and all features of
1514 // all nested parts.
1515 std::list<FeaturePtr> allFeatures(const DocumentPtr& theDocument)
1516 {
1517   std::list<FeaturePtr> aResultList;
1518   std::list<FeaturePtr> anAllFeatures = theDocument->allFeatures();
1519   foreach (const FeaturePtr& aFeature, anAllFeatures) {
1520     // The order of appending features of the part and the part itself is important
1521
1522     // Append features from a part feature
1523     foreach (const ResultPtr& aResult, aFeature->results()) {
1524       ResultPartPtr aResultPart =
1525           std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1526       if (aResultPart.get() && aResultPart->partDoc().get()) {
1527         // Recursion
1528         std::list<FeaturePtr> anAllFeatures = allFeatures(aResultPart->partDoc());
1529         aResultList.insert(aResultList.end(), anAllFeatures.begin(), anAllFeatures.end());
1530       }
1531     }
1532
1533     aResultList.push_back(aFeature);
1534   }
1535   return aResultList;
1536 }
1537
1538 //**************************************************************
1539 // Returns the list of features placed between theObject and the current feature
1540 // in the same document. Excludes theObject, includes the current feature.
1541 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1542 {
1543   std::list<FeaturePtr> aResult;
1544   DocumentPtr aDocument = theObject->document();
1545   std::list<FeaturePtr> anAllFeatures = allFeatures(aDocument);
1546   // find the object iterator
1547   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1548   if (aObjectIt == anAllFeatures.end())
1549     return aResult;
1550   // find the current feature iterator
1551   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1552   if (aCurrentIt == anAllFeatures.end())
1553     return aResult;
1554   // check the right order
1555   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1556     return aResult;
1557   // exclude the object
1558   std::advance(aObjectIt, 1);
1559   // include the current feature
1560   std::advance(aCurrentIt, 1);
1561   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1562 }
1563
1564 bool XGUI_Workshop::canMoveFeature()
1565 {
1566   QString anActionId = "MOVE_CMD";
1567
1568   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1569   QObjectPtrList aValidatedObjects;
1570   foreach (ObjectPtr aObject, aObjects) {
1571     if (!myModule->canApplyAction(aObject, anActionId))
1572       continue;
1573     // To be moved feature should be in active document
1574     if (aObject->document() != ModelAPI_Session::get()->activeDocument())
1575       continue;
1576     aValidatedObjects.append(aObject);
1577   }
1578   if (aValidatedObjects.size() != aObjects.size())
1579     aObjects = aValidatedObjects;
1580
1581   bool aCanMove = !aObjects.empty();
1582
1583   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1584   for (; anIt != aLast && aCanMove; anIt++) {
1585     ObjectPtr aObject = *anIt;
1586     // 1. Get features placed between selected and current in the document 
1587     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1588     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1589     if (aFeaturesBetween.empty())
1590       aCanMove = false;
1591     else {
1592       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1593       // 2. Get all reference features to the selected object in the document 
1594       std::set<FeaturePtr> aRefFeatures;
1595       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1596
1597       if (aRefFeatures.empty())
1598         continue;
1599       else {
1600         // 3. Find any placed features in all reference features
1601         std::set<FeaturePtr> aIntersectionFeatures;
1602         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1603                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1604                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1605         // 4. Return false if any reference feature is placed before current feature
1606         if (!aIntersectionFeatures.empty())
1607           aCanMove = false;
1608       }
1609     }
1610   }
1611   return aCanMove;
1612 }
1613
1614 //**************************************************************
1615 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1616 {
1617   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1618   if (!aCanBeShaded) {
1619     ResultCompSolidPtr aCompsolidResult =
1620                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1621     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1622       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1623         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1624     }
1625   }
1626   return aCanBeShaded;
1627 }
1628
1629 //**************************************************************
1630 bool XGUI_Workshop::canChangeColor() const
1631 {
1632   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1633
1634   std::set<std::string> aTypes;
1635   aTypes.insert(ModelAPI_ResultGroup::group());
1636   aTypes.insert(ModelAPI_ResultConstruction::group());
1637   aTypes.insert(ModelAPI_ResultBody::group());
1638   aTypes.insert(ModelAPI_ResultPart::group());
1639
1640   return hasResults(aObjects, aTypes);
1641 }
1642
1643 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1644 {
1645   if (!theResult.get())
1646     return;
1647
1648   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1649   if (aColorAttr.get() != NULL) {
1650     if (!aColorAttr->size()) {
1651       aColorAttr->setSize(3);
1652     }
1653     aColorAttr->setValue(0, theColor[0]);
1654     aColorAttr->setValue(1, theColor[1]);
1655     aColorAttr->setValue(2, theColor[2]);
1656   }
1657 }
1658
1659 //**************************************************************
1660 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1661 {
1662
1663   AttributeIntArrayPtr aColorAttr;
1664   // 1. find the current color of the object. This is a color of AIS presentation
1665   // The objects are iterated until a first valid color is found 
1666   std::vector<int> aColor;
1667   foreach(ObjectPtr anObject, theObjects) {
1668     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1669     if (aResult.get()) {
1670       XGUI_CustomPrs::getResultColor(aResult, aColor);
1671     }
1672     else {
1673       // TODO: remove the obtaining a color from the AIS object
1674       // this does not happen never because:
1675       // 1. The color can be changed only on results
1676       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1677       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1678       if (anAISObj.get()) {
1679         aColor.resize(3);
1680         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1681       }
1682     }
1683     if (!aColor.empty())
1684       break;
1685   }
1686   if (aColor.size() != 3)
1687     return;
1688
1689   if (!abortAllOperations())
1690   return; 
1691   // 2. show the dialog to change the value
1692   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(desktop());
1693   aDlg->setColor(aColor);
1694   aDlg->move(QCursor::pos());
1695   bool isDone = aDlg->exec() == QDialog::Accepted;
1696   if (!isDone)
1697     return;
1698
1699   bool isRandomColor = aDlg->isRandomColor();
1700
1701   // 3. abort the previous operation and start a new one
1702   SessionPtr aMgr = ModelAPI_Session::get();
1703   QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1704   aMgr->startOperation(aDescription.toStdString());
1705
1706   // 4. set the value to all results
1707   std::vector<int> aColorResult = aDlg->getColor();
1708   foreach(ObjectPtr anObj, theObjects) {
1709     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1710     if (aResult.get() != NULL) {
1711       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1712       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1713         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1714           setColor(aCompsolidResult->subResult(i), !isRandomColor ? aColorResult : aDlg->getRandomColor());
1715         }
1716       }
1717       setColor(aResult, !isRandomColor ? aColorResult : aDlg->getRandomColor());
1718     }
1719   }
1720   aMgr->finishOperation();
1721   updateCommandStatus();
1722 }
1723
1724 //**************************************************************
1725 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1726 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1727   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1728 }
1729 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1730 {
1731   foreach (ObjectPtr aObj, theList) {
1732     /*
1733     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1734     if (aPartRes) {
1735       DocumentPtr aDoc = aPartRes->partDoc();
1736       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1737       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1738       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1739     } else {
1740     */
1741       aObj->setDisplayed(isVisible);
1742     //}
1743   }
1744   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1745 }
1746
1747 //**************************************************************
1748 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1749 {
1750   // Hide all displayed objects
1751   QObjectPtrList aList = myDisplayer->displayedObjects();
1752   foreach (ObjectPtr aObj, aList) {
1753     if (module()->canEraseObject(aObj))
1754       aObj->setDisplayed(false);
1755   }
1756
1757   // Show only objects from the list
1758   foreach (ObjectPtr aObj, theList) {
1759     /*
1760     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1761     if (aPartRes) {
1762       DocumentPtr aDoc = aPartRes->partDoc();
1763       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1764       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1765       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1766     } else {
1767     */
1768       aObj->setDisplayed(true);
1769     //}
1770   }
1771   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1772
1773 }
1774
1775
1776 //**************************************************************
1777 void XGUI_Workshop::registerValidators() const
1778 {
1779   SessionPtr aMgr = ModelAPI_Session::get();
1780   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1781 }
1782
1783 //**************************************************************
1784 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1785 {
1786   if (!theDoc)
1787     return;
1788   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1789   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1790 }
1791
1792 //**************************************************************
1793 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1794 {
1795   for (int i = 0; i < theDoc->size(theGroup); i++) 
1796     theDoc->object(theGroup, i)->setDisplayed(true);
1797     //displayObject(theDoc->object(theGroup, i));
1798   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1799 }
1800
1801 //**************************************************************
1802 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1803 {
1804   foreach(ObjectPtr aObj, theList) {
1805     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1806
1807     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1808     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1809       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1810           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1811                                       (XGUI_Displayer::DisplayMode)theMode, false);
1812       }
1813     }
1814   }
1815   if (theList.size() > 0)
1816     myDisplayer->updateViewer();
1817 }
1818
1819 //**************************************************************
1820 void XGUI_Workshop::closeDocument()
1821 {
1822   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1823   while (anOperation) {
1824     anOperation->abort();
1825     anOperation = operationMgr()->currentOperation();
1826   }
1827   myDisplayer->closeLocalContexts();
1828   myDisplayer->eraseAll();
1829   objectBrowser()->clearContent();
1830
1831   module()->closeDocument();
1832
1833   SessionPtr aMgr = ModelAPI_Session::get();
1834   aMgr->closeAll();
1835 }
1836
1837 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1838 {
1839   XGUI_HistoryMenu* aMenu = NULL;
1840   if (isSalomeMode()) {
1841     QAction* anAction = qobject_cast<QAction*>(theObject);
1842     if (!anAction)
1843       return;
1844     aMenu = new XGUI_HistoryMenu(anAction);
1845   } else {
1846     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1847     aMenu = new XGUI_HistoryMenu(aButton);
1848   }
1849   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1850   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1851 }
1852
1853 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1854 {
1855   QList<ActionInfo> aResult;
1856   std::list<std::string>::const_iterator it = theList.cbegin();
1857   for (; it != theList.cend(); it++) {
1858     QString anId = QString::fromStdString(*it);
1859     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1860     if (isEditing) {
1861       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1862     }
1863     ActionInfo anInfo;
1864     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1865     if (aContextMenuAct) {
1866       anInfo.initFrom(aContextMenuAct);
1867     } else {
1868       anInfo = myActionsMgr->actionInfoById(anId);
1869     }
1870     if (isEditing) {
1871       anInfo.text = anInfo.text.prepend("Modify ");
1872     }
1873     aResult << anInfo;
1874   }
1875   return aResult;
1876 }
1877
1878 void XGUI_Workshop::synchronizeViewer()
1879 {
1880   SessionPtr aMgr = ModelAPI_Session::get();
1881   DocumentPtr aDoc = aMgr->activeDocument();
1882
1883   synchronizeGroupInViewer(aDoc, ModelAPI_ResultConstruction::group(), false);
1884   synchronizeGroupInViewer(aDoc, ModelAPI_ResultBody::group(), false);
1885   synchronizeGroupInViewer(aDoc, ModelAPI_ResultPart::group(), false);
1886   synchronizeGroupInViewer(aDoc, ModelAPI_ResultGroup::group(), false);
1887 }
1888
1889 void XGUI_Workshop::synchronizeGroupInViewer(const DocumentPtr& theDoc, 
1890                                              const std::string& theGroup, 
1891                                              bool theUpdateViewer)
1892 {
1893   ObjectPtr aObj;
1894   int aSize = theDoc->size(theGroup);
1895   for (int i = 0; i < aSize; i++) {
1896     aObj = theDoc->object(theGroup, i);
1897     if (aObj->isDisplayed())
1898       myDisplayer->display(aObj, false);
1899   }
1900   if (theUpdateViewer)
1901     myDisplayer->updateViewer();
1902 }