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