Salome HOME
The selection problem with an object deactivate:
[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 the operation is nested, do not deactivate objects
679   //if (myOperationMgr->operationsCount() == 0) {
680     // Activate selection mode for all objects
681   QIntList aModes;
682   // TODO: check on OCC_6.9.0
683   // the module current active modes should not be deactivated in order to save the objects selected
684   // the deactivate object in the mode of selection leads to the object is deselected in the viewer.
685   // But, in OCC_6.8.0 this deselection does not happened automatically. It is necessary to call
686   // ClearOutdatedSelection, but this method has an error in the realization, which should be fixed in
687   // the OCC_6.9.0 release. Moreother, it is possible that ClearOutdatedSelection will be called inside
688   // Deactivate method of AIS_InteractiveContext. In this case, we need not call it.
689   module()->activeSelectionModes(aModes);
690   myDisplayer->activateObjects(aModes);
691   //}
692 }
693
694
695 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
696 {
697   myModule->operationCommitted(theOperation);
698 }
699
700 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
701 {
702   myModule->operationAborted(theOperation);
703 }
704
705 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
706 {
707   if (this->isSalomeMode()) 
708     theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
709   else 
710     theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
711 }
712
713 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
714 {
715   showPropertyPanel();
716   QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
717   ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
718                                                                 myModuleConnector);
719
720   myPropertyPanel->cleanContent();
721   aFactory.createWidget(myPropertyPanel->contentWidget());
722
723   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
724   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
725     bool isStoreValue = !theOperation->isEditOperation() &&
726                         !aWidget->getDefaultValue().empty() &&
727                         !aWidget->isComputedDefault();
728     aWidget->setFeature(theOperation->feature(), isStoreValue);
729     aWidget->enableFocusProcessing();
730   }
731   
732   myPropertyPanel->setModelWidgets(aWidgets);
733   theOperation->setPropertyPanel(myPropertyPanel);
734
735   myModule->propertyPanelDefined(theOperation);
736
737   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
738 }
739
740 bool XGUI_Workshop::event(QEvent * theEvent)
741 {
742   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
743   if (aPostponedEv) {
744     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
745     processEvent(aEventPtr);
746     return true;
747   }
748   return false;
749 }
750
751 /*
752  *
753  */
754 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
755 {
756   if (!theMessage) {
757 #ifdef _DEBUG
758     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
759 #endif
760     return;
761   }
762   ActionInfo aFeatureInfo;
763   aFeatureInfo.initFrom(theMessage);
764   // Remember features icons
765   myIcons[QString::fromStdString(theMessage->id())] = aFeatureInfo.iconFile;
766
767   QString aWchName = QString::fromStdString(theMessage->workbenchId());
768   QStringList aNestedFeatures =
769       QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
770   QString aDocKind = QString::fromStdString(theMessage->documentKind());
771   QList<QAction*> aNestedActList;
772   bool isColumnButton = !aNestedFeatures.isEmpty();
773   if (isColumnButton) {
774     QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
775     if (aNestedActions.contains("accept")) {
776       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
777       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
778       aNestedActList << anAction;
779     }
780     if (aNestedActions.contains("abort")) {
781       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
782       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
783       aNestedActList << anAction;
784     }
785   }
786
787   if (isSalomeMode()) {
788     QAction* aAction;
789     if (isColumnButton) {
790       aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
791     } else {
792       aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
793     }
794     salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
795     salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
796
797     myActionsMgr->addCommand(aAction);
798     myModule->actionCreated(aAction);
799   } else {
800     //Find or create Workbench
801     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
802     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
803     if (!aPage) {
804       aPage = addWorkbench(aWchName);
805     }
806     //Find or create Group
807     QString aGroupName = QString::fromStdString(theMessage->groupId());
808     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
809     if (!aGroup) {
810       aGroup = aPage->addGroup(aGroupName);
811     }
812     // Check if hotkey sequence is already defined:
813     QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
814     if(aHotKey != aFeatureInfo.shortcut) {
815       aFeatureInfo.shortcut = aHotKey;
816     }
817     // Create feature...
818     AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
819                                                        aDocKind,
820                                                        aNestedFeatures);
821     // Enrich created button with accept/abort buttons if necessary
822     AppElements_Button* aButton = aCommand->button();
823     if (aButton->isColumnButton()) {
824       aButton->setAdditionalButtons(aNestedActList);
825     }
826     myActionsMgr->addCommand(aCommand);
827     myModule->actionCreated(aCommand);
828   }
829 }
830
831 /*
832  * Makes a signal/slot connections between Property Panel
833  * and given operation. The given operation becomes a
834  * current operation and previous operation if exists
835  */
836 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
837 {
838   QAction* aCommand = 0;
839   if (isSalomeMode()) {
840     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
841   } else {
842     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
843     FeaturePtr aFeature = theOperation->feature();
844     if(aFeature)
845       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
846   }
847   //Abort operation on uncheck the command
848   if (aCommand) {
849     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
850   }
851 }
852
853 /*
854  * Saves document with given name.
855  */
856 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
857 {
858   QApplication::restoreOverrideCursor();
859   SessionPtr aMgr = ModelAPI_Session::get();
860   aMgr->save(theName.toLatin1().constData(), theFileNames);
861   QApplication::restoreOverrideCursor();
862 }
863
864 bool XGUI_Workshop::isActiveOperationAborted()
865 {
866   return myOperationMgr->abortAllOperations();
867 }
868
869 //******************************************************
870 void XGUI_Workshop::onExit()
871 {
872   SessionPtr aMgr = ModelAPI_Session::get();
873   if (aMgr->isModified()) {
874     int anAnswer = QMessageBox::question(
875         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
876         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
877     if (anAnswer == QMessageBox::Save) {
878       bool saved = onSave();
879       if (!saved) {
880         return;
881       }
882     } else if (anAnswer == QMessageBox::Cancel) {
883       return;
884     }
885   }
886   qApp->exit();
887 }
888
889 //******************************************************
890 void XGUI_Workshop::onNew()
891 {
892   QApplication::setOverrideCursor(Qt::WaitCursor);
893   if (objectBrowser() == 0) {
894     createDockWidgets();
895     mySelector->connectViewers();
896   }
897   myViewerProxy->connectToViewer();
898   showObjectBrowser();
899   if (!isSalomeMode()) {
900     myMainWindow->showPythonConsole();
901     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
902     aWnd->showMaximized();
903     updateCommandStatus();
904   }
905   myContextMenuMgr->connectViewer();
906   QApplication::restoreOverrideCursor();
907 }
908
909 //******************************************************
910 void XGUI_Workshop::onOpen()
911 {
912   if(!isActiveOperationAborted())
913     return;
914   //save current file before close if modified
915   SessionPtr aSession = ModelAPI_Session::get();
916   if (aSession->isModified()) {
917     //TODO(sbh): re-launch the app?
918     int anAnswer = QMessageBox::question(
919         myMainWindow, tr("Save current file"),
920         tr("The document is modified, save before opening another?"),
921         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
922     if (anAnswer == QMessageBox::Save) {
923       onSave();
924     } else if (anAnswer == QMessageBox::Cancel) {
925       return;
926     }
927     aSession->closeAll();
928     myCurrentDir = "";
929   }
930
931   //show file dialog, check if readable and open
932   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
933   if (myCurrentDir.isEmpty())
934     return;
935   QFileInfo aFileInfo(myCurrentDir);
936   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
937     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
938     myCurrentDir = "";
939     return;
940   }
941   QApplication::setOverrideCursor(Qt::WaitCursor);
942   myIsLoadingData = true;
943   aSession->load(myCurrentDir.toLatin1().constData());
944   myObjectBrowser->rebuildDataTree();
945   displayAllResults();
946   updateCommandStatus();
947   myIsLoadingData = false;
948   QApplication::restoreOverrideCursor();
949 }
950
951 //******************************************************
952 bool XGUI_Workshop::onSave()
953 {
954   if(!isActiveOperationAborted())
955     return false;
956   if (myCurrentDir.isEmpty()) {
957     return onSaveAs();
958   }
959   std::list<std::string> aFiles;
960   saveDocument(myCurrentDir, aFiles);
961   updateCommandStatus();
962   if (!isSalomeMode())
963     myMainWindow->setModifiedState(false);
964   return true;
965 }
966
967 //******************************************************
968 bool XGUI_Workshop::onSaveAs()
969 {
970   if(!isActiveOperationAborted())
971     return false;
972   QFileDialog dialog(mainWindow());
973   dialog.setWindowTitle(tr("Select directory to save files..."));
974   dialog.setFileMode(QFileDialog::Directory);
975   dialog.setFilter(tr("Folders (*)"));
976   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
977   dialog.setViewMode(QFileDialog::Detail);
978
979   if (!dialog.exec()) {
980     return false;
981   }
982   QString aTempDir = dialog.selectedFiles().first();
983   QDir aDir(aTempDir);
984   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
985     int answer = QMessageBox::question(
986         myMainWindow,
987         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
988         tr("Save"),
989         tr("The folder already contains some files, save anyway?"),
990         QMessageBox::Save | QMessageBox::Cancel);
991     if (answer == QMessageBox::Cancel) {
992       return false;
993     }
994   }
995   myCurrentDir = aTempDir;
996   if (!isSalomeMode()) {
997     myMainWindow->setCurrentDir(myCurrentDir, false);
998     myMainWindow->setModifiedState(false);
999   }
1000   return onSave();
1001 }
1002
1003 //******************************************************
1004 void XGUI_Workshop::onUndo(int theTimes)
1005 {
1006   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1007   SessionPtr aMgr = ModelAPI_Session::get();
1008   if (aMgr->isOperation())
1009     operationMgr()->onAbortOperation();
1010   for (int i = 0; i < theTimes; ++i) {
1011     aMgr->undo();
1012   }
1013   updateCommandStatus();
1014 }
1015
1016 //******************************************************
1017 void XGUI_Workshop::onRedo(int theTimes)
1018 {
1019   // the viewer update should be blocked in order to avoid the features blinking. For the created
1020   // feature a results are created, the flush of the created signal caused the viewer redisplay for
1021   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
1022   // redo of all possible objects happens
1023   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
1024
1025   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
1026   SessionPtr aMgr = ModelAPI_Session::get();
1027   if (aMgr->isOperation())
1028     operationMgr()->onAbortOperation();
1029   for (int i = 0; i < theTimes; ++i) {
1030     aMgr->redo();
1031   }
1032   updateCommandStatus();
1033
1034   // unblock the viewer update functionality and make update on purpose
1035   myDisplayer->enableUpdateViewer(isUpdateEnabled);
1036   myDisplayer->updateViewer();
1037 }
1038
1039 //******************************************************
1040 void XGUI_Workshop::onRebuild()
1041 {
1042   SessionPtr aMgr = ModelAPI_Session::get();
1043   bool aWasOperation = aMgr->isOperation(); // keep this value
1044   if (!aWasOperation) {
1045     aMgr->startOperation("Rebuild");
1046   }
1047   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1048   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1049     new Events_Message(aRebuildEvent, this)));
1050   if (!aWasOperation) {
1051     aMgr->finishOperation();
1052   }
1053   updateCommandStatus();
1054 }
1055
1056 //******************************************************
1057 void XGUI_Workshop::onPreferences()
1058 {
1059   ModuleBase_Prefs aModif;
1060   ModuleBase_Preferences::editPreferences(aModif);
1061   if (aModif.size() > 0) {
1062     QString aSection;
1063     foreach (ModuleBase_Pref aPref, aModif)
1064     {
1065       aSection = aPref.first;
1066       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1067         if (!isSalomeMode())
1068           myMainWindow->viewer()->updateFromResources();
1069       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1070         if (!isSalomeMode())
1071           myMainWindow->menuObject()->updateFromResources();
1072       }
1073     }
1074   }
1075 }
1076
1077 //******************************************************
1078 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1079 {
1080   QString libName = QString::fromStdString(library(theModule.toStdString()));
1081   if (libName.isEmpty()) {
1082     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1083     return 0;
1084   }
1085
1086   QString err;
1087   CREATE_FUNC crtInst = 0;
1088
1089 #ifdef WIN32
1090   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1091   if (!modLib) {
1092     LPVOID lpMsgBuf;
1093     ::FormatMessage(
1094         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1095         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1096     QString aMsg((char*) &lpMsgBuf);
1097     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1098     ::LocalFree(lpMsgBuf);
1099   } else {
1100     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1101     if (!crtInst) {
1102       LPVOID lpMsgBuf;
1103       ::FormatMessage(
1104           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1105               | FORMAT_MESSAGE_IGNORE_INSERTS,
1106           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1107       QString aMsg((char*) &lpMsgBuf);
1108       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1109       ::LocalFree(lpMsgBuf);
1110     }
1111   }
1112 #else
1113   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1114   if ( !modLib ) {
1115     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1116   } else {
1117     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1118     if ( !crtInst ) {
1119       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1120     }
1121   }
1122 #endif
1123
1124   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1125
1126   if (!err.isEmpty()) {
1127     if (mainWindow()) {
1128       Events_Error::send(err.toStdString());
1129     } else {
1130       qWarning(qPrintable(err));
1131     }
1132   }
1133   return aModule;
1134 }
1135
1136 //******************************************************
1137 bool XGUI_Workshop::activateModule()
1138 {
1139   Config_ModuleReader aModuleReader;
1140   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1141   myModule = loadModule(moduleName);
1142   if (!myModule)
1143     return false;
1144
1145   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1146     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1147   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1148     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1149
1150   myModule->createFeatures();
1151   myActionsMgr->update();
1152   return true;
1153 }
1154
1155 //******************************************************
1156 void XGUI_Workshop::updateCommandStatus()
1157 {
1158   QList<QAction*> aCommands;
1159   if (isSalomeMode()) {  // update commands in SALOME mode
1160     aCommands = salomeConnector()->commandList();
1161   } else {
1162     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1163     foreach (AppElements_Command* aCmd, aMenuBar->features())
1164       aCommands.append(aCmd);
1165   }
1166   SessionPtr aMgr = ModelAPI_Session::get();
1167   if (aMgr->hasModuleDocument()) {
1168     QAction *aUndoCmd, *aRedoCmd;
1169     foreach(QAction* aCmd, aCommands) {
1170       QString aId = aCmd->data().toString();
1171       if (aId == "UNDO_CMD")
1172         aUndoCmd = aCmd;
1173       else if (aId == "REDO_CMD")
1174         aRedoCmd = aCmd;
1175       else
1176         // Enable all commands
1177         aCmd->setEnabled(true);
1178     }
1179
1180     aUndoCmd->setEnabled(myModule->canUndo());
1181     aRedoCmd->setEnabled(myModule->canRedo());
1182     updateHistory();
1183   } else {
1184     foreach(QAction* aCmd, aCommands) {
1185       QString aId = aCmd->data().toString();
1186       if (aId == "NEW_CMD")
1187         aCmd->setEnabled(true);
1188       else if (aId == "EXIT_CMD")
1189         aCmd->setEnabled(true);
1190       else
1191         aCmd->setEnabled(false);
1192     }
1193   }
1194   myActionsMgr->update();
1195   emit commandStatusUpdated();
1196 }
1197
1198 void XGUI_Workshop::updateHistory()
1199 {
1200   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1201   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1202   emit updateUndoHistory(aUndoRes);
1203
1204   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1205   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1206   emit updateRedoHistory(aRedoRes);
1207 }
1208
1209 //******************************************************
1210 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1211 {
1212   QDockWidget* aObjDock = new QDockWidget(theParent);
1213   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1214   aObjDock->setWindowTitle(tr("Object browser"));
1215   aObjDock->setStyleSheet(
1216       "::title { position: relative; padding-left: 5px; text-align: left center }");
1217   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1218   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1219           SLOT(changeCurrentDocument(ObjectPtr)));
1220   aObjDock->setWidget(myObjectBrowser);
1221
1222   myContextMenuMgr->connectObjectBrowser();
1223   return aObjDock;
1224 }
1225
1226 //******************************************************
1227 /*
1228  * Creates dock widgets, places them in corresponding area
1229  * and tabifies if necessary.
1230  */
1231 void XGUI_Workshop::createDockWidgets()
1232 {
1233   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1234   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1235   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1236   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1237   myPropertyPanel->setupActions(myActionsMgr);
1238   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1239   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1240   hidePropertyPanel();  ///<! Invisible by default
1241   hideObjectBrowser();
1242   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1243   myPropertyPanel->installEventFilter(myOperationMgr);
1244
1245   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1246   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1247   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1248   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1249   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1250   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1251           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1252   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1253           aOkAct,          SLOT(setEnabled(bool)));
1254   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1255   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
1256           aAcceptAllAct,   SLOT(setEnabled(bool)));
1257
1258 }
1259
1260 //******************************************************
1261 void XGUI_Workshop::showPropertyPanel()
1262 {
1263   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1264   ///<! Restore ability to close panel from the window's menu
1265   aViewAct->setEnabled(true);
1266   myPropertyPanel->show();
1267   myPropertyPanel->raise();
1268 }
1269
1270 //******************************************************
1271 void XGUI_Workshop::hidePropertyPanel()
1272 {
1273   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1274   ///<! Do not allow to show empty property panel
1275   aViewAct->setEnabled(false);
1276   myPropertyPanel->hide();
1277 }
1278
1279 //******************************************************
1280 void XGUI_Workshop::showObjectBrowser()
1281 {
1282   myObjectBrowser->parentWidget()->show();
1283 }
1284
1285 //******************************************************
1286 void XGUI_Workshop::hideObjectBrowser()
1287 {
1288   myObjectBrowser->parentWidget()->hide();
1289 }
1290
1291 //******************************************************
1292 void XGUI_Workshop::onFeatureTriggered()
1293 {
1294   QAction* aCmd = dynamic_cast<QAction*>(sender());
1295   if (aCmd) {
1296     QString aId = salomeConnector()->commandId(aCmd);
1297     if (!aId.isNull())
1298       myModule->launchOperation(aId);
1299   }
1300 }
1301
1302 //******************************************************
1303 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
1304 {
1305   SessionPtr aMgr = ModelAPI_Session::get();
1306   if (theObj) {
1307     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
1308     if (aPart) {
1309       DocumentPtr aPartDoc = aPart->partDoc();
1310       if (aPartDoc) {
1311         aMgr->setActiveDocument(aPartDoc);
1312         return;
1313       }
1314     }
1315   }
1316   aMgr->setActiveDocument(aMgr->moduleDocument());
1317 }
1318
1319 //******************************************************
1320 void XGUI_Workshop::salomeViewerSelectionChanged()
1321 {
1322   emit salomeViewerSelection();
1323 }
1324
1325 //**************************************************************
1326 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1327 {
1328   return mySalomeConnector->viewer();
1329 }
1330
1331 //**************************************************************
1332 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1333 {
1334   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1335   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
1336     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
1337     activatePart(aPart);
1338   } else if (theId == "DEACTIVATE_PART_CMD")
1339     activatePart(ResultPartPtr());
1340   else if (theId == "DELETE_CMD")
1341     deleteObjects();
1342   else if (theId == "COLOR_CMD")
1343     changeColor(aObjects);
1344   else if (theId == "SHOW_CMD")
1345     showObjects(aObjects, true);
1346   else if (theId == "HIDE_CMD")
1347     showObjects(aObjects, false);
1348   else if (theId == "SHOW_ONLY_CMD")
1349     showOnlyObjects(aObjects);
1350   else if (theId == "SHADING_CMD")
1351     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1352   else if (theId == "WIREFRAME_CMD")
1353     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1354   else if (theId == "HIDEALL_CMD")
1355     myDisplayer->eraseAll();
1356   else if (theId == "EDIT_CMD") {
1357     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
1358     if (aFeature == NULL) {
1359       ResultParameterPtr aParam = 
1360         std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aObjects.first());
1361       if (aParam.get() != NULL) {
1362         aFeature = ModelAPI_Feature::feature(aParam);
1363       }
1364     }
1365     if (aFeature.get() != NULL)
1366       myModule->editFeature(aFeature);
1367   }
1368 }
1369
1370 //**************************************************************
1371 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1372 {
1373   if (!myPartActivating) {
1374     myPartActivating = true;
1375     if (theFeature)
1376       theFeature->activate();
1377     changeCurrentDocument(theFeature);
1378     myObjectBrowser->activatePart(theFeature);
1379     myPartActivating = false;
1380   }
1381   updateCommandStatus();
1382 }
1383
1384 //**************************************************************
1385 //void XGUI_Workshop::activateLastPart()
1386 //{
1387 //  SessionPtr aMgr = ModelAPI_Session::get();
1388 //  DocumentPtr aDoc = aMgr->moduleDocument();
1389 //  std::string aGrpName = ModelAPI_ResultPart::group();
1390 //  ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1391 //  ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1392 //  if (aPart) {
1393 //    activatePart(aPart);
1394 //  }
1395 //}
1396
1397 //**************************************************************
1398 void XGUI_Workshop::deleteObjects()
1399 {
1400   ModuleBase_IModule* aModule = module();
1401   // 1. allow the module to delete objects, do nothing if it has succeed
1402   if (aModule->deleteObjects()) {
1403     updateCommandStatus();
1404     return;
1405   }
1406
1407   if (!isActiveOperationAborted())
1408     return;
1409   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1410   bool hasResult = false;
1411   bool hasFeature = false;
1412   bool hasParameter = false;
1413   XGUI_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1414   if (!(hasFeature || hasParameter))
1415     return;
1416
1417   // 1. start operation
1418   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1419   aDescription += tr(" %1");
1420   QStringList aObjectNames;
1421   foreach (ObjectPtr aObj, anObjects) {
1422     if (!aObj->data().get())
1423       continue;
1424     aObjectNames << QString::fromStdString(aObj->data()->name());
1425   }
1426   aDescription = aDescription.arg(aObjectNames.join(", "));
1427
1428   SessionPtr aMgr = ModelAPI_Session::get();
1429   aMgr->startOperation(aDescription.toStdString());
1430   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1431   foreach (ObjectPtr aObj, anObjects)
1432   {
1433     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1434     if (aPart) {
1435       DocumentPtr aDoc = aObj->document();
1436       if (aDoc == aMgr->activeDocument()) {
1437         aDoc->close();
1438       }
1439     }
1440   }
1441   // 3. delete objects
1442   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1443   std::set<FeaturePtr> anIgnoredFeatures;
1444   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1445     myDisplayer->updateViewer();
1446     aMgr->finishOperation();
1447     updateCommandStatus();
1448   }
1449   else {
1450     aMgr->abortOperation();
1451   }
1452 }
1453
1454 //**************************************************************
1455 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1456                                    std::set<FeaturePtr> theIgnoredFeatures,
1457                                    QWidget* theParent,
1458                                    const bool theAskAboutDeleteReferences)
1459 {
1460   // 1. find all referenced features
1461   std::set<FeaturePtr> aRefFeatures;
1462   foreach (ObjectPtr aObj, theList) {
1463     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1464     if (aFeature.get() != NULL) {
1465       aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1466     }
1467   }
1468   // 2. warn about the references remove, break the delete operation if the user chose it
1469   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1470     QStringList aRefNames;
1471     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1472                                          aLast = aRefFeatures.end();
1473     for (; anIt != aLast; anIt++) {
1474       aRefNames.append((*anIt)->name().c_str());
1475     }
1476     QString aNames = aRefNames.join(", ");
1477
1478     QMessageBox::StandardButton aRes = QMessageBox::warning(
1479         theParent, tr("Delete features"),
1480         QString(tr("Selected features are used in the following features: %1.\
1481 These features will be deleted also. Would you like to continue?")).arg(aNames),
1482         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1483     if (aRes != QMessageBox::Yes)
1484       return false;
1485   }
1486
1487   // 3. remove referenced features
1488   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1489                                        aLast = aRefFeatures.end();
1490   for (; anIt != aLast; anIt++) {
1491     FeaturePtr aFeature = (*anIt);
1492     DocumentPtr aDoc = aFeature->document();
1493     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1494       aDoc->removeFeature(aFeature);
1495   }
1496
1497   // 4. remove the parameter features
1498   foreach (ObjectPtr aObj, theList) {
1499     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1500     if (aFeature) {
1501       DocumentPtr aDoc = aObj->document();
1502       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1503         aDoc->removeFeature(aFeature);
1504     }
1505   }
1506   return true;
1507 }
1508
1509 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1510 {
1511   bool isFoundResultType = false;
1512   foreach(ObjectPtr anObj, theObjects)
1513   {
1514     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1515     if (aResult.get() == NULL)
1516       continue;
1517
1518     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1519     if (isFoundResultType)
1520       break;
1521   }
1522   return isFoundResultType;
1523 }
1524
1525 //**************************************************************
1526 bool XGUI_Workshop::canChangeColor() const
1527 {
1528   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1529
1530   std::set<std::string> aTypes;
1531   aTypes.insert(ModelAPI_ResultGroup::group());
1532   aTypes.insert(ModelAPI_ResultConstruction::group());
1533   aTypes.insert(ModelAPI_ResultBody::group());
1534   aTypes.insert(ModelAPI_ResultPart::group());
1535
1536   return hasResults(aObjects, aTypes);
1537 }
1538
1539 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1540 {
1541   if (!theResult.get())
1542     return;
1543
1544   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1545   if (aColorAttr.get() != NULL) {
1546     if (!aColorAttr->size()) {
1547       aColorAttr->setSize(3);
1548     }
1549     aColorAttr->setValue(0, theColor[0]);
1550     aColorAttr->setValue(1, theColor[1]);
1551     aColorAttr->setValue(2, theColor[2]);
1552   }
1553 }
1554
1555 //**************************************************************
1556 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1557 {
1558   AttributeIntArrayPtr aColorAttr;
1559   // 1. find the current color of the object. This is a color of AIS presentation
1560   // The objects are iterated until a first valid color is found 
1561   std::vector<int> aColor;
1562   foreach(ObjectPtr anObject, theObjects) {
1563     if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1564       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1565       DocumentPtr aPartDoc = aPart->partDoc();
1566       // the document should be checked on null, because in opened document if the part
1567       // has not been activated yet, the part document is empty
1568       if (!aPartDoc.get()) {
1569         emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1570       }
1571       else {
1572         if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1573           ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1574           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1575           if (aBody.get()) {
1576             std::string aSection, aName, aDefault;
1577             aBody->colorConfigInfo(aSection, aName, aDefault);
1578             if (!aSection.empty() && !aName.empty()) {
1579               aColor = Config_PropManager::color(aSection, aName, aDefault);
1580             }
1581           }
1582         }
1583       }
1584     }
1585     else {
1586       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1587       if (anAISObj.get()) {
1588         aColor.resize(3);
1589         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1590       }
1591     }
1592     if (!aColor.empty())
1593       break;
1594   }
1595   if (aColor.size() != 3)
1596     return;
1597
1598   // 2. show the dialog to change the value
1599   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1600   aDlg->setColor(aColor);
1601   aDlg->move(QCursor::pos());
1602   bool isDone = aDlg->exec() == QDialog::Accepted;
1603   if (!isDone)
1604     return;
1605
1606   bool isRandomColor = aDlg->isRandomColor();
1607
1608   // 3. abort the previous operation and start a new one
1609   SessionPtr aMgr = ModelAPI_Session::get();
1610   bool aWasOperation = aMgr->isOperation(); // keep this value
1611   if (!aWasOperation) {
1612     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1613     aMgr->startOperation(aDescription.toStdString());
1614   }
1615
1616   // 4. set the value to all results
1617   foreach(ObjectPtr anObj, theObjects) {
1618     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1619     if (aResult.get() != NULL) {
1620       if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1621         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1622         DocumentPtr aPartDoc = aPart->partDoc();
1623         // the document should be checked on null, because in opened document if the part
1624         // has not been activated yet, the part document is empty
1625         if (aPartDoc.get()) {
1626           for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1627             ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1628             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1629             std::vector<int> aColorResult = aDlg->getColor();
1630             setColor(aBody, aColorResult);
1631           }
1632         }
1633       }
1634       else {
1635         std::vector<int> aColorResult = aDlg->getColor();
1636         setColor(aResult, aColorResult);
1637       }
1638     }
1639   }
1640   if (!aWasOperation)
1641     aMgr->finishOperation();
1642   updateCommandStatus();
1643 }
1644
1645 //**************************************************************
1646 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1647 {
1648   foreach (ObjectPtr aObj, theList)
1649   {
1650     if (isVisible) {
1651       displayObject(aObj);
1652     } else {
1653       myDisplayer->erase(aObj, false);
1654     }
1655   }
1656   myDisplayer->updateViewer();
1657 }
1658
1659 //**************************************************************
1660 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1661 {
1662   myDisplayer->showOnly(theList);
1663 }
1664
1665
1666 //**************************************************************
1667 void XGUI_Workshop::registerValidators() const
1668 {
1669   SessionPtr aMgr = ModelAPI_Session::get();
1670   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1671 }
1672
1673 //**************************************************************
1674 void XGUI_Workshop::displayAllResults()
1675 {
1676   SessionPtr aMgr = ModelAPI_Session::get();
1677   DocumentPtr aRootDoc = aMgr->moduleDocument();
1678   displayDocumentResults(aRootDoc);
1679   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1680     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1681     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1682     displayDocumentResults(aPart->partDoc());
1683   }
1684   myDisplayer->updateViewer();
1685 }
1686
1687 //**************************************************************
1688 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1689 {
1690   if (!theDoc)
1691     return;
1692   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1693   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1694 }
1695
1696 //**************************************************************
1697 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1698 {
1699   for (int i = 0; i < theDoc->size(theGroup); i++)
1700     displayObject(theDoc->object(theGroup, i));
1701 }
1702
1703 //**************************************************************
1704 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1705 {
1706   foreach(ObjectPtr aObj, theList) {
1707     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1708   }
1709   if (theList.size() > 0)
1710     myDisplayer->updateViewer();
1711 }
1712
1713 //**************************************************************
1714 void XGUI_Workshop::closeDocument()
1715 {
1716   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1717   while (anOperation) {
1718     anOperation->abort();
1719     anOperation = operationMgr()->currentOperation();
1720   }
1721   myDisplayer->closeLocalContexts();
1722   myDisplayer->eraseAll();
1723   objectBrowser()->clearContent();
1724
1725   SessionPtr aMgr = ModelAPI_Session::get();
1726   aMgr->closeAll();
1727   objectBrowser()->clearContent();
1728 }
1729
1730 //**************************************************************
1731 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1732 {
1733   if (!myModule->canDisplayObject(theObj))
1734     return false;
1735
1736   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1737   if (aBody.get() != NULL) {
1738     int aNb = myDisplayer->objectsCount();
1739     myDisplayer->display(theObj, false);
1740     if (aNb == 0)
1741       viewer()->fitAll();
1742   } else if (!(myIsLoadingData || myPartActivating))
1743     myDisplayer->display(theObj, false);
1744
1745   return true;
1746 }
1747
1748 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1749 {
1750   XGUI_HistoryMenu* aMenu = NULL;
1751   if (isSalomeMode()) {
1752     QAction* anAction = qobject_cast<QAction*>(theObject);
1753     if (!anAction)
1754       return;
1755     aMenu = new XGUI_HistoryMenu(anAction);
1756   } else {
1757     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1758     aMenu = new XGUI_HistoryMenu(aButton);
1759   }
1760   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1761   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1762 }
1763
1764 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1765 {
1766   QList<ActionInfo> aResult;
1767   std::list<std::string>::const_iterator it = theList.cbegin();
1768   for (; it != theList.cend(); it++) {
1769     QString anId = QString::fromStdString(*it);
1770     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1771     if (isEditing) {
1772       anId.chop(ModuleBase_Operation::EditSuffix().size());
1773     }
1774     ActionInfo anInfo;
1775     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1776     if (aContextMenuAct) {
1777       anInfo.initFrom(aContextMenuAct);
1778     } else {
1779       anInfo = myActionsMgr->actionInfoById(anId);
1780     }
1781     if (isEditing) {
1782       anInfo.text = anInfo.text.prepend("Modify ");
1783     }
1784     aResult << anInfo;
1785   }
1786   return aResult;
1787 }