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