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