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