Salome HOME
Merge branch 'master' of newgeom:newgeom.git
[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   if (this->isSalomeMode()) 
410     aOperation->setNestedFeatures(mySalomeConnector->nestedActions(aOperation->id()));
411   else 
412     aOperation->setNestedFeatures(myActionsMgr->nestedCommands(aOperation->id()));
413   
414   if (aOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
415     connectWithOperation(aOperation);
416
417     showPropertyPanel();
418     QString aXmlRepr = aOperation->getDescription()->xmlRepresentation();
419     ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
420                                                                  myModuleConnector);
421
422     myPropertyPanel->cleanContent();
423     aFactory.createWidget(myPropertyPanel->contentWidget());
424
425     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
426     QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
427     ModuleBase_ModelWidget* aWidget;
428     for (; anIt != aLast; anIt++) {
429       aWidget = *anIt;
430       aWidget->setFeature(aOperation->feature());
431       //QObject::connect(aWidget, SIGNAL(valuesChanged()),  aOperation, SLOT(storeCustomValue()));
432       QObject::connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
433       // Init default values
434       if (!aOperation->isEditOperation()) {
435         //aWidget->storeValue(aOperation->feature());
436
437         aWidget->storeValue();
438       }
439     }
440
441     myPropertyPanel->setModelWidgets(aWidgets);
442     myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
443   }
444   updateCommandStatus();
445 }
446
447 //******************************************************
448 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
449 {
450   //!< No need for property panel
451   updateCommandStatus();
452   hidePropertyPanel();
453   myPropertyPanel->cleanContent();
454 }
455
456 /*
457  *
458  */
459 void XGUI_Workshop::addFeature(const Config_FeatureMessage* theMessage)
460 {
461   if (!theMessage) {
462 #ifdef _DEBUG
463     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
464 #endif
465     return;
466   }
467   // Remember features icons
468   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
469
470   //Find or create Workbench
471   QString aWchName = QString::fromStdString(theMessage->workbenchId());
472   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
473   bool isUsePropPanel = theMessage->isUseInput();
474   QString aFeatureId = QString::fromStdString(theMessage->id());
475   if (isSalomeMode()) {
476     QAction* aAction = salomeConnector()->addFeature(aWchName, aFeatureId,
477                                                      QString::fromStdString(theMessage->text()),
478                                                      QString::fromStdString(theMessage->tooltip()),
479                                                      QIcon(theMessage->icon().c_str()),
480                                                      QKeySequence(), isUsePropPanel);
481     salomeConnector()->setNestedActions(aFeatureId, aNestedFeatures.split(" ", QString::SkipEmptyParts));
482     myActionsMgr->addCommand(aAction);
483     myModule->featureCreated(aAction);
484   } else {
485
486     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
487     XGUI_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
488     if (!aPage) {
489       aPage = addWorkbench(aWchName);
490     }
491     //Find or create Group
492     QString aGroupName = QString::fromStdString(theMessage->groupId());
493     XGUI_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
494     if (!aGroup) {
495       aGroup = aPage->addGroup(aGroupName);
496     }
497     // Check if hotkey sequence is already defined:
498     QKeySequence aHotKey = myActionsMgr->registerShortcut(
499         QString::fromStdString(theMessage->keysequence()));
500     // Create feature...
501     XGUI_Command* aCommand = aGroup->addFeature(aFeatureId,
502                                                 QString::fromStdString(theMessage->text()),
503                                                 QString::fromStdString(theMessage->tooltip()),
504                                                 QIcon(theMessage->icon().c_str()), aHotKey,
505                                                 isUsePropPanel);
506     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
507     myActionsMgr->addCommand(aCommand);
508     myModule->featureCreated(aCommand);
509   }
510 }
511
512 /*
513  * Makes a signal/slot connections between Property Panel
514  * and given operation. The given operation becomes a
515  * current operation and previous operation if exists
516  */
517 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
518 {
519   QAction* aCommand = 0;
520   if (isSalomeMode()) {
521     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
522   } else {
523     XGUI_MainMenu* aMenu = myMainWindow->menuObject();
524     aCommand = aMenu->feature(theOperation->getDescription()->operationId());
525   }
526   //Abort operation on uncheck the command
527   if (aCommand)
528     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
529 }
530
531 /*
532  * Saves document with given name.
533  */
534 void XGUI_Workshop::saveDocument(QString theName)
535 {
536   QApplication::restoreOverrideCursor();
537   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
538   DocumentPtr aDoc = aMgr->rootDocument();
539   aDoc->save(theName.toLatin1().constData());
540   QApplication::restoreOverrideCursor();
541 }
542
543 //******************************************************
544 void XGUI_Workshop::onExit()
545 {
546   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
547   DocumentPtr aDoc = aMgr->rootDocument();
548   if (aDoc->isModified()) {
549     int anAnswer = QMessageBox::question(
550         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
551         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
552     if (anAnswer == QMessageBox::Save) {
553       bool saved = onSave();
554       if (!saved) {
555         return;
556       }
557     } else if (anAnswer == QMessageBox::Cancel) {
558       return;
559     }
560   }
561   qApp->exit();
562 }
563
564 //******************************************************
565 void XGUI_Workshop::onNew()
566 {
567   QApplication::setOverrideCursor(Qt::WaitCursor);
568   if (objectBrowser() == 0) {
569     createDockWidgets();
570     mySelector->connectViewers();
571   }
572   myViewerProxy->connectToViewer();
573   showObjectBrowser();
574   if (!isSalomeMode()) {
575     myMainWindow->showPythonConsole();
576     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
577     aWnd->showMaximized();
578     updateCommandStatus();
579   }
580   myContextMenuMgr->connectViewer();
581   QApplication::restoreOverrideCursor();
582 }
583
584 //******************************************************
585 void XGUI_Workshop::onOpen()
586 {
587   //save current file before close if modified
588   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
589   DocumentPtr aDoc = aMgr->rootDocument();
590   if (aDoc->isModified()) {
591     //TODO(sbh): re-launch the app?
592     int anAnswer = QMessageBox::question(
593         myMainWindow, tr("Save current file"),
594         tr("The document is modified, save before opening another?"),
595         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
596     if (anAnswer == QMessageBox::Save) {
597       onSave();
598     } else if (anAnswer == QMessageBox::Cancel) {
599       return;
600     }
601     aDoc->close();
602     myCurrentDir = "";
603   }
604
605   //show file dialog, check if readable and open
606   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
607   if (myCurrentDir.isEmpty())
608     return;
609   QFileInfo aFileInfo(myCurrentDir);
610   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
611     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
612     myCurrentDir = "";
613     return;
614   }
615   QApplication::setOverrideCursor(Qt::WaitCursor);
616   aDoc->load(myCurrentDir.toLatin1().constData());
617   myObjectBrowser->rebuildDataTree();
618   displayAllResults();
619   updateCommandStatus();
620   QApplication::restoreOverrideCursor();
621 }
622
623 //******************************************************
624 bool XGUI_Workshop::onSave()
625 {
626   if (myCurrentDir.isEmpty()) {
627     return onSaveAs();
628   }
629   saveDocument(myCurrentDir);
630   updateCommandStatus();
631   return true;
632 }
633
634 //******************************************************
635 bool XGUI_Workshop::onSaveAs()
636 {
637   QFileDialog dialog(mainWindow());
638   dialog.setWindowTitle(tr("Select directory to save files..."));
639   dialog.setFileMode(QFileDialog::Directory);
640   dialog.setFilter(tr("Folders (*)"));
641   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
642   dialog.setViewMode(QFileDialog::Detail);
643
644   if (!dialog.exec()) {
645     return false;
646   }
647   QString aTempDir = dialog.selectedFiles().first();
648   QDir aDir(aTempDir);
649   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
650     int answer = QMessageBox::question(
651         myMainWindow,
652         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
653         tr("Save"),
654         tr("The folder already contains some files, save anyway?"),
655         QMessageBox::Save | QMessageBox::Cancel);
656     if (answer == QMessageBox::Cancel) {
657       return false;
658     }
659   }
660   myCurrentDir = aTempDir;
661   return onSave();
662 }
663
664 //******************************************************
665 void XGUI_Workshop::onUndo()
666 {
667   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
668   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
669   DocumentPtr aDoc = aMgr->rootDocument();
670   if (aDoc->isOperation())
671     operationMgr()->abortOperation();
672   aDoc->undo();
673   updateCommandStatus();
674 }
675
676 //******************************************************
677 void XGUI_Workshop::onRedo()
678 {
679   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
680   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
681   DocumentPtr aDoc = aMgr->rootDocument();
682   if (aDoc->isOperation())
683     operationMgr()->abortOperation();
684   aDoc->redo();
685   updateCommandStatus();
686 }
687
688 //******************************************************
689 void XGUI_Workshop::onPreferences()
690 {
691   XGUI_Prefs aModif;
692   XGUI_Preferences::editPreferences(aModif);
693   if (aModif.size() > 0) {
694     QString aSection;
695     foreach (XGUI_Pref aPref, aModif)
696     {
697       aSection = aPref.first;
698       if (aSection == XGUI_Preferences::VIEWER_SECTION) {
699         if (!isSalomeMode())
700           myMainWindow->viewer()->updateFromResources();
701       } else if (aSection == XGUI_Preferences::MENU_SECTION) {
702         if (!isSalomeMode())
703           myMainWindow->menuObject()->updateFromResources();
704       }
705     }
706   }
707 }
708
709 //******************************************************
710 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
711 {
712   QString libName = QString::fromStdString(library(theModule.toStdString()));
713   if (libName.isEmpty()) {
714     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
715     return 0;
716   }
717
718   QString err;
719   CREATE_FUNC crtInst = 0;
720
721 #ifdef WIN32
722   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
723   if (!modLib) {
724     LPVOID lpMsgBuf;
725     ::FormatMessage(
726         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
727         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
728     QString aMsg((char*) &lpMsgBuf);
729     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
730     ::LocalFree(lpMsgBuf);
731   } else {
732     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
733     if (!crtInst) {
734       LPVOID lpMsgBuf;
735       ::FormatMessage(
736           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
737               | FORMAT_MESSAGE_IGNORE_INSERTS,
738           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
739       QString aMsg((char*) &lpMsgBuf);
740       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
741       ::LocalFree(lpMsgBuf);
742     }
743   }
744 #else
745   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
746   if ( !modLib ) {
747     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
748   } else {
749     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
750     if ( !crtInst ) {
751       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
752     }
753   }
754 #endif
755
756   ModuleBase_IModule* aModule = crtInst ? crtInst(this) : 0;
757
758   if (!err.isEmpty()) {
759     if (mainWindow()) {
760       QMessageBox::warning(mainWindow(), tr("Error"), err);
761     } else {
762       qWarning(qPrintable(err));
763     }
764   }
765   return aModule;
766 }
767
768 //******************************************************
769 bool XGUI_Workshop::activateModule()
770 {
771   Config_ModuleReader aModuleReader;
772   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
773   myModule = loadModule(moduleName);
774   if (!myModule)
775     return false;
776   myModule->createFeatures();
777   myActionsMgr->update();
778   return true;
779 }
780
781 //******************************************************
782 void XGUI_Workshop::updateCommandStatus()
783 {
784   QList<QAction*> aCommands;
785   if (isSalomeMode()) {  // update commands in SALOME mode
786     aCommands = salomeConnector()->commandList();
787   } else {
788     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
789     foreach (XGUI_Command* aCmd, aMenuBar->features())
790       aCommands.append(aCmd);
791   }
792   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
793   if (aMgr->hasRootDocument()) {
794     QAction* aUndoCmd;
795     QAction* aRedoCmd;
796     foreach(QAction* aCmd, aCommands)
797     {
798       QString aId = aCmd->data().toString();
799       if (aId == "UNDO_CMD")
800         aUndoCmd = aCmd;
801       else if (aId == "REDO_CMD")
802         aRedoCmd = aCmd;
803       else
804         // Enable all commands
805         aCmd->setEnabled(true);
806     }
807     DocumentPtr aDoc = aMgr->rootDocument();
808     aUndoCmd->setEnabled(aDoc->canUndo());
809     aRedoCmd->setEnabled(aDoc->canRedo());
810   } else {
811     foreach(QAction* aCmd, aCommands)
812     {
813       QString aId = aCmd->data().toString();
814       if (aId == "NEW_CMD")
815         aCmd->setEnabled(true);
816       else if (aId == "EXIT_CMD")
817         aCmd->setEnabled(true);
818       else
819         aCmd->setEnabled(false);
820     }
821   }
822   myActionsMgr->update();
823 }
824
825 //******************************************************
826 QList<QAction*> XGUI_Workshop::getModuleCommands() const
827 {
828   QList<QAction*> aCommands;
829   if (isSalomeMode()) {  // update commands in SALOME mode
830     aCommands = salomeConnector()->commandList();
831   } else {
832     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
833     foreach(XGUI_Command* aCmd, aMenuBar->features())
834     {
835       aCommands.append(aCmd);
836     }
837   }
838   return aCommands;
839 }
840
841 //******************************************************
842 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
843 {
844   QDockWidget* aObjDock = new QDockWidget(theParent);
845   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
846   aObjDock->setWindowTitle(tr("Object browser"));
847   aObjDock->setStyleSheet(
848       "::title { position: relative; padding-left: 5px; text-align: left center }");
849   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
850   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
851           SLOT(changeCurrentDocument(ObjectPtr)));
852   aObjDock->setWidget(myObjectBrowser);
853
854   myContextMenuMgr->connectObjectBrowser();
855   return aObjDock;
856 }
857
858 //******************************************************
859 /*
860  * Creates dock widgets, places them in corresponding area
861  * and tabifies if necessary.
862  */
863 void XGUI_Workshop::createDockWidgets()
864 {
865   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
866   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
867   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
868   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
869   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
870   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
871   hidePropertyPanel();  //<! Invisible by default
872   hideObjectBrowser();
873   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
874
875   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_OK);
876   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
877   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_CANCEL);
878   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
879 //TODO(sbh): KeyReleasedProblem
880   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
881           SLOT(onKeyReleased(QKeyEvent*)));
882
883   connect(myPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)), myOperationMgr,
884           SLOT(onWidgetActivated(ModuleBase_ModelWidget*)));
885   connect(myOperationMgr, SIGNAL(activateNextWidget(ModuleBase_ModelWidget*)), myPropertyPanel,
886           SLOT(onActivateNextWidget(ModuleBase_ModelWidget*)));
887   connect(myOperationMgr, SIGNAL(operationValidated(bool)), myPropertyPanel,
888           SLOT(setAcceptEnabled(bool)));
889
890 }
891
892 //******************************************************
893 void XGUI_Workshop::showPropertyPanel()
894 {
895   QAction* aViewAct = myPropertyPanel->toggleViewAction();
896   //<! Restore ability to close panel from the window's menu
897   aViewAct->setEnabled(true);
898   myPropertyPanel->show();
899   myPropertyPanel->raise();
900 }
901
902 //******************************************************
903 void XGUI_Workshop::hidePropertyPanel()
904 {
905   QAction* aViewAct = myPropertyPanel->toggleViewAction();
906   //<! Do not allow to show empty property panel
907   aViewAct->setEnabled(false);
908   myPropertyPanel->hide();
909 }
910
911 //******************************************************
912 void XGUI_Workshop::showObjectBrowser()
913 {
914   myObjectBrowser->parentWidget()->show();
915 }
916
917 //******************************************************
918 void XGUI_Workshop::hideObjectBrowser()
919 {
920   myObjectBrowser->parentWidget()->hide();
921 }
922
923 //******************************************************
924 void XGUI_Workshop::onFeatureTriggered()
925 {
926   QAction* aCmd = dynamic_cast<QAction*>(sender());
927   if (aCmd) {
928     QString aId = salomeConnector()->commandId(aCmd);
929     if (!aId.isNull())
930       myModule->launchOperation(aId);
931   }
932 }
933
934 //******************************************************
935 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
936 {
937   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
938   if (theObj) {
939     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
940     if (aPart) {
941       DocumentPtr aPartDoc = aPart->partDoc();
942       if (aPartDoc) {
943         aMgr->setCurrentDocument(aPartDoc);
944         return;
945       }
946     }
947   }
948   aMgr->setCurrentDocument(aMgr->rootDocument());
949 }
950
951 //******************************************************
952 void XGUI_Workshop::salomeViewerSelectionChanged()
953 {
954   emit salomeViewerSelection();
955 }
956
957 //**************************************************************
958 XGUI_SalomeViewer* XGUI_Workshop::salomeViewer() const
959 {
960   return mySalomeConnector->viewer();
961 }
962
963 //**************************************************************
964 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
965 {
966   QList<ObjectPtr> aObjects = mySelector->selection()->selectedObjects();
967   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
968     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
969     activatePart(aPart);
970   } else if (theId == "DEACTIVATE_PART_CMD")
971     activatePart(ResultPartPtr());
972   else if (theId == "DELETE_CMD")
973     deleteObjects(aObjects);
974   else if (theId == "SHOW_CMD")
975     showObjects(aObjects, true);
976   else if (theId == "HIDE_CMD")
977     showObjects(aObjects, false);
978   else if (theId == "SHOW_ONLY_CMD")
979     showOnlyObjects(aObjects);
980 }
981
982 //**************************************************************
983 void XGUI_Workshop::onWidgetValuesChanged()
984 {
985   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
986   FeaturePtr aFeature = anOperation->feature();
987
988   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
989   //if (aCustom)
990   //  aCustom->storeValue(aFeature);
991
992   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
993   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
994   for (; anIt != aLast; anIt++) {
995     ModuleBase_ModelWidget* aCustom = *anIt;
996     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/aCustom == aSenderWidget)) {
997       //aCustom->storeValue(aFeature);
998       aCustom->storeValue();
999     }
1000   }
1001 }
1002
1003 //**************************************************************
1004 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1005 {
1006   if (theFeature)
1007     theFeature->activate();
1008   changeCurrentDocument(theFeature);
1009   myObjectBrowser->activatePart(theFeature);
1010 }
1011
1012 //**************************************************************
1013 void XGUI_Workshop::activateLastPart()
1014 {
1015   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1016   DocumentPtr aDoc = aMgr->rootDocument();
1017   std::string aGrpName = ModelAPI_ResultPart::group();
1018   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1019   ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1020   if (aPart)
1021     activatePart(aPart);
1022 }
1023
1024 //**************************************************************
1025 void XGUI_Workshop::deleteObjects(const QList<ObjectPtr>& theList)
1026 {
1027   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1028   QMessageBox::StandardButton aRes = QMessageBox::warning(
1029       aDesktop, tr("Delete features"), tr("Seleted features will be deleted. Continue?"),
1030       QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1031   // ToDo: definbe deleting method
1032   if (aRes == QMessageBox::Yes) {
1033     PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1034     aMgr->rootDocument()->startOperation();
1035     foreach (ObjectPtr aObj, theList)
1036     {
1037       ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1038       if (aPart) {
1039         DocumentPtr aDoc = aPart->document();
1040         if (aDoc == aMgr->currentDocument()) {
1041           aDoc->close();
1042         }
1043         //aMgr->rootDocument()->removeFeature(aPart->owner());
1044       } else {
1045         FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1046         if (aFeature)
1047           aObj->document()->removeFeature(aFeature);
1048       }
1049     }
1050     myDisplayer->updateViewer();
1051     aMgr->rootDocument()->finishOperation();
1052   }
1053 }
1054
1055 //**************************************************************
1056 void XGUI_Workshop::showObjects(const QList<ObjectPtr>& theList, bool isVisible)
1057 {
1058   foreach (ObjectPtr aObj, theList)
1059   {
1060     ResultPtr aRes = boost::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1061     if (aRes) {
1062       if (isVisible) {
1063         myDisplayer->display(aRes, false);
1064       } else {
1065         myDisplayer->erase(aRes, false);
1066       }
1067     }
1068   }
1069   myDisplayer->updateViewer();
1070 }
1071
1072 //**************************************************************
1073 void XGUI_Workshop::showOnlyObjects(const QList<ObjectPtr>& theList)
1074 {
1075   myDisplayer->eraseAll(false);
1076   showObjects(theList, true);
1077 }
1078
1079
1080 //**************************************************************
1081 void XGUI_Workshop::updateCommandsOnViewSelection()
1082 {
1083   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1084   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1085   XGUI_Selection* aSelection = mySelector->selection();
1086   if (aSelection->getSelected().size() == 0)
1087     return;
1088
1089   QList<QAction*> aActions = getModuleCommands();
1090   foreach(QAction* aAction, aActions)
1091   {
1092     QString aId = aAction->data().toString();
1093     std::list<ModelAPI_Validator*> aValidators;
1094     std::list<std::list<std::string> > anArguments;
1095     aFactory->validators(aId.toStdString(), aValidators, anArguments);
1096     std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
1097     for (; aValidator != aValidators.end(); aValidator++) {
1098       if (*aValidator) {
1099         const ModuleBase_SelectionValidator* aSelValidator =
1100             dynamic_cast<const ModuleBase_SelectionValidator*>(*aValidator);
1101         if (aSelValidator) {
1102           aAction->setEnabled(aSelValidator->isValid(aSelection));
1103         }
1104       }
1105     }
1106   }
1107 }
1108
1109 //**************************************************************
1110 void XGUI_Workshop::registerValidators() const
1111 {
1112   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1113   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1114 }
1115
1116 //**************************************************************
1117 void XGUI_Workshop::displayAllResults()
1118 {
1119   PluginManagerPtr aMgr = ModelAPI_PluginManager::get();
1120   DocumentPtr aRootDoc = aMgr->rootDocument();
1121   displayDocumentResults(aRootDoc);
1122   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1123     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1124     ResultPartPtr aPart = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1125     displayDocumentResults(aPart->partDoc());
1126   }
1127   myDisplayer->updateViewer();
1128 }
1129
1130 //**************************************************************
1131 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1132 {
1133   if (!theDoc)
1134     return;
1135   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1136   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1137 }
1138
1139 //**************************************************************
1140 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1141 {
1142   for (int i = 0; i < theDoc->size(theGroup); i++)
1143     myDisplayer->display(theDoc->object(theGroup, i), false);
1144 }