Salome HOME
8706c57b7f9b6fec6efaf1de1b9dfc845035801a
[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 (myOperationMgr->operationsCount() == 0) {
604     // Activate selection mode for all objects
605     QIntList aModes;
606     myDisplayer->activateObjects(aModes);
607   }
608 }
609
610
611 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
612 {
613   myModule->operationCommitted(theOperation);
614 }
615
616 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
617 {
618   myModule->operationAborted(theOperation);
619 }
620
621 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
622 {
623   if (this->isSalomeMode()) 
624     theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
625   else 
626     theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
627 }
628
629 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
630 {
631   showPropertyPanel();
632   QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
633   ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
634                                                                 myModuleConnector);
635
636   myPropertyPanel->cleanContent();
637   aFactory.createWidget(myPropertyPanel->contentWidget());
638
639   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
640   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
641     bool isStoreValue = !theOperation->isEditOperation() &&
642                         !aWidget->getDefaultValue().empty() &&
643                         !aWidget->isComputedDefault();
644     aWidget->setFeature(theOperation->feature(), isStoreValue);
645     aWidget->enableFocusProcessing();
646   }
647   
648   myPropertyPanel->setModelWidgets(aWidgets);
649   theOperation->setPropertyPanel(myPropertyPanel);
650
651   myModule->propertyPanelDefined(theOperation);
652
653   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
654 }
655
656 bool XGUI_Workshop::event(QEvent * theEvent)
657 {
658   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
659   if (aPostponedEv) {
660     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
661     processEvent(aEventPtr);
662     return true;
663   }
664   return false;
665 }
666
667 /*
668  *
669  */
670 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
671 {
672   if (!theMessage) {
673 #ifdef _DEBUG
674     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
675 #endif
676     return;
677   }
678   ActionInfo aFeatureInfo;
679   aFeatureInfo.initFrom(theMessage);
680
681   QString aWchName = QString::fromStdString(theMessage->workbenchId());
682   QStringList aNestedFeatures =
683       QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
684   QString aDocKind = QString::fromStdString(theMessage->documentKind());
685   QList<QAction*> aNestedActList;
686   bool isColumnButton = !aNestedFeatures.isEmpty();
687   if (isColumnButton) {
688     QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
689     if (aNestedActions.contains("accept")) {
690       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
691       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
692       aNestedActList << anAction;
693     }
694     if (aNestedActions.contains("abort")) {
695       QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
696       connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
697       aNestedActList << anAction;
698     }
699   }
700
701   if (isSalomeMode()) {
702     QAction* aAction;
703     if (isColumnButton) {
704       aAction = salomeConnector()->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
705     } else {
706       aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
707     }
708     salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
709     salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
710
711     myActionsMgr->addCommand(aAction);
712     myModule->actionCreated(aAction);
713   } else {
714     //Find or create Workbench
715     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
716     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
717     if (!aPage) {
718       aPage = addWorkbench(aWchName);
719     }
720     //Find or create Group
721     QString aGroupName = QString::fromStdString(theMessage->groupId());
722     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
723     if (!aGroup) {
724       aGroup = aPage->addGroup(aGroupName);
725     }
726     // Check if hotkey sequence is already defined:
727     QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
728     if(aHotKey != aFeatureInfo.shortcut) {
729       aFeatureInfo.shortcut = aHotKey;
730     }
731     // Create feature...
732     AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
733                                                        aDocKind,
734                                                        aNestedFeatures);
735     // Enrich created button with accept/abort buttons if necessary
736     AppElements_Button* aButton = aCommand->button();
737     if (aButton->isColumnButton()) {
738       aButton->setAdditionalButtons(aNestedActList);
739     }
740     myActionsMgr->addCommand(aCommand);
741     myModule->actionCreated(aCommand);
742   }
743 }
744
745 /*
746  * Makes a signal/slot connections between Property Panel
747  * and given operation. The given operation becomes a
748  * current operation and previous operation if exists
749  */
750 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
751 {
752   QAction* aCommand = 0;
753   if (isSalomeMode()) {
754     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
755   } else {
756     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
757     FeaturePtr aFeature = theOperation->feature();
758     if(aFeature)
759       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
760   }
761   //Abort operation on uncheck the command
762   if (aCommand) {
763     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
764   }
765 }
766
767 /*
768  * Saves document with given name.
769  */
770 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
771 {
772   QApplication::restoreOverrideCursor();
773   SessionPtr aMgr = ModelAPI_Session::get();
774   aMgr->save(theName.toLatin1().constData(), theFileNames);
775   QApplication::restoreOverrideCursor();
776 }
777
778 bool XGUI_Workshop::isActiveOperationAborted()
779 {
780   return myOperationMgr->abortAllOperations();
781 }
782
783 //******************************************************
784 void XGUI_Workshop::onExit()
785 {
786   SessionPtr aMgr = ModelAPI_Session::get();
787   if (aMgr->isModified()) {
788     int anAnswer = QMessageBox::question(
789         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
790         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
791     if (anAnswer == QMessageBox::Save) {
792       bool saved = onSave();
793       if (!saved) {
794         return;
795       }
796     } else if (anAnswer == QMessageBox::Cancel) {
797       return;
798     }
799   }
800   qApp->exit();
801 }
802
803 //******************************************************
804 void XGUI_Workshop::onNew()
805 {
806   QApplication::setOverrideCursor(Qt::WaitCursor);
807   if (objectBrowser() == 0) {
808     createDockWidgets();
809     mySelector->connectViewers();
810   }
811   myViewerProxy->connectToViewer();
812   showObjectBrowser();
813   if (!isSalomeMode()) {
814     myMainWindow->showPythonConsole();
815     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
816     aWnd->showMaximized();
817     updateCommandStatus();
818   }
819   myContextMenuMgr->connectViewer();
820   QApplication::restoreOverrideCursor();
821 }
822
823 //******************************************************
824 void XGUI_Workshop::onOpen()
825 {
826   if(!isActiveOperationAborted())
827     return;
828   //save current file before close if modified
829   SessionPtr aSession = ModelAPI_Session::get();
830   if (aSession->isModified()) {
831     //TODO(sbh): re-launch the app?
832     int anAnswer = QMessageBox::question(
833         myMainWindow, tr("Save current file"),
834         tr("The document is modified, save before opening another?"),
835         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
836     if (anAnswer == QMessageBox::Save) {
837       onSave();
838     } else if (anAnswer == QMessageBox::Cancel) {
839       return;
840     }
841     aSession->closeAll();
842     myCurrentDir = "";
843   }
844
845   //show file dialog, check if readable and open
846   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
847   if (myCurrentDir.isEmpty())
848     return;
849   QFileInfo aFileInfo(myCurrentDir);
850   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
851     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
852     myCurrentDir = "";
853     return;
854   }
855   QApplication::setOverrideCursor(Qt::WaitCursor);
856   myIsLoadingData = true;
857   aSession->load(myCurrentDir.toLatin1().constData());
858   myObjectBrowser->rebuildDataTree();
859   displayAllResults();
860   updateCommandStatus();
861   myIsLoadingData = false;
862   QApplication::restoreOverrideCursor();
863 }
864
865 //******************************************************
866 bool XGUI_Workshop::onSave()
867 {
868   if(!isActiveOperationAborted())
869     return false;
870   if (myCurrentDir.isEmpty()) {
871     return onSaveAs();
872   }
873   std::list<std::string> aFiles;
874   saveDocument(myCurrentDir, aFiles);
875   updateCommandStatus();
876   if (!isSalomeMode())
877     myMainWindow->setModifiedState(false);
878   return true;
879 }
880
881 //******************************************************
882 bool XGUI_Workshop::onSaveAs()
883 {
884   if(!isActiveOperationAborted())
885     return false;
886   QFileDialog dialog(mainWindow());
887   dialog.setWindowTitle(tr("Select directory to save files..."));
888   dialog.setFileMode(QFileDialog::Directory);
889   dialog.setFilter(tr("Folders (*)"));
890   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
891   dialog.setViewMode(QFileDialog::Detail);
892
893   if (!dialog.exec()) {
894     return false;
895   }
896   QString aTempDir = dialog.selectedFiles().first();
897   QDir aDir(aTempDir);
898   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
899     int answer = QMessageBox::question(
900         myMainWindow,
901         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
902         tr("Save"),
903         tr("The folder already contains some files, save anyway?"),
904         QMessageBox::Save | QMessageBox::Cancel);
905     if (answer == QMessageBox::Cancel) {
906       return false;
907     }
908   }
909   myCurrentDir = aTempDir;
910   if (!isSalomeMode()) {
911     myMainWindow->setCurrentDir(myCurrentDir, false);
912     myMainWindow->setModifiedState(false);
913   }
914   return onSave();
915 }
916
917 //******************************************************
918 void XGUI_Workshop::onUndo(int theTimes)
919 {
920   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
921   SessionPtr aMgr = ModelAPI_Session::get();
922   if (aMgr->isOperation())
923     operationMgr()->onAbortOperation();
924   for (int i = 0; i < theTimes; ++i) {
925     aMgr->undo();
926   }
927   updateCommandStatus();
928 }
929
930 //******************************************************
931 void XGUI_Workshop::onRedo(int theTimes)
932 {
933   // the viewer update should be blocked in order to avoid the features blinking. For the created
934   // feature a results are created, the flush of the created signal caused the viewer redisplay for
935   // each created result. After a redisplay signal is flushed. So, the viewer update is blocked until
936   // redo of all possible objects happens
937   bool isUpdateEnabled = myDisplayer->enableUpdateViewer(false);
938
939   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
940   SessionPtr aMgr = ModelAPI_Session::get();
941   if (aMgr->isOperation())
942     operationMgr()->onAbortOperation();
943   for (int i = 0; i < theTimes; ++i) {
944     aMgr->redo();
945   }
946   updateCommandStatus();
947
948   // unblock the viewer update functionality and make update on purpose
949   myDisplayer->enableUpdateViewer(isUpdateEnabled);
950   myDisplayer->updateViewer();
951 }
952
953 //******************************************************
954 void XGUI_Workshop::onRebuild()
955 {
956   SessionPtr aMgr = ModelAPI_Session::get();
957   bool aWasOperation = aMgr->isOperation(); // keep this value
958   if (!aWasOperation) {
959     aMgr->startOperation("Rebuild");
960   }
961   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
962   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
963     new Events_Message(aRebuildEvent, this)));
964   if (!aWasOperation) {
965     aMgr->finishOperation();
966   }
967   updateCommandStatus();
968 }
969
970 //******************************************************
971 void XGUI_Workshop::onPreferences()
972 {
973   ModuleBase_Prefs aModif;
974   ModuleBase_Preferences::editPreferences(aModif);
975   if (aModif.size() > 0) {
976     QString aSection;
977     foreach (ModuleBase_Pref aPref, aModif)
978     {
979       aSection = aPref.first;
980       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
981         if (!isSalomeMode())
982           myMainWindow->viewer()->updateFromResources();
983       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
984         if (!isSalomeMode())
985           myMainWindow->menuObject()->updateFromResources();
986       }
987     }
988   }
989 }
990
991 //******************************************************
992 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
993 {
994   QString libName = QString::fromStdString(library(theModule.toStdString()));
995   if (libName.isEmpty()) {
996     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
997     return 0;
998   }
999
1000   QString err;
1001   CREATE_FUNC crtInst = 0;
1002
1003 #ifdef WIN32
1004   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
1005   if (!modLib) {
1006     LPVOID lpMsgBuf;
1007     ::FormatMessage(
1008         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1009         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1010     QString aMsg((char*) &lpMsgBuf);
1011     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1012     ::LocalFree(lpMsgBuf);
1013   } else {
1014     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1015     if (!crtInst) {
1016       LPVOID lpMsgBuf;
1017       ::FormatMessage(
1018           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1019               | FORMAT_MESSAGE_IGNORE_INSERTS,
1020           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1021       QString aMsg((char*) &lpMsgBuf);
1022       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1023       ::LocalFree(lpMsgBuf);
1024     }
1025   }
1026 #else
1027   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1028   if ( !modLib ) {
1029     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1030   } else {
1031     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1032     if ( !crtInst ) {
1033       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1034     }
1035   }
1036 #endif
1037
1038   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1039
1040   if (!err.isEmpty()) {
1041     if (mainWindow()) {
1042       Events_Error::send(err.toStdString());
1043     } else {
1044       qWarning(qPrintable(err));
1045     }
1046   }
1047   return aModule;
1048 }
1049
1050 //******************************************************
1051 bool XGUI_Workshop::activateModule()
1052 {
1053   Config_ModuleReader aModuleReader;
1054   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1055   myModule = loadModule(moduleName);
1056   if (!myModule)
1057     return false;
1058
1059   connect(myDisplayer, SIGNAL(objectDisplayed(ObjectPtr, AISObjectPtr)),
1060     myModule, SLOT(onObjectDisplayed(ObjectPtr, AISObjectPtr)));
1061   connect(myDisplayer, SIGNAL(beforeObjectErase(ObjectPtr, AISObjectPtr)),
1062     myModule, SLOT(onBeforeObjectErase(ObjectPtr, AISObjectPtr)));
1063
1064   myModule->createFeatures();
1065   myActionsMgr->update();
1066   return true;
1067 }
1068
1069 //******************************************************
1070 void XGUI_Workshop::updateCommandStatus()
1071 {
1072   QList<QAction*> aCommands;
1073   if (isSalomeMode()) {  // update commands in SALOME mode
1074     aCommands = salomeConnector()->commandList();
1075   } else {
1076     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1077     foreach (AppElements_Command* aCmd, aMenuBar->features())
1078       aCommands.append(aCmd);
1079   }
1080   SessionPtr aMgr = ModelAPI_Session::get();
1081   if (aMgr->hasModuleDocument()) {
1082     QAction *aUndoCmd, *aRedoCmd;
1083     foreach(QAction* aCmd, aCommands) {
1084       QString aId = aCmd->data().toString();
1085       if (aId == "UNDO_CMD")
1086         aUndoCmd = aCmd;
1087       else if (aId == "REDO_CMD")
1088         aRedoCmd = aCmd;
1089       else
1090         // Enable all commands
1091         aCmd->setEnabled(true);
1092     }
1093
1094     aUndoCmd->setEnabled(myModule->canUndo());
1095     aRedoCmd->setEnabled(myModule->canRedo());
1096     updateHistory();
1097   } else {
1098     foreach(QAction* aCmd, aCommands) {
1099       QString aId = aCmd->data().toString();
1100       if (aId == "NEW_CMD")
1101         aCmd->setEnabled(true);
1102       else if (aId == "EXIT_CMD")
1103         aCmd->setEnabled(true);
1104       else
1105         aCmd->setEnabled(false);
1106     }
1107   }
1108   myActionsMgr->update();
1109   emit commandStatusUpdated();
1110 }
1111
1112 void XGUI_Workshop::updateHistory()
1113 {
1114   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1115   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1116   emit updateUndoHistory(aUndoRes);
1117
1118   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1119   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1120   emit updateRedoHistory(aRedoRes);
1121 }
1122
1123 //******************************************************
1124 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1125 {
1126   QDockWidget* aObjDock = new QDockWidget(theParent);
1127   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1128   aObjDock->setWindowTitle(tr("Object browser"));
1129   aObjDock->setStyleSheet(
1130       "::title { position: relative; padding-left: 5px; text-align: left center }");
1131   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1132   myObjectBrowser->setDataModel(myModule->dataModel());
1133   //connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1134   //        SLOT(changeCurrentDocument(ObjectPtr)));
1135   aObjDock->setWidget(myObjectBrowser);
1136
1137   myContextMenuMgr->connectObjectBrowser();
1138   return aObjDock;
1139 }
1140
1141 //******************************************************
1142 /*
1143  * Creates dock widgets, places them in corresponding area
1144  * and tabifies if necessary.
1145  */
1146 void XGUI_Workshop::createDockWidgets()
1147 {
1148   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1149   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1150   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1151   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1152   myPropertyPanel->setupActions(myActionsMgr);
1153   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1154   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1155   hidePropertyPanel();  ///<! Invisible by default
1156   hideObjectBrowser();
1157   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1158   myPropertyPanel->installEventFilter(myOperationMgr);
1159
1160   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1161   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1162   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1163   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1164   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1165   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1166           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1167   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1168           aOkAct,          SLOT(setEnabled(bool)));
1169   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1170   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
1171           aAcceptAllAct,   SLOT(setEnabled(bool)));
1172
1173 }
1174
1175 //******************************************************
1176 void XGUI_Workshop::showPropertyPanel()
1177 {
1178   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1179   ///<! Restore ability to close panel from the window's menu
1180   aViewAct->setEnabled(true);
1181   myPropertyPanel->show();
1182   myPropertyPanel->raise();
1183 }
1184
1185 //******************************************************
1186 void XGUI_Workshop::hidePropertyPanel()
1187 {
1188   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1189   ///<! Do not allow to show empty property panel
1190   aViewAct->setEnabled(false);
1191   myPropertyPanel->hide();
1192 }
1193
1194 //******************************************************
1195 void XGUI_Workshop::showObjectBrowser()
1196 {
1197   myObjectBrowser->parentWidget()->show();
1198 }
1199
1200 //******************************************************
1201 void XGUI_Workshop::hideObjectBrowser()
1202 {
1203   myObjectBrowser->parentWidget()->hide();
1204 }
1205
1206 //******************************************************
1207 void XGUI_Workshop::onFeatureTriggered()
1208 {
1209   QAction* aCmd = dynamic_cast<QAction*>(sender());
1210   if (aCmd) {
1211     QString aId = salomeConnector()->commandId(aCmd);
1212     if (!aId.isNull())
1213       myModule->launchOperation(aId);
1214   }
1215 }
1216
1217 //******************************************************
1218 void XGUI_Workshop::salomeViewerSelectionChanged()
1219 {
1220   emit salomeViewerSelection();
1221 }
1222
1223 //**************************************************************
1224 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1225 {
1226   return mySalomeConnector->viewer();
1227 }
1228
1229 //**************************************************************
1230 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1231 {
1232   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1233   if (theId == "DELETE_CMD")
1234     deleteObjects();
1235   else if (theId == "COLOR_CMD")
1236     changeColor(aObjects);
1237   else if (theId == "SHOW_CMD")
1238     showObjects(aObjects, true);
1239   else if (theId == "HIDE_CMD")
1240     showObjects(aObjects, false);
1241   else if (theId == "SHOW_ONLY_CMD")
1242     showOnlyObjects(aObjects);
1243   else if (theId == "SHADING_CMD")
1244     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1245   else if (theId == "WIREFRAME_CMD")
1246     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1247   else if (theId == "HIDEALL_CMD")
1248     myDisplayer->eraseAll();
1249 }
1250
1251 //**************************************************************
1252 void XGUI_Workshop::deleteObjects()
1253 {
1254   ModuleBase_IModule* aModule = module();
1255   // 1. allow the module to delete objects, do nothing if it has succeed
1256   if (aModule->deleteObjects()) {
1257     updateCommandStatus();
1258     return;
1259   }
1260
1261   if (!isActiveOperationAborted())
1262     return;
1263   QObjectPtrList anObjects = mySelector->selection()->selectedObjects();
1264   bool hasResult = false;
1265   bool hasFeature = false;
1266   bool hasParameter = false;
1267   ModuleBase_Tools::checkObjects(anObjects, hasResult, hasFeature, hasParameter);
1268   if (!(hasFeature || hasParameter))
1269     return;
1270
1271   // 1. start operation
1272   QString aDescription = contextMenuMgr()->action("DELETE_CMD")->text();
1273   aDescription += tr(" %1");
1274   QStringList aObjectNames;
1275   foreach (ObjectPtr aObj, anObjects) {
1276     if (!aObj->data().get())
1277       continue;
1278     aObjectNames << QString::fromStdString(aObj->data()->name());
1279   }
1280   aDescription = aDescription.arg(aObjectNames.join(", "));
1281
1282   SessionPtr aMgr = ModelAPI_Session::get();
1283   aMgr->startOperation(aDescription.toStdString());
1284   // 2. close the documents of the removed parts if the result part is in a list of selected objects
1285   foreach (ObjectPtr aObj, anObjects)
1286   {
1287     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1288     if (aPart) {
1289       DocumentPtr aDoc = aObj->document();
1290       if (aDoc == aMgr->activeDocument()) {
1291         aDoc->close();
1292       }
1293     }
1294   }
1295   // 3. delete objects
1296   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1297   std::set<FeaturePtr> anIgnoredFeatures;
1298   if (deleteFeatures(anObjects, anIgnoredFeatures, aDesktop, true)) {
1299     myDisplayer->updateViewer();
1300     aMgr->finishOperation();
1301     updateCommandStatus();
1302   }
1303   else {
1304     aMgr->abortOperation();
1305   }
1306 }
1307
1308 //**************************************************************
1309 bool XGUI_Workshop::deleteFeatures(const QObjectPtrList& theList,
1310                                    std::set<FeaturePtr> theIgnoredFeatures,
1311                                    QWidget* theParent,
1312                                    const bool theAskAboutDeleteReferences)
1313 {
1314   // 1. find all referenced features
1315   std::set<FeaturePtr> aRefFeatures;
1316   foreach (ObjectPtr aObj, theList) {
1317     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1318     if (aFeature.get() != NULL) {
1319       aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1320     }
1321   }
1322   // 2. warn about the references remove, break the delete operation if the user chose it
1323   if (theAskAboutDeleteReferences && !aRefFeatures.empty()) {
1324     QStringList aRefNames;
1325     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1326                                          aLast = aRefFeatures.end();
1327     for (; anIt != aLast; anIt++) {
1328       aRefNames.append((*anIt)->name().c_str());
1329     }
1330     QString aNames = aRefNames.join(", ");
1331
1332     QMessageBox::StandardButton aRes = QMessageBox::warning(
1333         theParent, tr("Delete features"),
1334         QString(tr("Selected features are used in the following features: %1.\
1335 These features will be deleted also. Would you like to continue?")).arg(aNames),
1336         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1337     if (aRes != QMessageBox::Yes)
1338       return false;
1339   }
1340
1341   // 3. remove referenced features
1342   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1343                                        aLast = aRefFeatures.end();
1344   for (; anIt != aLast; anIt++) {
1345     FeaturePtr aFeature = (*anIt);
1346     DocumentPtr aDoc = aFeature->document();
1347     if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1348       aDoc->removeFeature(aFeature);
1349   }
1350
1351   // 4. remove the parameter features
1352   foreach (ObjectPtr aObj, theList) {
1353     FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
1354     if (aFeature) {
1355       DocumentPtr aDoc = aObj->document();
1356       if (theIgnoredFeatures.find(aFeature) == theIgnoredFeatures.end())
1357         aDoc->removeFeature(aFeature);
1358     }
1359   }
1360   return true;
1361 }
1362
1363 bool hasResults(QObjectPtrList theObjects, const std::set<std::string>& theTypes)
1364 {
1365   bool isFoundResultType = false;
1366   foreach(ObjectPtr anObj, theObjects)
1367   {
1368     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1369     if (aResult.get() == NULL)
1370       continue;
1371
1372     isFoundResultType = theTypes.find(aResult->groupName()) != theTypes.end();
1373     if (isFoundResultType)
1374       break;
1375   }
1376   return isFoundResultType;
1377 }
1378
1379 //**************************************************************
1380 bool XGUI_Workshop::canChangeColor() const
1381 {
1382   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1383
1384   std::set<std::string> aTypes;
1385   aTypes.insert(ModelAPI_ResultGroup::group());
1386   aTypes.insert(ModelAPI_ResultConstruction::group());
1387   aTypes.insert(ModelAPI_ResultBody::group());
1388   aTypes.insert(ModelAPI_ResultPart::group());
1389
1390   return hasResults(aObjects, aTypes);
1391 }
1392
1393 void setColor(ResultPtr theResult, std::vector<int>& theColor)
1394 {
1395   if (!theResult.get())
1396     return;
1397
1398   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1399   if (aColorAttr.get() != NULL) {
1400     if (!aColorAttr->size()) {
1401       aColorAttr->setSize(3);
1402     }
1403     aColorAttr->setValue(0, theColor[0]);
1404     aColorAttr->setValue(1, theColor[1]);
1405     aColorAttr->setValue(2, theColor[2]);
1406   }
1407 }
1408
1409 //**************************************************************
1410 void XGUI_Workshop::changeColor(const QObjectPtrList& theObjects)
1411 {
1412   AttributeIntArrayPtr aColorAttr;
1413   // 1. find the current color of the object. This is a color of AIS presentation
1414   // The objects are iterated until a first valid color is found 
1415   std::vector<int> aColor;
1416   foreach(ObjectPtr anObject, theObjects) {
1417     if (anObject->groupName() == ModelAPI_ResultPart::group()) {
1418       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anObject);
1419       DocumentPtr aPartDoc = aPart->partDoc();
1420       // the document should be checked on null, because in opened document if the part
1421       // has not been activated yet, the part document is empty
1422       if (!aPartDoc.get()) {
1423         emit errorOccurred(QString::fromLatin1("Color can not be changed on a part with an empty document"));
1424       }
1425       else {
1426         if (aPartDoc->size(ModelAPI_ResultBody::group()) > 0) {
1427           ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), 0);
1428           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1429           if (aBody.get()) {
1430             std::string aSection, aName, aDefault;
1431             aBody->colorConfigInfo(aSection, aName, aDefault);
1432             if (!aSection.empty() && !aName.empty()) {
1433               aColor = Config_PropManager::color(aSection, aName, aDefault);
1434             }
1435           }
1436         }
1437       }
1438     }
1439     else {
1440       AISObjectPtr anAISObj = myDisplayer->getAISObject(anObject);
1441       if (anAISObj.get()) {
1442         aColor.resize(3);
1443         anAISObj->getColor(aColor[0], aColor[1], aColor[2]);
1444       }
1445     }
1446     if (!aColor.empty())
1447       break;
1448   }
1449   if (aColor.size() != 3)
1450     return;
1451
1452   // 2. show the dialog to change the value
1453   XGUI_ColorDialog* aDlg = new XGUI_ColorDialog(mainWindow());
1454   aDlg->setColor(aColor);
1455   aDlg->move(QCursor::pos());
1456   bool isDone = aDlg->exec() == QDialog::Accepted;
1457   if (!isDone)
1458     return;
1459
1460   bool isRandomColor = aDlg->isRandomColor();
1461
1462   // 3. abort the previous operation and start a new one
1463   SessionPtr aMgr = ModelAPI_Session::get();
1464   bool aWasOperation = aMgr->isOperation(); // keep this value
1465   if (!aWasOperation) {
1466     QString aDescription = contextMenuMgr()->action("COLOR_CMD")->text();
1467     aMgr->startOperation(aDescription.toStdString());
1468   }
1469
1470   // 4. set the value to all results
1471   foreach(ObjectPtr anObj, theObjects) {
1472     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1473     if (aResult.get() != NULL) {
1474       if (aResult->groupName() == ModelAPI_ResultPart::group()) {
1475         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aResult);
1476         DocumentPtr aPartDoc = aPart->partDoc();
1477         // the document should be checked on null, because in opened document if the part
1478         // has not been activated yet, the part document is empty
1479         if (aPartDoc.get()) {
1480           for (int i = 0; i < aPartDoc->size(ModelAPI_ResultBody::group()); i++) {
1481             ObjectPtr aObject = aPartDoc->object(ModelAPI_ResultBody::group(), i);
1482             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aObject);
1483             std::vector<int> aColorResult = aDlg->getColor();
1484             setColor(aBody, aColorResult);
1485           }
1486         }
1487       }
1488       else {
1489         std::vector<int> aColorResult = aDlg->getColor();
1490         setColor(aResult, aColorResult);
1491       }
1492     }
1493   }
1494   if (!aWasOperation)
1495     aMgr->finishOperation();
1496   updateCommandStatus();
1497 }
1498
1499 //**************************************************************
1500 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1501 {
1502   foreach (ObjectPtr aObj, theList)
1503   {
1504     if (isVisible) {
1505       displayObject(aObj);
1506     } else {
1507       myDisplayer->erase(aObj, false);
1508     }
1509   }
1510   myDisplayer->updateViewer();
1511 }
1512
1513 //**************************************************************
1514 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1515 {
1516   myDisplayer->showOnly(theList);
1517 }
1518
1519
1520 //**************************************************************
1521 void XGUI_Workshop::registerValidators() const
1522 {
1523   SessionPtr aMgr = ModelAPI_Session::get();
1524   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1525 }
1526
1527 //**************************************************************
1528 void XGUI_Workshop::displayAllResults()
1529 {
1530   SessionPtr aMgr = ModelAPI_Session::get();
1531   DocumentPtr aRootDoc = aMgr->moduleDocument();
1532   displayDocumentResults(aRootDoc);
1533   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1534     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1535     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1536     displayDocumentResults(aPart->partDoc());
1537   }
1538   myDisplayer->updateViewer();
1539 }
1540
1541 //**************************************************************
1542 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1543 {
1544   if (!theDoc)
1545     return;
1546   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1547   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1548 }
1549
1550 //**************************************************************
1551 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1552 {
1553   for (int i = 0; i < theDoc->size(theGroup); i++)
1554     displayObject(theDoc->object(theGroup, i));
1555 }
1556
1557 //**************************************************************
1558 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1559 {
1560   foreach(ObjectPtr aObj, theList) {
1561     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1562   }
1563   if (theList.size() > 0)
1564     myDisplayer->updateViewer();
1565 }
1566
1567 //**************************************************************
1568 void XGUI_Workshop::closeDocument()
1569 {
1570   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1571   while (anOperation) {
1572     anOperation->abort();
1573     anOperation = operationMgr()->currentOperation();
1574   }
1575   myDisplayer->closeLocalContexts();
1576   myDisplayer->eraseAll();
1577   objectBrowser()->clearContent();
1578
1579   SessionPtr aMgr = ModelAPI_Session::get();
1580   aMgr->closeAll();
1581   objectBrowser()->clearContent();
1582 }
1583
1584 //**************************************************************
1585 bool XGUI_Workshop::displayObject(ObjectPtr theObj)
1586 {
1587   if (!myModule->canDisplayObject(theObj))
1588     return false;
1589
1590   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1591   if (aBody.get() != NULL) {
1592     int aNb = myDisplayer->objectsCount();
1593     myDisplayer->display(theObj, false);
1594     if (aNb == 0)
1595       viewer()->fitAll();
1596   } else if (!(myIsLoadingData || myPartActivating))
1597     myDisplayer->display(theObj, false);
1598
1599   return true;
1600 }
1601
1602 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1603 {
1604   XGUI_HistoryMenu* aMenu = NULL;
1605   if (isSalomeMode()) {
1606     QAction* anAction = qobject_cast<QAction*>(theObject);
1607     if (!anAction)
1608       return;
1609     aMenu = new XGUI_HistoryMenu(anAction);
1610   } else {
1611     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1612     aMenu = new XGUI_HistoryMenu(aButton);
1613   }
1614   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1615   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1616 }
1617
1618 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1619 {
1620   QList<ActionInfo> aResult;
1621   std::list<std::string>::const_iterator it = theList.cbegin();
1622   for (; it != theList.cend(); it++) {
1623     QString anId = QString::fromStdString(*it);
1624     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1625     if (isEditing) {
1626       anId.chop(ModuleBase_Operation::EditSuffix().size());
1627     }
1628     ActionInfo anInfo;
1629     QAction* aContextMenuAct = myContextMenuMgr->actionByName(anId);
1630     if (aContextMenuAct) {
1631       anInfo.initFrom(aContextMenuAct);
1632     } else {
1633       anInfo = myActionsMgr->actionInfoById(anId);
1634     }
1635     if (isEditing) {
1636       anInfo.text = anInfo.text.prepend("Modify ");
1637     }
1638     aResult << anInfo;
1639   }
1640   return aResult;
1641 }