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