Salome HOME
Issue #394 Undo-ing a Sketch element
[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     bool isStoreValue = !theOperation->isEditOperation() &&
655                         aWidget->isValueDefault() && !aWidget->isComputedDefault();
656     aWidget->setFeature(theOperation->feature(), isStoreValue);
657     aWidget->enableFocusProcessing();
658   }
659   
660   myPropertyPanel->setModelWidgets(aWidgets);
661   theOperation->setPropertyPanel(myPropertyPanel);
662
663   myModule->propertyPanelDefined(theOperation);
664
665   myPropertyPanel->setWindowTitle(theOperation->getDescription()->description());
666 }
667
668 bool XGUI_Workshop::event(QEvent * theEvent)
669 {
670   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
671   if (aPostponedEv) {
672     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
673     processEvent(aEventPtr);
674     return true;
675   }
676   return false;
677 }
678
679 /*
680  *
681  */
682 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
683 {
684   if (!theMessage) {
685 #ifdef _DEBUG
686     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
687 #endif
688     return;
689   }
690   ActionInfo aFeatureInfo;
691   aFeatureInfo.initFrom(theMessage);
692   // Remember features icons
693   myIcons[QString::fromStdString(theMessage->id())] = aFeatureInfo.iconFile;
694
695   QString aWchName = QString::fromStdString(theMessage->workbenchId());
696   QStringList aNestedFeatures =
697       QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
698   QString aDocKind = QString::fromStdString(theMessage->documentKind());
699   if (isSalomeMode()) {
700     QAction* aAction = salomeConnector()->addFeature(aWchName, aFeatureInfo);
701     salomeConnector()->setNestedActions(aFeatureInfo.id, aNestedFeatures);
702     salomeConnector()->setDocumentKind(aFeatureInfo.id, aDocKind);
703
704     myActionsMgr->addCommand(aAction);
705     myModule->actionCreated(aAction);
706   } else {
707     //Find or create Workbench
708     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
709     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
710     if (!aPage) {
711       aPage = addWorkbench(aWchName);
712     }
713     //Find or create Group
714     QString aGroupName = QString::fromStdString(theMessage->groupId());
715     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
716     if (!aGroup) {
717       aGroup = aPage->addGroup(aGroupName);
718     }
719     // Check if hotkey sequence is already defined:
720     QKeySequence aHotKey = myActionsMgr->registerShortcut(aFeatureInfo.shortcut);
721     if(aHotKey != aFeatureInfo.shortcut) {
722       aFeatureInfo.shortcut = aHotKey;
723     }
724     // Create feature...
725     AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo, aDocKind);
726     aCommand->setNestedCommands(aNestedFeatures);
727     myActionsMgr->addCommand(aCommand);
728     myModule->actionCreated(aCommand);
729   }
730 }
731
732 /*
733  * Makes a signal/slot connections between Property Panel
734  * and given operation. The given operation becomes a
735  * current operation and previous operation if exists
736  */
737 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
738 {
739   QAction* aCommand = 0;
740   if (isSalomeMode()) {
741     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
742   } else {
743     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
744     FeaturePtr aFeature = theOperation->feature();
745     if(aFeature)
746       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
747   }
748   //Abort operation on uncheck the command
749   if (aCommand) {
750     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
751   }
752 }
753
754 /*
755  * Saves document with given name.
756  */
757 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
758 {
759   QApplication::restoreOverrideCursor();
760   SessionPtr aMgr = ModelAPI_Session::get();
761   aMgr->save(theName.toLatin1().constData(), theFileNames);
762   QApplication::restoreOverrideCursor();
763 }
764
765 bool XGUI_Workshop::isActiveOperationAborted()
766 {
767   return myOperationMgr->abortAllOperations();
768 }
769
770 //******************************************************
771 void XGUI_Workshop::onExit()
772 {
773   SessionPtr aMgr = ModelAPI_Session::get();
774   if (aMgr->isModified()) {
775     int anAnswer = QMessageBox::question(
776         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
777         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
778     if (anAnswer == QMessageBox::Save) {
779       bool saved = onSave();
780       if (!saved) {
781         return;
782       }
783     } else if (anAnswer == QMessageBox::Cancel) {
784       return;
785     }
786   }
787   qApp->exit();
788 }
789
790 //******************************************************
791 void XGUI_Workshop::onNew()
792 {
793   QApplication::setOverrideCursor(Qt::WaitCursor);
794   if (objectBrowser() == 0) {
795     createDockWidgets();
796     mySelector->connectViewers();
797   }
798   myViewerProxy->connectToViewer();
799   showObjectBrowser();
800   if (!isSalomeMode()) {
801     myMainWindow->showPythonConsole();
802     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
803     aWnd->showMaximized();
804     updateCommandStatus();
805   }
806   myContextMenuMgr->connectViewer();
807   QApplication::restoreOverrideCursor();
808 }
809
810 //******************************************************
811 void XGUI_Workshop::onOpen()
812 {
813   if(!isActiveOperationAborted())
814     return;
815   //save current file before close if modified
816   SessionPtr aSession = ModelAPI_Session::get();
817   if (aSession->isModified()) {
818     //TODO(sbh): re-launch the app?
819     int anAnswer = QMessageBox::question(
820         myMainWindow, tr("Save current file"),
821         tr("The document is modified, save before opening another?"),
822         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
823     if (anAnswer == QMessageBox::Save) {
824       onSave();
825     } else if (anAnswer == QMessageBox::Cancel) {
826       return;
827     }
828     aSession->closeAll();
829     myCurrentDir = "";
830   }
831
832   //show file dialog, check if readable and open
833   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
834   if (myCurrentDir.isEmpty())
835     return;
836   QFileInfo aFileInfo(myCurrentDir);
837   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
838     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
839     myCurrentDir = "";
840     return;
841   }
842   QApplication::setOverrideCursor(Qt::WaitCursor);
843   aSession->load(myCurrentDir.toLatin1().constData());
844   myObjectBrowser->rebuildDataTree();
845   displayAllResults();
846   updateCommandStatus();
847   QApplication::restoreOverrideCursor();
848 }
849
850 //******************************************************
851 bool XGUI_Workshop::onSave()
852 {
853   if(!isActiveOperationAborted())
854     return false;
855   if (myCurrentDir.isEmpty()) {
856     return onSaveAs();
857   }
858   std::list<std::string> aFiles;
859   saveDocument(myCurrentDir, aFiles);
860   updateCommandStatus();
861   if (!isSalomeMode())
862     myMainWindow->setModifiedState(false);
863   return true;
864 }
865
866 //******************************************************
867 bool XGUI_Workshop::onSaveAs()
868 {
869   if(!isActiveOperationAborted())
870     return false;
871   QFileDialog dialog(mainWindow());
872   dialog.setWindowTitle(tr("Select directory to save files..."));
873   dialog.setFileMode(QFileDialog::Directory);
874   dialog.setFilter(tr("Folders (*)"));
875   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
876   dialog.setViewMode(QFileDialog::Detail);
877
878   if (!dialog.exec()) {
879     return false;
880   }
881   QString aTempDir = dialog.selectedFiles().first();
882   QDir aDir(aTempDir);
883   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
884     int answer = QMessageBox::question(
885         myMainWindow,
886         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
887         tr("Save"),
888         tr("The folder already contains some files, save anyway?"),
889         QMessageBox::Save | QMessageBox::Cancel);
890     if (answer == QMessageBox::Cancel) {
891       return false;
892     }
893   }
894   myCurrentDir = aTempDir;
895   if (!isSalomeMode()) {
896     myMainWindow->setCurrentDir(myCurrentDir, false);
897     myMainWindow->setModifiedState(false);
898   }
899   return onSave();
900 }
901
902 //******************************************************
903 void XGUI_Workshop::onUndo(int theTimes)
904 {
905   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
906   SessionPtr aMgr = ModelAPI_Session::get();
907   if (aMgr->isOperation())
908     operationMgr()->onAbortOperation();
909   for (int i = 0; i < theTimes; ++i) {
910     aMgr->undo();
911   }
912   updateCommandStatus();
913 }
914
915 //******************************************************
916 void XGUI_Workshop::onRedo(int theTimes)
917 {
918   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
919   SessionPtr aMgr = ModelAPI_Session::get();
920   if (aMgr->isOperation())
921     operationMgr()->onAbortOperation();
922   for (int i = 0; i < theTimes; ++i) {
923     aMgr->redo();
924   }
925   updateCommandStatus();
926 }
927
928 //******************************************************
929 void XGUI_Workshop::onRebuild()
930 {
931   SessionPtr aMgr = ModelAPI_Session::get();
932   bool aWasOperation = aMgr->isOperation(); // keep this value
933   if (!aWasOperation) {
934     aMgr->startOperation("Rebuild");
935   }
936   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
937   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
938     new Events_Message(aRebuildEvent, this)));
939   if (!aWasOperation) {
940     aMgr->finishOperation();
941   }
942 }
943
944 //******************************************************
945 void XGUI_Workshop::onPreferences()
946 {
947   ModuleBase_Prefs aModif;
948   ModuleBase_Preferences::editPreferences(aModif);
949   if (aModif.size() > 0) {
950     QString aSection;
951     foreach (ModuleBase_Pref aPref, aModif)
952     {
953       aSection = aPref.first;
954       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
955         if (!isSalomeMode())
956           myMainWindow->viewer()->updateFromResources();
957       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
958         if (!isSalomeMode())
959           myMainWindow->menuObject()->updateFromResources();
960       }
961     }
962   }
963 }
964
965 //******************************************************
966 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
967 {
968   QString libName = QString::fromStdString(library(theModule.toStdString()));
969   if (libName.isEmpty()) {
970     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
971     return 0;
972   }
973
974   QString err;
975   CREATE_FUNC crtInst = 0;
976
977 #ifdef WIN32
978   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
979   if (!modLib) {
980     LPVOID lpMsgBuf;
981     ::FormatMessage(
982         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
983         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
984     QString aMsg((char*) &lpMsgBuf);
985     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
986     ::LocalFree(lpMsgBuf);
987   } else {
988     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
989     if (!crtInst) {
990       LPVOID lpMsgBuf;
991       ::FormatMessage(
992           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
993               | FORMAT_MESSAGE_IGNORE_INSERTS,
994           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
995       QString aMsg((char*) &lpMsgBuf);
996       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
997       ::LocalFree(lpMsgBuf);
998     }
999   }
1000 #else
1001   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1002   if ( !modLib ) {
1003     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1004   } else {
1005     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1006     if ( !crtInst ) {
1007       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1008     }
1009   }
1010 #endif
1011
1012   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1013
1014   if (!err.isEmpty()) {
1015     if (mainWindow()) {
1016       Events_Error::send(err.toStdString());
1017     } else {
1018       qWarning(qPrintable(err));
1019     }
1020   }
1021   return aModule;
1022 }
1023
1024 //******************************************************
1025 bool XGUI_Workshop::activateModule()
1026 {
1027   Config_ModuleReader aModuleReader;
1028   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1029   myModule = loadModule(moduleName);
1030   if (!myModule)
1031     return false;
1032   myModule->createFeatures();
1033   myActionsMgr->update();
1034   return true;
1035 }
1036
1037 //******************************************************
1038 void XGUI_Workshop::updateCommandStatus()
1039 {
1040   QList<QAction*> aCommands;
1041   if (isSalomeMode()) {  // update commands in SALOME mode
1042     aCommands = salomeConnector()->commandList();
1043   } else {
1044     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1045     foreach (AppElements_Command* aCmd, aMenuBar->features())
1046       aCommands.append(aCmd);
1047   }
1048   SessionPtr aMgr = ModelAPI_Session::get();
1049   if (aMgr->hasModuleDocument()) {
1050     QAction *aUndoCmd, *aRedoCmd;
1051     foreach(QAction* aCmd, aCommands) {
1052       QString aId = aCmd->data().toString();
1053       if (aId == "UNDO_CMD")
1054         aUndoCmd = aCmd;
1055       else if (aId == "REDO_CMD")
1056         aRedoCmd = aCmd;
1057       else
1058         // Enable all commands
1059         aCmd->setEnabled(true);
1060     }
1061     aUndoCmd->setEnabled(aMgr->canUndo() && !aMgr->isOperation());
1062     aRedoCmd->setEnabled(aMgr->canRedo() && !aMgr->isOperation());
1063
1064     updateHistory();
1065
1066   } else {
1067     foreach(QAction* aCmd, aCommands) {
1068       QString aId = aCmd->data().toString();
1069       if (aId == "NEW_CMD")
1070         aCmd->setEnabled(true);
1071       else if (aId == "EXIT_CMD")
1072         aCmd->setEnabled(true);
1073       else
1074         aCmd->setEnabled(false);
1075     }
1076   }
1077   myActionsMgr->update();
1078   emit commandStatusUpdated();
1079 }
1080
1081 void XGUI_Workshop::updateHistory()
1082 {
1083   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1084   std::list<std::string>::iterator it = aUndoList.begin();
1085   QList<ActionInfo> aUndoRes;
1086   for ( ; it != aUndoList.end(); it++) {
1087     QString anId = QString::fromStdString(*it);
1088     QIcon aIcon;
1089     if (myIcons.contains(anId))
1090       aIcon = QIcon(myIcons[anId]);
1091     aUndoRes << ActionInfo(aIcon, anId);
1092   }
1093   emit updateUndoHistory(aUndoRes);
1094
1095   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1096   it = aRedoList.begin();
1097   QList<ActionInfo> aRedoRes;
1098   for ( ; it != aRedoList.end(); it++) {
1099     QString anId = QString::fromStdString(*it);
1100     QIcon aIcon;
1101     if (myIcons.contains(anId))
1102       aIcon = QIcon(myIcons[anId]);
1103     aRedoRes << ActionInfo(aIcon, anId);
1104   }
1105   emit updateRedoHistory(aUndoRes);
1106 }
1107
1108 //******************************************************
1109 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1110 {
1111   QDockWidget* aObjDock = new QDockWidget(theParent);
1112   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1113   aObjDock->setWindowTitle(tr("Object browser"));
1114   aObjDock->setStyleSheet(
1115       "::title { position: relative; padding-left: 5px; text-align: left center }");
1116   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1117   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1118           SLOT(changeCurrentDocument(ObjectPtr)));
1119   aObjDock->setWidget(myObjectBrowser);
1120
1121   myContextMenuMgr->connectObjectBrowser();
1122   return aObjDock;
1123 }
1124
1125 //******************************************************
1126 /*
1127  * Creates dock widgets, places them in corresponding area
1128  * and tabifies if necessary.
1129  */
1130 void XGUI_Workshop::createDockWidgets()
1131 {
1132   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1133   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1134   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1135   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1136   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1137
1138   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1139
1140   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1141   hidePropertyPanel();  ///<! Invisible by default
1142   hideObjectBrowser();
1143   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1144   myPropertyPanel->installEventFilter(myOperationMgr);
1145
1146   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_OK);
1147   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
1148   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(PROP_PANEL_CANCEL);
1149   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
1150   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
1151           SLOT(onKeyReleased(QKeyEvent*)));
1152   connect(myOperationMgr, SIGNAL(applyEnableChanged(bool)), myPropertyPanel,
1153           SLOT(setAcceptEnabled(bool)));
1154
1155 }
1156
1157 //******************************************************
1158 void XGUI_Workshop::showPropertyPanel()
1159 {
1160   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1161   ///<! Restore ability to close panel from the window's menu
1162   aViewAct->setEnabled(true);
1163   myPropertyPanel->show();
1164   myPropertyPanel->raise();
1165 }
1166
1167 //******************************************************
1168 void XGUI_Workshop::hidePropertyPanel()
1169 {
1170   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1171   ///<! Do not allow to show empty property panel
1172   aViewAct->setEnabled(false);
1173   myPropertyPanel->hide();
1174 }
1175
1176 //******************************************************
1177 void XGUI_Workshop::showObjectBrowser()
1178 {
1179   myObjectBrowser->parentWidget()->show();
1180 }
1181
1182 //******************************************************
1183 void XGUI_Workshop::hideObjectBrowser()
1184 {
1185   myObjectBrowser->parentWidget()->hide();
1186 }
1187
1188 //******************************************************
1189 void XGUI_Workshop::onFeatureTriggered()
1190 {
1191   QAction* aCmd = dynamic_cast<QAction*>(sender());
1192   if (aCmd) {
1193     QString aId = salomeConnector()->commandId(aCmd);
1194     if (!aId.isNull())
1195       myModule->launchOperation(aId);
1196   }
1197 }
1198
1199 //******************************************************
1200 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
1201 {
1202   SessionPtr aMgr = ModelAPI_Session::get();
1203   if (theObj) {
1204     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
1205     if (aPart) {
1206       DocumentPtr aPartDoc = aPart->partDoc();
1207       if (aPartDoc) {
1208         aMgr->setActiveDocument(aPartDoc);
1209         return;
1210       }
1211     }
1212   }
1213   aMgr->setActiveDocument(aMgr->moduleDocument());
1214 }
1215
1216 //******************************************************
1217 void XGUI_Workshop::salomeViewerSelectionChanged()
1218 {
1219   emit salomeViewerSelection();
1220 }
1221
1222 //**************************************************************
1223 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1224 {
1225   return mySalomeConnector->viewer();
1226 }
1227
1228 //**************************************************************
1229 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1230 {
1231   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1232   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
1233     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
1234     activatePart(aPart);
1235   } else if (theId == "DEACTIVATE_PART_CMD")
1236     activatePart(ResultPartPtr());
1237   else if (theId == "DELETE_CMD")
1238     deleteObjects(aObjects);
1239   else if (theId == "SHOW_CMD")
1240     showObjects(aObjects, true);
1241   else if (theId == "HIDE_CMD")
1242     showObjects(aObjects, false);
1243   else if (theId == "SHOW_ONLY_CMD")
1244     showOnlyObjects(aObjects);
1245   else if (theId == "SHADING_CMD")
1246     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1247   else if (theId == "WIREFRAME_CMD")
1248     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1249   else if (theId == "HIDEALL_CMD")
1250     myDisplayer->eraseAll();
1251   else if (theId == "EDIT_CMD") {
1252     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
1253     if (aFeature)
1254       myModule->editFeature(aFeature);
1255   }
1256 }
1257
1258 //**************************************************************
1259 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1260 {
1261   if (!myPartActivating) {
1262     myPartActivating = true;
1263     if (theFeature)
1264       theFeature->activate();
1265     changeCurrentDocument(theFeature);
1266     myObjectBrowser->activatePart(theFeature);
1267     myPartActivating = false;
1268   }
1269   updateCommandStatus();
1270 }
1271
1272 //**************************************************************
1273 //void XGUI_Workshop::activateLastPart()
1274 //{
1275 //  SessionPtr aMgr = ModelAPI_Session::get();
1276 //  DocumentPtr aDoc = aMgr->moduleDocument();
1277 //  std::string aGrpName = ModelAPI_ResultPart::group();
1278 //  ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1279 //  ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1280 //  if (aPart) {
1281 //    activatePart(aPart);
1282 //  }
1283 //}
1284
1285 //**************************************************************
1286 void XGUI_Workshop::deleteObjects(const QObjectPtrList& theList)
1287 {
1288   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1289
1290   std::set<FeaturePtr> aRefFeatures;
1291   foreach (ObjectPtr aObj, theList)
1292   {
1293     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1294     if (aPart) {
1295       // TODO: check for what there is this condition. It is placed here historicaly because
1296       // ther is this condition during remove features.
1297     } else {
1298       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1299       if (aFeature.get() != NULL) {
1300         aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1301       }
1302     }
1303   }
1304
1305   if (!aRefFeatures.empty()) {
1306     QStringList aRefNames;
1307     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1308                                          aLast = aRefFeatures.end();
1309     for (; anIt != aLast; anIt++) {
1310       FeaturePtr aFeature = (*anIt);
1311       std::string aFName = aFeature->data()->name().c_str();
1312       std::string aName = (*anIt)->name().c_str();
1313       aRefNames.append((*anIt)->name().c_str());
1314     }
1315     QString aNames = aRefNames.join(", ");
1316
1317     QMessageBox::StandardButton aRes = QMessageBox::warning(
1318         aDesktop, tr("Delete features"),
1319         QString(tr("Selected features are used in the following features: %1.\
1320 These features will be deleted also. Would you like to continue?")).arg(aNames),
1321         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1322     if (aRes != QMessageBox::Yes)
1323       return;
1324   }
1325
1326   SessionPtr aMgr = ModelAPI_Session::get();
1327   aMgr->startOperation("DeleteObjects");
1328   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1329                                        aLast = aRefFeatures.end();
1330   for (; anIt != aLast; anIt++) {
1331     FeaturePtr aRefFeature = (*anIt);
1332     DocumentPtr aDoc = aRefFeature->document();
1333     aDoc->removeFeature(aRefFeature);
1334    }
1335
1336
1337   foreach (ObjectPtr aObj, theList)
1338   {
1339     DocumentPtr aDoc = aObj->document();
1340     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1341     if (aPart) {
1342       if (aDoc == aMgr->activeDocument()) {
1343         aDoc->close();
1344       }
1345     } else {
1346       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1347       if (aFeature) {
1348         aDoc->removeFeature(aFeature);
1349       }
1350     }
1351   }
1352
1353   myDisplayer->updateViewer();
1354   aMgr->finishOperation();
1355 }
1356
1357 //**************************************************************
1358 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1359 {
1360   foreach (ObjectPtr aObj, theList)
1361   {
1362     if (isVisible) {
1363       displayObject(aObj);
1364     } else {
1365       myDisplayer->erase(aObj, false);
1366     }
1367   }
1368   myDisplayer->updateViewer();
1369 }
1370
1371 //**************************************************************
1372 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1373 {
1374   myDisplayer->showOnly(theList);
1375 }
1376
1377
1378 //**************************************************************
1379 void XGUI_Workshop::registerValidators() const
1380 {
1381   SessionPtr aMgr = ModelAPI_Session::get();
1382   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1383 }
1384
1385 //**************************************************************
1386 void XGUI_Workshop::displayAllResults()
1387 {
1388   SessionPtr aMgr = ModelAPI_Session::get();
1389   DocumentPtr aRootDoc = aMgr->moduleDocument();
1390   displayDocumentResults(aRootDoc);
1391   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1392     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1393     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1394     displayDocumentResults(aPart->partDoc());
1395   }
1396   myDisplayer->updateViewer();
1397 }
1398
1399 //**************************************************************
1400 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1401 {
1402   if (!theDoc)
1403     return;
1404   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1405   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1406 }
1407
1408 //**************************************************************
1409 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1410 {
1411   for (int i = 0; i < theDoc->size(theGroup); i++)
1412     displayObject(theDoc->object(theGroup, i));
1413 }
1414
1415 //**************************************************************
1416 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1417 {
1418   foreach(ObjectPtr aObj, theList) {
1419     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1420   }
1421   if (theList.size() > 0)
1422     myDisplayer->updateViewer();
1423 }
1424
1425 //**************************************************************
1426 void XGUI_Workshop::closeDocument()
1427 {
1428   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1429   while (anOperation) {
1430     anOperation->abort();
1431     anOperation = operationMgr()->currentOperation();
1432   }
1433   myDisplayer->closeLocalContexts();
1434   myDisplayer->eraseAll();
1435   objectBrowser()->clearContent();
1436
1437   SessionPtr aMgr = ModelAPI_Session::get();
1438   aMgr->closeAll();
1439   objectBrowser()->clearContent();
1440 }
1441
1442 //**************************************************************
1443 void XGUI_Workshop::displayObject(ObjectPtr theObj)
1444 {
1445   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1446   if (aBody.get() != NULL) {
1447     int aNb = myDisplayer->objectsCount();
1448     myDisplayer->display(theObj, false);
1449     if (aNb == 0)
1450       viewer()->fitAll();
1451   } else 
1452     myDisplayer->display(theObj, false);
1453 }
1454
1455 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1456 {
1457   XGUI_HistoryMenu* aMenu = NULL;
1458   if (isSalomeMode()) {
1459     QAction* anAction = qobject_cast<QAction*>(theObject);
1460     if (!anAction)
1461       return;
1462     aMenu = new XGUI_HistoryMenu(anAction);
1463   } else {
1464     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1465     aMenu = new XGUI_HistoryMenu(aButton);
1466   }
1467   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1468   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1469
1470 }