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