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