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