Salome HOME
b50412cc798ec06e62fd5e15a12fd5c3bd87b9ab
[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 #include <AppElements_Button.h>
28
29 #include <ModuleBase_IModule.h>
30 #include <ModuleBase_Preferences.h>
31
32 #include <ModelAPI_Events.h>
33 #include <ModelAPI_Session.h>
34 #include <ModelAPI_Feature.h>
35 #include <ModelAPI_Data.h>
36 #include <ModelAPI_AttributeDocRef.h>
37 #include <ModelAPI_Object.h>
38 #include <ModelAPI_Validator.h>
39 #include <ModelAPI_ResultConstruction.h>
40 #include <ModelAPI_ResultBody.h>
41
42 //#include <PartSetPlugin_Part.h>
43
44 #include <Events_Loop.h>
45 #include <Events_Error.h>
46 #include <Events_LongOp.h>
47
48 #include <ModuleBase_Operation.h>
49 #include <ModuleBase_Operation.h>
50 #include <ModuleBase_OperationDescription.h>
51 #include <ModuleBase_SelectionValidator.h>
52 #include <ModuleBase_WidgetFactory.h>
53 #include <ModuleBase_Tools.h>
54 #include <ModuleBase_IViewer.h>
55 #include<ModuleBase_FilterFactory.h>
56 #include <ModuleBase_PageBase.h>
57
58 #include <Config_Common.h>
59 #include <Config_FeatureMessage.h>
60 #include <Config_PointerMessage.h>
61 #include <Config_ModuleReader.h>
62 #include <Config_PropManager.h>
63 #include <Config_SelectionFilterMessage.h>
64
65 #include <QApplication>
66 #include <QFileDialog>
67 #include <QMessageBox>
68 #include <QMdiSubWindow>
69 #include <QPushButton>
70 #include <QDockWidget>
71 #include <QLayout>
72 #include <QThread>
73 #include <QObject>
74 #include <QMenu>
75 #include <QToolButton>
76 #include <QAction>
77
78 #ifdef _DEBUG
79 #include <QDebug>
80 #include <iostream>
81 #endif
82
83 #ifdef WIN32
84 #include <windows.h>
85 #else
86 #include <dlfcn.h>
87 #endif
88
89 QMap<QString, QString> XGUI_Workshop::myIcons;
90
91
92 QIcon XGUI_Workshop::featureIcon(const FeaturePtr& theFeature)
93 {
94   QIcon anIcon;
95
96   std::string aKind = theFeature->getKind();
97   QString aId(aKind.c_str());
98   if (!myIcons.contains(aId))
99     return anIcon;
100
101   QString anIconString = myIcons[aId];
102
103   ModelAPI_ExecState aState = theFeature->data()->execState();
104   switch(aState) {
105     case ModelAPI_StateDone:
106     case ModelAPI_StateNothing: {
107       anIcon = QIcon(anIconString);
108     }
109     break;
110     case ModelAPI_StateMustBeUpdated: {
111       anIcon = ModuleBase_Tools::lighter(anIconString);
112     }
113     break;
114     case ModelAPI_StateExecFailed: {
115       anIcon = ModuleBase_Tools::composite(":pictures/exec_state_failed.png", anIconString);
116     }
117     break;
118     case ModelAPI_StateInvalidArgument: {
119       anIcon = ModuleBase_Tools::composite(":pictures/exec_state_invalid_parameters.png",
120                                            anIconString);
121     }
122     break;
123     default: break;  
124   }
125   return anIcon;  
126 }
127
128 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
129     : QObject(),
130       myCurrentDir(QString()),
131       myModule(NULL),
132       mySalomeConnector(theConnector),
133       myPropertyPanel(0),
134       myObjectBrowser(0),
135       myDisplayer(0),
136       myUpdatePrefs(false),
137       myPartActivating(false)
138 {
139   myMainWindow = mySalomeConnector ? 0 : new AppElements_MainWindow();
140
141   myDisplayer = new XGUI_Displayer(this);
142
143   mySelector = new XGUI_SelectionMgr(this);
144   //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
145
146   myOperationMgr = new XGUI_OperationMgr(this);
147   myActionsMgr = new XGUI_ActionsMgr(this);
148   myErrorDlg = new XGUI_ErrorDialog(myMainWindow);
149   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
150   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
151           SLOT(onContextMenuCommand(const QString&, bool)));
152
153   myViewerProxy = new XGUI_ViewerProxy(this);
154   connect(myViewerProxy, SIGNAL(selectionChanged()),
155           myActionsMgr,  SLOT(updateOnViewSelection()));
156
157   myModuleConnector = new XGUI_ModuleConnector(this);
158
159   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)), 
160           SLOT(onOperationStarted(ModuleBase_Operation*)));
161   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)),
162           SLOT(onOperationResumed(ModuleBase_Operation*)));
163   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
164           SLOT(onOperationStopped(ModuleBase_Operation*)));
165   connect(myOperationMgr, SIGNAL(operationCommitted(ModuleBase_Operation*)), 
166           SLOT(onOperationCommitted(ModuleBase_Operation*)));
167   connect(myOperationMgr, SIGNAL(operationAborted(ModuleBase_Operation*)), 
168           SLOT(onOperationAborted(ModuleBase_Operation*)));
169   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
170   connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
171 }
172
173 //******************************************************
174 XGUI_Workshop::~XGUI_Workshop(void)
175 {
176   delete myDisplayer;
177 }
178
179 //******************************************************
180 void XGUI_Workshop::startApplication()
181 {
182   initMenu();
183
184   Config_PropManager::registerProp("Plugins", "default_path", "Default Path",
185                                    Config_Prop::Directory, "");
186
187   //Initialize event listening
188   Events_Loop* aLoop = Events_Loop::loop();
189   aLoop->registerListener(this, Events_Error::errorID());  //!< Listening application errors.
190   aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
191   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
192   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
193   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
194   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
195   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
196   aLoop->registerListener(this, Events_LongOp::eventID());
197   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
198   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_DOCUMENT_CHANGED));
199   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOSHOW));
200   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
201   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
202
203   registerValidators();
204
205   // Calling of  loadCustomProps before activating module is required
206   // by Config_PropManger to restore user-defined path to plugins
207   ModuleBase_Preferences::loadCustomProps();
208   activateModule();
209   if (myMainWindow) {
210     myMainWindow->show();
211     updateCommandStatus();
212   }
213   
214   onNew();
215
216   emit applicationStarted();
217 }
218
219 //******************************************************
220 void XGUI_Workshop::initMenu()
221 {
222   myContextMenuMgr->createActions();
223
224   if (isSalomeMode()) {
225     // Create only Undo, Redo commands
226     QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
227                                                          tr("Undo last command"),
228                                                          QIcon(":pictures/undo.png"),
229                                                          QKeySequence::Undo, false, "MEN_DESK_EDIT");
230     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
231     addHistoryMenu(aAction, SIGNAL(updateUndoHistory(const QList<ActionInfo>&)), SLOT(onUndo(int)));
232
233     aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
234                                                 QIcon(":pictures/redo.png"), QKeySequence::Redo,
235                                                 false, "MEN_DESK_EDIT");
236     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
237     addHistoryMenu(aAction, SIGNAL(updateRedoHistory(const QList<ActionInfo>&)), SLOT(onRedo(int)));
238
239     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
240     aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
241                                                 QIcon(":pictures/rebuild.png"), QKeySequence(),
242                                                 false, "MEN_DESK_EDIT");
243     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
244     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
245
246     aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
247                                                 QIcon(), QKeySequence(),
248                                                 false, "MEN_DESK_FILE");
249     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
250
251     aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
252                                                 QIcon(), QKeySequence(),
253                                                 false, "MEN_DESK_FILE");
254     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
255     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
256
257     return;
258   }
259   // File commands group
260   AppElements_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
261
262   AppElements_Command* aCommand;
263
264   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
265                                 QIcon(":pictures/save.png"), QKeySequence::Save);
266   aCommand->connectTo(this, SLOT(onSave()));
267   //aCommand->disable();
268
269   QString aUndoId = "UNDO_CMD";
270   aCommand = aGroup->addFeature(aUndoId, tr("Undo"), tr("Undo last command"),
271                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
272   aCommand->connectTo(this, SLOT(onUndo()));
273   AppElements_Button* aUndoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aUndoId));
274   addHistoryMenu(aUndoButton,
275                  SIGNAL(updateUndoHistory(const QList<ActionInfo>&)),
276                  SLOT(onUndo(int)));
277
278   QString aRedoId = "REDO_CMD";
279   aCommand = aGroup->addFeature(aRedoId, tr("Redo"), tr("Redo last command"),
280                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
281   aCommand->connectTo(this, SLOT(onRedo()));
282   AppElements_Button* aRedoButton = qobject_cast<AppElements_Button*>(aGroup->widget(aRedoId));
283   addHistoryMenu(aRedoButton,
284                  SIGNAL(updateRedoHistory(const QList<ActionInfo>&)),
285                  SLOT(onRedo(int)));
286
287   aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
288     QIcon(":pictures/rebuild.png"), QKeySequence());
289   aCommand->connectTo(this, SLOT(onRebuild()));
290
291   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
292                                 QIcon(":pictures/save.png"), QKeySequence());
293   aCommand->connectTo(this, SLOT(onSaveAs()));
294   //aCommand->disable();
295
296   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
297                                 QIcon(":pictures/open.png"), QKeySequence::Open);
298   aCommand->connectTo(this, SLOT(onOpen()));
299
300   //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
301   //                              QIcon(":pictures/new.png"), QKeySequence::New);
302   //aCommand->connectTo(this, SLOT(onNew()));
303
304   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
305                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
306   aCommand->connectTo(this, SLOT(onPreferences()));
307
308   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
309                                 QIcon(":pictures/close.png"), QKeySequence::Close);
310   aCommand->connectTo(this, SLOT(onExit()));
311   //FIXME: SBH's test action. Can be used for some GUI tests.
312 //  #ifdef _DEBUG
313 //    aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
314 //                                  QIcon(":pictures/close.png"), QKeySequence(), true);
315 //    aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
316 //  #endif
317 }
318
319 //******************************************************
320 AppElements_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
321 {
322   AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
323   return aMenuBar->addWorkbench(theName);
324 }
325
326 //******************************************************
327 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
328 {
329   if (QApplication::instance()->thread() != QThread::currentThread()) {
330     #ifdef _DEBUG
331     std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
332     #endif
333     SessionPtr aMgr = ModelAPI_Session::get();
334     PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
335     QApplication::postEvent(this, aPostponeEvent);
336     return;
337   }
338
339   //A message to start feature creation received.
340   if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
341     std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
342        std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
343     if (!aFeatureMsg->isInternal()) {
344       addFeature(aFeatureMsg);
345     }
346   }
347   // Process creation of Part
348   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
349     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
350         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
351     onFeatureCreatedMsg(aUpdMsg);
352     if (myUpdatePrefs) {
353       if (mySalomeConnector)
354         mySalomeConnector->createPreferences();
355       myUpdatePrefs = false;
356     }
357   }
358   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
359     myUpdatePrefs = true;
360   }
361   // Redisplay feature
362   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
363     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
364         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
365     onFeatureRedisplayMsg(aUpdMsg);
366   }
367   //Update property panel on corresponding message. If there is no current operation (no
368   //property panel), or received message has different feature to the current - do nothing.
369   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
370     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
371         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
372     onFeatureUpdatedMsg(anUpdateMsg);
373   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
374     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDelMsg =
375         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
376     onObjectDeletedMsg(aDelMsg);
377   } else if (theMessage->eventID() == Events_LongOp::eventID()) {
378     if (Events_LongOp::isPerformed()) {
379       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
380     } else {
381       QApplication::restoreOverrideCursor();
382     }
383   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOSHOW)) {
384     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
385         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
386     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
387     QObjectPtrList aList;
388     std::set<ObjectPtr>::const_iterator aIt;
389     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
390       aList.append(*aIt);
391     showObjects(aList, true);
392   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE)) {
393     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
394         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
395     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
396     QObjectPtrList aList;
397     std::set<ObjectPtr>::const_iterator aIt;
398     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
399       aList.append(*aIt);
400     showObjects(aList, false);
401   }
402   //An operation passed by message. Start it, process and commit.
403   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
404     std::shared_ptr<Config_PointerMessage> aPartSetMsg =
405         std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
406     //myPropertyPanel->cleanContent();
407     ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
408
409     if (myOperationMgr->startOperation(anOperation)) {
410       myPropertyPanel->updateContentWidget(anOperation->feature());
411       if (!anOperation->getDescription()->hasXmlRepresentation()) {
412         if (anOperation->commit())
413           updateCommandStatus();
414       }
415     }
416   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOCUMENT_CHANGED)) {
417     myActionsMgr->update();
418     // Find and Activate active part
419     if (myPartActivating)
420       return;
421     SessionPtr aMgr = ModelAPI_Session::get();
422     DocumentPtr aActiveDoc = aMgr->activeDocument();
423     DocumentPtr aDoc = aMgr->moduleDocument();
424     if (aActiveDoc == aDoc) {
425       activatePart(ResultPartPtr()); 
426       return;
427     }
428     std::string aGrpName = ModelAPI_ResultPart::group();
429     for (int i = 0; i < aDoc->size(aGrpName); i++) {
430       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
431       if (aPart->partDoc() == aActiveDoc) {
432         activatePart(aPart); // Activate a part which corresponds to active Doc
433         return;
434       }
435     }
436     // If not found then activate global document
437     activatePart(ResultPartPtr()); 
438
439   }
440   else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
441     std::shared_ptr<Config_SelectionFilterMessage> aMsg = 
442       std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
443     if (aMsg) {
444       ModuleBase_FilterFactory* aFactory = moduleConnector()->selectionFilters();
445       if (!aMsg->attributeId().empty()) {
446         aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
447                                aMsg->parameters());
448       }
449     }
450   } else {
451     //Show error dialog if error message received.
452     std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
453     if (anAppError) {
454       emit errorOccurred(QString::fromLatin1(anAppError->description()));
455     }
456     return;
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
651   QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
652   foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
653     bool isStoreValue = !theOperation->isEditOperation() &&
654                         !aWidget->getDefaultValue().empty() &&
655                         !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,
726                                                        aDocKind,
727                                                        aNestedFeatures);
728     // Enrich created button with accept/abort buttons if necessary
729     AppElements_Button* aButton = aCommand->button();
730     if (aButton->isColumnButton()) {
731       QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
732       QList<QAction*> anActList;
733       if (aNestedActions.contains("accept")) {
734         QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, aButton);
735         connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(commitAllOperations()));
736         anActList << anAction;
737       }
738       if (aNestedActions.contains("abort")) {
739         QAction* anAction = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, aButton);
740         connect(anAction, SIGNAL(triggered()), myOperationMgr, SLOT(abortAllOperations()));
741         anActList << anAction;
742       }
743       aButton->setAdditionalButtons(anActList);
744     }
745     myActionsMgr->addCommand(aCommand);
746     myModule->actionCreated(aCommand);
747   }
748 }
749
750 /*
751  * Makes a signal/slot connections between Property Panel
752  * and given operation. The given operation becomes a
753  * current operation and previous operation if exists
754  */
755 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
756 {
757   QAction* aCommand = 0;
758   if (isSalomeMode()) {
759     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
760   } else {
761     AppElements_MainMenu* aMenu = myMainWindow->menuObject();
762     FeaturePtr aFeature = theOperation->feature();
763     if(aFeature)
764       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
765   }
766   //Abort operation on uncheck the command
767   if (aCommand) {
768     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
769   }
770 }
771
772 /*
773  * Saves document with given name.
774  */
775 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
776 {
777   QApplication::restoreOverrideCursor();
778   SessionPtr aMgr = ModelAPI_Session::get();
779   aMgr->save(theName.toLatin1().constData(), theFileNames);
780   QApplication::restoreOverrideCursor();
781 }
782
783 bool XGUI_Workshop::isActiveOperationAborted()
784 {
785   return myOperationMgr->abortAllOperations();
786 }
787
788 //******************************************************
789 void XGUI_Workshop::onExit()
790 {
791   SessionPtr aMgr = ModelAPI_Session::get();
792   if (aMgr->isModified()) {
793     int anAnswer = QMessageBox::question(
794         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
795         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
796     if (anAnswer == QMessageBox::Save) {
797       bool saved = onSave();
798       if (!saved) {
799         return;
800       }
801     } else if (anAnswer == QMessageBox::Cancel) {
802       return;
803     }
804   }
805   qApp->exit();
806 }
807
808 //******************************************************
809 void XGUI_Workshop::onNew()
810 {
811   QApplication::setOverrideCursor(Qt::WaitCursor);
812   if (objectBrowser() == 0) {
813     createDockWidgets();
814     mySelector->connectViewers();
815   }
816   myViewerProxy->connectToViewer();
817   showObjectBrowser();
818   if (!isSalomeMode()) {
819     myMainWindow->showPythonConsole();
820     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
821     aWnd->showMaximized();
822     updateCommandStatus();
823   }
824   myContextMenuMgr->connectViewer();
825   QApplication::restoreOverrideCursor();
826 }
827
828 //******************************************************
829 void XGUI_Workshop::onOpen()
830 {
831   if(!isActiveOperationAborted())
832     return;
833   //save current file before close if modified
834   SessionPtr aSession = ModelAPI_Session::get();
835   if (aSession->isModified()) {
836     //TODO(sbh): re-launch the app?
837     int anAnswer = QMessageBox::question(
838         myMainWindow, tr("Save current file"),
839         tr("The document is modified, save before opening another?"),
840         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
841     if (anAnswer == QMessageBox::Save) {
842       onSave();
843     } else if (anAnswer == QMessageBox::Cancel) {
844       return;
845     }
846     aSession->closeAll();
847     myCurrentDir = "";
848   }
849
850   //show file dialog, check if readable and open
851   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
852   if (myCurrentDir.isEmpty())
853     return;
854   QFileInfo aFileInfo(myCurrentDir);
855   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
856     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
857     myCurrentDir = "";
858     return;
859   }
860   QApplication::setOverrideCursor(Qt::WaitCursor);
861   aSession->load(myCurrentDir.toLatin1().constData());
862   myObjectBrowser->rebuildDataTree();
863   displayAllResults();
864   updateCommandStatus();
865   QApplication::restoreOverrideCursor();
866 }
867
868 //******************************************************
869 bool XGUI_Workshop::onSave()
870 {
871   if(!isActiveOperationAborted())
872     return false;
873   if (myCurrentDir.isEmpty()) {
874     return onSaveAs();
875   }
876   std::list<std::string> aFiles;
877   saveDocument(myCurrentDir, aFiles);
878   updateCommandStatus();
879   if (!isSalomeMode())
880     myMainWindow->setModifiedState(false);
881   return true;
882 }
883
884 //******************************************************
885 bool XGUI_Workshop::onSaveAs()
886 {
887   if(!isActiveOperationAborted())
888     return false;
889   QFileDialog dialog(mainWindow());
890   dialog.setWindowTitle(tr("Select directory to save files..."));
891   dialog.setFileMode(QFileDialog::Directory);
892   dialog.setFilter(tr("Folders (*)"));
893   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
894   dialog.setViewMode(QFileDialog::Detail);
895
896   if (!dialog.exec()) {
897     return false;
898   }
899   QString aTempDir = dialog.selectedFiles().first();
900   QDir aDir(aTempDir);
901   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
902     int answer = QMessageBox::question(
903         myMainWindow,
904         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
905         tr("Save"),
906         tr("The folder already contains some files, save anyway?"),
907         QMessageBox::Save | QMessageBox::Cancel);
908     if (answer == QMessageBox::Cancel) {
909       return false;
910     }
911   }
912   myCurrentDir = aTempDir;
913   if (!isSalomeMode()) {
914     myMainWindow->setCurrentDir(myCurrentDir, false);
915     myMainWindow->setModifiedState(false);
916   }
917   return onSave();
918 }
919
920 //******************************************************
921 void XGUI_Workshop::onUndo(int theTimes)
922 {
923   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
924   SessionPtr aMgr = ModelAPI_Session::get();
925   if (aMgr->isOperation())
926     operationMgr()->onAbortOperation();
927   for (int i = 0; i < theTimes; ++i) {
928     aMgr->undo();
929   }
930   updateCommandStatus();
931 }
932
933 //******************************************************
934 void XGUI_Workshop::onRedo(int theTimes)
935 {
936   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
937   SessionPtr aMgr = ModelAPI_Session::get();
938   if (aMgr->isOperation())
939     operationMgr()->onAbortOperation();
940   for (int i = 0; i < theTimes; ++i) {
941     aMgr->redo();
942   }
943   updateCommandStatus();
944 }
945
946 //******************************************************
947 void XGUI_Workshop::onRebuild()
948 {
949   SessionPtr aMgr = ModelAPI_Session::get();
950   bool aWasOperation = aMgr->isOperation(); // keep this value
951   if (!aWasOperation) {
952     aMgr->startOperation("Rebuild");
953   }
954   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
955   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
956     new Events_Message(aRebuildEvent, this)));
957   if (!aWasOperation) {
958     aMgr->finishOperation();
959   }
960 }
961
962 //******************************************************
963 void XGUI_Workshop::onPreferences()
964 {
965   ModuleBase_Prefs aModif;
966   ModuleBase_Preferences::editPreferences(aModif);
967   if (aModif.size() > 0) {
968     QString aSection;
969     foreach (ModuleBase_Pref aPref, aModif)
970     {
971       aSection = aPref.first;
972       if (aSection == ModuleBase_Preferences::VIEWER_SECTION) {
973         if (!isSalomeMode())
974           myMainWindow->viewer()->updateFromResources();
975       } else if (aSection == ModuleBase_Preferences::MENU_SECTION) {
976         if (!isSalomeMode())
977           myMainWindow->menuObject()->updateFromResources();
978       }
979     }
980   }
981 }
982
983 //******************************************************
984 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
985 {
986   QString libName = QString::fromStdString(library(theModule.toStdString()));
987   if (libName.isEmpty()) {
988     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
989     return 0;
990   }
991
992   QString err;
993   CREATE_FUNC crtInst = 0;
994
995 #ifdef WIN32
996   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
997   if (!modLib) {
998     LPVOID lpMsgBuf;
999     ::FormatMessage(
1000         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1001         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1002     QString aMsg((char*) &lpMsgBuf);
1003     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
1004     ::LocalFree(lpMsgBuf);
1005   } else {
1006     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
1007     if (!crtInst) {
1008       LPVOID lpMsgBuf;
1009       ::FormatMessage(
1010           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1011               | FORMAT_MESSAGE_IGNORE_INSERTS,
1012           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
1013       QString aMsg((char*) &lpMsgBuf);
1014       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
1015       ::LocalFree(lpMsgBuf);
1016     }
1017   }
1018 #else
1019   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
1020   if ( !modLib ) {
1021     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
1022   } else {
1023     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
1024     if ( !crtInst ) {
1025       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
1026     }
1027   }
1028 #endif
1029
1030   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
1031
1032   if (!err.isEmpty()) {
1033     if (mainWindow()) {
1034       Events_Error::send(err.toStdString());
1035     } else {
1036       qWarning(qPrintable(err));
1037     }
1038   }
1039   return aModule;
1040 }
1041
1042 //******************************************************
1043 bool XGUI_Workshop::activateModule()
1044 {
1045   Config_ModuleReader aModuleReader;
1046   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
1047   myModule = loadModule(moduleName);
1048   if (!myModule)
1049     return false;
1050   myModule->createFeatures();
1051   myActionsMgr->update();
1052   return true;
1053 }
1054
1055 //******************************************************
1056 void XGUI_Workshop::updateCommandStatus()
1057 {
1058   QList<QAction*> aCommands;
1059   if (isSalomeMode()) {  // update commands in SALOME mode
1060     aCommands = salomeConnector()->commandList();
1061   } else {
1062     AppElements_MainMenu* aMenuBar = myMainWindow->menuObject();
1063     foreach (AppElements_Command* aCmd, aMenuBar->features())
1064       aCommands.append(aCmd);
1065   }
1066   SessionPtr aMgr = ModelAPI_Session::get();
1067   if (aMgr->hasModuleDocument()) {
1068     QAction *aUndoCmd, *aRedoCmd;
1069     foreach(QAction* aCmd, aCommands) {
1070       QString aId = aCmd->data().toString();
1071       if (aId == "UNDO_CMD")
1072         aUndoCmd = aCmd;
1073       else if (aId == "REDO_CMD")
1074         aRedoCmd = aCmd;
1075       else
1076         // Enable all commands
1077         aCmd->setEnabled(true);
1078     }
1079
1080     aUndoCmd->setEnabled(myModule->canUndo());
1081     aRedoCmd->setEnabled(myModule->canRedo());
1082     updateHistory();
1083   } else {
1084     foreach(QAction* aCmd, aCommands) {
1085       QString aId = aCmd->data().toString();
1086       if (aId == "NEW_CMD")
1087         aCmd->setEnabled(true);
1088       else if (aId == "EXIT_CMD")
1089         aCmd->setEnabled(true);
1090       else
1091         aCmd->setEnabled(false);
1092     }
1093   }
1094   myActionsMgr->update();
1095   emit commandStatusUpdated();
1096 }
1097
1098 void XGUI_Workshop::updateHistory()
1099 {
1100   std::list<std::string> aUndoList = ModelAPI_Session::get()->undoList();
1101   QList<ActionInfo> aUndoRes = processHistoryList(aUndoList);
1102   emit updateUndoHistory(aUndoRes);
1103
1104   std::list<std::string> aRedoList = ModelAPI_Session::get()->redoList();
1105   QList<ActionInfo> aRedoRes = processHistoryList(aRedoList);
1106   emit updateRedoHistory(aRedoRes);
1107 }
1108
1109 //******************************************************
1110 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1111 {
1112   QDockWidget* aObjDock = new QDockWidget(theParent);
1113   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1114   aObjDock->setWindowTitle(tr("Object browser"));
1115   aObjDock->setStyleSheet(
1116       "::title { position: relative; padding-left: 5px; text-align: left center }");
1117   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1118   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1119           SLOT(changeCurrentDocument(ObjectPtr)));
1120   aObjDock->setWidget(myObjectBrowser);
1121
1122   myContextMenuMgr->connectObjectBrowser();
1123   return aObjDock;
1124 }
1125
1126 //******************************************************
1127 /*
1128  * Creates dock widgets, places them in corresponding area
1129  * and tabifies if necessary.
1130  */
1131 void XGUI_Workshop::createDockWidgets()
1132 {
1133   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1134   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1135   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1136   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1137   myPropertyPanel->setupActions(myActionsMgr);
1138   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1139   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1140   hidePropertyPanel();  ///<! Invisible by default
1141   hideObjectBrowser();
1142   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1143   myPropertyPanel->installEventFilter(myOperationMgr);
1144
1145   QAction* aOkAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Accept);
1146   connect(aOkAct, SIGNAL(triggered()), myOperationMgr, SLOT(onCommitOperation()));
1147   QAction* aCancelAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::Abort);
1148   connect(aCancelAct, SIGNAL(triggered()), myOperationMgr, SLOT(onAbortOperation()));
1149   connect(myPropertyPanel, SIGNAL(noMoreWidgets()), myModule, SLOT(onNoMoreWidgets()));
1150   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)),
1151           myOperationMgr,  SLOT(onKeyReleased(QKeyEvent*)));
1152   connect(myOperationMgr,  SIGNAL(validationStateChanged(bool)),
1153           aOkAct,          SLOT(setEnabled(bool)));
1154   QAction* aAcceptAllAct = myActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll);
1155   connect(myOperationMgr,  SIGNAL(nestedStateChanged(bool)),
1156           aAcceptAllAct,   SLOT(setEnabled(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::activatePart(ResultPartPtr theFeature)
1263 {
1264   if (!myPartActivating) {
1265     myPartActivating = true;
1266     if (theFeature)
1267       theFeature->activate();
1268     changeCurrentDocument(theFeature);
1269     myObjectBrowser->activatePart(theFeature);
1270     myPartActivating = false;
1271   }
1272   updateCommandStatus();
1273 }
1274
1275 //**************************************************************
1276 //void XGUI_Workshop::activateLastPart()
1277 //{
1278 //  SessionPtr aMgr = ModelAPI_Session::get();
1279 //  DocumentPtr aDoc = aMgr->moduleDocument();
1280 //  std::string aGrpName = ModelAPI_ResultPart::group();
1281 //  ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1282 //  ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1283 //  if (aPart) {
1284 //    activatePart(aPart);
1285 //  }
1286 //}
1287
1288 //**************************************************************
1289 void XGUI_Workshop::deleteObjects(const QObjectPtrList& theList)
1290 {
1291   ModuleBase_IModule* aModule = module();
1292   if (aModule->deleteObjects())
1293     return;
1294
1295   if (!isActiveOperationAborted())
1296     return;
1297
1298   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1299   std::set<FeaturePtr> aRefFeatures;
1300   foreach (ObjectPtr aObj, theList)
1301   {
1302     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1303     if (aPart) {
1304       // TODO: check for what there is this condition. It is placed here historicaly because
1305       // ther is this condition during remove features.
1306     } else {
1307       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1308       if (aFeature.get() != NULL) {
1309         aObj->document()->refsToFeature(aFeature, aRefFeatures, false);
1310       }
1311     }
1312   }
1313
1314   if (!aRefFeatures.empty()) {
1315     QStringList aRefNames;
1316     std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1317                                          aLast = aRefFeatures.end();
1318     for (; anIt != aLast; anIt++) {
1319       FeaturePtr aFeature = (*anIt);
1320       std::string aFName = aFeature->data()->name().c_str();
1321       std::string aName = (*anIt)->name().c_str();
1322       aRefNames.append((*anIt)->name().c_str());
1323     }
1324     QString aNames = aRefNames.join(", ");
1325
1326     QMessageBox::StandardButton aRes = QMessageBox::warning(
1327         aDesktop, tr("Delete features"),
1328         QString(tr("Selected features are used in the following features: %1.\
1329 These features will be deleted also. Would you like to continue?")).arg(aNames),
1330         QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1331     if (aRes != QMessageBox::Yes)
1332       return;
1333   }
1334
1335   SessionPtr aMgr = ModelAPI_Session::get();
1336   QString aDescription = tr("Delete %1");
1337   QStringList aObjectNames;
1338   foreach (ObjectPtr aObj, theList) {
1339     if (!aObj->data().get())
1340       continue;
1341     aObjectNames << QString::fromStdString(aObj->data()->name());
1342   }
1343   aDescription = aDescription.arg(aObjectNames.join(", "));
1344   aMgr->startOperation(aDescription.toStdString());
1345   std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
1346                                        aLast = aRefFeatures.end();
1347   for (; anIt != aLast; anIt++) {
1348     FeaturePtr aRefFeature = (*anIt);
1349     DocumentPtr aDoc = aRefFeature->document();
1350     aDoc->removeFeature(aRefFeature);
1351    }
1352
1353
1354   foreach (ObjectPtr aObj, theList)
1355   {
1356     DocumentPtr aDoc = aObj->document();
1357     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1358     if (aPart) {
1359       if (aDoc == aMgr->activeDocument()) {
1360         aDoc->close();
1361       }
1362     } else {
1363       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1364       if (aFeature) {
1365         aDoc->removeFeature(aFeature);
1366       }
1367     }
1368   }
1369
1370   myDisplayer->updateViewer();
1371   aMgr->finishOperation();
1372   updateCommandStatus();
1373 }
1374
1375 //**************************************************************
1376 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1377 {
1378   foreach (ObjectPtr aObj, theList)
1379   {
1380     if (isVisible) {
1381       displayObject(aObj);
1382     } else {
1383       myDisplayer->erase(aObj, false);
1384     }
1385   }
1386   myDisplayer->updateViewer();
1387 }
1388
1389 //**************************************************************
1390 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1391 {
1392   myDisplayer->showOnly(theList);
1393 }
1394
1395
1396 //**************************************************************
1397 void XGUI_Workshop::registerValidators() const
1398 {
1399   SessionPtr aMgr = ModelAPI_Session::get();
1400   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1401 }
1402
1403 //**************************************************************
1404 void XGUI_Workshop::displayAllResults()
1405 {
1406   SessionPtr aMgr = ModelAPI_Session::get();
1407   DocumentPtr aRootDoc = aMgr->moduleDocument();
1408   displayDocumentResults(aRootDoc);
1409   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1410     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1411     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1412     displayDocumentResults(aPart->partDoc());
1413   }
1414   myDisplayer->updateViewer();
1415 }
1416
1417 //**************************************************************
1418 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1419 {
1420   if (!theDoc)
1421     return;
1422   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1423   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1424 }
1425
1426 //**************************************************************
1427 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1428 {
1429   for (int i = 0; i < theDoc->size(theGroup); i++)
1430     displayObject(theDoc->object(theGroup, i));
1431 }
1432
1433 //**************************************************************
1434 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1435 {
1436   foreach(ObjectPtr aObj, theList) {
1437     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1438   }
1439   if (theList.size() > 0)
1440     myDisplayer->updateViewer();
1441 }
1442
1443 //**************************************************************
1444 void XGUI_Workshop::closeDocument()
1445 {
1446   ModuleBase_Operation* anOperation = operationMgr()->currentOperation();
1447   while (anOperation) {
1448     anOperation->abort();
1449     anOperation = operationMgr()->currentOperation();
1450   }
1451   myDisplayer->closeLocalContexts();
1452   myDisplayer->eraseAll();
1453   objectBrowser()->clearContent();
1454
1455   SessionPtr aMgr = ModelAPI_Session::get();
1456   aMgr->closeAll();
1457   objectBrowser()->clearContent();
1458 }
1459
1460 //**************************************************************
1461 void XGUI_Workshop::displayObject(ObjectPtr theObj)
1462 {
1463   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
1464   if (aBody.get() != NULL) {
1465     int aNb = myDisplayer->objectsCount();
1466     myDisplayer->display(theObj, false);
1467     if (aNb == 0)
1468       viewer()->fitAll();
1469   } else 
1470     myDisplayer->display(theObj, false);
1471 }
1472
1473 void XGUI_Workshop::addHistoryMenu(QObject* theObject, const char* theSignal, const char* theSlot)
1474 {
1475   XGUI_HistoryMenu* aMenu = NULL;
1476   if (isSalomeMode()) {
1477     QAction* anAction = qobject_cast<QAction*>(theObject);
1478     if (!anAction)
1479       return;
1480     aMenu = new XGUI_HistoryMenu(anAction);
1481   } else {
1482     QToolButton* aButton =  qobject_cast<QToolButton*>(theObject);
1483     aMenu = new XGUI_HistoryMenu(aButton);
1484   }
1485   connect(this, theSignal, aMenu, SLOT(setHistory(const QList<ActionInfo>&)));
1486   connect(aMenu, SIGNAL(actionSelected(int)), this, theSlot);
1487 }
1488
1489 QList<ActionInfo> XGUI_Workshop::processHistoryList(const std::list<std::string>& theList) const
1490 {
1491   QList<ActionInfo> aResult;
1492   std::list<std::string>::const_iterator it = theList.cbegin();
1493   for (; it != theList.cend(); it++) {
1494     QString anId = QString::fromStdString(*it);
1495     bool isEditing = anId.endsWith(ModuleBase_Operation::EditSuffix());
1496     if (isEditing) {
1497       anId.chop(ModuleBase_Operation::EditSuffix().size());
1498     }
1499     ActionInfo anInfo = myActionsMgr->actionInfoById(anId);
1500     if (isEditing) {
1501       anInfo.text = anInfo.text.prepend("Modify ");
1502     }
1503     aResult << anInfo;
1504   }
1505   return aResult;
1506 }