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