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