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