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