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