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