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