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