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