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