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