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