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