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