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