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