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