]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Avoid hung-up on exit of SALOME when NewGeom is non active
[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());
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 directory 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   QString aTempDir = dialog.selectedFiles().first();
936   QDir aDir(aTempDir);
937   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
938     int answer = QMessageBox::question(
939         myMainWindow,
940         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
941         tr("Save"),
942         tr("The folder already contains some files, save anyway?"),
943         QMessageBox::Save | QMessageBox::Cancel);
944     if (answer == QMessageBox::Cancel) {
945       return false;
946     }
947   }
948   myCurrentDir = aTempDir;
949   if (!isSalomeMode()) {
950     myMainWindow->setCurrentDir(myCurrentDir, false);
951     myMainWindow->setModifiedState(false);
952   }
953   return onSave();
954 }
955
956 //******************************************************
957 void XGUI_Workshop::onUndo(int theTimes)
958 {
959   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
960   SessionPtr aMgr = ModelAPI_Session::get();
961   if (aMgr->isOperation())
962     operationMgr()->onAbortOperation();
963   for (int i = 0; i < theTimes; ++i) {
964     aMgr->undo();
965   }
966   updateCommandStatus();
967 }
968
969 //******************************************************
970 void XGUI_Workshop::onRedo(int theTimes)
971 {
972   // the viewer update should be blocked in order to avoid the features blinking. For the created
973   // feature a results are created, the flush of the created signal caused the viewer redisplay for
974   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
975   // redo of all possible objects happens
976   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
977
978   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
979   SessionPtr aMgr = ModelAPI_Session::get();
980   if (aMgr->isOperation())
981     operationMgr()->onAbortOperation();
982   for (int i = 0; i < theTimes; ++i) {
983     aMgr->redo();
984   }
985   updateCommandStatus();
986
987   // unblock the viewer update functionality and make update on purpose
988   myDisplayer->enableUpdateViewer(isUpdateEnabled);
989   myDisplayer->updateViewer();
990 }
991
992 //******************************************************
993 void XGUI_Workshop::onRebuild()
994 {
995   SessionPtr aMgr = ModelAPI_Session::get();
996   bool aWasOperation = aMgr->isOperation(); // keep this value
997   if (!aWasOperation) {
998     aMgr->startOperation("Rebuild");
999   }
1000   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
1001   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
1002     new Events_Message(aRebuildEvent, this)));
1003   if (!aWasOperation) {
1004     aMgr->finishOperation();
1005   }
1006   updateCommandStatus();
1007 }
1008
1009 //******************************************************
1010 void XGUI_Workshop::onPreferences()
1011 {
1012   ModuleBase_Prefs aModif;
1013   ModuleBase_Preferences::editPreferences(aModif);
1014   if (aModif.size() > 0) {
1015     QString aSection;
1016     foreach (ModuleBase_Pref aPref, aModif)
1017     {
1018       aSection = aPref.first;
1019       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
1020         if (!isSalomeMode())
1021           myMainWindow->viewer()->updateFromResources();
1022       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
1023         if (!isSalomeMode())
1024           myMainWindow->menuObject()->updateFromResources();
1025       }
1026     }
1027   }
1028 }
1029
1030 //******************************************************
1031 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
1032 {
1033   QString libName = QString::fromStdString(library(theModule.toStdString()));
1034   if (libName.isEmpty()) {
1035     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
1036     return 0;
1037   }
1038
1039   QString err;
1040   CREATE_FUNC crtInst = 0;
1041
1042 #ifdef WIN32
1043   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1044   if (!modLib) {
1045     LPVOID lpMsgBuf;
1046     ::FormatMessage(
1047         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1048         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1049     QString aMsg((char*) &lpMsgBuf);
1050     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1051     ::LocalFree(lpMsgBuf);
1052   } else {
1053     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1054     if (!crtInst) {
1055       LPVOID lpMsgBuf;
1056       ::FormatMessage(
1057           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1058               | FORMAT_MESSAGE_IGNORE_INSERTS,
1059           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1060       QString aMsg((char*) &lpMsgBuf);
1061       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1062       ::LocalFree(lpMsgBuf);
1063     }
1064   }
1065 #else
1066   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1067   if ( !modLib ) {
1068     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1069   } else {
1070     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1071     if ( !crtInst ) {
1072       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1073     }
1074   }
1075 #endif
1076
1077   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1078
1079   if (!err.isEmpty()) {
1080     if (mainWindow()) {
1081       Events_Error::send(err.toStdString());
1082     } else {
1083       qWarning(qPrintable(err));
1084     }
1085   }
1086   return aModule;
1087 }
1088
1089 //******************************************************
1090 bool XGUI_Workshop::createModule()
1091 {
1092   Config_ModuleReader aModuleReader;
1093   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1094   myModule = loadModule(moduleName);
1095   if (!myModule)
1096     return false;
1097
1098   //connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1099   //  myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1100   //connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1101   //  myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1102
1103   myModule->createFeatures();
1104   //myActionsMgr->update();
1105   return true;
1106 }
1107
1108 //******************************************************
1109 void XGUI_Workshop::updateCommandStatus()
1110 {
1111   QList<QAction*> aCommands;
1112   if (isSalomeMode()) {  // update commands in SALOME mode
1113     aCommands = salomeConnector()->commandList();
1114   } else {
1115     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1116     foreach (AppElements_Command* aCmd, aMenuBar->features())
1117       aCommands.append(aCmd);
1118   }
1119   SessionPtr aMgr = ModelAPI_Session::get();
1120   if (aMgr->hasModuleDocument()) {
1121     foreach(QAction* aCmd, aCommands) {
1122       QString aId = aCmd->data().toString();
1123       if (aId == "UNDO_CMD")
1124         aCmd->setEnabled(myModule->canUndo());
1125       else if (aId == "REDO_CMD")
1126         aCmd->setEnabled(myModule->canRedo());
1127       else
1128         // Enable all commands
1129         aCmd->setEnabled(true);
1130     }
1131     updateHistory();
1132   } else {
1133     foreach(QAction* aCmd, aCommands) {
1134       QString aId = aCmd->data().toString();
1135       if (aId == "NEW_CMD")
1136         aCmd->setEnabled(true);
1137       else if (aId == "EXIT_CMD")
1138         aCmd->setEnabled(true);
1139       else
1140         aCmd->setEnabled(false);
1141     }
1142   }
1143   myActionsMgr->update();
1144   emit commandStatusUpdated();
1145 }
1146
1147 void XGUI_Workshop::updateHistory()
1148 {
1149   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1150   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1151   emit updateUndoHistory(aUndoRes);
1152
1153   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1154   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1155   emit updateRedoHistory(aRedoRes);
1156 }
1157
1158 //******************************************************
1159 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1160 {
1161   QDockWidget* aObjDock = new QDockWidget(theParent);
1162   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1163   aObjDock->setWindowTitle(tr("Object browser"));
1164   aObjDock->setStyleSheet(
1165       "::title { position: relative; padding-left: 5px; text-align: left center }");
1166   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1167   myObjectBrowser->setDataModel(myModule->dataModel());
1168   myModule->customizeObjectBrowser(myObjectBrowser);
1169   aObjDock->setWidget(myObjectBrowser);
1170
1171   myContextMenuMgr->connectObjectBrowser();
1172   return aObjDock;
1173 }
1174
1175 //******************************************************
1176 /*
1177  * Creates dock widgets, places them in corresponding area
1178  * and tabifies if necessary.
1179  */
1180 void XGUI_Workshop::createDockWidgets()
1181 {
1182   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1183   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1184   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1185   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1186   myPropertyPanel->setupActions(myActionsMgr);
1187   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1188   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1189   hidePropertyPanel();  ///<! Invisible by default
1190   hideObjectBrowser();
1191   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1192   myPropertyPanel->installEventFilter(myOperationMgr);
1193
1194   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1195   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1196   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1197   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1198   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1199   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1200           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1201   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1202           aOkAct,          SLOT(setEnabled(bool)));
1203   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1204   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
1205           aAcceptAllAct,   SLOT(setEnabled(bool)));
1206
1207 }
1208
1209 //******************************************************
1210 void XGUI_Workshop::showPropertyPanel()
1211 {
1212   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1213   ///<! Restore ability to close panel from the window's menu
1214   aViewAct->setEnabled(true);
1215   myPropertyPanel->show();
1216   myPropertyPanel->raise();
1217 }
1218
1219 //******************************************************
1220 void XGUI_Workshop::hidePropertyPanel()
1221 {
1222   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1223   ///<! Do not allow to show empty property panel
1224   aViewAct->setEnabled(false);
1225   myPropertyPanel->hide();
1226 }
1227
1228 //******************************************************
1229 void XGUI_Workshop::showObjectBrowser()
1230 {
1231   myObjectBrowser->parentWidget()->show();
1232 }
1233
1234 //******************************************************
1235 void XGUI_Workshop::hideObjectBrowser()
1236 {
1237   myObjectBrowser->parentWidget()->hide();
1238 }
1239
1240 //******************************************************
1241 //void XGUI_Workshop::onFeatureTriggered()
1242 //{
1243 //  QAction* aCmd = dynamic_cast<QAction*>(sender());
1244 //  if (aCmd) {
1245 //    QString aId = salomeConnector()->commandId(aCmd);
1246 //    if (!aId.isNull())
1247 //      myModule->launchOperation(aId);
1248 //  }
1249 //}
1250
1251 //******************************************************
1252 void XGUI_Workshop::salomeViewerSelectionChanged()
1253 {
1254   emit salomeViewerSelection();
1255 }
1256
1257 //**************************************************************
1258 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1259 {
1260   return mySalomeConnector->viewer();
1261 }
1262
1263 //**************************************************************
1264 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1265 {
1266   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1267   if (theId == "DELETE_CMD")
1268     deleteObjects();
1269   else if (theId == "COLOR_CMD")
1270     changeColor(aObjects);
1271   else if (theId == "SHOW_CMD")
1272     showObjects(aObjects, true);
1273   else if (theId == "HIDE_CMD")
1274     showObjects(aObjects, false);
1275   else if (theId == "SHOW_ONLY_CMD")
1276     showOnlyObjects(aObjects);
1277   else if (theId == "SHADING_CMD")
1278     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1279   else if (theId == "WIREFRAME_CMD")
1280     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1281   else if (theId == "HIDEALL_CMD") {
1282     QObjectPtrList aList = myDisplayer->displayedObjects();
1283     foreach (ObjectPtr aObj, aList)
1284       aObj->setDisplayed(false);
1285     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1286   }
1287 }
1288
1289 //**************************************************************
1290 void XGUI_Workshop::deleteObjects()
1291 {
1292   ModuleBase_IModule* aModule = module();
1293   // 1. allow the module to delete objects, do nothing if it has succeed
1294   if (aModule->deleteObjects()) {
1295     updateCommandStatus();
1296     return;
1297   }
1298
1299   if (!isActiveOperationAborted())
1300     return;
1301   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1302   bool hasResult = false;
1303   bool hasFeature = false;
1304   bool hasParameter = false;
1305   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1306   if (!(hasFeature || hasParameter))
1307     return;
1308
1309   // 1. start operation
1310   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1311   aDescription += tr(" %1");
1312   QStringList aObjectNames;
1313   foreach (ObjectPtr aObj, anObjects) {
1314     if (!aObj->data()->isValid())
1315       continue;
1316     aObjectNames << QString::fromStdString(aObj->data()->name());
1317   }
1318   aDescription = aDescription.arg(aObjectNames.join(", "));
1319
1320   SessionPtr aMgr = ModelAPI_Session::get();
1321   aMgr->startOperation(aDescription.toStdString());
1322   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1323   // this is performed in the RemoveFeature of Part object.
1324   /*foreach (ObjectPtr aObj, anObjects)
1325   {
1326     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1327     if (aPart) {
1328       DocumentPtr aDoc = aObj->document();
1329       if (aDoc == aMgr->activeDocument()) {
1330         aDoc->close();
1331       }
1332     }
1333   }*/
1334   // 3. delete objects
1335   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1336   std::set<FeaturePtr> anIgnoredFeatures;
1337   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1338     myDisplayer->updateViewer();
1339     aMgr->finishOperation();
1340     updateCommandStatus();
1341   }
1342   else {
1343     aMgr->abortOperation();
1344   }
1345 }
1346
1347 //**************************************************************
1348 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1349                                    std::set<FeaturePtr> theIgnoredFeatures,
1350                                    QWidget* theParent,
1351                                    const bool theAskAboutDeleteReferences)
1352 {
1353   // 1. find all referenced features
1354   std::set<FeaturePtr> aRefFeatures;
1355   foreach (ObjectPtr aDeletedObj, theList) {
1356     FeaturePtr aDeletedFeature = ModelAPI_Feature::feature(aDeletedObj);
1357     if (aDeletedFeature.get() != NULL) {
1358       DocumentPtr aDeletedFeatureDoc = aDeletedObj->document();
1359       // 1.1 find references in the current document
1360       aDeletedFeatureDoc->refsToFeature(aDeletedFeature, aRefFeatures, false);
1361       // 1.2 find references in all documents if the document of the feature is
1362       // "PartSet". Features of this document can be used in all other documents
1363       SessionPtr aMgr = ModelAPI_Session::get();
1364       DocumentPtr aModuleDoc = aMgr->moduleDocument();
1365       if (aDeletedFeatureDoc == aModuleDoc) {
1366         // the deleted feature and results of the feature should be found in references
1367         std::list<ObjectPtr> aDeletedObjects;
1368         aDeletedObjects.push_back(aDeletedFeature);
1369         typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
1370         const ResultsList& aDeletedResults = aDeletedFeature->results();
1371         ResultsList::const_iterator aRIter = aDeletedResults.begin();
1372         for (; aRIter != aDeletedResults.cend(); aRIter++) {
1373           ResultPtr aRes = *aRIter;
1374           if (aRes.get())
1375             aDeletedObjects.push_back(aRes);
1376         }
1377         // get all opened documents; found features in the documents;
1378         // get a list of objects where a feature refers;
1379         // search in these objects the deleted objects.
1380         std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
1381         std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
1382                                                aLast = anOpenedDocs.end();
1383         std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1384         for (; anIt != aLast; anIt++) {
1385           DocumentPtr aDocument = *anIt;
1386           if (aDocument == aDeletedFeatureDoc)
1387             continue; // this document has been already processed in 1.1
1388
1389           int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
1390           for (int aId = 0; aId < aFeaturesCount; aId++) {
1391             ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
1392             FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1393             if (!aFeature.get())
1394               continue;
1395
1396             aRefs.clear();
1397             aFeature->data()->referencesToObjects(aRefs);
1398             std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
1399             bool aHasReferenceToDeleted = false;
1400             for(; aRef != aRefs.end() && !aHasReferenceToDeleted; aRef++) {
1401               std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
1402               for(; aRefObj != aRef->second.end() && !aHasReferenceToDeleted; aRefObj++) {
1403                 std::list<ObjectPtr>::const_iterator aDelIt = aDeletedObjects.begin();
1404                 for(; aDelIt != aDeletedObjects.end() && !aHasReferenceToDeleted; aDelIt++) {
1405                   aHasReferenceToDeleted = *aDelIt == *aRefObj;
1406                 }
1407               }
1408             }
1409             if (aHasReferenceToDeleted)
1410               aRefFeatures.insert(aFeature);
1411           }
1412         }
1413       }
1414     }
1415   }
1416   // 2. warn about the references remove, break the delete operation if the user chose it
1417   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1418     QStringList aRefNames;
1419     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1420                                          aLast = aRefFeatures.end();
1421     for (; anIt != aLast; anIt++) {
1422       aRefNames.append((*anIt)->name().c_str());
1423     }
1424     QString aNames = aRefNames.join(", ");
1425
1426     QMessageBox::StandardButton aRes = QMessageBox::warning(
1427         theParent, tr("Delete features"),
1428         QString(tr("Selected features are used in the following features: %1.\
1429 These features will be deleted also. Would you like to continue?")).arg(aNames),
1430         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1431     if (aRes != QMessageBox::Yes)
1432       return false;
1433   }
1434
1435   // 3. remove referenced features
1436   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1437                                        aLast = aRefFeatures.end();
1438 #ifdef DEBUG_DELETE
1439   QStringList anInfo;
1440 #endif
1441   for (; anIt != aLast; anIt++) {
1442     FeaturePtr aFeature = (*anIt);
1443     DocumentPtr aDoc = aFeature->document();
1444     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1445       aDoc->removeFeature(aFeature);
1446 #ifdef DEBUG_DELETE
1447       anInfo.append(ModuleBase_Tools::objectInfo(aFeature).toStdString().c_str());
1448 #endif
1449     }
1450   }
1451 #ifdef DEBUG_DELETE
1452   qDebug(QString("remove references:%1").arg(anInfo.join("; ")).toStdString().c_str());
1453   anInfo.clear();
1454 #endif
1455
1456   // 4. remove the parameter features
1457   foreach (ObjectPtr aObj, theList) {
1458     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1459     if (aResult.get() != NULL) { // results could not be removed,
1460       // they are removed by a corresponded feature remove
1461       continue;
1462     }
1463     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1464     if (aFeature) {
1465       // TODO: to learn the workshop to delegate the Part object deletion to the PartSet module
1466       // part features are removed in the PartSet module. This condition should be moved there
1467       if (aFeature->getKind() == "Part")
1468         continue;
1469
1470       DocumentPtr aDoc = aObj->document();
1471       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end()) {
1472         aDoc->removeFeature(aFeature);
1473 #ifdef DEBUG_DELETE
1474         QString anInfoStr = ModuleBase_Tools::objectInfo(aFeature);
1475         anInfo.append(anInfoStr);
1476         qDebug(QString("remove feature :%1").arg(anInfoStr).toStdString().c_str());
1477 #endif
1478       }
1479     }
1480   }
1481 #ifdef DEBUG_DELETE
1482   qDebug(QString("remove features:%1").arg(anInfo.join("; ")).toStdString().c_str());
1483 #endif
1484   return true;
1485 }
1486
1487 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1488 {
1489   bool isFoundResultType = false;
1490   foreach(ObjectPtr anObj, theObjects)
1491   {
1492     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1493     if (aResult.get() == NULL)
1494       continue;
1495
1496     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1497     if (isFoundResultType)
1498       break;
1499   }
1500   return isFoundResultType;
1501 }
1502
1503 //**************************************************************
1504 bool XGUI_Workshop::canChangeColor() const
1505 {
1506   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1507
1508   std::set<std::string> aTypes;
1509   aTypes.insert(ModelAPI_ResultGroup::group());
1510   aTypes.insert(ModelAPI_ResultConstruction::group());
1511   aTypes.insert(ModelAPI_ResultBody::group());
1512   aTypes.insert(ModelAPI_ResultPart::group());
1513
1514   return hasResults(aObjects, aTypes);
1515 }
1516
1517 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1518 {
1519   if (!theResult.get())
1520     return;
1521
1522   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1523   if (aColorAttr.get() != NULL) {
1524     if (!aColorAttr->size()) {
1525       aColorAttr->setSize(3);
1526     }
1527     aColorAttr->setValue(0, theColor[0]);
1528     aColorAttr->setValue(1, theColor[1]);
1529     aColorAttr->setValue(2, theColor[2]);
1530   }
1531 }
1532
1533 //**************************************************************
1534 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1535 {
1536   AttributeIntArrayPtr aColorAttr;
1537   // 1. find the current color of the object. This is a color of AIS presentation
1538   // The objects are iterated until a first valid color is found 
1539   std::vector<int> aColor;
1540   foreach(ObjectPtr anObject, theObjects) {
1541     if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1542       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1543       DocumentPtr aPartDoc = aPart->partDoc();
1544       // the document should be checked on null, because in opened document if the part
1545       // has not been activated yet, the part document is empty
1546       if (!aPartDoc.get()) {
1547         emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1548       }
1549       else {
1550         if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1551           ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1552           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1553           if (aBody.get()) {
1554             XGUI_CustomPrs::getResultColor(aBody, aColor);
1555           }
1556         }
1557       }
1558     }
1559     else {
1560       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1561       if (aResult.get())
1562         XGUI_CustomPrs::getResultColor(aResult, aColor);
1563       else {
1564         // TODO: remove the obtaining a color from the AIS object
1565         // this does not happen never because:
1566         // 1. The color can be changed only on results
1567         // 2. The result can be not visualized in the viewer(e.g. Origin Construction)
1568         AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1569         if (anAISObj.get()) {
1570           aColor.resize(3);
1571           anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1572         }
1573       }
1574     }
1575     if (!aColor.empty())
1576       break;
1577   }
1578   if (aColor.size() != 3)
1579     return;
1580
1581   // 2. show the dialog to change the value
1582   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1583   aDlg->setColor(aColor);
1584   aDlg->move(QCursor::pos());
1585   bool isDone = aDlg->exec() == QDialog::Accepted;
1586   if (!isDone)
1587     return;
1588
1589   bool isRandomColor = aDlg->isRandomColor();
1590
1591   // 3. abort the previous operation and start a new one
1592   SessionPtr aMgr = ModelAPI_Session::get();
1593   bool aWasOperation = aMgr->isOperation(); // keep this value
1594   if (!aWasOperation) {
1595     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1596     aMgr->startOperation(aDescription.toStdString());
1597   }
1598
1599   // 4. set the value to all results
1600   foreach(ObjectPtr anObj, theObjects) {
1601     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1602     if (aResult.get() != NULL) {
1603       if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1604         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1605         DocumentPtr aPartDoc = aPart->partDoc();
1606         // the document should be checked on null, because in opened document if the part
1607         // has not been activated yet, the part document is empty
1608         if (aPartDoc.get()) {
1609           for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1610             ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1611             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1612             std::vector<int> aColorResult = aDlg->getColor();
1613             setColor(aBody, aColorResult);
1614           }
1615         }
1616       }
1617       else {
1618         std::vector<int> aColorResult = aDlg->getColor();
1619         setColor(aResult, aColorResult);
1620       }
1621     }
1622   }
1623   if (!aWasOperation)
1624     aMgr->finishOperation();
1625   updateCommandStatus();
1626 }
1627
1628 //**************************************************************
1629 #define SET_DISPLAY_GROUP(aGroupName, aDisplay) \
1630 for (int i = 0; i < aDoc->size(aGroupName); i++) { \
1631   aDoc->object(aGroupName, i)->setDisplayed(aDisplay); \
1632 }
1633 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1634 {
1635   foreach (ObjectPtr aObj, theList) {
1636     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1637     if (aPartRes) {
1638       DocumentPtr aDoc = aPartRes->partDoc();
1639       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), isVisible)
1640       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), isVisible)
1641       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), isVisible)
1642     } else {
1643       aObj->setDisplayed(isVisible);
1644     }
1645   }
1646   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1647 }
1648
1649 //**************************************************************
1650 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1651 {
1652   // Hide all displayed objects
1653   QObjectPtrList aList = myDisplayer->displayedObjects();
1654   foreach (ObjectPtr aObj, aList)
1655     aObj->setDisplayed(false);
1656
1657   // Show only objects from the list
1658   foreach (ObjectPtr aObj, theList) {
1659     ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1660     if (aPartRes) {
1661       DocumentPtr aDoc = aPartRes->partDoc();
1662       SET_DISPLAY_GROUP(ModelAPI_ResultBody::group(), true)
1663       SET_DISPLAY_GROUP(ModelAPI_ResultConstruction::group(), true)
1664       SET_DISPLAY_GROUP(ModelAPI_ResultGroup::group(), true)
1665     } else {
1666       aObj->setDisplayed(true);
1667     }
1668   }
1669   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1670
1671 }
1672
1673
1674 //**************************************************************
1675 void XGUI_Workshop::registerValidators() const
1676 {
1677   SessionPtr aMgr = ModelAPI_Session::get();
1678   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1679 }
1680
1681 //**************************************************************
1682 /*void XGUI_Workshop::displayAllResults()
1683 {
1684   SessionPtr aMgr = ModelAPI_Session::get();
1685   DocumentPtr aRootDoc = aMgr->moduleDocument();
1686   displayDocumentResults(aRootDoc);
1687   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1688     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1689     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1690     displayDocumentResults(aPart->partDoc());
1691   }
1692   myDisplayer->updateViewer();
1693 }*/
1694
1695 //**************************************************************
1696 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1697 {
1698   if (!theDoc)
1699     return;
1700   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1701   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1702 }
1703
1704 //**************************************************************
1705 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1706 {
1707   for (int i = 0; i < theDoc->size(theGroup); i++) 
1708     theDoc->object(theGroup, i)->setDisplayed(true);
1709     //displayObject(theDoc->object(theGroup, i));
1710   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1711 }
1712
1713 //**************************************************************
1714 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1715 {
1716   foreach(ObjectPtr aObj, theList) {
1717     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1718   }
1719   if (theList.size() > 0)
1720     myDisplayer->updateViewer();
1721 }
1722
1723 //**************************************************************
1724 void XGUI_Workshop::closeDocument()
1725 {
1726   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1727   while (anOperation) {
1728     anOperation->abort();
1729     anOperation = operationMgr()->currentOperation();
1730   }
1731   myDisplayer->closeLocalContexts();
1732   myDisplayer->eraseAll();
1733   objectBrowser()->clearContent();
1734
1735   SessionPtr aMgr = ModelAPI_Session::get();
1736   aMgr->closeAll();
1737 }
1738
1739 //**************************************************************
1740 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1741 {
1742   if (!myModule->canDisplayObject(theObj))
1743     return false;
1744
1745   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1746   if (aBody.get() != NULL) {
1747     int aNb = myDisplayer->objectsCount();
1748     myDisplayer->display(theObj, false);
1749     if (aNb == 0)
1750       viewer()->fitAll();
1751   } else if (!(myIsLoadingData || myPartActivating))
1752     myDisplayer->display(theObj, false);
1753
1754   return true;
1755 }
1756
1757 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1758 {
1759   XGUI_HistoryMenu* aMenu = NULL;
1760   if (isSalomeMode()) {
1761     QAction* anAction = qobject_cast<QAction*>(theObject);
1762     if (!anAction)
1763       return;
1764     aMenu = new XGUI_HistoryMenu(anAction);
1765   } else {
1766     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1767     aMenu = new XGUI_HistoryMenu(aButton);
1768   }
1769   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1770   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1771 }
1772
1773 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1774 {
1775   QList<ActionInfo> aResult;
1776   std::list<std::string>::const_iterator it = theList.cbegin();
1777   for (; it != theList.cend(); it++) {
1778     QString anId = QString::fromStdString(*it);
1779     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1780     if (isEditing) {
1781       anId.chop(ModuleBase_Operation::EditSuffix().size());
1782     }
1783     ActionInfo anInfo;
1784     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1785     if (aContextMenuAct) {
1786       anInfo.initFrom(aContextMenuAct);
1787     } else {
1788       anInfo = myActionsMgr->actionInfoById(anId);
1789     }
1790     if (isEditing) {
1791       anInfo.text = anInfo.text.prepend("Modify ");
1792     }
1793     aResult << anInfo;
1794   }
1795   return aResult;
1796 }