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