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