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