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