Salome HOME
Merge remote-tracking branch 'origin/Dev_0.6.1' into Dev_0.6.1
[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       if (!aOperation->activateByPreselection())
597         myPropertyPanel->activateNextWidget(NULL);
598     }
599     // Set final definitions if they are necessary
600     myModule->propertyPanelDefined(aOperation);
601
602     // Widget activation (from the previous method) may commit the current operation
603     // if pre-selection is enougth for it. So we shouldn't update prop panel's title
604     if(myOperationMgr->isCurrentOperation(aOperation)) {
605       myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
606     }
607   }
608   updateCommandStatus();
609 }
610
611 //******************************************************
612 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
613 {
614   //!< No need for property panel
615   updateCommandStatus();
616   hidePropertyPanel();
617   myPropertyPanel->cleanContent();
618
619   // Activate objects created by current operation
620   FeaturePtr aFeature = theOperation->feature();
621   myDisplayer->activate(aFeature);
622   const std::list<ResultPtr>& aResults = aFeature->results();
623   std::list<ResultPtr>::const_iterator aIt;
624   for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
625     myDisplayer->activate(*aIt);
626   }
627 }
628
629 bool XGUI_Workshop::event(QEvent * theEvent)
630 {
631   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
632   if (aPostponedEv) {
633     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
634     processEvent(aEventPtr);
635     return true;
636   }
637   return false;
638 }
639
640 /*
641  *
642  */
643 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
644 {
645   if (!theMessage) {
646 #ifdef _DEBUG
647     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
648 #endif
649     return;
650   }
651   // Remember features icons
652   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
653
654   //Find or create Workbench
655   QString aWchName = QString::fromStdString(theMessage->workbenchId());
656   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
657   bool isUsePropPanel = theMessage->isUseInput();
658   QString aFeatureId = QString::fromStdString(theMessage->id());
659   if (isSalomeMode()) {
660     QAction* aAction = salomeConnector()->addFeature(aWchName, aFeatureId,
661                                                      QString::fromStdString(theMessage->text()),
662                                                      QString::fromStdString(theMessage->tooltip()),
663                                                      QIcon(theMessage->icon().c_str()),
664                                                      QKeySequence(),
665                                                      isUsePropPanel);
666     salomeConnector()->setNestedActions(aFeatureId, aNestedFeatures.split(" ", QString::SkipEmptyParts));
667     salomeConnector()->setDocumentKind(aFeatureId, QString::fromStdString(theMessage->documentKind()));
668
669     myActionsMgr->addCommand(aAction);
670     myModule->actionCreated(aAction);
671   } else {
672
673     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
674     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
675     if (!aPage) {
676       aPage = addWorkbench(aWchName);
677     }
678     //Find or create Group
679     QString aGroupName = QString::fromStdString(theMessage->groupId());
680     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
681     if (!aGroup) {
682       aGroup = aPage->addGroup(aGroupName);
683     }
684     QString aDocKind = QString::fromStdString(theMessage->documentKind());
685     // Check if hotkey sequence is already defined:
686     QKeySequence aHotKey = myActionsMgr->registerShortcut(
687         QString::fromStdString(theMessage->keysequence()));
688     // Create feature...
689     AppElements_Command* aCommand = aGroup->addFeature(aFeatureId,
690                                                 QString::fromStdString(theMessage->text()),
691                                                 QString::fromStdString(theMessage->tooltip()),
692                                                 QIcon(theMessage->icon().c_str()),
693                                                 aDocKind,
694                                                 aHotKey,
695                                                 isUsePropPanel);
696     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
697     myActionsMgr->addCommand(aCommand);
698     myModule->actionCreated(aCommand);
699   }
700 }
701
702 /*
703  * Makes a signal/slot connections between Property Panel
704  * and given operation. The given operation becomes a
705  * current operation and previous operation if exists
706  */
707 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
708 {
709   QAction* aCommand = 0;
710   if (isSalomeMode()) {
711     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
712   } else {
713     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
714     FeaturePtr aFeature = theOperation->feature();
715     if(aFeature)
716       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
717   }
718   //Abort operation on uncheck the command
719   if (aCommand) {
720     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
721   }
722 }
723
724 /*
725  * Saves document with given name.
726  */
727 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
728 {
729   QApplication::restoreOverrideCursor();
730   SessionPtr aMgr = ModelAPI_Session::get();
731   aMgr->save(theName.toLatin1().constData(), theFileNames);
732   QApplication::restoreOverrideCursor();
733 }
734
735 bool XGUI_Workshop::isActiveOperationAborted()
736 {
737   return myOperationMgr->abortAllOperations();
738 }
739
740 //******************************************************
741 void XGUI_Workshop::onExit()
742 {
743   SessionPtr aMgr = ModelAPI_Session::get();
744   if (aMgr->isModified()) {
745     int anAnswer = QMessageBox::question(
746         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
747         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
748     if (anAnswer == QMessageBox::Save) {
749       bool saved = onSave();
750       if (!saved) {
751         return;
752       }
753     } else if (anAnswer == QMessageBox::Cancel) {
754       return;
755     }
756   }
757   qApp->exit();
758 }
759
760 //******************************************************
761 void XGUI_Workshop::onNew()
762 {
763   QApplication::setOverrideCursor(Qt::WaitCursor);
764   if (objectBrowser() == 0) {
765     createDockWidgets();
766     mySelector->connectViewers();
767   }
768   myViewerProxy->connectToViewer();
769   showObjectBrowser();
770   if (!isSalomeMode()) {
771     myMainWindow->showPythonConsole();
772     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
773     aWnd->showMaximized();
774     updateCommandStatus();
775   }
776   myContextMenuMgr->connectViewer();
777   QApplication::restoreOverrideCursor();
778 }
779
780 //******************************************************
781 void XGUI_Workshop::onOpen()
782 {
783   if(!isActiveOperationAborted())
784     return;
785   //save current file before close if modified
786   SessionPtr aSession = ModelAPI_Session::get();
787   if (aSession->isModified()) {
788     //TODO(sbh): re-launch the app?
789     int anAnswer = QMessageBox::question(
790         myMainWindow, tr("Save current file"),
791         tr("The document is modified, save before opening another?"),
792         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
793     if (anAnswer == QMessageBox::Save) {
794       onSave();
795     } else if (anAnswer == QMessageBox::Cancel) {
796       return;
797     }
798     aSession->closeAll();
799     myCurrentDir = "";
800   }
801
802   //show file dialog, check if readable and open
803   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
804   if (myCurrentDir.isEmpty())
805     return;
806   QFileInfo aFileInfo(myCurrentDir);
807   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
808     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
809     myCurrentDir = "";
810     return;
811   }
812   QApplication::setOverrideCursor(Qt::WaitCursor);
813   aSession->load(myCurrentDir.toLatin1().constData());
814   myObjectBrowser->rebuildDataTree();
815   displayAllResults();
816   updateCommandStatus();
817   QApplication::restoreOverrideCursor();
818 }
819
820 //******************************************************
821 bool XGUI_Workshop::onSave()
822 {
823   if(!isActiveOperationAborted())
824     return false;
825   if (myCurrentDir.isEmpty()) {
826     return onSaveAs();
827   }
828   std::list<std::string> aFiles;
829   saveDocument(myCurrentDir, aFiles);
830   updateCommandStatus();
831   if (!isSalomeMode())
832     myMainWindow->setModifiedState(false);
833   return true;
834 }
835
836 //******************************************************
837 bool XGUI_Workshop::onSaveAs()
838 {
839   if(!isActiveOperationAborted())
840     return false;
841   QFileDialog dialog(mainWindow());
842   dialog.setWindowTitle(tr("Select directory to save files..."));
843   dialog.setFileMode(QFileDialog::Directory);
844   dialog.setFilter(tr("Folders (*)"));
845   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
846   dialog.setViewMode(QFileDialog::Detail);
847
848   if (!dialog.exec()) {
849     return false;
850   }
851   QString aTempDir = dialog.selectedFiles().first();
852   QDir aDir(aTempDir);
853   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
854     int answer = QMessageBox::question(
855         myMainWindow,
856         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
857         tr("Save"),
858         tr("The folder already contains some files, save anyway?"),
859         QMessageBox::Save | QMessageBox::Cancel);
860     if (answer == QMessageBox::Cancel) {
861       return false;
862     }
863   }
864   myCurrentDir = aTempDir;
865   if (!isSalomeMode()) {
866     myMainWindow->setCurrentDir(myCurrentDir, false);
867     myMainWindow->setModifiedState(false);
868   }
869   return onSave();
870 }
871
872 //******************************************************
873 void XGUI_Workshop::onUndo()
874 {
875   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
876   SessionPtr aMgr = ModelAPI_Session::get();
877   if (aMgr->isOperation())
878     operationMgr()->onAbortOperation();
879   aMgr->undo();
880   updateCommandStatus();
881 }
882
883 //******************************************************
884 void XGUI_Workshop::onRedo()
885 {
886   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
887   SessionPtr aMgr = ModelAPI_Session::get();
888   if (aMgr->isOperation())
889     operationMgr()->onAbortOperation();
890   aMgr->redo();
891   updateCommandStatus();
892 }
893
894 //******************************************************
895 void XGUI_Workshop::onRebuild()
896 {
897   SessionPtr aMgr = ModelAPI_Session::get();
898   bool aWasOperation = aMgr->isOperation(); // keep this value
899   if (!aWasOperation) {
900     aMgr->startOperation();
901   }
902   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
903   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
904     new Events_Message(aRebuildEvent, this)));
905   if (!aWasOperation) {
906     aMgr->finishOperation();
907   }
908 }
909
910 //******************************************************
911 void XGUI_Workshop::onPreferences()
912 {
913   ModuleBase_Prefs aModif;
914   ModuleBase_Preferences::editPreferences(aModif);
915   if (aModif.size() > 0) {
916     QString aSection;
917     foreach (ModuleBase_Pref aPref, aModif)
918     {
919       aSection = aPref.first;
920       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
921         if (!isSalomeMode())
922           myMainWindow->viewer()->updateFromResources();
923       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
924         if (!isSalomeMode())
925           myMainWindow->menuObject()->updateFromResources();
926       }
927     }
928   }
929 }
930
931 //******************************************************
932 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
933 {
934   QString libName = QString::fromStdString(library(theModule.toStdString()));
935   if (libName.isEmpty()) {
936     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
937     return 0;
938   }
939
940   QString err;
941   CREATE_FUNC crtInst = 0;
942
943 #ifdef WIN32
944   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
945   if (!modLib) {
946     LPVOID lpMsgBuf;
947     ::FormatMessage(
948         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
949         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
950     QString aMsg((char*) &lpMsgBuf);
951     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
952     ::LocalFree(lpMsgBuf);
953   } else {
954     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
955     if (!crtInst) {
956       LPVOID lpMsgBuf;
957       ::FormatMessage(
958           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
959               | FORMAT_MESSAGE_IGNORE_INSERTS,
960           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
961       QString aMsg((char*) &lpMsgBuf);
962       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
963       ::LocalFree(lpMsgBuf);
964     }
965   }
966 #else
967   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
968   if ( !modLib ) {
969     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
970   } else {
971     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
972     if ( !crtInst ) {
973       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
974     }
975   }
976 #endif
977
978   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
979
980   if (!err.isEmpty()) {
981     if (mainWindow()) {
982       Events_Error::send(err.toStdString());
983     } else {
984       qWarning(qPrintable(err));
985     }
986   }
987   return aModule;
988 }
989
990 //******************************************************
991 bool XGUI_Workshop::activateModule()
992 {
993   Config_ModuleReader aModuleReader;
994   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
995   myModule = loadModule(moduleName);
996   if (!myModule)
997     return false;
998   myModule->createFeatures();
999   myActionsMgr->update();
1000   return true;
1001 }
1002
1003 //******************************************************
1004 void XGUI_Workshop::updateCommandStatus()
1005 {
1006   QList<QAction*> aCommands;
1007   if (isSalomeMode()) {  // update commands in SALOME mode
1008     aCommands = salomeConnector()->commandList();
1009   } else {
1010     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1011     foreach (AppElements_Command* aCmd, aMenuBar->features())
1012       aCommands.append(aCmd);
1013   }
1014   SessionPtr aMgr = ModelAPI_Session::get();
1015   if (aMgr->hasModuleDocument()) {
1016     QAction *aUndoCmd, *aRedoCmd;
1017     foreach(QAction* aCmd, aCommands) {
1018       QString aId = aCmd->data().toString();
1019       if (aId == "UNDO_CMD")
1020         aUndoCmd = aCmd;
1021       else if (aId == "REDO_CMD")
1022         aRedoCmd = aCmd;
1023       else
1024         // Enable all commands
1025         aCmd->setEnabled(true);
1026     }
1027     aUndoCmd->setEnabled(aMgr->canUndo() && !aMgr->isOperation());
1028     aRedoCmd->setEnabled(aMgr->canRedo() && !aMgr->isOperation());
1029   } else {
1030     foreach(QAction* aCmd, aCommands) {
1031       QString aId = aCmd->data().toString();
1032       if (aId == "NEW_CMD")
1033         aCmd->setEnabled(true);
1034       else if (aId == "EXIT_CMD")
1035         aCmd->setEnabled(true);
1036       else
1037         aCmd->setEnabled(false);
1038     }
1039   }
1040   myActionsMgr->update();
1041 }
1042
1043 //******************************************************
1044 QList<QAction*> XGUI_Workshop::getModuleCommands() const
1045 {
1046   QList<QAction*> aCommands;
1047   if (isSalomeMode()) {  // update commands in SALOME mode
1048     aCommands = salomeConnector()->commandList();
1049   } else {
1050     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1051     foreach(AppElements_Command* aCmd, aMenuBar->features())
1052     {
1053       aCommands.append(aCmd);
1054     }
1055   }
1056   return aCommands;
1057 }
1058
1059 //******************************************************
1060 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1061 {
1062   QDockWidget* aObjDock = new QDockWidget(theParent);
1063   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1064   aObjDock->setWindowTitle(tr("Object browser"));
1065   aObjDock->setStyleSheet(
1066       "::title { position: relative; padding-left: 5px; text-align: left center }");
1067   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1068   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1069           SLOT(changeCurrentDocument(ObjectPtr)));
1070   aObjDock->setWidget(myObjectBrowser);
1071
1072   myContextMenuMgr->connectObjectBrowser();
1073   return aObjDock;
1074 }
1075
1076 //******************************************************
1077 /*
1078  * Creates dock widgets, places them in corresponding area
1079  * and tabifies if necessary.
1080  */
1081 void XGUI_Workshop::createDockWidgets()
1082 {
1083   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1084   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1085   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1086   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1087   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1088
1089   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1090
1091   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1092   hidePropertyPanel();  //<! Invisible by default
1093   hideObjectBrowser();
1094   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1095   myPropertyPanel->installEventFilter(myOperationMgr);
1096
1097   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_OK);
1098   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
1099   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_CANCEL);
1100   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
1101   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
1102           SLOT(onKeyReleased(QKeyEvent*)));
1103   connect(myOperationMgr, SIGNAL(operationValidated(bool)), myPropertyPanel,
1104           SLOT(setAcceptEnabled(bool)));
1105
1106 }
1107
1108 //******************************************************
1109 void XGUI_Workshop::showPropertyPanel()
1110 {
1111   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1112   //<! Restore ability to close panel from the window's menu
1113   aViewAct->setEnabled(true);
1114   myPropertyPanel->show();
1115   myPropertyPanel->raise();
1116 }
1117
1118 //******************************************************
1119 void XGUI_Workshop::hidePropertyPanel()
1120 {
1121   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1122   //<! Do not allow to show empty property panel
1123   aViewAct->setEnabled(false);
1124   myPropertyPanel->hide();
1125 }
1126
1127 //******************************************************
1128 void XGUI_Workshop::showObjectBrowser()
1129 {
1130   myObjectBrowser->parentWidget()->show();
1131 }
1132
1133 //******************************************************
1134 void XGUI_Workshop::hideObjectBrowser()
1135 {
1136   myObjectBrowser->parentWidget()->hide();
1137 }
1138
1139 //******************************************************
1140 void XGUI_Workshop::onFeatureTriggered()
1141 {
1142   QAction* aCmd = dynamic_cast<QAction*>(sender());
1143   if (aCmd) {
1144     QString aId = salomeConnector()->commandId(aCmd);
1145     if (!aId.isNull())
1146       myModule->launchOperation(aId);
1147   }
1148 }
1149
1150 //******************************************************
1151 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
1152 {
1153   SessionPtr aMgr = ModelAPI_Session::get();
1154   if (theObj) {
1155     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
1156     if (aPart) {
1157       DocumentPtr aPartDoc = aPart->partDoc();
1158       if (aPartDoc) {
1159         aMgr->setActiveDocument(aPartDoc);
1160         return;
1161       }
1162     }
1163   }
1164   aMgr->setActiveDocument(aMgr->moduleDocument());
1165 }
1166
1167 //******************************************************
1168 void XGUI_Workshop::salomeViewerSelectionChanged()
1169 {
1170   emit salomeViewerSelection();
1171 }
1172
1173 //**************************************************************
1174 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1175 {
1176   return mySalomeConnector->viewer();
1177 }
1178
1179 //**************************************************************
1180 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1181 {
1182   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1183   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
1184     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
1185     activatePart(aPart);
1186   } else if (theId == "DEACTIVATE_PART_CMD")
1187     activatePart(ResultPartPtr());
1188   else if (theId == "DELETE_CMD")
1189     deleteObjects(aObjects);
1190   else if (theId == "SHOW_CMD")
1191     showObjects(aObjects, true);
1192   else if (theId == "HIDE_CMD")
1193     showObjects(aObjects, false);
1194   else if (theId == "SHOW_ONLY_CMD")
1195     showOnlyObjects(aObjects);
1196   else if (theId == "SHADING_CMD")
1197     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1198   else if (theId == "WIREFRAME_CMD")
1199     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1200   else if (theId == "HIDEALL_CMD")
1201     myDisplayer->eraseAll();
1202   else if (theId == "EDIT_CMD") {
1203     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
1204     if (aFeature)
1205       myModule->editFeature(aFeature);
1206   }
1207 }
1208
1209 //**************************************************************
1210 void XGUI_Workshop::onWidgetValuesChanged()
1211 {
1212   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1213   FeaturePtr aFeature = anOperation->feature();
1214
1215   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
1216   //if (aCustom)
1217   //  aCustom->storeValue(aFeature);
1218
1219   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
1220   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
1221   for (; anIt != aLast; anIt++) {
1222     ModuleBase_ModelWidget* aCustom = *anIt;
1223     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/aCustom == aSenderWidget)) {
1224       //aCustom->storeValue(aFeature);
1225       aCustom->storeValue();
1226     }
1227   }
1228 }
1229
1230 //**************************************************************
1231 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1232 {
1233   if (!myPartActivating) {
1234     myPartActivating = true;
1235     if (theFeature)
1236       theFeature->activate();
1237     changeCurrentDocument(theFeature);
1238     myObjectBrowser->activatePart(theFeature);
1239     myPartActivating = false;
1240   }
1241 }
1242
1243 //**************************************************************
1244 void XGUI_Workshop::activateLastPart()
1245 {
1246   SessionPtr aMgr = ModelAPI_Session::get();
1247   DocumentPtr aDoc = aMgr->moduleDocument();
1248   std::string aGrpName = ModelAPI_ResultPart::group();
1249   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1250   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1251   if (aPart) {
1252     activatePart(aPart);
1253   }
1254 }
1255
1256 //**************************************************************
1257 void XGUI_Workshop::deleteObjects(const QObjectPtrList& theList)
1258 {
1259   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1260   QMessageBox::StandardButton aRes = QMessageBox::warning(
1261       aDesktop, tr("Delete features"), tr("Seleted features will be deleted. Continue?"),
1262       QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1263   // ToDo: definbe deleting method
1264   if (aRes == QMessageBox::Yes) {
1265     SessionPtr aMgr = ModelAPI_Session::get();
1266     aMgr->startOperation();
1267     foreach (ObjectPtr aObj, theList)
1268     {
1269       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1270       if (aPart) {
1271         DocumentPtr aDoc = aPart->document();
1272         if (aDoc == aMgr->activeDocument()) {
1273           aDoc->close();
1274         }
1275         //aMgr->moduleDocument()->removeFeature(aPart->owner());
1276       } else {
1277         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1278         if (aFeature)
1279           aObj->document()->removeFeature(aFeature);
1280       }
1281     }
1282     myDisplayer->updateViewer();
1283     aMgr->finishOperation();
1284   }
1285 }
1286
1287 //**************************************************************
1288 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1289 {
1290   foreach (ObjectPtr aObj, theList)
1291   {
1292     if (isVisible) {
1293       myDisplayer->display(aObj, false);
1294     } else {
1295       myDisplayer->erase(aObj, false);
1296     }
1297   }
1298   myDisplayer->updateViewer();
1299 }
1300
1301 //**************************************************************
1302 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1303 {
1304   myDisplayer->showOnly(theList);
1305 }
1306
1307
1308 //**************************************************************
1309 void XGUI_Workshop::updateCommandsOnViewSelection()
1310 {
1311   XGUI_Selection* aSelection = mySelector->selection();
1312   if (aSelection->getSelected().size() == 0)
1313     return;
1314
1315   // Restrict validators to manage only nested (child) features
1316   // of the current feature i.e. if current feature is Sketch -
1317   // Sketch Features & Constraints can be validated.
1318   QStringList aNestedIds;
1319   if(myOperationMgr->hasOperation()) {
1320     FeaturePtr aFeature = myOperationMgr->currentOperation()->feature();
1321     if(aFeature) {
1322       aNestedIds << myActionsMgr->nestedCommands(QString::fromStdString(aFeature->getKind()));
1323     }
1324   }
1325   SessionPtr aMgr = ModelAPI_Session::get();
1326   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1327   QList<QAction*> aActions = getModuleCommands();
1328   foreach(QAction* aAction, aActions) {
1329     QString aId = aAction->data().toString();
1330     if(!aNestedIds.contains(aId))
1331       continue;
1332     std::list<ModelAPI_Validator*> aValidators;
1333     std::list<std::list<std::string> > anArguments;
1334     aFactory->validators(aId.toStdString(), aValidators, anArguments);
1335     std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
1336     for (; aValidator != aValidators.end(); aValidator++) {
1337       if (*aValidator) {
1338         const ModuleBase_SelectionValidator* aSelValidator =
1339             dynamic_cast<const ModuleBase_SelectionValidator*>(*aValidator);
1340         if (aSelValidator) {
1341           aAction->setEnabled(aSelValidator->isValid(aSelection));
1342         }
1343       }
1344     }
1345   }
1346 }
1347
1348 //**************************************************************
1349 void XGUI_Workshop::registerValidators() const
1350 {
1351   SessionPtr aMgr = ModelAPI_Session::get();
1352   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1353 }
1354
1355 //**************************************************************
1356 void XGUI_Workshop::displayAllResults()
1357 {
1358   SessionPtr aMgr = ModelAPI_Session::get();
1359   DocumentPtr aRootDoc = aMgr->moduleDocument();
1360   displayDocumentResults(aRootDoc);
1361   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1362     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1363     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1364     displayDocumentResults(aPart->partDoc());
1365   }
1366   myDisplayer->updateViewer();
1367 }
1368
1369 //**************************************************************
1370 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1371 {
1372   if (!theDoc)
1373     return;
1374   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1375   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1376 }
1377
1378 //**************************************************************
1379 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1380 {
1381   for (int i = 0; i < theDoc->size(theGroup); i++)
1382     myDisplayer->display(theDoc->object(theGroup, i), false);
1383 }
1384
1385 //**************************************************************
1386 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1387 {
1388   foreach(ObjectPtr aObj, theList) {
1389     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1390   }
1391   if (theList.size() > 0)
1392     myDisplayer->updateViewer();
1393 }
1394
1395 //**************************************************************
1396 void XGUI_Workshop::closeDocument()
1397 {
1398   myDisplayer->closeLocalContexts();
1399   myDisplayer->eraseAll();
1400   objectBrowser()->clearContent();
1401
1402   SessionPtr aMgr = ModelAPI_Session::get();
1403   aMgr->closeAll();
1404   objectBrowser()->clearContent();
1405 }