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