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