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