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