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