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