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