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