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