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