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