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