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