]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
a8d23dd5212af78cc510beffafac2f6a03ed8269
[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_LongOp::eventID()) {
268     if (Events_LongOp::isPerformed())
269       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
270       //QTimer::singleShot(10, this, SLOT(onStartWaiting()));
271     else 
272       QApplication::restoreOverrideCursor();
273     return;
274   }
275
276   //An operation passed by message. Start it, process and commit.
277   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
278     const Config_PointerMessage* aPartSetMsg = dynamic_cast<const Config_PointerMessage*>(theMessage);
279     //myPropertyPanel->cleanContent();
280     ModuleBase_Operation* anOperation = (ModuleBase_Operation*)aPartSetMsg->pointer();
281
282     if (myOperationMgr->startOperation(anOperation)) {
283       myPropertyPanel->updateContentWidget(anOperation->feature());
284       if (!anOperation->getDescription()->hasXmlRepresentation()) {
285         anOperation->commit();
286         updateCommandStatus();
287       }
288     }
289     return;
290   }
291   //Show error dialog if error message received.
292   const Events_Error* anAppError = dynamic_cast<const Events_Error*>(theMessage);
293   if (anAppError) {
294     emit errorOccurred(QString::fromLatin1(anAppError->description()));
295   }
296 }
297
298 //******************************************************
299 void XGUI_Workshop::onStartWaiting()
300 {
301   if (Events_LongOp::isPerformed()) {
302     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
303   }
304 }
305
306 //******************************************************
307 void XGUI_Workshop::onFeatureUpdatedMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
308 {
309   std::set<ObjectPtr> aFeatures = theMsg->objects();
310   if (myOperationMgr->hasOperation())
311   {
312     FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
313     std::set<ObjectPtr>::const_iterator aIt;
314     for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
315       ObjectPtr aNewFeature = (*aIt);
316       if(aNewFeature == aCurrentFeature) {
317         myPropertyPanel->updateContentWidget(aCurrentFeature);
318         break;
319       } 
320     }
321   }
322 }
323
324 //******************************************************
325 void XGUI_Workshop::onFeatureRedisplayMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
326 {
327   std::set<ObjectPtr> aObjects = theMsg->objects();
328   std::set<ObjectPtr>::const_iterator aIt;
329   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
330     ObjectPtr aObj = (*aIt);
331     if (!aObj->data() || !aObj->data()->isValid())
332       myDisplayer->erase(aObj, false);
333     else {
334       if (myDisplayer->isVisible(aObj)) // TODO VSV: Correction sketch drawing
335         myDisplayer->display(aObj, false); // In order to update presentation
336       else {
337         if(myOperationMgr->hasOperation()) {
338           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
339           if (aOperation->hasObject(aObj)) { // Display only current operation results
340             myDisplayer->display(aObj, false);        
341           }
342         }
343       }
344     }
345   }
346   myDisplayer->updateViewer();
347 }
348
349 //******************************************************
350 void XGUI_Workshop::onFeatureCreatedMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
351 {
352   std::set<ObjectPtr> aObjects = theMsg->objects();
353
354   std::set<ObjectPtr>::const_iterator aIt;
355   bool aHasPart = false;
356   bool isDisplayed = false;
357   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
358     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(*aIt);
359     if (aPart) {
360       aHasPart = true;
361     // If a feature is created from the aplication's python console  
362     // it doesn't stored in the operation mgr and doesn't displayed
363     } else if(myOperationMgr->hasOperation()) {
364       ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
365       if (aOperation->hasObject(*aIt)) { // Display only current operation results
366         myDisplayer->display(*aIt, false);
367         isDisplayed = true;
368       }
369     }
370   }
371   if (isDisplayed)
372     myDisplayer->updateViewer();
373   if (aHasPart) {
374     //The created part will be created in Object Browser later and we have to activate it
375     // only when it is created everywere
376     QTimer::singleShot(50, this, SLOT(activateLastPart()));
377   }
378 }
379
380 //******************************************************
381 void XGUI_Workshop::onObjectDeletedMsg(const ModelAPI_ObjectDeletedMessage* theMsg)
382 {
383   //std::set<ObjectPtr> aFeatures = theMsg->objects();
384 }
385  
386 //******************************************************
387 void XGUI_Workshop::onOperationStarted()
388 {
389   ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
390
391   if(aOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
392     connectWithOperation(aOperation);
393
394     showPropertyPanel();
395     QString aXmlRepr = aOperation->getDescription()->xmlRepresentation();
396     ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(), myModuleConnector);
397
398     myPropertyPanel->cleanContent();
399     aFactory.createWidget(myPropertyPanel->contentWidget());
400     
401     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
402     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
403     ModuleBase_ModelWidget* aWidget;
404     for (; anIt != aLast; anIt++) {
405       aWidget = *anIt;
406       //QObject::connect(aWidget, SIGNAL(valuesChanged()),  aOperation, SLOT(storeCustomValue()));
407       QObject::connect(aWidget, SIGNAL(valuesChanged()),
408                        this, SLOT(onWidgetValuesChanged()));
409       // Init default values
410       if (!aOperation->isEditOperation() && aWidget->hasDefaultValue()) {
411         aWidget->storeValue(aOperation->feature());
412       }
413     }
414
415     myPropertyPanel->setModelWidgets(aWidgets);
416     myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
417   }
418   updateCommandStatus();
419 }
420
421 //******************************************************
422 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
423 {
424   //!< No need for property panel
425   updateCommandStatus();
426   hidePropertyPanel();
427   myPropertyPanel->cleanContent();
428 }
429
430 /*
431  *
432  */
433 void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
434 {
435   if (!theMessage) {
436 #ifdef _DEBUG
437     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
438 #endif
439     return;
440   }
441   // Remember features icons
442   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
443
444   //Find or create Workbench
445   QString aWchName = QString::fromStdString(theMessage->workbenchId());
446   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
447   bool isUsePropPanel = theMessage->isUseInput();
448   QString aId = QString::fromStdString(theMessage->id());
449   if (isSalomeMode()) {
450     QAction* aAction = salomeConnector()->addFeature(aWchName,
451                               aId,
452                               QString::fromStdString(theMessage->text()),
453                               QString::fromStdString(theMessage->tooltip()),
454                               QIcon(theMessage->icon().c_str()),
455                               QKeySequence(), isUsePropPanel);
456     salomeConnector()->setNestedActions(aId, aNestedFeatures.split(" "));
457     myActionsMgr->addCommand(aAction);
458     myModule->featureCreated(aAction);
459   } else {
460
461     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
462     XGUI_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
463     if (!aPage) {
464       aPage = addWorkbench(aWchName);
465     }
466     //Find or create Group
467     QString aGroupName = QString::fromStdString(theMessage->groupId());
468     XGUI_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
469     if (!aGroup) {
470       aGroup = aPage->addGroup(aGroupName);
471     }
472     //Create feature...
473     XGUI_Command* aCommand = aGroup->addFeature(aId,
474                                                 QString::fromStdString(theMessage->text()),
475                                                 QString::fromStdString(theMessage->tooltip()),
476                                                 QIcon(theMessage->icon().c_str()),
477                                                 QKeySequence(), isUsePropPanel);
478     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
479     myActionsMgr->addCommand(aCommand);
480     myModule->featureCreated(aCommand);
481   }
482 }
483
484 /*
485  * Makes a signal/slot connections between Property Panel
486  * and given operation. The given operation becomes a
487  * current operation and previous operation if exists
488  */
489 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
490 {
491   QAction* aCommand = 0;
492   if (isSalomeMode()) {
493     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
494   } else {
495     XGUI_MainMenu* aMenu = myMainWindow->menuObject();
496     aCommand = aMenu->feature(theOperation->getDescription()->operationId());
497   }
498   //Abort operation on uncheck the command
499   if (aCommand)
500     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
501 }
502
503 /*
504  * Saves document with given name.
505  */
506 void XGUI_Workshop::saveDocument(QString theName)
507 {
508   QApplication::restoreOverrideCursor();
509   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
510   DocumentPtr aDoc = aMgr->rootDocument();
511   aDoc->save(theName.toLatin1().constData());
512   QApplication::restoreOverrideCursor();
513 }
514
515 //******************************************************
516 void XGUI_Workshop::onExit()
517 {
518   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
519   DocumentPtr aDoc = aMgr->rootDocument();
520   if(aDoc->isModified()) {
521     int anAnswer = QMessageBox::question(
522         myMainWindow, tr("Save current file"),
523         tr("The document is modified, save before exit?"),
524         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
525     if(anAnswer == QMessageBox::Save) {
526       bool saved = onSave();
527       if(!saved) {
528         return;
529       }
530     } else if (anAnswer == QMessageBox::Cancel) {
531       return;
532     }
533   }
534   qApp->exit();
535 }
536
537 //******************************************************
538 void XGUI_Workshop::onNew()
539 {
540   QApplication::setOverrideCursor(Qt::WaitCursor);
541   if (objectBrowser() == 0) {
542     createDockWidgets();
543     mySelector->connectViewers();
544   }
545   myViewerProxy->connectToViewer();
546   showObjectBrowser();
547   if (!isSalomeMode()) {
548     myMainWindow->showPythonConsole();
549     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
550     aWnd->showMaximized();
551     updateCommandStatus();
552   }
553   myContextMenuMgr->connectViewer();
554   QApplication::restoreOverrideCursor();
555 }
556
557 //******************************************************
558 void XGUI_Workshop::onOpen()
559 {
560   //save current file before close if modified
561   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
562   DocumentPtr aDoc = aMgr->rootDocument();
563   if(aDoc->isModified()) {
564     //TODO(sbh): re-launch the app?
565     int anAnswer = QMessageBox::question(
566         myMainWindow, tr("Save current file"),
567         tr("The document is modified, save before opening another?"),
568         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
569     if(anAnswer == QMessageBox::Save) {
570       onSave();
571     } else if (anAnswer == QMessageBox::Cancel) {
572       return;
573     }
574     aDoc->close();
575     myCurrentDir = "";
576   }
577
578   //show file dialog, check if readable and open
579   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
580   if(myCurrentDir.isEmpty())
581     return;
582   QFileInfo aFileInfo(myCurrentDir);
583   if(!aFileInfo.exists() || !aFileInfo.isReadable()) {
584     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
585     myCurrentDir = "";
586     return;
587   }
588   QApplication::setOverrideCursor(Qt::WaitCursor);
589   aDoc->load(myCurrentDir.toLatin1().constData());
590   myObjectBrowser->rebuildDataTree();
591   displayAllResults();
592   updateCommandStatus();
593   QApplication::restoreOverrideCursor();
594 }
595
596 //******************************************************
597 bool XGUI_Workshop::onSave()
598 {
599   if(myCurrentDir.isEmpty()) {
600     return onSaveAs();
601   }
602   saveDocument(myCurrentDir);
603   updateCommandStatus();
604   return true;
605 }
606
607 //******************************************************
608 bool XGUI_Workshop::onSaveAs()
609 {
610   QFileDialog dialog(mainWindow());
611   dialog.setWindowTitle(tr("Select directory to save files..."));
612   dialog.setFileMode(QFileDialog::Directory);
613   dialog.setFilter(tr("Folders (*)"));
614   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
615   dialog.setViewMode(QFileDialog::Detail);
616
617   if(!dialog.exec()) {
618     return false;
619   }
620   QString aTempDir = dialog.selectedFiles().first();
621   QDir aDir(aTempDir);
622   if(aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot|QDir::AllEntries).isEmpty()) {
623     int answer = QMessageBox::question(myMainWindow,
624                                        //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
625                                        tr("Save"),
626                                        tr("The folder already contains some files, save anyway?"),
627                                        QMessageBox::Save|QMessageBox::Cancel);
628     if(answer == QMessageBox::Cancel) {
629       return false;
630     }
631   }
632   myCurrentDir = aTempDir;
633   return onSave();
634 }
635
636 //******************************************************
637 void XGUI_Workshop::onUndo()
638 {
639   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
640   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
641   DocumentPtr aDoc = aMgr->rootDocument();
642   if (aDoc->isOperation())
643     operationMgr()->abortOperation();
644   aDoc->undo();
645   updateCommandStatus();
646 }
647
648 //******************************************************
649 void XGUI_Workshop::onRedo()
650 {
651   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
652   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
653   DocumentPtr aDoc = aMgr->rootDocument();
654   if (aDoc->isOperation())
655     operationMgr()->abortOperation();
656   aDoc->redo();
657   updateCommandStatus();
658 }
659
660 //******************************************************
661 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
662 {
663   QString libName =
664       QString::fromStdString(library(theModule.toStdString()));
665   if (libName.isEmpty()) {
666     qWarning(
667     qPrintable( tr( "Information about module \"%1\" doesn't exist." ).arg( theModule ) ));
668     return 0;
669   }
670
671   QString err;
672   CREATE_FUNC crtInst = 0;
673
674 #ifdef WIN32
675   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
676   if (!modLib) {
677     LPVOID lpMsgBuf;
678     ::FormatMessage(
679         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
680         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
681     QString aMsg((char*) &lpMsgBuf);
682     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
683     ::LocalFree(lpMsgBuf);
684   } else {
685     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
686     if (!crtInst) {
687       LPVOID lpMsgBuf;
688       ::FormatMessage(
689           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
690               | FORMAT_MESSAGE_IGNORE_INSERTS,
691           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
692       QString aMsg((char*) &lpMsgBuf);
693       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
694       ::LocalFree(lpMsgBuf);
695     }
696   }
697 #else
698   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
699   if ( !modLib ) {
700     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
701   } else {
702     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
703     if ( !crtInst ) {
704       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
705     }
706   }
707 #endif
708
709   ModuleBase_IModule* aModule = crtInst ? crtInst(this) : 0;
710
711   if (!err.isEmpty()) {
712     if (mainWindow()) {
713       QMessageBox::warning(mainWindow(), tr("Error"), err);
714     } else {
715       qWarning( qPrintable( err ));
716     }
717   }
718   return aModule;
719 }
720
721 //******************************************************
722 bool XGUI_Workshop::activateModule()
723 {
724   Config_ModuleReader aModuleReader;
725   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
726   myModule = loadModule(moduleName);
727   if (!myModule)
728     return false;
729   myModule->createFeatures();
730   myActionsMgr->update();
731   return true;
732 }
733
734 //******************************************************
735 void XGUI_Workshop::updateCommandStatus()
736 {
737   QList<QAction*> aCommands;
738   if (isSalomeMode()) { // update commands in SALOME mode
739     aCommands = salomeConnector()->commandList();
740   } else {
741     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
742     foreach (XGUI_Command* aCmd, aMenuBar->features())
743       aCommands.append(aCmd);
744   }
745   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
746   if (aMgr->hasRootDocument()) {
747     QAction* aUndoCmd;
748     QAction* aRedoCmd;
749     foreach(QAction* aCmd, aCommands) {
750       QString aId = aCmd->data().toString();
751       if (aId == "UNDO_CMD")
752         aUndoCmd = aCmd;
753       else if (aId == "REDO_CMD")
754         aRedoCmd = aCmd;
755       else // Enable all commands
756         aCmd->setEnabled(true);
757     }
758     DocumentPtr aDoc = aMgr->rootDocument();
759     aUndoCmd->setEnabled(aDoc->canUndo());
760     aRedoCmd->setEnabled(aDoc->canRedo());
761   } else {
762     foreach(QAction* aCmd, aCommands) {
763       QString aId = aCmd->data().toString();
764       if (aId == "NEW_CMD")
765         aCmd->setEnabled(true);
766       else if (aId == "EXIT_CMD")
767         aCmd->setEnabled(true);
768       else 
769         aCmd->setEnabled(false);
770     }
771   }
772   myActionsMgr->update();
773 }
774
775 //******************************************************
776 QList<QAction*> XGUI_Workshop::getModuleCommands() const
777 {
778   QList<QAction*> aCommands;
779   if (isSalomeMode()) { // update commands in SALOME mode
780     aCommands = salomeConnector()->commandList();
781   } else {
782     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
783     foreach (XGUI_Workbench* aWb, aMenuBar->workbenches()) {
784       if (aWb != aMenuBar->generalPage()) {
785         foreach(XGUI_Command* aCmd, aWb->features())
786           aCommands.append(aCmd);
787       }
788     }
789   }
790   return aCommands;
791 }
792
793 //******************************************************
794 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
795 {
796   QDockWidget* aObjDock = new QDockWidget(theParent);
797   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
798   aObjDock->setWindowTitle(tr("Object browser"));
799   aObjDock->setStyleSheet("::title { position: relative; padding-left: 5px; text-align: left center }");
800   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
801   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this, SLOT(changeCurrentDocument(ObjectPtr)));
802   aObjDock->setWidget(myObjectBrowser);
803
804   myContextMenuMgr->connectObjectBrowser();
805   return aObjDock;
806 }
807
808 //******************************************************
809 /*
810  * Creates dock widgets, places them in corresponding area
811  * and tabifies if necessary.
812  */
813 void XGUI_Workshop::createDockWidgets()
814 {
815   QMainWindow* aDesktop = isSalomeMode()? salomeConnector()->desktop() :
816                                           myMainWindow;
817   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
818   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
819   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
820   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
821   hidePropertyPanel(); //<! Invisible by default
822   hideObjectBrowser();
823   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
824
825   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_OK);
826   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
827   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_CANCEL);
828   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
829
830   connect(myPropertyPanel, SIGNAL(keyReleased(const std::string&, QKeyEvent*)),
831           myOperationMgr, SLOT(onKeyReleased(const std::string&, QKeyEvent*)));
832
833   connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
834           myOperationMgr, SLOT(onWidgetActivated(ModuleBase_ModelWidget*)));
835   connect(myOperationMgr, SIGNAL(activateNextWidget(ModuleBase_ModelWidget*)),
836           myPropertyPanel, SLOT(onActivateNextWidget(ModuleBase_ModelWidget*)));
837 }
838
839 //******************************************************
840 void XGUI_Workshop::showPropertyPanel()
841 {
842   QAction* aViewAct = myPropertyPanel->toggleViewAction();
843   //<! Restore ability to close panel from the window's menu
844   aViewAct->setEnabled(true);
845   myPropertyPanel->show();
846   myPropertyPanel->raise();
847 }
848
849 //******************************************************
850 void XGUI_Workshop::hidePropertyPanel()
851 {
852   QAction* aViewAct = myPropertyPanel->toggleViewAction();
853   //<! Do not allow to show empty property panel
854   aViewAct->setEnabled(false);
855   myPropertyPanel->hide();
856 }
857
858 //******************************************************
859 void XGUI_Workshop::showObjectBrowser()
860 {
861   myObjectBrowser->parentWidget()->show();
862 }
863
864 //******************************************************
865 void XGUI_Workshop::hideObjectBrowser()
866 {
867   myObjectBrowser->parentWidget()->hide();
868 }
869
870 //******************************************************
871 void XGUI_Workshop::onFeatureTriggered()
872 {
873   QAction* aCmd = dynamic_cast<QAction*>(sender());
874   if (aCmd) {
875     QString aId = salomeConnector()->commandId(aCmd);
876     if (!aId.isNull())
877       myModule->launchOperation(aId);
878   }
879 }
880
881 //******************************************************
882 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
883 {
884   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
885   if (theObj) {
886     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
887     if (aPart) {
888       DocumentPtr aPartDoc = aPart->partDoc();
889       if (aPartDoc) {
890         aMgr->setCurrentDocument(aPartDoc);
891         return;
892       }
893     }
894   } 
895   aMgr->setCurrentDocument(aMgr->rootDocument());
896 }
897
898 //******************************************************
899 void XGUI_Workshop::salomeViewerSelectionChanged()
900 {
901   emit salomeViewerSelection();
902 }
903
904
905 //**************************************************************
906 XGUI_SalomeViewer* XGUI_Workshop::salomeViewer() const 
907
908   return mySalomeConnector->viewer(); 
909 }
910
911 //**************************************************************
912 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
913 {
914   QList<ObjectPtr> aObjects = mySelector->selection()->selectedObjects();
915   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
916     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
917     activatePart(aPart);
918   } else if (theId == "DEACTIVATE_PART_CMD") 
919     activatePart(ResultPartPtr());
920   else if (theId == "DELETE_CMD")
921     deleteObjects(aObjects);
922   else if (theId == "SHOW_CMD")
923     showObjects(aObjects, true);
924   else if (theId == "HIDE_CMD")
925     showObjects(aObjects, false);
926 }
927
928 //**************************************************************
929 void XGUI_Workshop::onWidgetValuesChanged()
930 {
931   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
932   FeaturePtr aFeature = anOperation->feature();
933
934   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
935   //if (aCustom)
936   //  aCustom->storeValue(aFeature);
937
938   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
939   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
940   for (; anIt != aLast; anIt++) {
941     ModuleBase_ModelWidget* aCustom = *anIt;
942     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/ aCustom == aSenderWidget)) {
943       aCustom->storeValue(aFeature);
944     }
945   }
946 }
947
948 //**************************************************************
949 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
950 {
951   changeCurrentDocument(theFeature);
952   myObjectBrowser->activatePart(theFeature);
953 }
954
955 //**************************************************************
956 void XGUI_Workshop::activateLastPart()
957 {
958   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
959   DocumentPtr aDoc = aMgr->rootDocument();
960   std::string aGrpName = ModelAPI_ResultPart::group();
961   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
962   ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
963   if (aPart)
964     activatePart(aPart);
965 }
966
967 //**************************************************************
968 void XGUI_Workshop::deleteObjects(const QList<ObjectPtr>& theList)
969 {
970   QMainWindow* aDesktop = isSalomeMode()? salomeConnector()->desktop() : myMainWindow;
971   QMessageBox::StandardButton aRes = QMessageBox::warning(aDesktop, tr("Delete features"), 
972                                                           tr("Seleted features will be deleted. Continue?"), 
973                                                           QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
974   // ToDo: definbe deleting method
975   if (aRes == QMessageBox::Yes) {
976     PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
977     aMgr->rootDocument()->startOperation();
978     foreach (ObjectPtr aObj, theList) {
979       ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
980       if (aPart) {
981         DocumentPtr aDoc = aPart->document();
982         if (aDoc == aMgr->currentDocument()) {
983           aDoc->close();
984         }
985         //aMgr->rootDocument()->removeFeature(aPart->owner());
986       } else {
987         FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
988         if (aFeature)
989           aObj->document()->removeFeature(aFeature);
990       }
991     }
992     myDisplayer->updateViewer();
993     aMgr->rootDocument()->finishOperation();
994   }
995 }
996
997 //**************************************************************
998 void XGUI_Workshop::showObjects(const QList<ObjectPtr>& theList, bool isVisible)
999 {
1000   foreach (ObjectPtr aObj, theList) {
1001     ResultPtr aRes = boost::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1002     if (aRes) {
1003       if (isVisible) {
1004         myDisplayer->display(aRes, false);
1005       } else {
1006         myDisplayer->erase(aRes, false);
1007       }
1008     }
1009   }
1010   myDisplayer->updateViewer();
1011 }
1012
1013 //**************************************************************
1014 void XGUI_Workshop::updateCommandsOnViewSelection()
1015 {
1016   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1017   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1018   XGUI_Selection* aSelection = mySelector->selection();
1019   if (aSelection->getSelected().size() == 0)
1020     return;
1021
1022   QList<QAction*> aActions = getModuleCommands();
1023   foreach(QAction* aAction, aActions) {
1024     QString aId = aAction->data().toString();
1025     const ModelAPI_Validator* aValidator = aFactory->validator(aId.toStdString());
1026     if (aValidator) {
1027       const ModuleBase_SelectionValidator* aSelValidator = 
1028         dynamic_cast<const ModuleBase_SelectionValidator*>(aValidator);
1029       if (aSelValidator) {
1030         aAction->setEnabled(aSelValidator->isValid(aSelection));
1031       }
1032     }
1033   }
1034 }
1035
1036
1037 //**************************************************************
1038 void XGUI_Workshop::registerValidators() const
1039 {
1040   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1041   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1042
1043   aFactory->registerValidator("ModuleBase_ResultPointValidator", new ModuleBase_ResultPointValidator);
1044   aFactory->registerValidator("ModuleBase_ResultLineValidator", new ModuleBase_ResultLineValidator);
1045   aFactory->registerValidator("ModuleBase_ResultArcValidator", new ModuleBase_ResultArcValidator);
1046 }
1047
1048
1049 //**************************************************************
1050 void XGUI_Workshop::displayAllResults()
1051 {
1052   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1053   DocumentPtr aRootDoc = aMgr->rootDocument();
1054   displayDocumentResults(aRootDoc);
1055   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1056     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1057     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1058     displayDocumentResults(aPart->partDoc());
1059   }
1060   myDisplayer->updateViewer();
1061 }
1062
1063 //**************************************************************
1064 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1065 {
1066   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1067   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1068 }
1069
1070 //**************************************************************
1071 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1072 {
1073   for (int i = 0; i < theDoc->size(theGroup); i++)
1074     myDisplayer->display(theDoc->object(theGroup, i), false);
1075 }