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