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