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