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