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