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