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