]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
8aa17ceb66c8337496bd9c9ebd2b3d4f5d7706e5
[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   // check whether the object can be deleted. There should not be parts which are not loaded
1023   if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1024     return;
1025
1026   bool hasResult = false;
1027   bool hasFeature = false;
1028   bool hasParameter = false;
1029   bool hasSubFeature = false;
1030   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1031   if (!(hasFeature || hasParameter))
1032     return;
1033
1034   // 1. start operation
1035   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1036   aDescription += tr(" %1");
1037   QStringList aObjectNames;
1038   foreach (ObjectPtr aObj, anObjects) {
1039     if (!aObj->data()->isValid())
1040       continue;
1041     aObjectNames << QString::fromStdString(aObj->data()->name());
1042   }
1043   aDescription = aDescription.arg(aObjectNames.join(", "));
1044
1045   SessionPtr aMgr = ModelAPI_Session::get();
1046   aMgr->startOperation(aDescription.toStdString());
1047   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1048   // this is performed in the RemoveFeature of Part object.
1049   /*foreach (ObjectPtr aObj, anObjects)
1050   {
1051     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1052     if (aPart) {
1053       DocumentPtr aDoc = aObj->document();
1054       if (aDoc == aMgr->activeDocument()) {
1055         aDoc->close();
1056       }
1057     }
1058   }*/
1059   // 3. delete objects
1060   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1061   std::set<FeaturePtr> anIgnoredFeatures;
1062   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1063     myDisplayer->updateViewer();
1064     aMgr->finishOperation();
1065     updateCommandStatus();
1066   }
1067   else {
1068     aMgr->abortOperation();
1069   }
1070 }
1071
1072 //**************************************************************
1073 void XGUI_Workshop::moveObjects()
1074 {
1075   if (!isActiveOperationAborted())
1076     return;
1077
1078   SessionPtr aMgr = ModelAPI_Session::get();
1079
1080   QString anActionId = "MOVE_CMD";
1081   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1082   aMgr->startOperation(aDescription.toStdString());
1083
1084   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1085   DocumentPtr anActiveDocument = aMgr->activeDocument();
1086
1087   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1088   foreach (ObjectPtr aObject, anObjects) {
1089     if (!myModule->canApplyAction(aObject, anActionId))
1090       continue;
1091
1092     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1093     if (aFeature.get()) {
1094       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1095       aCurrentFeature = anActiveDocument->currentFeature(true);
1096     }
1097   }
1098   aMgr->finishOperation();
1099 }
1100
1101 //**************************************************************
1102 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1103                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1104                                    QWidget* theParent,
1105                                    const bool theAskAboutDeleteReferences)
1106 {
1107 #ifdef DEBUG_DELETE
1108   QStringList aDInfo;
1109   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1110   for (; aDIt != aDLast; ++aDIt) {
1111     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1112   }
1113   QString anInfoStr = aDInfo.join(", ");
1114   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1115 #endif
1116
1117   // 1. find all referenced features
1118   std::set<FeaturePtr> aRefFeatures;
1119   foreach (ObjectPtr aDeletedObj, theList) {
1120     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aRefFeatures);
1121   }
1122   // 2. warn about the references remove, break the delete operation if the user chose it
1123   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1124     QStringList aRefNames;
1125     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1126                                          aLast = aRefFeatures.end();
1127     for (; anIt != aLast; anIt++) {
1128       aRefNames.append((*anIt)->name().c_str());
1129     }
1130     QString aNames = aRefNames.join(", ");
1131
1132     QMessageBox::StandardButton aRes = QMessageBox::warning(
1133         theParent, tr("Delete features"),
1134         QString(tr("Selected features are used in the following features: %1.\
1135 These features will be deleted also. Would you like to continue?")).arg(aNames),
1136         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1137     if (aRes != QMessageBox::Yes)
1138       return false;
1139   }
1140
1141   // 3. remove referenced features
1142   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1143                                        aLast = aRefFeatures.end();
1144 #ifdef DEBUG_DELETE
1145   QStringList anInfo;
1146 #endif
1147   for (; anIt != aLast; anIt++) {
1148     FeaturePtr aFeature = (*anIt);
1149     DocumentPtr aDoc = aFeature->document();
1150     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1151       aDoc->removeFeature(aFeature);
1152 #ifdef DEBUG_DELETE
1153       anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1154 #endif
1155     }
1156   }
1157 #ifdef DEBUG_DELETE
1158   qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1159   anInfo.clear();
1160 #endif
1161
1162   QString anActionId = "DELETE_CMD";
1163   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1164   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1165   // 4. remove the parameter features
1166   foreach (ObjectPtr aObj, theList) {
1167     // features and parameters can be removed here,
1168     // the results are removed only by a corresponded feature remove
1169     std::string aGroupName = aObj->groupName();
1170     if (!anObjectGroups.contains(aGroupName.c_str()))
1171       continue;
1172
1173     if (!myModule->canApplyAction(aObj, anActionId))
1174       continue;
1175
1176     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1177     if (aFeature) {
1178       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1179       // part features are removed in the PartSet module. This condition should be moved there
1180       if (aFeature->getKind() == "Part")
1181         continue;
1182         */
1183       DocumentPtr aDoc = aObj->document();
1184       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1185 #ifdef DEBUG_DELETE
1186         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1187         anInfo.append(anInfoStr);
1188         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1189 #endif
1190         aDoc->removeFeature(aFeature);
1191       }
1192     }
1193   }
1194 #ifdef DEBUG_DELETE
1195   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1196 #endif
1197   return true;
1198 }
1199
1200 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1201 {
1202   bool isFoundResultType = false;
1203   foreach(ObjectPtr anObj, theObjects)
1204   {
1205     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1206     if (aResult.get() == NULL)
1207       continue;
1208
1209     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1210     if (isFoundResultType)
1211       break;
1212   }
1213   return isFoundResultType;
1214 }
1215
1216 //**************************************************************
1217 // Returns the list of features placed between theObject and the current feature
1218 // in the same document. Excludes theObject, includes the current feature.
1219 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1220 {
1221   std::list<FeaturePtr> aResult;
1222   DocumentPtr aDocument = theObject->document();
1223   std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1224   // find the object iterator
1225   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1226   if (aObjectIt == anAllFeatures.end()) 
1227     return aResult;
1228   // find the current feature iterator
1229   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1230   if (aCurrentIt == anAllFeatures.end()) 
1231     return aResult;
1232   // check the right order
1233   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1234     return aResult;
1235   // exclude the object
1236   std::advance(aObjectIt, 1);
1237   // include the current feature
1238   std::advance(aCurrentIt, 1);
1239   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1240 }
1241
1242 bool XGUI_Workshop::canMoveFeature()
1243 {
1244   QString anActionId = "MOVE_CMD";
1245
1246   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1247   QObjectPtrList aValidatedObjects;
1248   foreach (ObjectPtr aObject, aObjects) {
1249     if (myModule->canApplyAction(aObject, anActionId))
1250       aValidatedObjects.append(aObject);
1251   }
1252   if (aValidatedObjects.size() != aObjects.size())
1253     aObjects = aValidatedObjects;
1254
1255   bool aCanMove = !aObjects.empty();
1256
1257   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1258   for (; anIt != aLast && aCanMove; anIt++) {
1259     ObjectPtr aObject = *anIt;
1260     // 1. Get features placed between selected and current in the document 
1261     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1262     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1263     if (aFeaturesBetween.empty())
1264       aCanMove = false;
1265     else {
1266       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1267       // 2. Get all reference features to the selected object in the document 
1268       std::set<FeaturePtr> aRefFeatures;
1269       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1270
1271       if (aRefFeatures.empty())
1272         continue;
1273       else {
1274         // 3. Find any placed features in all reference features
1275         std::set<FeaturePtr> aIntersectionFeatures;
1276         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1277                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1278                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1279         // 4. Return false if any reference feature is placed before curent feature
1280         if (!aIntersectionFeatures.empty())
1281           aCanMove = false;
1282       }
1283     }
1284   }
1285   return aCanMove;
1286 }
1287
1288 //**************************************************************
1289 bool XGUI_Workshop::canChangeColor() const
1290 {
1291   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1292
1293   std::set<std::string> aTypes;
1294   aTypes.insert(ModelAPI_ResultGroup::group());
1295   aTypes.insert(ModelAPI_ResultConstruction::group());
1296   aTypes.insert(ModelAPI_ResultBody::group());
1297   aTypes.insert(ModelAPI_ResultPart::group());
1298
1299   return hasResults(aObjects, aTypes);
1300 }
1301
1302 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1303 {
1304   if (!theResult.get())
1305     return;
1306
1307   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1308   if (aColorAttr.get() != NULL) {
1309     if (!aColorAttr->size()) {
1310       aColorAttr->setSize(3);
1311     }
1312     aColorAttr->setValue(0, theColor[0]);
1313     aColorAttr->setValue(1, theColor[1]);
1314     aColorAttr->setValue(2, theColor[2]);
1315   }
1316 }
1317
1318 //**************************************************************
1319 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1320 {
1321   AttributeIntArrayPtr aColorAttr;
1322   // 1. find the current color of the object. This is a color of AIS presentation
1323   // The objects are iterated until a first valid color is found 
1324   std::vector<int> aColor;
1325   foreach(ObjectPtr anObject, theObjects) {
1326     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1327     if (aResult.get())
1328       XGUI_CustomPrs::getResultColor(aResult, aColor);
1329     else {
1330       // TODO: remove the obtaining a color from the AIS object
1331       // this does not happen never because:
1332       // 1. The color can be changed only on results
1333       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1334       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1335       if (anAISObj.get()) {
1336         aColor.resize(3);
1337         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1338       }
1339     }
1340     if (!aColor.empty())
1341       break;
1342   }
1343   if (aColor.size() != 3)
1344     return;
1345
1346   // 2. show the dialog to change the value
1347   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1348   aDlg->setColor(aColor);
1349   aDlg->move(QCursor::pos());
1350   bool isDone = aDlg->exec() == QDialog::Accepted;
1351   if (!isDone)
1352     return;
1353
1354   bool isRandomColor = aDlg->isRandomColor();
1355
1356   // 3. abort the previous operation and start a new one
1357   SessionPtr aMgr = ModelAPI_Session::get();
1358   bool aWasOperation = aMgr->isOperation(); // keep this value
1359   if (!aWasOperation) {
1360     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1361     aMgr->startOperation(aDescription.toStdString());
1362   }
1363
1364   // 4. set the value to all results
1365   foreach(ObjectPtr anObj, theObjects) {
1366     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1367     if (aResult.get() != NULL) {
1368       std::vector<int> aColorResult = aDlg->getColor();
1369       setColor(aResult, aColorResult);
1370     }
1371   }
1372   if (!aWasOperation)
1373     aMgr->finishOperation();
1374   updateCommandStatus();
1375 }
1376
1377 //**************************************************************
1378 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1379 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1380   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1381 }
1382 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1383 {
1384   foreach (ObjectPtr aObj, theList) {
1385     /*
1386     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1387     if (aPartRes) {
1388       DocumentPtr aDoc = aPartRes->partDoc();
1389       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1390       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1391       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1392     } else {
1393     */
1394       aObj->setDisplayed(isVisible);
1395     //}
1396   }
1397   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1398 }
1399
1400 //**************************************************************
1401 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1402 {
1403   // Hide all displayed objects
1404   QObjectPtrList aList = myDisplayer->displayedObjects();
1405   foreach (ObjectPtr aObj, aList)
1406     aObj->setDisplayed(false);
1407
1408   // Show only objects from the list
1409   foreach (ObjectPtr aObj, theList) {
1410     /*
1411     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1412     if (aPartRes) {
1413       DocumentPtr aDoc = aPartRes->partDoc();
1414       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1415       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1416       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1417     } else {
1418     */
1419       aObj->setDisplayed(true);
1420     //}
1421   }
1422   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1423
1424 }
1425
1426
1427 //**************************************************************
1428 void XGUI_Workshop::registerValidators() const
1429 {
1430   SessionPtr aMgr = ModelAPI_Session::get();
1431   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1432 }
1433
1434 //**************************************************************
1435 /*void XGUI_Workshop::displayAllResults()
1436 {
1437   SessionPtr aMgr = ModelAPI_Session::get();
1438   DocumentPtr aRootDoc = aMgr->moduleDocument();
1439   displayDocumentResults(aRootDoc);
1440   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1441     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1442     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1443     displayDocumentResults(aPart->partDoc());
1444   }
1445   myDisplayer->updateViewer();
1446 }*/
1447
1448 //**************************************************************
1449 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1450 {
1451   if (!theDoc)
1452     return;
1453   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1454   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1455 }
1456
1457 //**************************************************************
1458 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1459 {
1460   for (int i = 0; i < theDoc->size(theGroup); i++) 
1461     theDoc->object(theGroup, i)->setDisplayed(true);
1462     //displayObject(theDoc->object(theGroup, i));
1463   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1464 }
1465
1466 //**************************************************************
1467 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1468 {
1469   foreach(ObjectPtr aObj, theList) {
1470     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1471   }
1472   if (theList.size() > 0)
1473     myDisplayer->updateViewer();
1474 }
1475
1476 //**************************************************************
1477 void XGUI_Workshop::closeDocument()
1478 {
1479   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1480   while (anOperation) {
1481     anOperation->abort();
1482     anOperation = operationMgr()->currentOperation();
1483   }
1484   myDisplayer->closeLocalContexts();
1485   myDisplayer->eraseAll();
1486   objectBrowser()->clearContent();
1487
1488   SessionPtr aMgr = ModelAPI_Session::get();
1489   aMgr->closeAll();
1490 }
1491
1492 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1493 {
1494   XGUI_HistoryMenu* aMenu = NULL;
1495   if (isSalomeMode()) {
1496     QAction* anAction = qobject_cast<QAction*>(theObject);
1497     if (!anAction)
1498       return;
1499     aMenu = new XGUI_HistoryMenu(anAction);
1500   } else {
1501     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1502     aMenu = new XGUI_HistoryMenu(aButton);
1503   }
1504   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1505   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1506 }
1507
1508 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1509 {
1510   QList<ActionInfo> aResult;
1511   std::list<std::string>::const_iterator it = theList.cbegin();
1512   for (; it != theList.cend(); it++) {
1513     QString anId = QString::fromStdString(*it);
1514     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1515     if (isEditing) {
1516       anId.chop(ModuleBase_Operation::EditSuffix().size());
1517     }
1518     ActionInfo anInfo;
1519     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1520     if (aContextMenuAct) {
1521       anInfo.initFrom(aContextMenuAct);
1522     } else {
1523       anInfo = myActionsMgr->actionInfoById(anId);
1524     }
1525     if (isEditing) {
1526       anInfo.text = anInfo.text.prepend("Modify ");
1527     }
1528     aResult << anInfo;
1529   }
1530   return aResult;
1531 }