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