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