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