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