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