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