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