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