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