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