]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
27ef45623acef008b35523d72895c2f86583bf35
[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   bool aCurrentValid = operationMgr()->currentOperation() &&
861                        operationMgr()->currentOperation()->isValid();
862
863   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
864   aAcceptAllAct->setEnabled(aParentValid && (aCanUndo || aCurrentValid));
865 }
866
867 void XGUI_Workshop::updateHistory()
868 {
869   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
870   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
871   emit updateUndoHistory(aUndoRes);
872
873   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
874   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
875   emit updateRedoHistory(aRedoRes);
876 }
877
878 //******************************************************
879 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
880 {
881   QDockWidget* aObjDock = new QDockWidget(theParent);
882   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
883   aObjDock->setWindowTitle(tr("Object browser"));
884   aObjDock->setStyleSheet(
885       "::title { position: relative; padding-left: 5px; text-align: left center }");
886   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
887   myObjectBrowser->setDataModel(myModule->dataModel());
888   myModule->customizeObjectBrowser(myObjectBrowser);
889   aObjDock->setWidget(myObjectBrowser);
890
891   myContextMenuMgr->connectObjectBrowser();
892   return aObjDock;
893 }
894
895 //******************************************************
896 /*
897  * Creates dock widgets, places them in corresponding area
898  * and tabifies if necessary.
899  */
900 void XGUI_Workshop::createDockWidgets()
901 {
902   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
903   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
904   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
905   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
906   myPropertyPanel->setupActions(myActionsMgr);
907   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
908   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
909   hidePropertyPanel();  ///<! Invisible by default
910   hideObjectBrowser();
911   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
912   myPropertyPanel->installEventFilter(myOperationMgr);
913
914   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
915   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
916   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
917   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
918   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
919   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
920           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
921   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
922           aOkAct,          SLOT(setEnabled(bool)));
923   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
924   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
925           aAcceptAllAct,   SLOT(setEnabled(bool)));
926
927 }
928
929 //******************************************************
930 void XGUI_Workshop::showPropertyPanel()
931 {
932   QAction* aViewAct = myPropertyPanel->toggleViewAction();
933   ///<! Restore ability to close panel from the window's menu
934   aViewAct->setEnabled(true);
935   myPropertyPanel->show();
936   myPropertyPanel->raise();
937 }
938
939 //******************************************************
940 void XGUI_Workshop::hidePropertyPanel()
941 {
942   QAction* aViewAct = myPropertyPanel->toggleViewAction();
943   ///<! Do not allow to show empty property panel
944   aViewAct->setEnabled(false);
945   myPropertyPanel->hide();
946 }
947
948 //******************************************************
949 void XGUI_Workshop::showObjectBrowser()
950 {
951   myObjectBrowser->parentWidget()->show();
952 }
953
954 //******************************************************
955 void XGUI_Workshop::hideObjectBrowser()
956 {
957   myObjectBrowser->parentWidget()->hide();
958 }
959
960 //******************************************************
961 //void XGUI_Workshop::onFeatureTriggered()
962 //{
963 //  QAction* aCmd = dynamic_cast<QAction*>(sender());
964 //  if (aCmd) {
965 //    QString aId = salomeConnector()->commandId(aCmd);
966 //    if (!aId.isNull())
967 //      myModule->launchOperation(aId);
968 //  }
969 //}
970
971 //******************************************************
972 void XGUI_Workshop::salomeViewerSelectionChanged()
973 {
974   emit salomeViewerSelection();
975 }
976
977 //**************************************************************
978 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
979 {
980   return mySalomeConnector->viewer();
981 }
982
983 //**************************************************************
984 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
985 {
986   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
987   if (theId == "DELETE_CMD")
988     deleteObjects();
989   if (theId == "MOVE_CMD")
990     moveObjects();
991   else if (theId == "COLOR_CMD")
992     changeColor(aObjects);
993   else if (theId == "SHOW_CMD")
994     showObjects(aObjects, true);
995   else if (theId == "HIDE_CMD")
996     showObjects(aObjects, false);
997   else if (theId == "SHOW_ONLY_CMD")
998     showOnlyObjects(aObjects);
999   else if (theId == "SHADING_CMD")
1000     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1001   else if (theId == "WIREFRAME_CMD")
1002     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1003   else if (theId == "HIDEALL_CMD") {
1004     QObjectPtrList aList = myDisplayer->displayedObjects();
1005     foreach (ObjectPtr aObj, aList)
1006       aObj->setDisplayed(false);
1007     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1008   }
1009 }
1010
1011 //**************************************************************
1012 void XGUI_Workshop::deleteObjects()
1013 {
1014   ModuleBase_IModule* aModule = module();
1015   // 1. allow the module to delete objects, do nothing if it has succeed
1016   if (aModule->deleteObjects()) {
1017     updateCommandStatus();
1018     return;
1019   }
1020
1021   if (!isActiveOperationAborted())
1022     return;
1023   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1024   // It is necessary to clear selection in order to avoid selection changed event during
1025   // deleteion and negative consequences connected with processing of already deleted items
1026   mySelector->clearSelection();
1027   // check whether the object can be deleted. There should not be parts which are not loaded
1028   if (!XGUI_Tools::canRemoveOrRename(myMainWindow, anObjects))
1029     return;
1030
1031   bool hasResult = false;
1032   bool hasFeature = false;
1033   bool hasParameter = false;
1034   bool hasSubFeature = false;
1035   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter, hasSubFeature);
1036   if (!(hasFeature || hasParameter))
1037     return;
1038
1039   // 1. start operation
1040   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1041   aDescription += tr(" %1");
1042   QStringList aObjectNames;
1043   foreach (ObjectPtr aObj, anObjects) {
1044     if (!aObj->data()->isValid())
1045       continue;
1046     aObjectNames << QString::fromStdString(aObj->data()->name());
1047   }
1048   aDescription = aDescription.arg(aObjectNames.join(", "));
1049
1050   SessionPtr aMgr = ModelAPI_Session::get();
1051   aMgr->startOperation(aDescription.toStdString());
1052   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1053   // this is performed in the RemoveFeature of Part object.
1054   /*foreach (ObjectPtr aObj, anObjects)
1055   {
1056     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1057     if (aPart) {
1058       DocumentPtr aDoc = aObj->document();
1059       if (aDoc == aMgr->activeDocument()) {
1060         aDoc->close();
1061       }
1062     }
1063   }*/
1064   // 3. delete objects
1065   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1066   std::set<FeaturePtr> anIgnoredFeatures;
1067   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1068     myDisplayer->updateViewer();
1069     aMgr->finishOperation();
1070     updateCommandStatus();
1071   }
1072   else {
1073     aMgr->abortOperation();
1074   }
1075 }
1076
1077 //**************************************************************
1078 void XGUI_Workshop::moveObjects()
1079 {
1080   if (!isActiveOperationAborted())
1081     return;
1082
1083   SessionPtr aMgr = ModelAPI_Session::get();
1084
1085   QString anActionId = "MOVE_CMD";
1086   QString aDescription = contextMenuMgr()->action(anActionId)->text();
1087   aMgr->startOperation(aDescription.toStdString());
1088
1089   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1090   DocumentPtr anActiveDocument = aMgr->activeDocument();
1091
1092   FeaturePtr aCurrentFeature = anActiveDocument->currentFeature(true);
1093   foreach (ObjectPtr aObject, anObjects) {
1094     if (!myModule->canApplyAction(aObject, anActionId))
1095       continue;
1096
1097     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObject);
1098     if (aFeature.get()) {
1099       anActiveDocument->moveFeature(aFeature, aCurrentFeature);
1100       aCurrentFeature = anActiveDocument->currentFeature(true);
1101     }
1102   }
1103   aMgr->finishOperation();
1104 }
1105
1106 //**************************************************************
1107 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1108                                    const std::set<FeaturePtr>& theIgnoredFeatures,
1109                                    QWidget* theParent,
1110                                    const bool theAskAboutDeleteReferences)
1111 {
1112 #ifdef DEBUG_DELETE
1113   QStringList aDInfo;
1114   QObjectPtrList::const_iterator aDIt = theList.begin(), aDLast = theList.end();
1115   for (; aDIt != aDLast; ++aDIt) {
1116     aDInfo.append(ModuleBase_Tools::objectInfo((*aDIt)));
1117   }
1118   QString anInfoStr = aDInfo.join(", ");
1119   qDebug(QString("deleteFeatures: %1, %2").arg(theList.size()).arg(anInfoStr).toStdString().c_str());
1120 #endif
1121
1122   // 1. find all referenced features
1123   std::set<FeaturePtr> aRefFeatures;
1124   foreach (ObjectPtr aDeletedObj, theList) {
1125     XGUI_Tools::refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, aRefFeatures);
1126   }
1127   // 2. warn about the references remove, break the delete operation if the user chose it
1128   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1129     QStringList aRefNames;
1130     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1131                                          aLast = aRefFeatures.end();
1132     for (; anIt != aLast; anIt++) {
1133       aRefNames.append((*anIt)->name().c_str());
1134     }
1135     QString aNames = aRefNames.join(", ");
1136
1137     QMessageBox::StandardButton aRes = QMessageBox::warning(
1138         theParent, tr("Delete features"),
1139         QString(tr("Selected features are used in the following features: %1.\
1140 These features will be deleted also. Would you like to continue?")).arg(aNames),
1141         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1142     if (aRes != QMessageBox::Yes)
1143       return false;
1144   }
1145
1146   // 3. remove referenced features
1147   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1148                                        aLast = aRefFeatures.end();
1149 #ifdef DEBUG_DELETE
1150   QStringList anInfo;
1151 #endif
1152   for (; anIt != aLast; anIt++) {
1153     FeaturePtr aFeature = (*anIt);
1154     DocumentPtr aDoc = aFeature->document();
1155     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1156       aDoc->removeFeature(aFeature);
1157 #ifdef DEBUG_DELETE
1158       anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1159 #endif
1160     }
1161   }
1162 #ifdef DEBUG_DELETE
1163   qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1164   anInfo.clear();
1165 #endif
1166
1167   QString anActionId = "DELETE_CMD";
1168   QString anId = QString::fromStdString(anActionId.toStdString().c_str());
1169   QStringList anObjectGroups = contextMenuMgr()->actionObjectGroups(anId);
1170   // 4. remove the parameter features
1171   foreach (ObjectPtr aObj, theList) {
1172     // features and parameters can be removed here,
1173     // the results are removed only by a corresponded feature remove
1174     std::string aGroupName = aObj->groupName();
1175     if (!anObjectGroups.contains(aGroupName.c_str()))
1176       continue;
1177
1178     if (!myModule->canApplyAction(aObj, anActionId))
1179       continue;
1180
1181     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1182     if (aFeature) {
1183       /*// TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1184       // part features are removed in the PartSet module. This condition should be moved there
1185       if (aFeature->getKind() == "Part")
1186         continue;
1187         */
1188       DocumentPtr aDoc = aObj->document();
1189       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1190 #ifdef DEBUG_DELETE
1191         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1192         anInfo.append(anInfoStr);
1193         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1194 #endif
1195         aDoc->removeFeature(aFeature);
1196       }
1197     }
1198   }
1199 #ifdef DEBUG_DELETE
1200   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1201 #endif
1202   return true;
1203 }
1204
1205 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1206 {
1207   bool isFoundResultType = false;
1208   foreach(ObjectPtr anObj, theObjects)
1209   {
1210     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1211     if (aResult.get() == NULL)
1212       continue;
1213
1214     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1215     if (isFoundResultType)
1216       break;
1217   }
1218   return isFoundResultType;
1219 }
1220
1221 //**************************************************************
1222 // Returns the list of features placed between theObject and the current feature
1223 // in the same document. Excludes theObject, includes the current feature.
1224 std::list<FeaturePtr> toCurrentFeatures(const ObjectPtr& theObject)
1225 {
1226   std::list<FeaturePtr> aResult;
1227   DocumentPtr aDocument = theObject->document();
1228   std::list<FeaturePtr> anAllFeatures = aDocument->allFeatures();
1229   // find the object iterator
1230   std::list<FeaturePtr>::iterator aObjectIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), theObject);
1231   if (aObjectIt == anAllFeatures.end()) 
1232     return aResult;
1233   // find the current feature iterator
1234   std::list<FeaturePtr>::iterator aCurrentIt = std::find(anAllFeatures.begin(), anAllFeatures.end(), aDocument->currentFeature(true));
1235   if (aCurrentIt == anAllFeatures.end()) 
1236     return aResult;
1237   // check the right order
1238   if (std::distance(aObjectIt, anAllFeatures.end()) <= std::distance(aCurrentIt, anAllFeatures.end()))
1239     return aResult;
1240   // exclude the object
1241   std::advance(aObjectIt, 1);
1242   // include the current feature
1243   std::advance(aCurrentIt, 1);
1244   return std::list<FeaturePtr>(aObjectIt, aCurrentIt);
1245 }
1246
1247 bool XGUI_Workshop::canMoveFeature()
1248 {
1249   QString anActionId = "MOVE_CMD";
1250
1251   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1252   QObjectPtrList aValidatedObjects;
1253   foreach (ObjectPtr aObject, aObjects) {
1254     if (myModule->canApplyAction(aObject, anActionId))
1255       aValidatedObjects.append(aObject);
1256   }
1257   if (aValidatedObjects.size() != aObjects.size())
1258     aObjects = aValidatedObjects;
1259
1260   bool aCanMove = !aObjects.empty();
1261
1262   QObjectPtrList::const_iterator anIt = aObjects.begin(), aLast = aObjects.end();
1263   for (; anIt != aLast && aCanMove; anIt++) {
1264     ObjectPtr aObject = *anIt;
1265     // 1. Get features placed between selected and current in the document 
1266     std::list<FeaturePtr> aFeaturesBetween = toCurrentFeatures(aObject);
1267     // if aFeaturesBetween is empty it means wrong order or aObject is the current feature
1268     if (aFeaturesBetween.empty())
1269       aCanMove = false;
1270     else {
1271       std::set<FeaturePtr> aPlacedFeatures(aFeaturesBetween.begin(), aFeaturesBetween.end());
1272       // 2. Get all reference features to the selected object in the document 
1273       std::set<FeaturePtr> aRefFeatures;
1274       XGUI_Tools::refsToFeatureInFeatureDocument(aObject, aRefFeatures);
1275
1276       if (aRefFeatures.empty())
1277         continue;
1278       else {
1279         // 3. Find any placed features in all reference features
1280         std::set<FeaturePtr> aIntersectionFeatures;
1281         std::set_intersection(aRefFeatures.begin(), aRefFeatures.end(),
1282                               aPlacedFeatures.begin(), aPlacedFeatures.end(),
1283                               std::inserter(aIntersectionFeatures, aIntersectionFeatures.begin()));
1284         // 4. Return false if any reference feature is placed before curent feature
1285         if (!aIntersectionFeatures.empty())
1286           aCanMove = false;
1287       }
1288     }
1289   }
1290   return aCanMove;
1291 }
1292
1293 //**************************************************************
1294 bool XGUI_Workshop::canChangeColor() const
1295 {
1296   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1297
1298   std::set<std::string> aTypes;
1299   aTypes.insert(ModelAPI_ResultGroup::group());
1300   aTypes.insert(ModelAPI_ResultConstruction::group());
1301   aTypes.insert(ModelAPI_ResultBody::group());
1302   aTypes.insert(ModelAPI_ResultPart::group());
1303
1304   return hasResults(aObjects, aTypes);
1305 }
1306
1307 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1308 {
1309   if (!theResult.get())
1310     return;
1311
1312   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1313   if (aColorAttr.get() != NULL) {
1314     if (!aColorAttr->size()) {
1315       aColorAttr->setSize(3);
1316     }
1317     aColorAttr->setValue(0, theColor[0]);
1318     aColorAttr->setValue(1, theColor[1]);
1319     aColorAttr->setValue(2, theColor[2]);
1320   }
1321 }
1322
1323 //**************************************************************
1324 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1325 {
1326   AttributeIntArrayPtr aColorAttr;
1327   // 1. find the current color of the object. This is a color of AIS presentation
1328   // The objects are iterated until a first valid color is found 
1329   std::vector<int> aColor;
1330   foreach(ObjectPtr anObject, theObjects) {
1331     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1332     if (aResult.get())
1333       XGUI_CustomPrs::getResultColor(aResult, aColor);
1334     else {
1335       // TODO: remove the obtaining a color from the AIS object
1336       // this does not happen never because:
1337       // 1. The color can be changed only on results
1338       // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1339       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1340       if (anAISObj.get()) {
1341         aColor.resize(3);
1342         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1343       }
1344     }
1345     if (!aColor.empty())
1346       break;
1347   }
1348   if (aColor.size() != 3)
1349     return;
1350
1351   // 2. show the dialog to change the value
1352   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1353   aDlg->setColor(aColor);
1354   aDlg->move(QCursor::pos());
1355   bool isDone = aDlg->exec() == QDialog::Accepted;
1356   if (!isDone)
1357     return;
1358
1359   bool isRandomColor = aDlg->isRandomColor();
1360
1361   // 3. abort the previous operation and start a new one
1362   SessionPtr aMgr = ModelAPI_Session::get();
1363   bool aWasOperation = aMgr->isOperation(); // keep this value
1364   if (!aWasOperation) {
1365     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1366     aMgr->startOperation(aDescription.toStdString());
1367   }
1368
1369   // 4. set the value to all results
1370   foreach(ObjectPtr anObj, theObjects) {
1371     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1372     if (aResult.get() != NULL) {
1373       std::vector<int> aColorResult = aDlg->getColor();
1374       setColor(aResult, aColorResult);
1375     }
1376   }
1377   if (!aWasOperation)
1378     aMgr->finishOperation();
1379   updateCommandStatus();
1380 }
1381
1382 //**************************************************************
1383 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1384 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1385   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1386 }
1387 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1388 {
1389   foreach (ObjectPtr aObj, theList) {
1390     /*
1391     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1392     if (aPartRes) {
1393       DocumentPtr aDoc = aPartRes->partDoc();
1394       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1395       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1396       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1397     } else {
1398     */
1399       aObj->setDisplayed(isVisible);
1400     //}
1401   }
1402   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1403 }
1404
1405 //**************************************************************
1406 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1407 {
1408   // Hide all displayed objects
1409   QObjectPtrList aList = myDisplayer->displayedObjects();
1410   foreach (ObjectPtr aObj, aList)
1411     aObj->setDisplayed(false);
1412
1413   // Show only objects from the list
1414   foreach (ObjectPtr aObj, theList) {
1415     /*
1416     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1417     if (aPartRes) {
1418       DocumentPtr aDoc = aPartRes->partDoc();
1419       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1420       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1421       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1422     } else {
1423     */
1424       aObj->setDisplayed(true);
1425     //}
1426   }
1427   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1428
1429 }
1430
1431
1432 //**************************************************************
1433 void XGUI_Workshop::registerValidators() const
1434 {
1435   SessionPtr aMgr = ModelAPI_Session::get();
1436   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1437 }
1438
1439 //**************************************************************
1440 /*void XGUI_Workshop::displayAllResults()
1441 {
1442   SessionPtr aMgr = ModelAPI_Session::get();
1443   DocumentPtr aRootDoc = aMgr->moduleDocument();
1444   displayDocumentResults(aRootDoc);
1445   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1446     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1447     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1448     displayDocumentResults(aPart->partDoc());
1449   }
1450   myDisplayer->updateViewer();
1451 }*/
1452
1453 //**************************************************************
1454 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1455 {
1456   if (!theDoc)
1457     return;
1458   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1459   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1460 }
1461
1462 //**************************************************************
1463 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1464 {
1465   for (int i = 0; i < theDoc->size(theGroup); i++) 
1466     theDoc->object(theGroup, i)->setDisplayed(true);
1467     //displayObject(theDoc->object(theGroup, i));
1468   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1469 }
1470
1471 //**************************************************************
1472 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1473 {
1474   foreach(ObjectPtr aObj, theList) {
1475     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1476   }
1477   if (theList.size() > 0)
1478     myDisplayer->updateViewer();
1479 }
1480
1481 //**************************************************************
1482 void XGUI_Workshop::closeDocument()
1483 {
1484   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1485   while (anOperation) {
1486     anOperation->abort();
1487     anOperation = operationMgr()->currentOperation();
1488   }
1489   myDisplayer->closeLocalContexts();
1490   myDisplayer->eraseAll();
1491   objectBrowser()->clearContent();
1492
1493   SessionPtr aMgr = ModelAPI_Session::get();
1494   aMgr->closeAll();
1495 }
1496
1497 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1498 {
1499   XGUI_HistoryMenu* aMenu = NULL;
1500   if (isSalomeMode()) {
1501     QAction* anAction = qobject_cast<QAction*>(theObject);
1502     if (!anAction)
1503       return;
1504     aMenu = new XGUI_HistoryMenu(anAction);
1505   } else {
1506     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1507     aMenu = new XGUI_HistoryMenu(aButton);
1508   }
1509   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1510   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1511 }
1512
1513 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1514 {
1515   QList<ActionInfo> aResult;
1516   std::list<std::string>::const_iterator it = theList.cbegin();
1517   for (; it != theList.cend(); it++) {
1518     QString anId = QString::fromStdString(*it);
1519     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1520     if (isEditing) {
1521       anId.chop(ModuleBase_Operation::EditSuffix().size());
1522     }
1523     ActionInfo anInfo;
1524     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1525     if (aContextMenuAct) {
1526       anInfo.initFrom(aContextMenuAct);
1527     } else {
1528       anInfo = myActionsMgr->actionInfoById(anId);
1529     }
1530     if (isEditing) {
1531       anInfo.text = anInfo.text.prepend("Modify ");
1532     }
1533     aResult << anInfo;
1534   }
1535   return aResult;
1536 }