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