]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Merge branch 'Dev_0.6.1' of newgeom:newgeom into Dev_0.6.1
[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_ViewerProxy.h"
15 #include "XGUI_PropertyPanel.h"
16 #include "XGUI_ContextMenuMgr.h"
17 #include "XGUI_ModuleConnector.h"
18 #include <XGUI_QtEvents.h>
19
20 #include <AppElements_Workbench.h>
21 #include <AppElements_Viewer.h>
22 #include <AppElements_Command.h>
23 #include <AppElements_MainMenu.h>
24 #include <AppElements_MainWindow.h>
25 #include <AppElements_MenuGroupPanel.h>
26
27 #include <ModuleBase_IModule.h>
28 #include <ModuleBase_Preferences.h>
29
30 #include <ModelAPI_Events.h>
31 #include <ModelAPI_Session.h>
32 #include <ModelAPI_Feature.h>
33 #include <ModelAPI_Data.h>
34 #include <ModelAPI_AttributeDocRef.h>
35 #include <ModelAPI_Object.h>
36 #include <ModelAPI_Validator.h>
37 #include <ModelAPI_ResultConstruction.h>
38 #include <ModelAPI_ResultBody.h>
39
40 //#include <PartSetPlugin_Part.h>
41
42 #include <Events_Loop.h>
43 #include <Events_Error.h>
44 #include <Events_LongOp.h>
45
46 #include <ModuleBase_Operation.h>
47 #include <ModuleBase_Operation.h>
48 #include <ModuleBase_OperationDescription.h>
49 #include <ModuleBase_SelectionValidator.h>
50 #include <ModuleBase_WidgetFactory.h>
51 #include <ModuleBase_Tools.h>
52 #include <ModuleBase_IViewer.h>
53 #include<ModuleBase_FilterFactory.h>
54
55 #include <Config_Common.h>
56 #include <Config_FeatureMessage.h>
57 #include <Config_PointerMessage.h>
58 #include <Config_ModuleReader.h>
59 #include <Config_PropManager.h>
60 #include <Config_SelectionFilterMessage.h>
61
62 #include <QApplication>
63 #include <QFileDialog>
64 #include <QMessageBox>
65 #include <QMdiSubWindow>
66 #include <QPushButton>
67 #include <QDockWidget>
68 #include <QLayout>
69 #include <QThread>
70 #include <QObject>
71
72 #ifdef _DEBUG
73 #include <QDebug>
74 #include <iostream>
75 #endif
76
77 #ifdef WIN32
78 #include <windows.h>
79 #else
80 #include <dlfcn.h>
81 #endif
82
83 QMap<QString, QString> XGUI_Workshop::myIcons;
84
85
86 QIcon XGUI_Workshop::featureIcon(const FeaturePtr& theFeature)
87 {
88   QIcon anIcon;
89
90   std::string aKind = theFeature->getKind();
91   QString aId(aKind.c_str());
92   if (!myIcons.contains(aId))
93     return anIcon;
94
95   QString anIconString = myIcons[aId];
96
97   ModelAPI_ExecState aState = theFeature->data()->execState();
98   switch(aState) {
99     case ModelAPI_StateDone:
100     case ModelAPI_StateNothing:
101       anIcon = QIcon(anIconString);
102     case ModelAPI_StateMustBeUpdated: {
103       anIcon = ModuleBase_Tools::lighter(anIconString);
104     }
105     break;
106     case ModelAPI_StateExecFailed: {
107       anIcon = ModuleBase_Tools::composite(":pictures/exec_state_failed.png", anIconString);
108     }
109     break;
110     case ModelAPI_StateInvalidArgument: {
111       anIcon = ModuleBase_Tools::composite(":pictures/exec_state_invalid_parameters.png",
112                                            anIconString);
113     }
114     break;
115     default: break;  
116   }
117   return anIcon;  
118 }
119
120 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
121     : QObject(),
122       myCurrentDir(QString()),
123       myModule(NULL),
124       mySalomeConnector(theConnector),
125       myPropertyPanel(0),
126       myObjectBrowser(0),
127       myDisplayer(0),
128       myUpdatePrefs(false),
129       myPartActivating(false)
130 {
131   myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
132
133   myDisplayer = new XGUI_Displayer(this);
134
135   mySelector = new XGUI_SelectionMgr(this);
136   //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
137
138   myOperationMgr = new XGUI_OperationMgr(this);
139   myActionsMgr = new XGUI_ActionsMgr(this);
140   myErrorDlg = new XGUI_ErrorDialog(myMainWindow);
141   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
142   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
143           SLOT(onContextMenuCommand(const QString&, bool)));
144
145   myViewerProxy = new XGUI_ViewerProxy(this);
146   connect(myViewerProxy, SIGNAL(selectionChanged()), this, SLOT(updateCommandsOnViewSelection()));
147
148   myModuleConnector = new XGUI_ModuleConnector(this);
149
150   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)), 
151           SLOT(onOperationStarted(ModuleBase_Operation*)));
152   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
153           SLOT(onOperationResumed(ModuleBase_Operation*)));
154   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
155           SLOT(onOperationStopped(ModuleBase_Operation*)));
156   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)), 
157           SLOT(onOperationCommitted(ModuleBase_Operation*)));
158   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)), 
159           SLOT(onOperationAborted(ModuleBase_Operation*)));
160   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
161   // TODO(sbh): It seems that application works properly without update on operationStarted
162   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
163           myActionsMgr,   SLOT(update()));
164   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
165           myActionsMgr,   SLOT(update()));
166   connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
167 }
168
169 //******************************************************
170 XGUI_Workshop::~XGUI_Workshop(void)
171 {
172   delete myDisplayer;
173 }
174
175 //******************************************************
176 void XGUI_Workshop::startApplication()
177 {
178   initMenu();
179
180   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
181                                    Config_Prop::Directory, "");
182
183   //Initialize event listening
184   Events_Loop* aLoop = Events_Loop::loop();
185   aLoop->registerListener(this, Events_Error::errorID());  //!< Listening application errors.
186   aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
187   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
188   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
189   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
190   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
191   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
192   aLoop->registerListener(this, Events_Loop::eventByName("LongOperation"));
193   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
194   aLoop->registerListener(this, Events_Loop::eventByName("CurrentDocumentChanged"));
195   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOSHOW));
196   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
197   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
198
199   registerValidators();
200
201   // Calling of  loadCustomProps before activating module is required
202   // by Config_PropManger to restore user-defined path to plugins
203   ModuleBase_Preferences::loadCustomProps();
204   activateModule();
205   if (myMainWindow) {
206     myMainWindow->show();
207     updateCommandStatus();
208   }
209   
210   onNew();
211 }
212
213 //******************************************************
214 void XGUI_Workshop::initMenu()
215 {
216   myContextMenuMgr->createActions();
217
218   if (isSalomeMode()) {
219     // Create only Undo, Redo commands
220     QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
221                                                          tr("Undo last command"),
222                                                          QIcon(":pictures/undo.png"),
223                                                          QKeySequence::Undo, false, "MEN_DESK_EDIT");
224     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
225     aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
226                                                 QIcon(":pictures/redo.png"), QKeySequence::Redo,
227                                                 false, "MEN_DESK_EDIT");
228     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
229     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
230     aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
231                                                 QIcon(":pictures/rebuild.png"), QKeySequence(),
232                                                 false, "MEN_DESK_EDIT");
233     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
234     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
235
236     aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
237                                                 QIcon(), QKeySequence(),
238                                                 false, "MEN_DESK_FILE");
239     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
240
241     aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
242                                                 QIcon(), QKeySequence(),
243                                                 false, "MEN_DESK_FILE");
244     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
245     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
246
247     return;
248   }
249   // File commands group
250   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
251
252   AppElements_Command* aCommand;
253
254   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
255                                 QIcon(":pictures/save.png"), QKeySequence::Save);
256   aCommand->connectTo(this, SLOT(onSave()));
257   //aCommand->disable();
258
259   aCommand = aGroup->addFeature("UNDO_CMD", tr("Undo"), tr("Undo last command"),
260                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
261   aCommand->connectTo(this, SLOT(onUndo()));
262
263   aCommand = aGroup->addFeature("REDO_CMD", tr("Redo"), tr("Redo last command"),
264                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
265   aCommand->connectTo(this, SLOT(onRedo()));
266
267   aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
268     QIcon(":pictures/rebuild.png"), QKeySequence());
269   aCommand->connectTo(this, SLOT(onRebuild()));
270
271   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
272                                 QIcon(":pictures/save.png"), QKeySequence());
273   aCommand->connectTo(this, SLOT(onSaveAs()));
274   //aCommand->disable();
275
276   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
277                                 QIcon(":pictures/open.png"), QKeySequence::Open);
278   aCommand->connectTo(this, SLOT(onOpen()));
279
280   //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
281   //                              QIcon(":pictures/new.png"), QKeySequence::New);
282   //aCommand->connectTo(this, SLOT(onNew()));
283
284   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
285                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
286   aCommand->connectTo(this, SLOT(onPreferences()));
287
288   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
289                                 QIcon(":pictures/close.png"), QKeySequence::Close);
290   aCommand->connectTo(this, SLOT(onExit()));
291   //FIXME: SBH's test action. Can be used for some GUI tests.
292 //  #ifdef _DEBUG
293 //    aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
294 //                                  QIcon(":pictures/close.png"), QKeySequence(), true);
295 //    aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
296 //  #endif
297 }
298
299 //******************************************************
300 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
301 {
302   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
303   return aMenuBar->addWorkbench(theName);
304 }
305
306 //******************************************************
307 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
308 {
309   if (QApplication::instance()->thread() != QThread::currentThread()) {
310     #ifdef _DEBUG
311     std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
312     #endif
313     SessionPtr aMgr = ModelAPI_Session::get();
314     PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
315     QApplication::postEvent(this, aPostponeEvent);
316     return;
317   }
318
319   //A message to start feature creation received.
320   if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
321     std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
322        std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
323     if (!aFeatureMsg->isInternal()) {
324       addFeature(aFeatureMsg);
325     }
326   }
327
328   // Process creation of Part
329   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
330     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
331         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
332     onFeatureCreatedMsg(aUpdMsg);
333     if (myUpdatePrefs) {
334       if (mySalomeConnector)
335         mySalomeConnector->createPreferences();
336       myUpdatePrefs = false;
337     }
338   }
339   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
340     myUpdatePrefs = true;
341   }
342
343   // Redisplay feature
344   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
345     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
346         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
347     onFeatureRedisplayMsg(aUpdMsg);
348   }
349
350   //Update property panel on corresponding message. If there is no current operation (no
351   //property panel), or received message has different feature to the current - do nothing.
352   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
353     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
354         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
355     onFeatureUpdatedMsg(anUpdateMsg);
356   }
357
358   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
359     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDelMsg =
360         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
361     onObjectDeletedMsg(aDelMsg);
362   }
363
364   else if (theMessage->eventID() == Events_LongOp::eventID()) {
365     if (Events_LongOp::isPerformed())
366       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
367     else
368       QApplication::restoreOverrideCursor();
369   }
370
371   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOSHOW)) {
372     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
373         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
374     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
375     QObjectPtrList aList;
376     std::set<ObjectPtr>::const_iterator aIt;
377     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
378       aList.append(*aIt);
379     showObjects(aList, true);
380   }
381
382   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE)) {
383     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
384         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
385     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
386     QObjectPtrList aList;
387     std::set<ObjectPtr>::const_iterator aIt;
388     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
389       aList.append(*aIt);
390     showObjects(aList, false);
391   }
392
393   //An operation passed by message. Start it, process and commit.
394   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
395     std::shared_ptr<Config_PointerMessage> aPartSetMsg =
396         std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
397     //myPropertyPanel->cleanContent();
398     ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
399
400     if (myOperationMgr->startOperation(anOperation)) {
401       myPropertyPanel->updateContentWidget(anOperation->feature());
402       if (!anOperation->getDescription()->hasXmlRepresentation()) {
403         if (anOperation->commit())
404           updateCommandStatus();
405       }
406     }
407   }
408   else if (theMessage->eventID() == Events_Loop::loop()->eventByName("CurrentDocumentChanged")) {
409     myActionsMgr->update();
410     // Find and Activate active part
411     if (myPartActivating)
412       return;
413     SessionPtr aMgr = ModelAPI_Session::get();
414     DocumentPtr aActiveDoc = aMgr->activeDocument();
415     DocumentPtr aDoc = aMgr->moduleDocument();
416     if (aActiveDoc == aDoc) {
417       activatePart(ResultPartPtr()); 
418       return;
419     }
420     std::string aGrpName = ModelAPI_ResultPart::group();
421     for (int i = 0; i < aDoc->size(aGrpName); i++) {
422       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
423       if (aPart->partDoc() == aActiveDoc) {
424         activatePart(aPart); // Activate a part which corresponds to active Doc
425         return;
426       }
427     }
428     // If not found then activate global document
429     activatePart(ResultPartPtr()); 
430
431   }
432   else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
433     std::shared_ptr<Config_SelectionFilterMessage> aMsg = 
434       std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
435     if (aMsg) {
436       if (aMsg->attributeId().empty()) {  // feature validator
437         moduleConnector()->selectionFilters()->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId());
438       } else {  // attribute validator
439         moduleConnector()->selectionFilters()->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId());
440       }
441     }
442   }
443
444   
445   else {
446     //Show error dialog if error message received.
447     std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
448     if (anAppError) {
449       emit errorOccurred(QString::fromLatin1(anAppError->description()));
450     }
451   }
452   if (!isSalomeMode()) {
453     SessionPtr aMgr = ModelAPI_Session::get();
454     if (aMgr->isModified() != myMainWindow->isModifiedState())
455       myMainWindow->setModifiedState(aMgr->isModified());
456   }
457 }
458
459
460 //******************************************************
461 void XGUI_Workshop::onStartWaiting()
462 {
463   if (Events_LongOp::isPerformed()) {
464     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
465   }
466 }
467
468 //******************************************************
469 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
470 {
471   std::set<ObjectPtr> aFeatures = theMsg->objects();
472   if (myOperationMgr->hasOperation()) {
473     FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
474     std::set<ObjectPtr>::const_iterator aIt;
475     for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
476       ObjectPtr aNewFeature = (*aIt);
477       if (aNewFeature == aCurrentFeature) {
478         myPropertyPanel->updateContentWidget(aCurrentFeature);
479         break;
480       }
481     }
482   }
483   myOperationMgr->onValidateOperation();
484   if (myObjectBrowser)
485     myObjectBrowser->processEvent(theMsg);
486 }
487
488 //******************************************************
489 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
490 {
491   std::set<ObjectPtr> aObjects = theMsg->objects();
492   std::set<ObjectPtr>::const_iterator aIt;
493   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
494     ObjectPtr aObj = (*aIt);
495     bool aHide = !aObj->data() || !aObj->data()->isValid();
496     if (!aHide) { // check that this is not hidden result
497       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
498       aHide = aRes && aRes->isConcealed();
499     }
500     if (aHide)
501       myDisplayer->erase(aObj, false);
502     else {
503       if (myDisplayer->isVisible(aObj))  {
504         myDisplayer->display(aObj, false);  // In order to update presentation
505         if (myOperationMgr->hasOperation()) {
506           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
507           if (aOperation->hasObject(aObj) && myDisplayer->isActive(aObj))
508             myDisplayer->deactivate(aObj);
509         }
510       } else {
511         if (myOperationMgr->hasOperation()) {
512           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
513           // Display only current operation results if operation has preview
514           if (aOperation->hasObject(aObj)/* && aOperation->hasPreview()*/) {
515             myDisplayer->display(aObj, false);
516             // Deactivate object of current operation from selection
517             if (myDisplayer->isActive(aObj))
518               myDisplayer->deactivate(aObj);
519           }
520         }
521       }
522     }
523   }
524   myDisplayer->updateViewer();
525 }
526
527 //******************************************************
528 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
529 {
530   std::set<ObjectPtr> aObjects = theMsg->objects();
531
532   std::set<ObjectPtr>::const_iterator aIt;
533   bool aHasPart = false;
534   bool isDisplayed = false;
535   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
536     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aIt);
537     if (aPart) {
538       aHasPart = true;
539       // If a feature is created from the aplication's python console  
540       // it doesn't stored in the operation mgr and doesn't displayed
541     } else if (myOperationMgr->hasOperation()) {
542       ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
543       if (aOperation->hasObject(*aIt)) {  // Display only current operation results
544         myDisplayer->display(*aIt, false);
545         isDisplayed = true;
546       }
547     }
548   }
549   if (myObjectBrowser)
550     myObjectBrowser->processEvent(theMsg);
551   if (isDisplayed)
552     myDisplayer->updateViewer();
553   //if (aHasPart) { // TODO: Avoid activate last part on loading of document
554   //  activateLastPart();
555   //}
556 }
557
558 //******************************************************
559 void XGUI_Workshop::onObjectDeletedMsg(const std::shared_ptr<ModelAPI_ObjectDeletedMessage>& theMsg)
560 {
561   if (myObjectBrowser)
562     myObjectBrowser->processEvent(theMsg);
563   //std::set<ObjectPtr> aFeatures = theMsg->objects();
564 }
565
566 //******************************************************
567 void XGUI_Workshop::onOperationStarted(ModuleBase_Operation* theOperation)
568 {
569   setNestedFeatures(theOperation);
570
571   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
572     connectWithOperation(theOperation);
573     setPropertyPanel(theOperation);
574   }
575   updateCommandStatus();
576
577   myModule->operationStarted(theOperation);
578 }
579
580 //******************************************************
581 void XGUI_Workshop::onOperationResumed(ModuleBase_Operation* theOperation)
582 {
583   setNestedFeatures(theOperation);
584
585   if (theOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
586     connectWithOperation(theOperation);
587     setPropertyPanel(theOperation);
588   }
589   updateCommandStatus();
590
591   myModule->operationResumed(theOperation);
592 }
593
594
595 //******************************************************
596 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
597 {
598   //!< No need for property panel
599   updateCommandStatus();
600   hidePropertyPanel();
601   myPropertyPanel->cleanContent();
602
603   // Activate objects created by current operation
604   FeaturePtr aFeature = theOperation->feature();
605   myDisplayer->activate(aFeature);
606   const std::list<ResultPtr>& aResults = aFeature->results();
607   std::list<ResultPtr>::const_iterator aIt;
608   for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
609     myDisplayer->activate(*aIt);
610   }
611   myModule->operationStopped(theOperation);
612 }
613
614
615 void XGUI_Workshop::onOperationCommitted(ModuleBase_Operation* theOperation)
616 {
617   myModule->operationCommitted(theOperation);
618 }
619
620 void XGUI_Workshop::onOperationAborted(ModuleBase_Operation* theOperation)
621 {
622   myModule->operationAborted(theOperation);
623 }
624
625 void XGUI_Workshop::setNestedFeatures(ModuleBase_Operation* theOperation)
626 {
627   if (this->isSalomeMode()) 
628     theOperation->setNestedFeatures(mySalomeConnector->nestedActions(theOperation->id()));
629   else 
630     theOperation->setNestedFeatures(myActionsMgr->nestedCommands(theOperation->id()));
631 }
632
633 void XGUI_Workshop::setPropertyPanel(ModuleBase_Operation* theOperation)
634 {
635   showPropertyPanel();
636   QString aXmlRepr = theOperation->getDescription()->xmlRepresentation();
637   ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
638                                                                 myModuleConnector);
639
640   myPropertyPanel->cleanContent();
641   aFactory.createWidget(myPropertyPanel->contentWidget());
642   ModuleBase_Tools::zeroMargins(myPropertyPanel->contentWidget());
643
644   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
645   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
646     aWidget->setFeature(theOperation->feature());
647     aWidget->enableFocusProcessing();
648     QObject::connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
649     // Init default values
650     if (!theOperation->isEditOperation() && !aWidget->isComputedDefault()) {
651       aWidget->storeValue();
652     }
653   }
654   
655   myPropertyPanel->setModelWidgets(aWidgets);
656   theOperation->setPropertyPanel(myPropertyPanel);
657
658   myModule->propertyPanelDefined(theOperation);
659
660   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
661 }
662
663 bool XGUI_Workshop::event(QEvent * theEvent)
664 {
665   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
666   if (aPostponedEv) {
667     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
668     processEvent(aEventPtr);
669     return true;
670   }
671   return false;
672 }
673
674 /*
675  *
676  */
677 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
678 {
679   if (!theMessage) {
680 #ifdef _DEBUG
681     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
682 #endif
683     return;
684   }
685   // Remember features icons
686   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
687
688   //Find or create Workbench
689   QString aWchName = QString::fromStdString(theMessage->workbenchId());
690   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
691   bool isUsePropPanel = theMessage->isUseInput();
692   QString aFeatureId = QString::fromStdString(theMessage->id());
693   if (isSalomeMode()) {
694     QAction* aAction = salomeConnector()->addFeature(aWchName, aFeatureId,
695                                                      QString::fromStdString(theMessage->text()),
696                                                      QString::fromStdString(theMessage->tooltip()),
697                                                      QIcon(theMessage->icon().c_str()),
698                                                      QKeySequence(),
699                                                      isUsePropPanel);
700     salomeConnector()->setNestedActions(aFeatureId, aNestedFeatures.split(" ", QString::SkipEmptyParts));
701     salomeConnector()->setDocumentKind(aFeatureId, QString::fromStdString(theMessage->documentKind()));
702
703     myActionsMgr->addCommand(aAction);
704     myModule->actionCreated(aAction);
705   } else {
706
707     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
708     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
709     if (!aPage) {
710       aPage = addWorkbench(aWchName);
711     }
712     //Find or create Group
713     QString aGroupName = QString::fromStdString(theMessage->groupId());
714     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
715     if (!aGroup) {
716       aGroup = aPage->addGroup(aGroupName);
717     }
718     QString aDocKind = QString::fromStdString(theMessage->documentKind());
719     // Check if hotkey sequence is already defined:
720     QKeySequence aHotKey = myActionsMgr->registerShortcut(
721         QString::fromStdString(theMessage->keysequence()));
722     // Create feature...
723     AppElements_Command* aCommand = aGroup->addFeature(aFeatureId,
724                                                 QString::fromStdString(theMessage->text()),
725                                                 QString::fromStdString(theMessage->tooltip()),
726                                                 QIcon(theMessage->icon().c_str()),
727                                                 aDocKind,
728                                                 aHotKey,
729                                                 isUsePropPanel);
730     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
731     myActionsMgr->addCommand(aCommand);
732     myModule->actionCreated(aCommand);
733   }
734 }
735
736 /*
737  * Makes a signal/slot connections between Property Panel
738  * and given operation. The given operation becomes a
739  * current operation and previous operation if exists
740  */
741 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
742 {
743   QAction* aCommand = 0;
744   if (isSalomeMode()) {
745     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
746   } else {
747     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
748     FeaturePtr aFeature = theOperation->feature();
749     if(aFeature)
750       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
751   }
752   //Abort operation on uncheck the command
753   if (aCommand) {
754     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
755   }
756 }
757
758 /*
759  * Saves document with given name.
760  */
761 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
762 {
763   QApplication::restoreOverrideCursor();
764   SessionPtr aMgr = ModelAPI_Session::get();
765   aMgr->save(theName.toLatin1().constData(), theFileNames);
766   QApplication::restoreOverrideCursor();
767 }
768
769 bool XGUI_Workshop::isActiveOperationAborted()
770 {
771   return myOperationMgr->abortAllOperations();
772 }
773
774 //******************************************************
775 void XGUI_Workshop::onExit()
776 {
777   SessionPtr aMgr = ModelAPI_Session::get();
778   if (aMgr->isModified()) {
779     int anAnswer = QMessageBox::question(
780         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
781         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
782     if (anAnswer == QMessageBox::Save) {
783       bool saved = onSave();
784       if (!saved) {
785         return;
786       }
787     } else if (anAnswer == QMessageBox::Cancel) {
788       return;
789     }
790   }
791   qApp->exit();
792 }
793
794 //******************************************************
795 void XGUI_Workshop::onNew()
796 {
797   QApplication::setOverrideCursor(Qt::WaitCursor);
798   if (objectBrowser() == 0) {
799     createDockWidgets();
800     mySelector->connectViewers();
801   }
802   myViewerProxy->connectToViewer();
803   showObjectBrowser();
804   if (!isSalomeMode()) {
805     myMainWindow->showPythonConsole();
806     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
807     aWnd->showMaximized();
808     updateCommandStatus();
809   }
810   myContextMenuMgr->connectViewer();
811   QApplication::restoreOverrideCursor();
812 }
813
814 //******************************************************
815 void XGUI_Workshop::onOpen()
816 {
817   if(!isActiveOperationAborted())
818     return;
819   //save current file before close if modified
820   SessionPtr aSession = ModelAPI_Session::get();
821   if (aSession->isModified()) {
822     //TODO(sbh): re-launch the app?
823     int anAnswer = QMessageBox::question(
824         myMainWindow, tr("Save current file"),
825         tr("The document is modified, save before opening another?"),
826         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
827     if (anAnswer == QMessageBox::Save) {
828       onSave();
829     } else if (anAnswer == QMessageBox::Cancel) {
830       return;
831     }
832     aSession->closeAll();
833     myCurrentDir = "";
834   }
835
836   //show file dialog, check if readable and open
837   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
838   if (myCurrentDir.isEmpty())
839     return;
840   QFileInfo aFileInfo(myCurrentDir);
841   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
842     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
843     myCurrentDir = "";
844     return;
845   }
846   QApplication::setOverrideCursor(Qt::WaitCursor);
847   aSession->load(myCurrentDir.toLatin1().constData());
848   myObjectBrowser->rebuildDataTree();
849   displayAllResults();
850   updateCommandStatus();
851   QApplication::restoreOverrideCursor();
852 }
853
854 //******************************************************
855 bool XGUI_Workshop::onSave()
856 {
857   if(!isActiveOperationAborted())
858     return false;
859   if (myCurrentDir.isEmpty()) {
860     return onSaveAs();
861   }
862   std::list<std::string> aFiles;
863   saveDocument(myCurrentDir, aFiles);
864   updateCommandStatus();
865   if (!isSalomeMode())
866     myMainWindow->setModifiedState(false);
867   return true;
868 }
869
870 //******************************************************
871 bool XGUI_Workshop::onSaveAs()
872 {
873   if(!isActiveOperationAborted())
874     return false;
875   QFileDialog dialog(mainWindow());
876   dialog.setWindowTitle(tr("Select directory to save files..."));
877   dialog.setFileMode(QFileDialog::Directory);
878   dialog.setFilter(tr("Folders (*)"));
879   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
880   dialog.setViewMode(QFileDialog::Detail);
881
882   if (!dialog.exec()) {
883     return false;
884   }
885   QString aTempDir = dialog.selectedFiles().first();
886   QDir aDir(aTempDir);
887   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
888     int answer = QMessageBox::question(
889         myMainWindow,
890         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
891         tr("Save"),
892         tr("The folder already contains some files, save anyway?"),
893         QMessageBox::Save | QMessageBox::Cancel);
894     if (answer == QMessageBox::Cancel) {
895       return false;
896     }
897   }
898   myCurrentDir = aTempDir;
899   if (!isSalomeMode()) {
900     myMainWindow->setCurrentDir(myCurrentDir, false);
901     myMainWindow->setModifiedState(false);
902   }
903   return onSave();
904 }
905
906 //******************************************************
907 void XGUI_Workshop::onUndo()
908 {
909   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
910   SessionPtr aMgr = ModelAPI_Session::get();
911   if (aMgr->isOperation())
912     operationMgr()->onAbortOperation();
913   aMgr->undo();
914   updateCommandStatus();
915 }
916
917 //******************************************************
918 void XGUI_Workshop::onRedo()
919 {
920   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
921   SessionPtr aMgr = ModelAPI_Session::get();
922   if (aMgr->isOperation())
923     operationMgr()->onAbortOperation();
924   aMgr->redo();
925   updateCommandStatus();
926 }
927
928 //******************************************************
929 void XGUI_Workshop::onRebuild()
930 {
931   SessionPtr aMgr = ModelAPI_Session::get();
932   bool aWasOperation = aMgr->isOperation(); // keep this value
933   if (!aWasOperation) {
934     aMgr->startOperation();
935   }
936   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
937   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
938     new Events_Message(aRebuildEvent, this)));
939   if (!aWasOperation) {
940     aMgr->finishOperation();
941   }
942 }
943
944 //******************************************************
945 void XGUI_Workshop::onPreferences()
946 {
947   ModuleBase_Prefs aModif;
948   ModuleBase_Preferences::editPreferences(aModif);
949   if (aModif.size() > 0) {
950     QString aSection;
951     foreach (ModuleBase_Pref aPref, aModif)
952     {
953       aSection = aPref.first;
954       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
955         if (!isSalomeMode())
956           myMainWindow->viewer()->updateFromResources();
957       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
958         if (!isSalomeMode())
959           myMainWindow->menuObject()->updateFromResources();
960       }
961     }
962   }
963 }
964
965 //******************************************************
966 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
967 {
968   QString libName = QString::fromStdString(library(theModule.toStdString()));
969   if (libName.isEmpty()) {
970     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
971     return 0;
972   }
973
974   QString err;
975   CREATE_FUNC crtInst = 0;
976
977 #ifdef WIN32
978   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
979   if (!modLib) {
980     LPVOID lpMsgBuf;
981     ::FormatMessage(
982         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
983         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
984     QString aMsg((char*) &lpMsgBuf);
985     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
986     ::LocalFree(lpMsgBuf);
987   } else {
988     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
989     if (!crtInst) {
990       LPVOID lpMsgBuf;
991       ::FormatMessage(
992           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
993               | FORMAT_MESSAGE_IGNORE_INSERTS,
994           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
995       QString aMsg((char*) &lpMsgBuf);
996       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
997       ::LocalFree(lpMsgBuf);
998     }
999   }
1000 #else
1001   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1002   if ( !modLib ) {
1003     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1004   } else {
1005     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1006     if ( !crtInst ) {
1007       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1008     }
1009   }
1010 #endif
1011
1012   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1013
1014   if (!err.isEmpty()) {
1015     if (mainWindow()) {
1016       Events_Error::send(err.toStdString());
1017     } else {
1018       qWarning(qPrintable(err));
1019     }
1020   }
1021   return aModule;
1022 }
1023
1024 //******************************************************
1025 bool XGUI_Workshop::activateModule()
1026 {
1027   Config_ModuleReader aModuleReader;
1028   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1029   myModule = loadModule(moduleName);
1030   if (!myModule)
1031     return false;
1032   myModule->createFeatures();
1033   myActionsMgr->update();
1034   return true;
1035 }
1036
1037 //******************************************************
1038 void XGUI_Workshop::updateCommandStatus()
1039 {
1040   QList<QAction*> aCommands;
1041   if (isSalomeMode()) {  // update commands in SALOME mode
1042     aCommands = salomeConnector()->commandList();
1043   } else {
1044     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1045     foreach (AppElements_Command* aCmd, aMenuBar->features())
1046       aCommands.append(aCmd);
1047   }
1048   SessionPtr aMgr = ModelAPI_Session::get();
1049   if (aMgr->hasModuleDocument()) {
1050     QAction *aUndoCmd, *aRedoCmd;
1051     foreach(QAction* aCmd, aCommands) {
1052       QString aId = aCmd->data().toString();
1053       if (aId == "UNDO_CMD")
1054         aUndoCmd = aCmd;
1055       else if (aId == "REDO_CMD")
1056         aRedoCmd = aCmd;
1057       else
1058         // Enable all commands
1059         aCmd->setEnabled(true);
1060     }
1061     aUndoCmd->setEnabled(aMgr->canUndo() && !aMgr->isOperation());
1062     aRedoCmd->setEnabled(aMgr->canRedo() && !aMgr->isOperation());
1063   } else {
1064     foreach(QAction* aCmd, aCommands) {
1065       QString aId = aCmd->data().toString();
1066       if (aId == "NEW_CMD")
1067         aCmd->setEnabled(true);
1068       else if (aId == "EXIT_CMD")
1069         aCmd->setEnabled(true);
1070       else
1071         aCmd->setEnabled(false);
1072     }
1073   }
1074   myActionsMgr->update();
1075 }
1076
1077 //******************************************************
1078 QList<QAction*> XGUI_Workshop::getModuleCommands() const
1079 {
1080   QList<QAction*> aCommands;
1081   if (isSalomeMode()) {  // update commands in SALOME mode
1082     aCommands = salomeConnector()->commandList();
1083   } else {
1084     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1085     foreach(AppElements_Command* aCmd, aMenuBar->features())
1086     {
1087       aCommands.append(aCmd);
1088     }
1089   }
1090   return aCommands;
1091 }
1092
1093 //******************************************************
1094 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1095 {
1096   QDockWidget* aObjDock = new QDockWidget(theParent);
1097   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1098   aObjDock->setWindowTitle(tr("Object browser"));
1099   aObjDock->setStyleSheet(
1100       "::title { position: relative; padding-left: 5px; text-align: left center }");
1101   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1102   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1103           SLOT(changeCurrentDocument(ObjectPtr)));
1104   aObjDock->setWidget(myObjectBrowser);
1105
1106   myContextMenuMgr->connectObjectBrowser();
1107   return aObjDock;
1108 }
1109
1110 //******************************************************
1111 /*
1112  * Creates dock widgets, places them in corresponding area
1113  * and tabifies if necessary.
1114  */
1115 void XGUI_Workshop::createDockWidgets()
1116 {
1117   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1118   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1119   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1120   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1121   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1122
1123   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1124
1125   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1126   hidePropertyPanel();  //<! Invisible by default
1127   hideObjectBrowser();
1128   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1129   myPropertyPanel->installEventFilter(myOperationMgr);
1130
1131   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_OK);
1132   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
1133   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_CANCEL);
1134   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
1135   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
1136           SLOT(onKeyReleased(QKeyEvent*)));
1137   connect(myOperationMgr, SIGNAL(operationValidated(bool)), myPropertyPanel,
1138           SLOT(setAcceptEnabled(bool)));
1139
1140 }
1141
1142 //******************************************************
1143 void XGUI_Workshop::showPropertyPanel()
1144 {
1145   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1146   //<! Restore ability to close panel from the window's menu
1147   aViewAct->setEnabled(true);
1148   myPropertyPanel->show();
1149   myPropertyPanel->raise();
1150 }
1151
1152 //******************************************************
1153 void XGUI_Workshop::hidePropertyPanel()
1154 {
1155   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1156   //<! Do not allow to show empty property panel
1157   aViewAct->setEnabled(false);
1158   myPropertyPanel->hide();
1159 }
1160
1161 //******************************************************
1162 void XGUI_Workshop::showObjectBrowser()
1163 {
1164   myObjectBrowser->parentWidget()->show();
1165 }
1166
1167 //******************************************************
1168 void XGUI_Workshop::hideObjectBrowser()
1169 {
1170   myObjectBrowser->parentWidget()->hide();
1171 }
1172
1173 //******************************************************
1174 void XGUI_Workshop::onFeatureTriggered()
1175 {
1176   QAction* aCmd = dynamic_cast<QAction*>(sender());
1177   if (aCmd) {
1178     QString aId = salomeConnector()->commandId(aCmd);
1179     if (!aId.isNull())
1180       myModule->launchOperation(aId);
1181   }
1182 }
1183
1184 //******************************************************
1185 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
1186 {
1187   SessionPtr aMgr = ModelAPI_Session::get();
1188   if (theObj) {
1189     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
1190     if (aPart) {
1191       DocumentPtr aPartDoc = aPart->partDoc();
1192       if (aPartDoc) {
1193         aMgr->setActiveDocument(aPartDoc);
1194         return;
1195       }
1196     }
1197   }
1198   aMgr->setActiveDocument(aMgr->moduleDocument());
1199 }
1200
1201 //******************************************************
1202 void XGUI_Workshop::salomeViewerSelectionChanged()
1203 {
1204   emit salomeViewerSelection();
1205 }
1206
1207 //**************************************************************
1208 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1209 {
1210   return mySalomeConnector->viewer();
1211 }
1212
1213 //**************************************************************
1214 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1215 {
1216   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1217   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
1218     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
1219     activatePart(aPart);
1220   } else if (theId == "DEACTIVATE_PART_CMD")
1221     activatePart(ResultPartPtr());
1222   else if (theId == "DELETE_CMD")
1223     deleteObjects(aObjects);
1224   else if (theId == "SHOW_CMD")
1225     showObjects(aObjects, true);
1226   else if (theId == "HIDE_CMD")
1227     showObjects(aObjects, false);
1228   else if (theId == "SHOW_ONLY_CMD")
1229     showOnlyObjects(aObjects);
1230   else if (theId == "SHADING_CMD")
1231     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1232   else if (theId == "WIREFRAME_CMD")
1233     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1234   else if (theId == "HIDEALL_CMD")
1235     myDisplayer->eraseAll();
1236   else if (theId == "EDIT_CMD") {
1237     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
1238     if (aFeature)
1239       myModule->editFeature(aFeature);
1240   }
1241 }
1242
1243 //**************************************************************
1244 void XGUI_Workshop::onWidgetValuesChanged()
1245 {
1246   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1247   FeaturePtr aFeature = anOperation->feature();
1248
1249   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
1250   //if (aCustom)
1251   //  aCustom->storeValue(aFeature);
1252
1253   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
1254   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
1255   for (; anIt != aLast; anIt++) {
1256     ModuleBase_ModelWidget* aCustom = *anIt;
1257     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/aCustom == aSenderWidget)) {
1258       //aCustom->storeValue(aFeature);
1259       aCustom->storeValue();
1260     }
1261   }
1262 }
1263
1264 //**************************************************************
1265 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1266 {
1267   if (!myPartActivating) {
1268     myPartActivating = true;
1269     if (theFeature)
1270       theFeature->activate();
1271     changeCurrentDocument(theFeature);
1272     myObjectBrowser->activatePart(theFeature);
1273     myPartActivating = false;
1274   }
1275 }
1276
1277 //**************************************************************
1278 void XGUI_Workshop::activateLastPart()
1279 {
1280   SessionPtr aMgr = ModelAPI_Session::get();
1281   DocumentPtr aDoc = aMgr->moduleDocument();
1282   std::string aGrpName = ModelAPI_ResultPart::group();
1283   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1284   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1285   if (aPart) {
1286     activatePart(aPart);
1287   }
1288 }
1289
1290 //**************************************************************
1291 void XGUI_Workshop::deleteObjects(const QObjectPtrList& theList)
1292 {
1293   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1294   QMessageBox::StandardButton aRes = QMessageBox::warning(
1295       aDesktop, tr("Delete features"), tr("Seleted features will be deleted. Continue?"),
1296       QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1297   // ToDo: definbe deleting method
1298   if (aRes == QMessageBox::Yes) {
1299     SessionPtr aMgr = ModelAPI_Session::get();
1300     aMgr->startOperation();
1301     foreach (ObjectPtr aObj, theList)
1302     {
1303       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1304       if (aPart) {
1305         DocumentPtr aDoc = aPart->document();
1306         if (aDoc == aMgr->activeDocument()) {
1307           aDoc->close();
1308         }
1309         //aMgr->moduleDocument()->removeFeature(aPart->owner());
1310       } else {
1311         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1312         if (aFeature)
1313           aObj->document()->removeFeature(aFeature);
1314       }
1315     }
1316     myDisplayer->updateViewer();
1317     aMgr->finishOperation();
1318   }
1319 }
1320
1321 //**************************************************************
1322 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1323 {
1324   foreach (ObjectPtr aObj, theList)
1325   {
1326     if (isVisible) {
1327       myDisplayer->display(aObj, false);
1328     } else {
1329       myDisplayer->erase(aObj, false);
1330     }
1331   }
1332   myDisplayer->updateViewer();
1333 }
1334
1335 //**************************************************************
1336 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1337 {
1338   myDisplayer->showOnly(theList);
1339 }
1340
1341
1342 //**************************************************************
1343 void XGUI_Workshop::updateCommandsOnViewSelection()
1344 {
1345   XGUI_Selection* aSelection = mySelector->selection();
1346   if (aSelection->getSelected().size() == 0)
1347     return;
1348
1349   // Restrict validators to manage only nested (child) features
1350   // of the current feature i.e. if current feature is Sketch -
1351   // Sketch Features & Constraints can be validated.
1352   QStringList aNestedIds;
1353   if(myOperationMgr->hasOperation()) {
1354     FeaturePtr aFeature = myOperationMgr->currentOperation()->feature();
1355     if(aFeature) {
1356       aNestedIds << myActionsMgr->nestedCommands(QString::fromStdString(aFeature->getKind()));
1357     }
1358   }
1359   SessionPtr aMgr = ModelAPI_Session::get();
1360   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1361   QList<QAction*> aActions = getModuleCommands();
1362   foreach(QAction* aAction, aActions) {
1363     QString aId = aAction->data().toString();
1364     if(!aNestedIds.contains(aId))
1365       continue;
1366     std::list<ModelAPI_Validator*> aValidators;
1367     std::list<std::list<std::string> > anArguments;
1368     aFactory->validators(aId.toStdString(), aValidators, anArguments);
1369     std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
1370     for (; aValidator != aValidators.end(); aValidator++) {
1371       if (*aValidator) {
1372         const ModuleBase_SelectionValidator* aSelValidator =
1373             dynamic_cast<const ModuleBase_SelectionValidator*>(*aValidator);
1374         if (aSelValidator) {
1375           aAction->setEnabled(aSelValidator->isValid(aSelection));
1376         }
1377       }
1378     }
1379   }
1380 }
1381
1382 //**************************************************************
1383 void XGUI_Workshop::registerValidators() const
1384 {
1385   SessionPtr aMgr = ModelAPI_Session::get();
1386   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1387 }
1388
1389 //**************************************************************
1390 void XGUI_Workshop::displayAllResults()
1391 {
1392   SessionPtr aMgr = ModelAPI_Session::get();
1393   DocumentPtr aRootDoc = aMgr->moduleDocument();
1394   displayDocumentResults(aRootDoc);
1395   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1396     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1397     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1398     displayDocumentResults(aPart->partDoc());
1399   }
1400   myDisplayer->updateViewer();
1401 }
1402
1403 //**************************************************************
1404 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1405 {
1406   if (!theDoc)
1407     return;
1408   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1409   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1410 }
1411
1412 //**************************************************************
1413 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1414 {
1415   for (int i = 0; i < theDoc->size(theGroup); i++)
1416     myDisplayer->display(theDoc->object(theGroup, i), false);
1417 }
1418
1419 //**************************************************************
1420 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1421 {
1422   foreach(ObjectPtr aObj, theList) {
1423     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1424   }
1425   if (theList.size() > 0)
1426     myDisplayer->updateViewer();
1427 }
1428
1429 //**************************************************************
1430 void XGUI_Workshop::closeDocument()
1431 {
1432   myDisplayer->closeLocalContexts();
1433   myDisplayer->eraseAll();
1434   objectBrowser()->clearContent();
1435
1436   SessionPtr aMgr = ModelAPI_Session::get();
1437   aMgr->closeAll();
1438   objectBrowser()->clearContent();
1439 }