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