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