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