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