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