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