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