Salome HOME
ebe199c4be719929259ac2d868e2e013dc1bef7c
[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   updateCommandStatus();
635   QApplication::restoreOverrideCursor();
636 }
637
638 //******************************************************
639 bool XGUI_Workshop::onSave()
640 {
641   if(!abortAllOperations())
642     return false;
643   if (myCurrentDir.isEmpty()) {
644     return onSaveAs();
645   }
646   std::list<std::string> aFiles;
647   saveDocument(myCurrentDir, aFiles);
648   updateCommandStatus();
649   if (!isSalomeMode())
650     myMainWindow->setModifiedState(false);
651   return true;
652 }
653
654 //******************************************************
655 bool XGUI_Workshop::onSaveAs()
656 {
657   if(!abortAllOperations())
658     return false;
659   QFileDialog dialog(mainWindow());
660   dialog.setWindowTitle(tr("Select directory to save files..."));
661   dialog.setFileMode(QFileDialog::Directory);
662   dialog.setFilter(tr("Directories (*)"));
663   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
664   dialog.setViewMode(QFileDialog::Detail);
665
666   if (!dialog.exec()) {
667     return false;
668   }
669
670   QString aTempDir = dialog.selectedFiles().first();
671   QDir aDir(aTempDir);
672   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
673     int answer = QMessageBox::question(
674         myMainWindow,
675         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
676         tr("Save"),
677         tr("The directory already contains some files, save anyway?"),
678         QMessageBox::Save | QMessageBox::Cancel);
679     if (answer == QMessageBox::Cancel) {
680       return false;
681     }
682   }
683   myCurrentDir = aTempDir;
684   if (!isSalomeMode()) {
685     myMainWindow->setCurrentDir(myCurrentDir, false);
686     myMainWindow->setModifiedState(false);
687   }
688   return onSave();
689 }
690
691 //******************************************************
692 void XGUI_Workshop::onUndo(int theTimes)
693 {
694   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
695   SessionPtr aMgr = ModelAPI_Session::get();
696   if (aMgr->isOperation()) {
697     /// this is important for nested operrations
698     /// when sketch opeation is active, this condition is false and 
699     /// the sketch operation is not aborted
700     operationMgr()->onAbortOperation();
701   }
702   for (int i = 0; i < theTimes; ++i) {
703     aMgr->undo();
704   }
705
706   operationMgr()->updateApplyOfOperations();
707   updateCommandStatus();
708 }
709
710 //******************************************************
711 void XGUI_Workshop::onRedo(int theTimes)
712 {
713   // the viewer update should be blocked in order to avoid the features blinking. For the created
714   // feature a results are created, the flush of the created signal caused the viewer redisplay for
715   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
716   // redo of all possible objects happens
717   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
718
719   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
720   SessionPtr aMgr = ModelAPI_Session::get();
721   if (aMgr->isOperation()) {
722     /// this is important for nested operrations
723     /// when sketch opeation is active, this condition is false and 
724     /// the sketch operation is not aborted
725     operationMgr()->onAbortOperation();
726   }
727   for (int i = 0; i < theTimes; ++i) {
728     aMgr->redo();
729   }
730   operationMgr()->updateApplyOfOperations();
731   updateCommandStatus();
732
733   // unblock the viewer update functionality and make update on purpose
734   myDisplayer->enableUpdateViewer(isUpdateEnabled);
735   myDisplayer->updateViewer();
736 }
737
738 //******************************************************
739 void XGUI_Workshop::onRebuild()
740 {
741   SessionPtr aMgr = ModelAPI_Session::get();
742   bool aWasOperation = aMgr->isOperation(); // keep this value
743   if (!aWasOperation) {
744     aMgr->startOperation("Rebuild");
745   }
746   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
747   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
748     new Events_Message(aRebuildEvent, this)));
749   if (!aWasOperation) {
750     aMgr->finishOperation();
751   }
752   updateCommandStatus();
753 }
754
755 //******************************************************
756 void XGUI_Workshop::onPreferences()
757 {
758   ModuleBase_Prefs aModif;
759   ModuleBase_Preferences::editPreferences(aModif);
760   if (aModif.size() > 0) {
761     QString aSection;
762     foreach (ModuleBase_Pref aPref, aModif)
763     {
764       aSection = aPref.first;
765       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
766         if (!isSalomeMode())
767           myMainWindow->viewer()->updateFromResources();
768       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
769         if (!isSalomeMode())
770           myMainWindow->menuObject()->updateFromResources();
771       }
772     }
773     displayer()->redisplayObjects();
774   }
775 }
776
777 //******************************************************
778 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
779 {
780   QString libName = QString::fromStdString(library(theModule.toStdString()));
781   if (libName.isEmpty()) {
782     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
783     return 0;
784   }
785
786   QString err;
787   CREATE_FUNC crtInst = 0;
788
789 #ifdef WIN32
790   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
791   if (!modLib) {
792     LPVOID lpMsgBuf;
793     ::FormatMessage(
794         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
795         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
796     QString aMsg((char*) &lpMsgBuf);
797     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
798     ::LocalFree(lpMsgBuf);
799   } else {
800     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
801     if (!crtInst) {
802       LPVOID lpMsgBuf;
803       ::FormatMessage(
804           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
805               | FORMAT_MESSAGE_IGNORE_INSERTS,
806           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
807       QString aMsg((char*) &lpMsgBuf);
808       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
809       ::LocalFree(lpMsgBuf);
810     }
811   }
812 #else
813   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
814   if ( !modLib ) {
815     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
816   } else {
817     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
818     if ( !crtInst ) {
819       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
820     }
821   }
822 #endif
823
824   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
825
826   if (!err.isEmpty()) {
827     if (mainWindow()) {
828       Events_Error::send(err.toStdString());
829     } else {
830       qWarning(qPrintable(err));
831     }
832   }
833   return aModule;
834 }
835
836 //******************************************************
837 bool XGUI_Workshop::createModule()
838 {
839   Config_ModuleReader aModuleReader;
840   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
841   myModule = loadModule(moduleName);
842   if (!myModule)
843     return false;
844
845   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
846   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
847   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
848   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
849
850   myModule->createFeatures();
851   //myActionsMgr->update();
852   return true;
853 }
854
855 //******************************************************
856 void XGUI_Workshop::updateCommandStatus()
857 {
858   QList<QAction*> aCommands;
859   if (isSalomeMode()) {  // update commands in SALOME mode
860     aCommands = salomeConnector()->commandList();
861   } else {
862     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
863     foreach (AppElements_Command* aCmd, aMenuBar->features())
864       aCommands.append(aCmd);
865   }
866   SessionPtr aMgr = ModelAPI_Session::get();
867   if (aMgr->hasModuleDocument()) {
868     foreach(QAction* aCmd, aCommands) {
869       QString aId = aCmd->data().toString();
870       if (aId == "UNDO_CMD")
871         aCmd->setEnabled(myModule->canUndo());
872       else if (aId == "REDO_CMD")
873         aCmd->setEnabled(myModule->canRedo());
874       else
875         // Enable all commands
876         aCmd->setEnabled(true);
877     }
878     updateHistory();
879   } else {
880     foreach(QAction* aCmd, aCommands) {
881       QString aId = aCmd->data().toString();
882       if (aId == "NEW_CMD")
883         aCmd->setEnabled(true);
884       else if (aId == "EXIT_CMD")
885         aCmd->setEnabled(true);
886       else
887         aCmd->setEnabled(false);
888     }
889   }
890   myActionsMgr->update();
891   emit commandStatusUpdated();
892 }
893
894 void XGUI_Workshop::updateHistory()
895 {
896   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
897   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
898   emit updateUndoHistory(aUndoRes);
899
900   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
901   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
902   emit updateRedoHistory(aRedoRes);
903 }
904
905 //******************************************************
906 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
907 {
908   QDockWidget* aObjDock = new QDockWidget(theParent);
909   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
910   aObjDock->setWindowTitle(tr("Object browser"));
911   aObjDock->setStyleSheet(
912       "::title { position: relative; padding-left: 5px; text-align: left center }");
913   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
914 #ifdef ModuleDataModel
915   myObjectBrowser->setDataModel(myModule->dataModel());
916 #endif
917   myModule->customizeObjectBrowser(myObjectBrowser);
918   aObjDock->setWidget(myObjectBrowser);
919
920   myContextMenuMgr->connectObjectBrowser();
921   return aObjDock;
922 }
923
924 //******************************************************
925 /*
926  * Creates dock widgets, places them in corresponding area
927  * and tabifies if necessary.
928  */
929 void XGUI_Workshop::createDockWidgets()
930 {
931   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
932   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
933   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
934   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
935   myPropertyPanel->setupActions(myActionsMgr);
936   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
937   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
938   hidePropertyPanel();  ///<! Invisible by default
939   hideObjectBrowser();
940   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
941   myPropertyPanel->installEventFilter(myOperationMgr);
942
943   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
944   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
945   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
946   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
947   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
948   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
949           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
950   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
951           aOkAct,          SLOT(setEnabled(bool)));
952 }
953
954 //******************************************************
955 void XGUI_Workshop::showPropertyPanel()
956 {
957   QAction* aViewAct = myPropertyPanel->toggleViewAction();
958   ///<! Restore ability to close panel from the window's menu
959   aViewAct->setEnabled(true);
960   myPropertyPanel->show();
961   myPropertyPanel->raise();
962 }
963
964 //******************************************************
965 void XGUI_Workshop::hidePropertyPanel()
966 {
967   QAction* aViewAct = myPropertyPanel->toggleViewAction();
968   ///<! Do not allow to show empty property panel
969   aViewAct->setEnabled(false);
970   myPropertyPanel->hide();
971 }
972
973 //******************************************************
974 void XGUI_Workshop::showObjectBrowser()
975 {
976   myObjectBrowser->parentWidget()->show();
977 }
978
979 //******************************************************
980 void XGUI_Workshop::hideObjectBrowser()
981 {
982   myObjectBrowser->parentWidget()->hide();
983 }
984
985 //******************************************************
986 void XGUI_Workshop::salomeViewerSelectionChanged()
987 {
988   emit salomeViewerSelection();
989 }
990
991 //**************************************************************
992 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
993 {
994   return mySalomeConnector->viewer();
995 }
996
997 //**************************************************************
998 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
999 {
1000   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1001   if (theId == "DELETE_CMD")
1002     deleteObjects();
1003   else if (theId == "MOVE_CMD")
1004     moveObjects();
1005   else if (theId == "COLOR_CMD")
1006     changeColor(aObjects);
1007   else if (theId == "SHOW_CMD")
1008     showObjects(aObjects, true);
1009   else if (theId == "HIDE_CMD")
1010     showObjects(aObjects, false);
1011   else if (theId == "SHOW_ONLY_CMD")
1012     showOnlyObjects(aObjects);
1013   else if (theId == "SHADING_CMD")
1014     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1015   else if (theId == "WIREFRAME_CMD")
1016     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1017   else if (theId == "HIDEALL_CMD") {
1018     QObjectPtrList aList = myDisplayer->displayedObjects();
1019     foreach (ObjectPtr aObj, aList) {
1020       if (module()->canEraseObject(aObj))
1021         aObj->setDisplayed(false);
1022     }
1023     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1024   }
1025 }
1026
1027 //**************************************************************
1028 void XGUI_Workshop::deleteObjects()
1029 {
1030   ModuleBase_IModule* aModule = module();
1031   // 1. allow the module to delete objects, do nothing if it has succeed
1032   if (aModule->deleteObjects()) {
1033     updateCommandStatus();
1034     return;
1035   }
1036
1037   if (!abortAllOperations())
1038     return;
1039   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1040   // It is necessary to clear selection in order to avoid selection changed event during
1041   // deleteion and negative consequences connected with processing of already deleted items
1042   mySelector->clearSelection();
1043   // check whether the object can be deleted. There should not be parts which are not loaded
1044   if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1045     return;
1046
1047   bool hasResult = false;
1048   bool hasFeature = false;
1049   bool hasParameter = false;
1050   bool hasSubFeature = false;
1051   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1052   if (!(hasFeature || hasParameter))
1053     return;
1054
1055   // 1. start operation
1056   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1057   aDescription += tr(" %1");
1058   QStringList aObjectNames;
1059   foreach (ObjectPtr aObj, anObjects) {
1060     if (!aObj->data()->isValid())
1061       continue;
1062     aObjectNames << QString::fromStdString(aObj->data()->name());
1063   }
1064   aDescription = aDescription.arg(aObjectNames.join(", "));
1065   ModuleBase_OperationAction* anOpAction = new ModuleBase_OperationAction(aDescription, module());
1066
1067   operationMgr()->startOperation(anOpAction);
1068   // 3. delete objects
1069   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1070   std::set<FeaturePtr> anIgnoredFeatures;
1071   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1072     operationMgr()->commitOperation();
1073   }
1074   else {
1075     operationMgr()->abortOperation(operationMgr()->currentOperation());
1076   }
1077 }
1078
1079 //**************************************************************
1080 void XGUI_Workshop::moveObjects()
1081 {
1082   if (!abortAllOperations())
1083     return;
1084
1085   SessionPtr aMgr = ModelAPI_Session::get();
1086
1087   QString anActionId = "MOVE_CMD";
1088   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1089   aMgr->startOperation(aDescription.toStdString());
1090
1091   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1092   DocumentPtr anActiveDocument = aMgr->activeDocument();
1093
1094   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1095   foreach (ObjectPtr aObject, anObjects) {
1096     if (!myModule->canApplyAction(aObject, anActionId))
1097       continue;
1098
1099     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1100     if (aFeature.get()) {
1101       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1102       aCurrentFeature = anActiveDocument->currentFeature(true);
1103     }
1104   }
1105   aMgr->finishOperation();
1106 }
1107
1108 //**************************************************************
1109 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1110                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1111                                    QWidget* theParent,
1112                                    const bool theAskAboutDeleteReferences)
1113 {
1114 #ifdef DEBUG_DELETE
1115   QStringList aDInfo;
1116   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1117   for (; aDIt != aDLast; ++aDIt) {
1118     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1119   }
1120   QString anInfoStr = aDInfo.join(", ");
1121   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1122 #endif
1123
1124   // 1. find all referenced features
1125   std::set<FeaturePtr> aDirectRefFeatures, aIndirectRefFeatures;
1126   foreach (ObjectPtr aDeletedObj, theList) {
1127     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aDirectRefFeatures, aIndirectRefFeatures);
1128     std::set<FeaturePtr> aDifference;
1129     std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
1130                         aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
1131                         std::inserter(aDifference, aDifference.begin()));
1132     aIndirectRefFeatures = aDifference;
1133   }
1134   // 2. warn about the references remove, break the delete operation if the user chose it
1135   if (theAskAboutDeleteReferences && !aDirectRefFeatures.empty()) {
1136     QStringList aDirectRefNames;
1137     foreach(const FeaturePtr& aFeature, aDirectRefFeatures)
1138       aDirectRefNames.append(aFeature->name().c_str());
1139     QString aDirectNames = aDirectRefNames.join(", ");
1140
1141     QStringList aIndirectRefNames;
1142     foreach(const FeaturePtr& aFeature, aIndirectRefFeatures)
1143       aIndirectRefNames.append(aFeature->name().c_str());
1144     QString aIndirectNames = aIndirectRefNames.join(", ");
1145
1146     QMessageBox::StandardButton aRes = QMessageBox::warning(
1147         theParent, tr("Delete features"),
1148         QString(tr("Selected features are used in the following features: %1.\
1149  These features will be deleted.\n%2Would you like to continue?")).arg(aDirectNames)
1150             .arg(aIndirectNames.isEmpty() ? QString() : QString("Also these features will be deleted: %1.\n").arg(aIndirectNames)),
1151         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1152     if (aRes != QMessageBox::Yes)
1153       return false;
1154   }
1155
1156   // 3. remove referenced features
1157   std::set<FeaturePtr> aFeaturesToDelete = aDirectRefFeatures;
1158   aFeaturesToDelete.insert(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end());
1159   std::set<FeaturePtr>::const_iterator anIt = aFeaturesToDelete.begin(),
1160                                        aLast = aFeaturesToDelete.end();
1161 #ifdef DEBUG_DELETE
1162   QStringList anInfo;
1163 #endif
1164   for (; anIt != aLast; anIt++) {
1165     FeaturePtr aFeature = (*anIt);
1166     DocumentPtr aDoc = aFeature->document();
1167     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1168       aDoc->removeFeature(aFeature);
1169 #ifdef DEBUG_DELETE
1170       anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1171 #endif
1172     }
1173   }
1174 #ifdef DEBUG_DELETE
1175   qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1176   anInfo.clear();
1177 #endif
1178
1179   QString anActionId = "DELETE_CMD";
1180   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1181   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1182   // 4. remove the parameter features
1183   foreach (ObjectPtr aObj, theList) {
1184     // features and parameters can be removed here,
1185     // the results are removed only by a corresponded feature remove
1186     std::string aGroupName = aObj->groupName();
1187     if (!anObjectGroups.contains(aGroupName.c_str()))
1188       continue;
1189
1190     if (!myModule->canApplyAction(aObj, anActionId))
1191       continue;
1192
1193     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1194     if (aFeature) {
1195       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1196       // part features are removed in the PartSet module. This condition should be moved there
1197       if (aFeature->getKind() == "Part")
1198         continue;
1199         */
1200       DocumentPtr aDoc = aObj->document();
1201       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1202 #ifdef DEBUG_DELETE
1203         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1204         anInfo.append(anInfoStr);
1205         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1206 #endif
1207         aDoc->removeFeature(aFeature);
1208       }
1209     }
1210   }
1211 #ifdef DEBUG_DELETE
1212   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1213 #endif
1214   return true;
1215 }
1216
1217 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1218 {
1219   bool isFoundResultType = false;
1220   foreach(ObjectPtr anObj, theObjects)
1221   {
1222     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1223     if (aResult.get() == NULL)
1224       continue;
1225
1226     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1227     if (isFoundResultType)
1228       break;
1229   }
1230   return isFoundResultType;
1231 }
1232
1233 //**************************************************************
1234 // Returns the list of features placed between theObject and the current feature
1235 // in the same document. Excludes theObject, includes the current feature.
1236 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1237 {
1238   std::list<FeaturePtr> aResult;
1239   DocumentPtr aDocument = theObject->document();
1240   std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1241   // find the object iterator
1242   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1243   if (aObjectIt == anAllFeatures.end()) 
1244     return aResult;
1245   // find the current feature iterator
1246   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1247   if (aCurrentIt == anAllFeatures.end()) 
1248     return aResult;
1249   // check the right order
1250   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1251     return aResult;
1252   // exclude the object
1253   std::advance(aObjectIt, 1);
1254   // include the current feature
1255   std::advance(aCurrentIt, 1);
1256   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1257 }
1258
1259 bool XGUI_Workshop::canMoveFeature()
1260 {
1261   QString anActionId = "MOVE_CMD";
1262
1263   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1264   QObjectPtrList aValidatedObjects;
1265   foreach (ObjectPtr aObject, aObjects) {
1266     if (myModule->canApplyAction(aObject, anActionId))
1267       aValidatedObjects.append(aObject);
1268   }
1269   if (aValidatedObjects.size() != aObjects.size())
1270     aObjects = aValidatedObjects;
1271
1272   bool aCanMove = !aObjects.empty();
1273
1274   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1275   for (; anIt != aLast && aCanMove; anIt++) {
1276     ObjectPtr aObject = *anIt;
1277     // 1. Get features placed between selected and current in the document 
1278     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1279     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1280     if (aFeaturesBetween.empty())
1281       aCanMove = false;
1282     else {
1283       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1284       // 2. Get all reference features to the selected object in the document 
1285       std::set<FeaturePtr> aRefFeatures;
1286       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1287
1288       if (aRefFeatures.empty())
1289         continue;
1290       else {
1291         // 3. Find any placed features in all reference features
1292         std::set<FeaturePtr> aIntersectionFeatures;
1293         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1294                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1295                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1296         // 4. Return false if any reference feature is placed before curent feature
1297         if (!aIntersectionFeatures.empty())
1298           aCanMove = false;
1299       }
1300     }
1301   }
1302   return aCanMove;
1303 }
1304
1305 //**************************************************************
1306 bool XGUI_Workshop::canBeShaded(const ObjectPtr& theObject) const
1307 {
1308   bool aCanBeShaded = myDisplayer->canBeShaded(theObject);
1309   if (!aCanBeShaded) {
1310     ResultCompSolidPtr aCompsolidResult =
1311                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
1312     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1313       for(int i = 0; i < aCompsolidResult->numberOfSubs() && !aCanBeShaded; i++)
1314         aCanBeShaded = myDisplayer->canBeShaded(aCompsolidResult->subResult(i));
1315     }
1316   }
1317   return aCanBeShaded;
1318 }
1319
1320 //**************************************************************
1321 bool XGUI_Workshop::canChangeColor() const
1322 {
1323   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1324
1325   std::set<std::string> aTypes;
1326   aTypes.insert(ModelAPI_ResultGroup::group());
1327   aTypes.insert(ModelAPI_ResultConstruction::group());
1328   aTypes.insert(ModelAPI_ResultBody::group());
1329   aTypes.insert(ModelAPI_ResultPart::group());
1330
1331   return hasResults(aObjects, aTypes);
1332 }
1333
1334 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1335 {
1336   if (!theResult.get())
1337     return;
1338
1339   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1340   if (aColorAttr.get() != NULL) {
1341     if (!aColorAttr->size()) {
1342       aColorAttr->setSize(3);
1343     }
1344     aColorAttr->setValue(0, theColor[0]);
1345     aColorAttr->setValue(1, theColor[1]);
1346     aColorAttr->setValue(2, theColor[2]);
1347   }
1348 }
1349
1350 //**************************************************************
1351 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1352 {
1353   AttributeIntArrayPtr aColorAttr;
1354   // 1. find the current color of the object. This is a color of AIS presentation
1355   // The objects are iterated until a first valid color is found 
1356   std::vector<int> aColor;
1357   foreach(ObjectPtr anObject, theObjects) {
1358     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1359     if (aResult.get()) {
1360       XGUI_CustomPrs::getResultColor(aResult, aColor);
1361     }
1362     else {
1363       // TODO: remove the obtaining a color from the AIS object
1364       // this does not happen never because:
1365       // 1. The color can be changed only on results
1366       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1367       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1368       if (anAISObj.get()) {
1369         aColor.resize(3);
1370         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1371       }
1372     }
1373     if (!aColor.empty())
1374       break;
1375   }
1376   if (aColor.size() != 3)
1377     return;
1378
1379   // 2. show the dialog to change the value
1380   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1381   aDlg->setColor(aColor);
1382   aDlg->move(QCursor::pos());
1383   bool isDone = aDlg->exec() == QDialog::Accepted;
1384   if (!isDone)
1385     return;
1386
1387   bool isRandomColor = aDlg->isRandomColor();
1388
1389   // 3. abort the previous operation and start a new one
1390   SessionPtr aMgr = ModelAPI_Session::get();
1391   bool aWasOperation = aMgr->isOperation(); // keep this value
1392   if (!aWasOperation) {
1393     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1394     aMgr->startOperation(aDescription.toStdString());
1395   }
1396
1397   // 4. set the value to all results
1398   std::vector<int> aColorResult = aDlg->getColor();
1399   foreach(ObjectPtr anObj, theObjects) {
1400     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1401     if (aResult.get() != NULL) {
1402       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
1403       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1404         for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++)
1405           setColor(aCompsolidResult->subResult(i), aColorResult);
1406       }
1407       setColor(aResult, aColorResult);
1408     }
1409   }
1410   if (!aWasOperation)
1411     aMgr->finishOperation();
1412   updateCommandStatus();
1413 }
1414
1415 //**************************************************************
1416 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1417 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1418   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1419 }
1420 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1421 {
1422   foreach (ObjectPtr aObj, theList) {
1423     /*
1424     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1425     if (aPartRes) {
1426       DocumentPtr aDoc = aPartRes->partDoc();
1427       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1428       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1429       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1430     } else {
1431     */
1432       aObj->setDisplayed(isVisible);
1433     //}
1434   }
1435   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1436 }
1437
1438 //**************************************************************
1439 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1440 {
1441   // Hide all displayed objects
1442   QObjectPtrList aList = myDisplayer->displayedObjects();
1443   foreach (ObjectPtr aObj, aList) {
1444     if (module()->canEraseObject(aObj))
1445       aObj->setDisplayed(false);
1446   }
1447
1448   // Show only objects from the list
1449   foreach (ObjectPtr aObj, theList) {
1450     /*
1451     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1452     if (aPartRes) {
1453       DocumentPtr aDoc = aPartRes->partDoc();
1454       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1455       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1456       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1457     } else {
1458     */
1459       aObj->setDisplayed(true);
1460     //}
1461   }
1462   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1463
1464 }
1465
1466
1467 //**************************************************************
1468 void XGUI_Workshop::registerValidators() const
1469 {
1470   SessionPtr aMgr = ModelAPI_Session::get();
1471   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1472 }
1473
1474 //**************************************************************
1475 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1476 {
1477   if (!theDoc)
1478     return;
1479   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1480   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1481 }
1482
1483 //**************************************************************
1484 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1485 {
1486   for (int i = 0; i < theDoc->size(theGroup); i++) 
1487     theDoc->object(theGroup, i)->setDisplayed(true);
1488     //displayObject(theDoc->object(theGroup, i));
1489   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1490 }
1491
1492 //**************************************************************
1493 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1494 {
1495   foreach(ObjectPtr aObj, theList) {
1496     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1497
1498     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aObj);
1499     if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
1500       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
1501           myDisplayer->setDisplayMode(aCompsolidResult->subResult(i),
1502                                       (XGUI_Displayer::DisplayMode)theMode, false);
1503       }
1504     }
1505   }
1506   if (theList.size() > 0)
1507     myDisplayer->updateViewer();
1508 }
1509
1510 //**************************************************************
1511 void XGUI_Workshop::closeDocument()
1512 {
1513   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1514   while (anOperation) {
1515     anOperation->abort();
1516     anOperation = operationMgr()->currentOperation();
1517   }
1518   myDisplayer->closeLocalContexts();
1519   myDisplayer->eraseAll();
1520   objectBrowser()->clearContent();
1521
1522   module()->closeDocument();
1523
1524   SessionPtr aMgr = ModelAPI_Session::get();
1525   aMgr->closeAll();
1526 }
1527
1528 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1529 {
1530   XGUI_HistoryMenu* aMenu = NULL;
1531   if (isSalomeMode()) {
1532     QAction* anAction = qobject_cast<QAction*>(theObject);
1533     if (!anAction)
1534       return;
1535     aMenu = new XGUI_HistoryMenu(anAction);
1536   } else {
1537     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1538     aMenu = new XGUI_HistoryMenu(aButton);
1539   }
1540   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1541   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1542 }
1543
1544 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1545 {
1546   QList<ActionInfo> aResult;
1547   std::list<std::string>::const_iterator it = theList.cbegin();
1548   for (; it != theList.cend(); it++) {
1549     QString anId = QString::fromStdString(*it);
1550     bool isEditing = anId.endsWith(ModuleBase_OperationFeature::EditSuffix());
1551     if (isEditing) {
1552       anId.chop(ModuleBase_OperationFeature::EditSuffix().size());
1553     }
1554     ActionInfo anInfo;
1555     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1556     if (aContextMenuAct) {
1557       anInfo.initFrom(aContextMenuAct);
1558     } else {
1559       anInfo = myActionsMgr->actionInfoById(anId);
1560     }
1561     if (isEditing) {
1562       anInfo.text = anInfo.text.prepend("Modify ");
1563     }
1564     aResult << anInfo;
1565   }
1566   return aResult;
1567 }