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