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