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