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