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