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