]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
0ca48658f2fdde9b5e57a5016e1427497a5813ea
[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   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
309     ObjectPtr aObj = (*aIt);
310     if (!aObj->data() )
311       myDisplayer->erase(aObj, false);
312     else {
313       if (myDisplayer->isVisible(aObj)) // TODO VSV: Correction sketch drawing
314         myDisplayer->display(aObj, false); // In order to update presentation
315     }
316   }
317   myDisplayer->updateViewer();
318 }
319
320 //******************************************************
321 void XGUI_Workshop::onFeatureCreatedMsg(const ModelAPI_ObjectUpdatedMessage* theMsg)
322 {
323   std::set<ObjectPtr> aObjects = theMsg->objects();
324
325   std::set<ObjectPtr>::const_iterator aIt;
326   bool aHasPart = false;
327   bool isDisplayed = false;
328   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
329     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(*aIt);
330     if (aPart) {
331       aHasPart = true;
332     } else {
333       ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
334       if (aOperation->hasObject(*aIt)) { // Display only current operation results
335         myDisplayer->display(*aIt, false);
336         isDisplayed = true;
337       }
338     }
339   }
340   if (isDisplayed)
341     myDisplayer->updateViewer();
342   if (aHasPart) {
343     //The created part will be created in Object Browser later and we have to activate it
344     // only when it is created everywere
345     QTimer::singleShot(50, this, SLOT(activateLastPart()));
346   }
347 }
348
349 //******************************************************
350 void XGUI_Workshop::onObjectDeletedMsg(const ModelAPI_ObjectDeletedMessage* theMsg)
351 {
352   //std::set<ObjectPtr> aFeatures = theMsg->objects();
353 }
354  
355 //******************************************************
356 void XGUI_Workshop::onOperationStarted()
357 {
358   ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
359
360   if(aOperation->getDescription()->hasXmlRepresentation()) { //!< No need for property panel
361     connectWithOperation(aOperation);
362
363     showPropertyPanel();
364     QString aXmlRepr = aOperation->getDescription()->xmlRepresentation();
365     ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(), myModuleConnector);
366
367     myPropertyPanel->cleanContent();
368     aFactory.createWidget(myPropertyPanel->contentWidget());
369     
370     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
371     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
372     ModuleBase_ModelWidget* aWidget;
373     for (; anIt != aLast; anIt++) {
374       aWidget = *anIt;
375       //QObject::connect(aWidget, SIGNAL(valuesChanged()),  aOperation, SLOT(storeCustomValue()));
376       QObject::connect(aWidget, SIGNAL(valuesChanged()),
377                        this, SLOT(onWidgetValuesChanged()));
378       // Init default values
379       if (!aOperation->isEditOperation() && aWidget->hasDefaultValue()) {
380         aWidget->storeValue(aOperation->feature());
381       }
382     }
383
384     myPropertyPanel->setModelWidgets(aWidgets);
385     myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
386   }
387   updateCommandStatus();
388 }
389
390 //******************************************************
391 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
392 {
393   //!< No need for property panel
394   updateCommandStatus();
395   hidePropertyPanel();
396   myPropertyPanel->cleanContent();
397 }
398
399 /*
400  *
401  */
402 void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
403 {
404   if (!theMessage) {
405 #ifdef _DEBUG
406     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
407 #endif
408     return;
409   }
410   // Remember features icons
411   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
412
413   //Find or create Workbench
414   QString aWchName = QString::fromStdString(theMessage->workbenchId());
415   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
416   bool isUsePropPanel = theMessage->isUseInput();
417   QString aId = QString::fromStdString(theMessage->id());
418   if (isSalomeMode()) {
419     QAction* aAction = salomeConnector()->addFeature(aWchName,
420                               aId,
421                               QString::fromStdString(theMessage->text()),
422                               QString::fromStdString(theMessage->tooltip()),
423                               QIcon(theMessage->icon().c_str()),
424                               QKeySequence(), isUsePropPanel);
425     salomeConnector()->setNestedActions(aId, aNestedFeatures.split(" "));
426     myActionsMgr->addCommand(aAction);
427     myModule->featureCreated(aAction);
428   } else {
429
430     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
431     XGUI_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
432     if (!aPage) {
433       aPage = addWorkbench(aWchName);
434     }
435     //Find or create Group
436     QString aGroupName = QString::fromStdString(theMessage->groupId());
437     XGUI_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
438     if (!aGroup) {
439       aGroup = aPage->addGroup(aGroupName);
440     }
441     //Create feature...
442     XGUI_Command* aCommand = aGroup->addFeature(aId,
443                                                 QString::fromStdString(theMessage->text()),
444                                                 QString::fromStdString(theMessage->tooltip()),
445                                                 QIcon(theMessage->icon().c_str()),
446                                                 QKeySequence(), isUsePropPanel);
447     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
448     myActionsMgr->addCommand(aCommand);
449     myModule->featureCreated(aCommand);
450   }
451 }
452
453 /*
454  * Makes a signal/slot connections between Property Panel
455  * and given operation. The given operation becomes a
456  * current operation and previous operation if exists
457  */
458 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
459 {
460   QAction* aCommand = 0;
461   if (isSalomeMode()) {
462     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
463   } else {
464     XGUI_MainMenu* aMenu = myMainWindow->menuObject();
465     aCommand = aMenu->feature(theOperation->getDescription()->operationId());
466   }
467   //Abort operation on uncheck the command
468   connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
469 }
470
471 /*
472  * Saves document with given name.
473  */
474 void XGUI_Workshop::saveDocument(QString theName)
475 {
476   QApplication::restoreOverrideCursor();
477   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
478   DocumentPtr aDoc = aMgr->rootDocument();
479   aDoc->save(theName.toLatin1().constData());
480   QApplication::restoreOverrideCursor();
481 }
482
483 //******************************************************
484 void XGUI_Workshop::onExit()
485 {
486   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
487   DocumentPtr aDoc = aMgr->rootDocument();
488   if(aDoc->isModified()) {
489     int anAnswer = QMessageBox::question(
490         myMainWindow, tr("Save current file"),
491         tr("The document is modified, save before exit?"),
492         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
493     if(anAnswer == QMessageBox::Save) {
494       bool saved = onSave();
495       if(!saved) {
496         return;
497       }
498     } else if (anAnswer == QMessageBox::Cancel) {
499       return;
500     }
501   }
502   qApp->exit();
503 }
504
505 //******************************************************
506 void XGUI_Workshop::onNew()
507 {
508   QApplication::setOverrideCursor(Qt::WaitCursor);
509   if (objectBrowser() == 0) {
510     createDockWidgets();
511     mySelector->connectViewers();
512   }
513   myViewerProxy->connectToViewer();
514   showObjectBrowser();
515   if (!isSalomeMode()) {
516     myMainWindow->showPythonConsole();
517     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
518     aWnd->showMaximized();
519     updateCommandStatus();
520   }
521   myContextMenuMgr->connectViewer();
522   QApplication::restoreOverrideCursor();
523 }
524
525 //******************************************************
526 void XGUI_Workshop::onOpen()
527 {
528   //save current file before close if modified
529   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
530   DocumentPtr aDoc = aMgr->rootDocument();
531   if(aDoc->isModified()) {
532     //TODO(sbh): re-launch the app?
533     int anAnswer = QMessageBox::question(
534         myMainWindow, tr("Save current file"),
535         tr("The document is modified, save before opening another?"),
536         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
537     if(anAnswer == QMessageBox::Save) {
538       onSave();
539     } else if (anAnswer == QMessageBox::Cancel) {
540       return;
541     }
542     aDoc->close();
543     myCurrentDir = "";
544   }
545
546   //show file dialog, check if readable and open
547   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
548   if(myCurrentDir.isEmpty())
549     return;
550   QFileInfo aFileInfo(myCurrentDir);
551   if(!aFileInfo.exists() || !aFileInfo.isReadable()) {
552     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
553     myCurrentDir = "";
554     return;
555   }
556   QApplication::setOverrideCursor(Qt::WaitCursor);
557   aDoc->load(myCurrentDir.toLatin1().constData());
558   updateCommandStatus();
559   myObjectBrowser->rebuildDataTree();
560   QApplication::restoreOverrideCursor();
561 }
562
563 //******************************************************
564 bool XGUI_Workshop::onSave()
565 {
566   if(myCurrentDir.isEmpty()) {
567     return onSaveAs();
568   }
569   saveDocument(myCurrentDir);
570   updateCommandStatus();
571   return true;
572 }
573
574 //******************************************************
575 bool XGUI_Workshop::onSaveAs()
576 {
577   QFileDialog dialog(mainWindow());
578   dialog.setWindowTitle(tr("Select directory to save files..."));
579   dialog.setFileMode(QFileDialog::Directory);
580   dialog.setFilter(tr("Folders (*)"));
581   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
582   dialog.setViewMode(QFileDialog::Detail);
583
584   if(!dialog.exec()) {
585     return false;
586   }
587   QString aTempDir = dialog.selectedFiles().first();
588   QDir aDir(aTempDir);
589   if(aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot|QDir::AllEntries).isEmpty()) {
590     int answer = QMessageBox::question(myMainWindow,
591                                        //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
592                                        tr("Save"),
593                                        tr("The folder already contains some files, save anyway?"),
594                                        QMessageBox::Save|QMessageBox::Cancel);
595     if(answer == QMessageBox::Cancel) {
596       return false;
597     }
598   }
599   myCurrentDir = aTempDir;
600   return onSave();
601 }
602
603 //******************************************************
604 void XGUI_Workshop::onUndo()
605 {
606   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
607   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
608   DocumentPtr aDoc = aMgr->rootDocument();
609   if (aDoc->isOperation())
610     operationMgr()->abortOperation();
611   aDoc->undo();
612   updateCommandStatus();
613 }
614
615 //******************************************************
616 void XGUI_Workshop::onRedo()
617 {
618   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
619   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
620   DocumentPtr aDoc = aMgr->rootDocument();
621   if (aDoc->isOperation())
622     operationMgr()->abortOperation();
623   aDoc->redo();
624   updateCommandStatus();
625 }
626
627 //******************************************************
628 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
629 {
630   QString libName =
631       QString::fromStdString(library(theModule.toStdString()));
632   if (libName.isEmpty()) {
633     qWarning(
634     qPrintable( tr( "Information about module \"%1\" doesn't exist." ).arg( theModule ) ));
635     return 0;
636   }
637
638   QString err;
639   CREATE_FUNC crtInst = 0;
640
641 #ifdef WIN32
642   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
643   if (!modLib) {
644     LPVOID lpMsgBuf;
645     ::FormatMessage(
646         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
647         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
648     QString aMsg((char*) &lpMsgBuf);
649     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
650     ::LocalFree(lpMsgBuf);
651   } else {
652     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
653     if (!crtInst) {
654       LPVOID lpMsgBuf;
655       ::FormatMessage(
656           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
657               | FORMAT_MESSAGE_IGNORE_INSERTS,
658           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
659       QString aMsg((char*) &lpMsgBuf);
660       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
661       ::LocalFree(lpMsgBuf);
662     }
663   }
664 #else
665   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
666   if ( !modLib ) {
667     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
668   } else {
669     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
670     if ( !crtInst ) {
671       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
672     }
673   }
674 #endif
675
676   ModuleBase_IModule* aModule = crtInst ? crtInst(this) : 0;
677
678   if (!err.isEmpty()) {
679     if (mainWindow()) {
680       QMessageBox::warning(mainWindow(), tr("Error"), err);
681     } else {
682       qWarning( qPrintable( err ));
683     }
684   }
685   return aModule;
686 }
687
688 //******************************************************
689 bool XGUI_Workshop::activateModule()
690 {
691   Config_ModuleReader aModuleReader;
692   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
693   myModule = loadModule(moduleName);
694   if (!myModule)
695     return false;
696   myModule->createFeatures();
697   myActionsMgr->update();
698   return true;
699 }
700
701 //******************************************************
702 void XGUI_Workshop::updateCommandStatus()
703 {
704   QList<QAction*> aCommands;
705   if (isSalomeMode()) { // update commands in SALOME mode
706     aCommands = salomeConnector()->commandList();
707   } else {
708     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
709     foreach (XGUI_Command* aCmd, aMenuBar->features())
710       aCommands.append(aCmd);
711   }
712   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
713   if (aMgr->hasRootDocument()) {
714     QAction* aUndoCmd;
715     QAction* aRedoCmd;
716     foreach(QAction* aCmd, aCommands) {
717       QString aId = aCmd->data().toString();
718       if (aId == "UNDO_CMD")
719         aUndoCmd = aCmd;
720       else if (aId == "REDO_CMD")
721         aRedoCmd = aCmd;
722       else // Enable all commands
723         aCmd->setEnabled(true);
724     }
725     DocumentPtr aDoc = aMgr->rootDocument();
726     aUndoCmd->setEnabled(aDoc->canUndo());
727     aRedoCmd->setEnabled(aDoc->canRedo());
728   } else {
729     foreach(QAction* aCmd, aCommands) {
730       QString aId = aCmd->data().toString();
731       if (aId == "NEW_CMD")
732         aCmd->setEnabled(true);
733       else if (aId == "EXIT_CMD")
734         aCmd->setEnabled(true);
735       else 
736         aCmd->setEnabled(false);
737     }
738   }
739   myActionsMgr->update();
740 }
741
742 //******************************************************
743 QList<QAction*> XGUI_Workshop::getModuleCommands() const
744 {
745   QList<QAction*> aCommands;
746   if (isSalomeMode()) { // update commands in SALOME mode
747     aCommands = salomeConnector()->commandList();
748   } else {
749     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
750     foreach (XGUI_Workbench* aWb, aMenuBar->workbenches()) {
751       if (aWb != aMenuBar->generalPage()) {
752         foreach(XGUI_Command* aCmd, aWb->features())
753           aCommands.append(aCmd);
754       }
755     }
756   }
757   return aCommands;
758 }
759
760 //******************************************************
761 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
762 {
763   QDockWidget* aObjDock = new QDockWidget(theParent);
764   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
765   aObjDock->setWindowTitle(tr("Object browser"));
766   aObjDock->setStyleSheet("::title { position: relative; padding-left: 5px; text-align: left center }");
767   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
768   connect(myObjectBrowser, SIGNAL(activePartChanged(FeaturePtr)), this, SLOT(changeCurrentDocument(FeaturePtr)));
769   aObjDock->setWidget(myObjectBrowser);
770
771   myContextMenuMgr->connectObjectBrowser();
772   return aObjDock;
773 }
774
775 //******************************************************
776 /*
777  * Creates dock widgets, places them in corresponding area
778  * and tabifies if necessary.
779  */
780 void XGUI_Workshop::createDockWidgets()
781 {
782   QMainWindow* aDesktop = isSalomeMode()? salomeConnector()->desktop() :
783                                           myMainWindow;
784   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
785   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
786   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
787   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
788   hidePropertyPanel(); //<! Invisible by default
789   hideObjectBrowser();
790   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
791
792   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_OK);
793   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
794   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_CANCEL);
795   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
796
797   connect(myPropertyPanel, SIGNAL(keyReleased(const std::string&, QKeyEvent*)),
798           myOperationMgr, SLOT(onKeyReleased(const std::string&, QKeyEvent*)));
799
800   connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
801           myOperationMgr, SLOT(onWidgetActivated(ModuleBase_ModelWidget*)));
802   connect(myOperationMgr, SIGNAL(activateNextWidget(ModuleBase_ModelWidget*)),
803           myPropertyPanel, SLOT(onActivateNextWidget(ModuleBase_ModelWidget*)));
804 }
805
806 //******************************************************
807 void XGUI_Workshop::showPropertyPanel()
808 {
809   QAction* aViewAct = myPropertyPanel->toggleViewAction();
810   //<! Restore ability to close panel from the window's menu
811   aViewAct->setEnabled(true);
812   myPropertyPanel->show();
813   myPropertyPanel->raise();
814 }
815
816 //******************************************************
817 void XGUI_Workshop::hidePropertyPanel()
818 {
819   QAction* aViewAct = myPropertyPanel->toggleViewAction();
820   //<! Do not allow to show empty property panel
821   aViewAct->setEnabled(false);
822   myPropertyPanel->hide();
823 }
824
825 //******************************************************
826 void XGUI_Workshop::showObjectBrowser()
827 {
828   myObjectBrowser->parentWidget()->show();
829 }
830
831 //******************************************************
832 void XGUI_Workshop::hideObjectBrowser()
833 {
834   myObjectBrowser->parentWidget()->hide();
835 }
836
837 //******************************************************
838 void XGUI_Workshop::onFeatureTriggered()
839 {
840   QAction* aCmd = dynamic_cast<QAction*>(sender());
841   if (aCmd) {
842     QString aId = salomeConnector()->commandId(aCmd);
843     if (!aId.isNull())
844       myModule->launchOperation(aId);
845   }
846 }
847
848 //******************************************************
849 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
850 {
851   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
852   if (theObj) {
853     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
854     if (aPart) {
855       DocumentPtr aPartDoc = aPart->partDoc();
856       if (aPartDoc) {
857         aMgr->setCurrentDocument(aPartDoc);
858         return;
859       }
860     }
861   } 
862   aMgr->setCurrentDocument(aMgr->rootDocument());
863 }
864
865 //******************************************************
866 void XGUI_Workshop::salomeViewerSelectionChanged()
867 {
868   emit salomeViewerSelection();
869 }
870
871
872 //**************************************************************
873 XGUI_SalomeViewer* XGUI_Workshop::salomeViewer() const 
874
875   return mySalomeConnector->viewer(); 
876 }
877
878 //**************************************************************
879 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
880 {
881   QList<ObjectPtr> aObjects = mySelector->selection()->selectedObjects();
882   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
883     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
884     activatePart(aPart);
885   } else if (theId == "DEACTIVATE_PART_CMD") 
886     activatePart(ResultPartPtr());
887   else if (theId == "DELETE_CMD")
888     deleteObjects(aObjects);
889   else if (theId == "SHOW_CMD")
890     showObjects(aObjects, true);
891   else if (theId == "HIDE_CMD")
892     showObjects(aObjects, false);
893 }
894
895 //**************************************************************
896 void XGUI_Workshop::onWidgetValuesChanged()
897 {
898   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
899   FeaturePtr aFeature = anOperation->feature();
900
901   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
902   //if (aCustom)
903   //  aCustom->storeValue(aFeature);
904
905   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
906   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
907   for (; anIt != aLast; anIt++) {
908     ModuleBase_ModelWidget* aCustom = *anIt;
909     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/ aCustom == aSenderWidget)) {
910       aCustom->storeValue(aFeature);
911     }
912   }
913 }
914
915 //**************************************************************
916 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
917 {
918   changeCurrentDocument(theFeature);
919   myObjectBrowser->activatePart(theFeature);
920 }
921
922 //**************************************************************
923 void XGUI_Workshop::activateLastPart()
924 {
925   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
926   DocumentPtr aDoc = aMgr->rootDocument();
927   std::string aGrpName = ModelAPI_ResultPart::group();
928   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
929   ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
930   if (aPart)
931     activatePart(aPart);
932 }
933
934 //**************************************************************
935 void XGUI_Workshop::deleteObjects(const QList<ObjectPtr>& theList)
936 {
937   QMainWindow* aDesktop = isSalomeMode()? salomeConnector()->desktop() : myMainWindow;
938   QMessageBox::StandardButton aRes = QMessageBox::warning(aDesktop, tr("Delete features"), 
939                                                           tr("Seleted features will be deleted. Continue?"), 
940                                                           QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
941   // ToDo: definbe deleting method
942   if (aRes == QMessageBox::Yes) {
943     PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
944     aMgr->rootDocument()->startOperation();
945     foreach (ObjectPtr aObj, theList) {
946       ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
947       if (aPart) {
948         DocumentPtr aDoc = aPart->document();
949         if (aDoc == aMgr->currentDocument()) {
950           aDoc->close();
951         }
952         //aMgr->rootDocument()->removeFeature(aPart->owner());
953       } else {
954         FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
955         if (aFeature)
956           aObj->document()->removeFeature(aFeature);
957       }
958     }
959     myDisplayer->updateViewer();
960     aMgr->rootDocument()->finishOperation();
961   }
962 }
963
964 //**************************************************************
965 void XGUI_Workshop::showObjects(const QList<ObjectPtr>& theList, bool isVisible)
966 {
967   foreach (ObjectPtr aObj, theList) {
968     ResultPtr aRes = boost::dynamic_pointer_cast<ModelAPI_Result>(aObj);
969     if (aRes) {
970       if (isVisible) {
971         myDisplayer->display(aRes, false);
972       } else {
973         myDisplayer->erase(aRes, false);
974       }
975     }
976   }
977   myDisplayer->updateViewer();
978 }
979
980 //**************************************************************
981 void XGUI_Workshop::updateCommandsOnViewSelection()
982 {
983   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
984   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
985   XGUI_Selection* aSelection = mySelector->selection();
986
987   QList<QAction*> aActions = getModuleCommands();
988   foreach(QAction* aAction, aActions) {
989     QString aId = aAction->data().toString();
990     const ModelAPI_Validator* aValidator = aFactory->validator(aId.toStdString());
991     if (aValidator) {
992       const ModuleBase_SelectionValidator* aSelValidator = 
993         dynamic_cast<const ModuleBase_SelectionValidator*>(aValidator);
994       if (aSelValidator) {
995         aAction->setEnabled(aSelValidator->isValid(aSelection));
996       }
997     }
998   }
999 }