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