]> SALOME platform Git repositories - modules/shaper.git/blob - src/XGUI/XGUI_Workshop.cpp
Salome HOME
Merge branch 'Dev_0.6' of newgeom:newgeom into Dev_0.6
[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_ActionsMgr.h"
18 #include "XGUI_ErrorDialog.h"
19 #include "XGUI_ViewerProxy.h"
20 #include "XGUI_PropertyPanel.h"
21 #include "XGUI_ContextMenuMgr.h"
22 #include "XGUI_ModuleConnector.h"
23 #include "XGUI_Preferences.h"
24 #include <XGUI_QtEvents.h>
25
26 #include <ModelAPI_Events.h>
27 #include <ModelAPI_Session.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 #include <ModuleBase_Tools.h>
48 #include <ModuleBase_IViewer.h>
49
50 #include <Config_Common.h>
51 #include <Config_FeatureMessage.h>
52 #include <Config_PointerMessage.h>
53 #include <Config_ModuleReader.h>
54
55 #include <QApplication>
56 #include <QFileDialog>
57 #include <QMessageBox>
58 #include <QMdiSubWindow>
59 #include <QPushButton>
60 #include <QDockWidget>
61 #include <QLayout>
62 #include <QThread>
63 #include <QObject>
64
65 #ifdef _DEBUG
66 #include <QDebug>
67 #include <iostream>
68 #endif
69
70 #ifdef WIN32
71 #include <windows.h>
72 #else
73 #include <dlfcn.h>
74 #endif
75
76 QMap<QString, QString> XGUI_Workshop::myIcons;
77
78 QString XGUI_Workshop::featureIcon(const std::string& theId)
79 {
80   QString aId(theId.c_str());
81   if (myIcons.contains(aId))
82     return myIcons[aId];
83   return QString();
84 }
85
86 XGUI_Workshop::XGUI_Workshop(XGUI_SalomeConnector* theConnector)
87     : QObject(),
88       myCurrentDir(QString()),
89       myModule(NULL),
90       mySalomeConnector(theConnector),
91       myPropertyPanel(0),
92       myObjectBrowser(0),
93       myDisplayer(0),
94       myUpdatePrefs(false),
95       myPartActivating(false)
96 {
97   myMainWindow = mySalomeConnector ? 0 : new XGUI_MainWindow();
98
99   myDisplayer = new XGUI_Displayer(this);
100
101   mySelector = new XGUI_SelectionMgr(this);
102   //connect(mySelector, SIGNAL(selectionChanged()), this, SLOT(updateModuleCommands()));
103
104   myOperationMgr = new XGUI_OperationMgr(this);
105   myActionsMgr = new XGUI_ActionsMgr(this);
106   myErrorDlg = new XGUI_ErrorDialog(myMainWindow);
107   myContextMenuMgr = new XGUI_ContextMenuMgr(this);
108   connect(myContextMenuMgr, SIGNAL(actionTriggered(const QString&, bool)), this,
109           SLOT(onContextMenuCommand(const QString&, bool)));
110
111   myViewerProxy = new XGUI_ViewerProxy(this);
112   connect(myViewerProxy, SIGNAL(selectionChanged()), this, SLOT(updateCommandsOnViewSelection()));
113
114   myModuleConnector = new XGUI_ModuleConnector(this);
115
116   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)), 
117           SLOT(onOperationStarted()));
118   connect(myOperationMgr, SIGNAL(operationResumed(ModuleBase_Operation*)), SLOT(onOperationStarted()));
119   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
120           SLOT(onOperationStopped(ModuleBase_Operation*)));
121   connect(myMainWindow, SIGNAL(exitKeySequence()), SLOT(onExit()));
122   // TODO(sbh): It seems that application works properly without update on operationStarted
123   connect(myOperationMgr, SIGNAL(operationStarted(ModuleBase_Operation*)),
124           myActionsMgr,   SLOT(update()));
125   connect(myOperationMgr, SIGNAL(operationStopped(ModuleBase_Operation*)),
126           myActionsMgr,   SLOT(update()));
127   connect(this, SIGNAL(errorOccurred(const QString&)), myErrorDlg, SLOT(addError(const QString&)));
128 }
129
130 //******************************************************
131 XGUI_Workshop::~XGUI_Workshop(void)
132 {
133   delete myDisplayer;
134 }
135
136 //******************************************************
137 void XGUI_Workshop::startApplication()
138 {
139   initMenu();
140   //Initialize event listening
141   Events_Loop* aLoop = Events_Loop::loop();
142   aLoop->registerListener(this, Events_Error::errorID());  //!< Listening application errors.
143   aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
144   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
145   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
146   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
147   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
148   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
149   aLoop->registerListener(this, Events_Loop::eventByName("LongOperation"));
150   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
151   aLoop->registerListener(this, Events_Loop::eventByName("CurrentDocumentChanged"));
152   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOSHOW));
153   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
154
155   registerValidators();
156   activateModule();
157   if (myMainWindow) {
158     myMainWindow->show();
159     updateCommandStatus();
160   }
161   XGUI_Preferences::loadCustomProps();
162   onNew();
163 }
164
165 //******************************************************
166 void XGUI_Workshop::initMenu()
167 {
168   myContextMenuMgr->createActions();
169
170   if (isSalomeMode()) {
171     // Create only Undo, Redo commands
172     QAction* aAction = salomeConnector()->addDesktopCommand("UNDO_CMD", tr("Undo"),
173                                                          tr("Undo last command"),
174                                                          QIcon(":pictures/undo.png"),
175                                                          QKeySequence::Undo, false, "MEN_DESK_EDIT");
176     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onUndo()));
177     aAction = salomeConnector()->addDesktopCommand("REDO_CMD", tr("Redo"), tr("Redo last command"),
178                                                 QIcon(":pictures/redo.png"), QKeySequence::Redo,
179                                                 false, "MEN_DESK_EDIT");
180     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRedo()));
181     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
182     aAction = salomeConnector()->addDesktopCommand("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
183                                                 QIcon(":pictures/rebuild.png"), QKeySequence(),
184                                                 false, "MEN_DESK_EDIT");
185     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onRebuild()));
186     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_EDIT");
187
188     aAction = salomeConnector()->addDesktopCommand("SAVEAS_CMD", tr("Export NewGeom..."), tr("Export the current document into a NewGeom file"),
189                                                 QIcon(), QKeySequence(),
190                                                 false, "MEN_DESK_FILE");
191     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onSaveAs()));
192
193     aAction = salomeConnector()->addDesktopCommand("OPEN_CMD", tr("Import NewGeom..."), tr("Import a NewGeom file"),
194                                                 QIcon(), QKeySequence(),
195                                                 false, "MEN_DESK_FILE");
196     connect(aAction, SIGNAL(triggered(bool)), this, SLOT(onOpen()));
197     salomeConnector()->addDesktopMenuSeparator("MEN_DESK_FILE");
198
199     return;
200   }
201   // File commands group
202   XGUI_MenuGroupPanel* aGroup = myMainWindow->menuObject()->generalPage();
203
204   XGUI_Command* aCommand;
205
206   aCommand = aGroup->addFeature("SAVE_CMD", tr("Save..."), tr("Save the document"),
207                                 QIcon(":pictures/save.png"), QKeySequence::Save);
208   aCommand->connectTo(this, SLOT(onSave()));
209   //aCommand->disable();
210
211   aCommand = aGroup->addFeature("UNDO_CMD", tr("Undo"), tr("Undo last command"),
212                                 QIcon(":pictures/undo.png"), QKeySequence::Undo);
213   aCommand->connectTo(this, SLOT(onUndo()));
214
215   aCommand = aGroup->addFeature("REDO_CMD", tr("Redo"), tr("Redo last command"),
216                                 QIcon(":pictures/redo.png"), QKeySequence::Redo);
217   aCommand->connectTo(this, SLOT(onRedo()));
218
219   aCommand = aGroup->addFeature("REBUILD_CMD", tr("Rebuild"), tr("Rebuild data objects"),
220     QIcon(":pictures/rebuild.png"), QKeySequence());
221   aCommand->connectTo(this, SLOT(onRebuild()));
222
223   aCommand = aGroup->addFeature("SAVEAS_CMD", tr("Save as..."), tr("Save the document into a file"),
224                                 QIcon(":pictures/save.png"), QKeySequence());
225   aCommand->connectTo(this, SLOT(onSaveAs()));
226   //aCommand->disable();
227
228   aCommand = aGroup->addFeature("OPEN_CMD", tr("Open..."), tr("Open a new document"),
229                                 QIcon(":pictures/open.png"), QKeySequence::Open);
230   aCommand->connectTo(this, SLOT(onOpen()));
231
232   //aCommand = aGroup->addFeature("NEW_CMD", tr("New"), tr("Create a new document"),
233   //                              QIcon(":pictures/new.png"), QKeySequence::New);
234   //aCommand->connectTo(this, SLOT(onNew()));
235
236   aCommand = aGroup->addFeature("PREF_CMD", tr("Preferences"), tr("Edit preferences"),
237                                 QIcon(":pictures/preferences.png"), QKeySequence::Preferences);
238   aCommand->connectTo(this, SLOT(onPreferences()));
239
240   aCommand = aGroup->addFeature("EXIT_CMD", tr("Exit"), tr("Exit application"),
241                                 QIcon(":pictures/close.png"), QKeySequence::Close);
242   aCommand->connectTo(this, SLOT(onExit()));
243   //FIXME: SBH's test action. Can be used for some GUI tests.
244 //  #ifdef _DEBUG
245 //    aCommand = aGroup->addFeature("TEST_CMD", "Test!", "Private debug button",
246 //                                  QIcon(":pictures/close.png"), QKeySequence(), true);
247 //    aCommand->connectTo(myMainWindow, SLOT(dockPythonConsole()));
248 //  #endif
249 }
250
251 //******************************************************
252 XGUI_Workbench* XGUI_Workshop::addWorkbench(const QString& theName)
253 {
254   XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
255   return aMenuBar->addWorkbench(theName);
256 }
257
258 //******************************************************
259 void XGUI_Workshop::processEvent(const std::shared_ptr<Events_Message>& theMessage)
260 {
261   if (QApplication::instance()->thread() != QThread::currentThread()) {
262     #ifdef _DEBUG
263     std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
264     #endif
265     SessionPtr aMgr = ModelAPI_Session::get();
266     PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
267     QApplication::postEvent(this, aPostponeEvent);
268     return;
269   }
270
271   //A message to start feature creation received.
272   if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
273     std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
274        std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
275     if (!aFeatureMsg->isInternal()) {
276       addFeature(aFeatureMsg);
277     }
278   }
279
280   // Process creation of Part
281   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
282     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
283         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
284     onFeatureCreatedMsg(aUpdMsg);
285     if (myUpdatePrefs) {
286       if (mySalomeConnector)
287         mySalomeConnector->createPreferences();
288       myUpdatePrefs = false;
289     }
290   }
291   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
292     myUpdatePrefs = true;
293   }
294
295   // Redisplay feature
296   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
297     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
298         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
299     onFeatureRedisplayMsg(aUpdMsg);
300   }
301
302   //Update property panel on corresponding message. If there is no current operation (no
303   //property panel), or received message has different feature to the current - do nothing.
304   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
305     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
306         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
307     onFeatureUpdatedMsg(anUpdateMsg);
308   }
309
310   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
311     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDelMsg =
312         std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
313     onObjectDeletedMsg(aDelMsg);
314   }
315
316   else if (theMessage->eventID() == Events_LongOp::eventID()) {
317     if (Events_LongOp::isPerformed())
318       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
319     else
320       QApplication::restoreOverrideCursor();
321   }
322
323   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOSHOW)) {
324     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
325         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
326     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
327     QObjectPtrList aList;
328     std::set<ObjectPtr>::const_iterator aIt;
329     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
330       aList.append(*aIt);
331     showObjects(aList, true);
332   }
333
334   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TOHIDE)) {
335     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
336         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
337     const std::set<ObjectPtr>& aObjList = anUpdateMsg->objects();
338     QObjectPtrList aList;
339     std::set<ObjectPtr>::const_iterator aIt;
340     for (aIt = aObjList.cbegin(); aIt != aObjList.cend(); ++aIt)
341       aList.append(*aIt);
342     showObjects(aList, false);
343   }
344
345   //An operation passed by message. Start it, process and commit.
346   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
347     std::shared_ptr<Config_PointerMessage> aPartSetMsg =
348         std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
349     //myPropertyPanel->cleanContent();
350     ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
351
352     if (myOperationMgr->startOperation(anOperation)) {
353       myPropertyPanel->updateContentWidget(anOperation->feature());
354       if (!anOperation->getDescription()->hasXmlRepresentation()) {
355         if (anOperation->commit())
356           updateCommandStatus();
357       }
358     }
359   }
360   else if (theMessage->eventID() == Events_Loop::loop()->eventByName("CurrentDocumentChanged")) {
361     myActionsMgr->update();
362     // Find and Activate active part
363     if (myPartActivating)
364       return;
365     SessionPtr aMgr = ModelAPI_Session::get();
366     DocumentPtr aActiveDoc = aMgr->activeDocument();
367     DocumentPtr aDoc = aMgr->moduleDocument();
368     if (aActiveDoc == aDoc) {
369       activatePart(ResultPartPtr()); 
370       return;
371     }
372     std::string aGrpName = ModelAPI_ResultPart::group();
373     for (int i = 0; i < aDoc->size(aGrpName); i++) {
374       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aDoc->object(aGrpName, i));
375       if (aPart->partDoc() == aActiveDoc) {
376         activatePart(aPart); // Activate a part which corresponds to active Doc
377         return;
378       }
379     }
380     // If not found then activate global document
381     activatePart(ResultPartPtr()); 
382
383   } else {
384     //Show error dialog if error message received.
385     std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
386     if (anAppError) {
387       emit errorOccurred(QString::fromLatin1(anAppError->description()));
388     }
389   }
390   if (!isSalomeMode()) {
391     SessionPtr aMgr = ModelAPI_Session::get();
392     if (aMgr->isModified() != myMainWindow->isModifiedState())
393       myMainWindow->setModifiedState(aMgr->isModified());
394   }
395 }
396
397
398 //******************************************************
399 void XGUI_Workshop::onStartWaiting()
400 {
401   if (Events_LongOp::isPerformed()) {
402     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
403   }
404 }
405
406 //******************************************************
407 void XGUI_Workshop::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
408 {
409   std::set<ObjectPtr> aFeatures = theMsg->objects();
410   if (myOperationMgr->hasOperation()) {
411     FeaturePtr aCurrentFeature = myOperationMgr->currentOperation()->feature();
412     std::set<ObjectPtr>::const_iterator aIt;
413     for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
414       ObjectPtr aNewFeature = (*aIt);
415       if (aNewFeature == aCurrentFeature) {
416         myPropertyPanel->updateContentWidget(aCurrentFeature);
417         break;
418       }
419     }
420   }
421   myOperationMgr->onValidateOperation();
422   if (myObjectBrowser)
423     myObjectBrowser->processEvent(theMsg);
424 }
425
426 //******************************************************
427 void XGUI_Workshop::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
428 {
429   std::set<ObjectPtr> aObjects = theMsg->objects();
430   std::set<ObjectPtr>::const_iterator aIt;
431   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
432     ObjectPtr aObj = (*aIt);
433     bool aHide = !aObj->data() || !aObj->data()->isValid();
434     if (!aHide) { // check that this is not hidden result
435       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
436       aHide = aRes && aRes->isConcealed();
437     }
438     if (aHide)
439       myDisplayer->erase(aObj, false);
440     else {
441       if (myDisplayer->isVisible(aObj))  {
442         myDisplayer->display(aObj, false);  // In order to update presentation
443         if (myOperationMgr->hasOperation()) {
444           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
445           if (aOperation->hasObject(aObj) && myDisplayer->isActive(aObj))
446             myDisplayer->deactivate(aObj);
447         }
448       } else {
449         if (myOperationMgr->hasOperation()) {
450           ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
451           // Display only current operation results if operation has preview
452           if (aOperation->hasObject(aObj)/* && aOperation->hasPreview()*/) {
453             myDisplayer->display(aObj, false);
454             // Deactivate object of current operation from selection
455             if (myDisplayer->isActive(aObj))
456               myDisplayer->deactivate(aObj);
457           }
458         }
459       }
460     }
461   }
462   myDisplayer->updateViewer();
463 }
464
465 //******************************************************
466 void XGUI_Workshop::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
467 {
468   std::set<ObjectPtr> aObjects = theMsg->objects();
469
470   std::set<ObjectPtr>::const_iterator aIt;
471   bool aHasPart = false;
472   bool isDisplayed = false;
473   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
474     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aIt);
475     if (aPart) {
476       aHasPart = true;
477       // If a feature is created from the aplication's python console  
478       // it doesn't stored in the operation mgr and doesn't displayed
479     } else if (myOperationMgr->hasOperation()) {
480       ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
481       if (aOperation->hasObject(*aIt)) {  // Display only current operation results
482         myDisplayer->display(*aIt, false);
483         isDisplayed = true;
484       }
485     }
486   }
487   if (myObjectBrowser)
488     myObjectBrowser->processEvent(theMsg);
489   if (isDisplayed)
490     myDisplayer->updateViewer();
491   //if (aHasPart) { // TODO: Avoid activate last part on loading of document
492   //  activateLastPart();
493   //}
494 }
495
496 //******************************************************
497 void XGUI_Workshop::onObjectDeletedMsg(const std::shared_ptr<ModelAPI_ObjectDeletedMessage>& theMsg)
498 {
499   if (myObjectBrowser)
500     myObjectBrowser->processEvent(theMsg);
501   //std::set<ObjectPtr> aFeatures = theMsg->objects();
502 }
503
504 //******************************************************
505 void XGUI_Workshop::onOperationStarted()
506 {
507   ModuleBase_Operation* aOperation = myOperationMgr->currentOperation();
508   if (this->isSalomeMode()) 
509     aOperation->setNestedFeatures(mySalomeConnector->nestedActions(aOperation->id()));
510   else 
511     aOperation->setNestedFeatures(myActionsMgr->nestedCommands(aOperation->id()));
512   
513   if (aOperation->getDescription()->hasXmlRepresentation()) {  //!< No need for property panel
514     connectWithOperation(aOperation);
515
516     showPropertyPanel();
517     QString aXmlRepr = aOperation->getDescription()->xmlRepresentation();
518     ModuleBase_WidgetFactory aFactory = ModuleBase_WidgetFactory(aXmlRepr.toStdString(),
519                                                                  myModuleConnector);
520
521     myPropertyPanel->cleanContent();
522     aFactory.createWidget(myPropertyPanel->contentWidget());
523     ModuleBase_Tools::zeroMargins(myPropertyPanel->contentWidget());
524
525     QList<ModuleBase_ModelWidget*> aWidgets = aFactory.getModelWidgets();
526     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
527       aWidget->setFeature(aOperation->feature());
528       aWidget->enableFocusProcessing();
529       QObject::connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
530       // Init default values
531       if (!aOperation->isEditOperation() && !aWidget->isComputedDefault()) {
532         aWidget->storeValue();
533       }
534     }
535
536     myPropertyPanel->setModelWidgets(aWidgets);
537     aOperation->setPropertyPanel(myPropertyPanel);
538     // Do not activate widgets by default if the current operation is editing operation
539     // Because we don't know which widget is going to be edited. 
540     if ((!aOperation->isEditOperation())) {
541       if (!aOperation->activateByPreselection())
542         myPropertyPanel->activateNextWidget(NULL);
543     }
544     // Set final definitions if they are necessary
545     myModule->propertyPanelDefined(aOperation);
546
547     // Widget activation (from the previous method) may commit the current operation
548     // if pre-selection is enougth for it. So we shouldn't update prop panel's title
549     if(myOperationMgr->isCurrentOperation(aOperation)) {
550       myPropertyPanel->setWindowTitle(aOperation->getDescription()->description());
551     }
552   }
553   updateCommandStatus();
554 }
555
556 //******************************************************
557 void XGUI_Workshop::onOperationStopped(ModuleBase_Operation* theOperation)
558 {
559   //!< No need for property panel
560   updateCommandStatus();
561   hidePropertyPanel();
562   myPropertyPanel->cleanContent();
563
564   // Activate objects created by current operation
565   FeaturePtr aFeature = theOperation->feature();
566   myDisplayer->activate(aFeature);
567   const std::list<ResultPtr>& aResults = aFeature->results();
568   std::list<ResultPtr>::const_iterator aIt;
569   for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
570     myDisplayer->activate(*aIt);
571   }
572 }
573
574 bool XGUI_Workshop::event(QEvent * theEvent)
575 {
576   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
577   if (aPostponedEv) {
578     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
579     processEvent(aEventPtr);
580     return true;
581   }
582   return false;
583 }
584
585 /*
586  *
587  */
588 void XGUI_Workshop::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
589 {
590   if (!theMessage) {
591 #ifdef _DEBUG
592     qDebug() << "XGUI_Workshop::addFeature: NULL message.";
593 #endif
594     return;
595   }
596   // Remember features icons
597   myIcons[QString::fromStdString(theMessage->id())] = QString::fromStdString(theMessage->icon());
598
599   //Find or create Workbench
600   QString aWchName = QString::fromStdString(theMessage->workbenchId());
601   QString aNestedFeatures = QString::fromStdString(theMessage->nestedFeatures());
602   bool isUsePropPanel = theMessage->isUseInput();
603   QString aFeatureId = QString::fromStdString(theMessage->id());
604   if (isSalomeMode()) {
605     QAction* aAction = salomeConnector()->addFeature(aWchName, aFeatureId,
606                                                      QString::fromStdString(theMessage->text()),
607                                                      QString::fromStdString(theMessage->tooltip()),
608                                                      QIcon(theMessage->icon().c_str()),
609                                                      QKeySequence(),
610                                                      isUsePropPanel);
611     salomeConnector()->setNestedActions(aFeatureId, aNestedFeatures.split(" ", QString::SkipEmptyParts));
612     salomeConnector()->setDocumentKind(aFeatureId, QString::fromStdString(theMessage->documentKind()));
613
614     myActionsMgr->addCommand(aAction);
615     myModule->actionCreated(aAction);
616   } else {
617
618     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
619     XGUI_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
620     if (!aPage) {
621       aPage = addWorkbench(aWchName);
622     }
623     //Find or create Group
624     QString aGroupName = QString::fromStdString(theMessage->groupId());
625     XGUI_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
626     if (!aGroup) {
627       aGroup = aPage->addGroup(aGroupName);
628     }
629     QString aDocKind = QString::fromStdString(theMessage->documentKind());
630     // Check if hotkey sequence is already defined:
631     QKeySequence aHotKey = myActionsMgr->registerShortcut(
632         QString::fromStdString(theMessage->keysequence()));
633     // Create feature...
634     XGUI_Command* aCommand = aGroup->addFeature(aFeatureId,
635                                                 QString::fromStdString(theMessage->text()),
636                                                 QString::fromStdString(theMessage->tooltip()),
637                                                 QIcon(theMessage->icon().c_str()),
638                                                 aDocKind,
639                                                 aHotKey,
640                                                 isUsePropPanel);
641     aCommand->setNestedCommands(aNestedFeatures.split(" ", QString::SkipEmptyParts));
642     myActionsMgr->addCommand(aCommand);
643     myModule->actionCreated(aCommand);
644   }
645 }
646
647 /*
648  * Makes a signal/slot connections between Property Panel
649  * and given operation. The given operation becomes a
650  * current operation and previous operation if exists
651  */
652 void XGUI_Workshop::connectWithOperation(ModuleBase_Operation* theOperation)
653 {
654   QAction* aCommand = 0;
655   if (isSalomeMode()) {
656     aCommand = salomeConnector()->command(theOperation->getDescription()->operationId());
657   } else {
658     XGUI_MainMenu* aMenu = myMainWindow->menuObject();
659     FeaturePtr aFeature = theOperation->feature();
660     if(aFeature)
661       aCommand = aMenu->feature(QString::fromStdString(aFeature->getKind()));
662   }
663   //Abort operation on uncheck the command
664   if (aCommand) {
665     connect(aCommand, SIGNAL(triggered(bool)), theOperation, SLOT(setRunning(bool)));
666   }
667 }
668
669 /*
670  * Saves document with given name.
671  */
672 void XGUI_Workshop::saveDocument(const QString& theName, std::list<std::string>& theFileNames)
673 {
674   QApplication::restoreOverrideCursor();
675   SessionPtr aMgr = ModelAPI_Session::get();
676   aMgr->save(theName.toLatin1().constData(), theFileNames);
677   QApplication::restoreOverrideCursor();
678 }
679
680 bool XGUI_Workshop::isActiveOperationAborted()
681 {
682   return myOperationMgr->abortAllOperations();
683 }
684
685 //******************************************************
686 void XGUI_Workshop::onExit()
687 {
688   SessionPtr aMgr = ModelAPI_Session::get();
689   if (aMgr->isModified()) {
690     int anAnswer = QMessageBox::question(
691         myMainWindow, tr("Save current file"), tr("The document is modified, save before exit?"),
692         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
693     if (anAnswer == QMessageBox::Save) {
694       bool saved = onSave();
695       if (!saved) {
696         return;
697       }
698     } else if (anAnswer == QMessageBox::Cancel) {
699       return;
700     }
701   }
702   qApp->exit();
703 }
704
705 //******************************************************
706 void XGUI_Workshop::onNew()
707 {
708   QApplication::setOverrideCursor(Qt::WaitCursor);
709   if (objectBrowser() == 0) {
710     createDockWidgets();
711     mySelector->connectViewers();
712   }
713   myViewerProxy->connectToViewer();
714   showObjectBrowser();
715   if (!isSalomeMode()) {
716     myMainWindow->showPythonConsole();
717     QMdiSubWindow* aWnd = myMainWindow->viewer()->createView();
718     aWnd->showMaximized();
719     updateCommandStatus();
720   }
721   myContextMenuMgr->connectViewer();
722   QApplication::restoreOverrideCursor();
723 }
724
725 //******************************************************
726 void XGUI_Workshop::onOpen()
727 {
728   if(!isActiveOperationAborted())
729     return;
730   //save current file before close if modified
731   SessionPtr aSession = ModelAPI_Session::get();
732   if (aSession->isModified()) {
733     //TODO(sbh): re-launch the app?
734     int anAnswer = QMessageBox::question(
735         myMainWindow, tr("Save current file"),
736         tr("The document is modified, save before opening another?"),
737         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel);
738     if (anAnswer == QMessageBox::Save) {
739       onSave();
740     } else if (anAnswer == QMessageBox::Cancel) {
741       return;
742     }
743     aSession->closeAll();
744     myCurrentDir = "";
745   }
746
747   //show file dialog, check if readable and open
748   myCurrentDir = QFileDialog::getExistingDirectory(mainWindow());
749   if (myCurrentDir.isEmpty())
750     return;
751   QFileInfo aFileInfo(myCurrentDir);
752   if (!aFileInfo.exists() || !aFileInfo.isReadable()) {
753     QMessageBox::critical(myMainWindow, tr("Warning"), tr("Unable to open the file."));
754     myCurrentDir = "";
755     return;
756   }
757   QApplication::setOverrideCursor(Qt::WaitCursor);
758   aSession->load(myCurrentDir.toLatin1().constData());
759   myObjectBrowser->rebuildDataTree();
760   displayAllResults();
761   updateCommandStatus();
762   QApplication::restoreOverrideCursor();
763 }
764
765 //******************************************************
766 bool XGUI_Workshop::onSave()
767 {
768   if(!isActiveOperationAborted())
769     return false;
770   if (myCurrentDir.isEmpty()) {
771     return onSaveAs();
772   }
773   std::list<std::string> aFiles;
774   saveDocument(myCurrentDir, aFiles);
775   updateCommandStatus();
776   if (!isSalomeMode())
777     myMainWindow->setModifiedState(false);
778   return true;
779 }
780
781 //******************************************************
782 bool XGUI_Workshop::onSaveAs()
783 {
784   if(!isActiveOperationAborted())
785     return false;
786   QFileDialog dialog(mainWindow());
787   dialog.setWindowTitle(tr("Select directory to save files..."));
788   dialog.setFileMode(QFileDialog::Directory);
789   dialog.setFilter(tr("Folders (*)"));
790   dialog.setOptions(QFileDialog::HideNameFilterDetails | QFileDialog::ShowDirsOnly);
791   dialog.setViewMode(QFileDialog::Detail);
792
793   if (!dialog.exec()) {
794     return false;
795   }
796   QString aTempDir = dialog.selectedFiles().first();
797   QDir aDir(aTempDir);
798   if (aDir.exists() && !aDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).isEmpty()) {
799     int answer = QMessageBox::question(
800         myMainWindow,
801         //: Title of the dialog which asks user if he wants to save study in existing non-empty folder
802         tr("Save"),
803         tr("The folder already contains some files, save anyway?"),
804         QMessageBox::Save | QMessageBox::Cancel);
805     if (answer == QMessageBox::Cancel) {
806       return false;
807     }
808   }
809   myCurrentDir = aTempDir;
810   if (!isSalomeMode()) {
811     myMainWindow->setCurrentDir(myCurrentDir, false);
812     myMainWindow->setModifiedState(false);
813   }
814   return onSave();
815 }
816
817 //******************************************************
818 void XGUI_Workshop::onUndo()
819 {
820   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
821   SessionPtr aMgr = ModelAPI_Session::get();
822   if (aMgr->isOperation())
823     operationMgr()->onAbortOperation();
824   aMgr->undo();
825   updateCommandStatus();
826 }
827
828 //******************************************************
829 void XGUI_Workshop::onRedo()
830 {
831   objectBrowser()->treeView()->setCurrentIndex(QModelIndex());
832   SessionPtr aMgr = ModelAPI_Session::get();
833   if (aMgr->isOperation())
834     operationMgr()->onAbortOperation();
835   aMgr->redo();
836   updateCommandStatus();
837 }
838
839 //******************************************************
840 void XGUI_Workshop::onRebuild()
841 {
842   SessionPtr aMgr = ModelAPI_Session::get();
843   bool aWasOperation = aMgr->isOperation(); // keep this value
844   if (!aWasOperation) {
845     aMgr->startOperation();
846   }
847   static const Events_ID aRebuildEvent = Events_Loop::loop()->eventByName("Rebuild");
848   Events_Loop::loop()->send(std::shared_ptr<Events_Message>(
849     new Events_Message(aRebuildEvent, this)));
850   if (!aWasOperation) {
851     aMgr->finishOperation();
852   }
853 }
854
855 //******************************************************
856 void XGUI_Workshop::onPreferences()
857 {
858   XGUI_Prefs aModif;
859   XGUI_Preferences::editPreferences(aModif);
860   if (aModif.size() > 0) {
861     QString aSection;
862     foreach (XGUI_Pref aPref, aModif)
863     {
864       aSection = aPref.first;
865       if (aSection == XGUI_Preferences::VIEWER_SECTION) {
866         if (!isSalomeMode())
867           myMainWindow->viewer()->updateFromResources();
868       } else if (aSection == XGUI_Preferences::MENU_SECTION) {
869         if (!isSalomeMode())
870           myMainWindow->menuObject()->updateFromResources();
871       }
872     }
873   }
874 }
875
876 //******************************************************
877 ModuleBase_IModule* XGUI_Workshop::loadModule(const QString& theModule)
878 {
879   QString libName = QString::fromStdString(library(theModule.toStdString()));
880   if (libName.isEmpty()) {
881     qWarning(qPrintable(tr("Information about module \"%1\" doesn't exist.").arg(theModule)));
882     return 0;
883   }
884
885   QString err;
886   CREATE_FUNC crtInst = 0;
887
888 #ifdef WIN32
889   HINSTANCE modLib = ::LoadLibrary((LPTSTR) qPrintable(libName));
890   if (!modLib) {
891     LPVOID lpMsgBuf;
892     ::FormatMessage(
893         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
894         0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
895     QString aMsg((char*) &lpMsgBuf);
896     err = QString("Failed to load  %1. %2").arg(libName).arg(aMsg);
897     ::LocalFree(lpMsgBuf);
898   } else {
899     crtInst = (CREATE_FUNC) ::GetProcAddress(modLib, CREATE_MODULE);
900     if (!crtInst) {
901       LPVOID lpMsgBuf;
902       ::FormatMessage(
903           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
904               | FORMAT_MESSAGE_IGNORE_INSERTS,
905           0, ::GetLastError(), 0, (LPTSTR) & lpMsgBuf, 0, 0);
906       QString aMsg((char*) &lpMsgBuf);
907       err = QString("Failed to find  %1 function. %2").arg( CREATE_MODULE).arg(aMsg);
908       ::LocalFree(lpMsgBuf);
909     }
910   }
911 #else
912   void* modLib = dlopen( libName.toLatin1(), RTLD_LAZY | RTLD_GLOBAL );
913   if ( !modLib ) {
914     err = QString( "Can not load library %1. %2" ).arg( libName ).arg( dlerror() );
915   } else {
916     crtInst = (CREATE_FUNC)dlsym( modLib, CREATE_MODULE );
917     if ( !crtInst ) {
918       err = QString( "Failed to find function %1. %2" ).arg( CREATE_MODULE ).arg( dlerror() );
919     }
920   }
921 #endif
922
923   ModuleBase_IModule* aModule = crtInst ? crtInst(myModuleConnector) : 0;
924
925   if (!err.isEmpty()) {
926     if (mainWindow()) {
927       Events_Error::send(err.toStdString());
928     } else {
929       qWarning(qPrintable(err));
930     }
931   }
932   return aModule;
933 }
934
935 //******************************************************
936 bool XGUI_Workshop::activateModule()
937 {
938   Config_ModuleReader aModuleReader;
939   QString moduleName = QString::fromStdString(aModuleReader.getModuleName());
940   myModule = loadModule(moduleName);
941   if (!myModule)
942     return false;
943   myModule->createFeatures();
944   myActionsMgr->update();
945   return true;
946 }
947
948 //******************************************************
949 void XGUI_Workshop::updateCommandStatus()
950 {
951   QList<QAction*> aCommands;
952   if (isSalomeMode()) {  // update commands in SALOME mode
953     aCommands = salomeConnector()->commandList();
954   } else {
955     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
956     foreach (XGUI_Command* aCmd, aMenuBar->features())
957       aCommands.append(aCmd);
958   }
959   SessionPtr aMgr = ModelAPI_Session::get();
960   if (aMgr->hasModuleDocument()) {
961     QAction *aUndoCmd, *aRedoCmd;
962     foreach(QAction* aCmd, aCommands) {
963       QString aId = aCmd->data().toString();
964       if (aId == "UNDO_CMD")
965         aUndoCmd = aCmd;
966       else if (aId == "REDO_CMD")
967         aRedoCmd = aCmd;
968       else
969         // Enable all commands
970         aCmd->setEnabled(true);
971     }
972     aUndoCmd->setEnabled(aMgr->canUndo() && !aMgr->isOperation());
973     aRedoCmd->setEnabled(aMgr->canRedo() && !aMgr->isOperation());
974   } else {
975     foreach(QAction* aCmd, aCommands) {
976       QString aId = aCmd->data().toString();
977       if (aId == "NEW_CMD")
978         aCmd->setEnabled(true);
979       else if (aId == "EXIT_CMD")
980         aCmd->setEnabled(true);
981       else
982         aCmd->setEnabled(false);
983     }
984   }
985   myActionsMgr->update();
986 }
987
988 //******************************************************
989 QList<QAction*> XGUI_Workshop::getModuleCommands() const
990 {
991   QList<QAction*> aCommands;
992   if (isSalomeMode()) {  // update commands in SALOME mode
993     aCommands = salomeConnector()->commandList();
994   } else {
995     XGUI_MainMenu* aMenuBar = myMainWindow->menuObject();
996     foreach(XGUI_Command* aCmd, aMenuBar->features())
997     {
998       aCommands.append(aCmd);
999     }
1000   }
1001   return aCommands;
1002 }
1003
1004 //******************************************************
1005 QDockWidget* XGUI_Workshop::createObjectBrowser(QWidget* theParent)
1006 {
1007   QDockWidget* aObjDock = new QDockWidget(theParent);
1008   aObjDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1009   aObjDock->setWindowTitle(tr("Object browser"));
1010   aObjDock->setStyleSheet(
1011       "::title { position: relative; padding-left: 5px; text-align: left center }");
1012   myObjectBrowser = new XGUI_ObjectsBrowser(aObjDock);
1013   connect(myObjectBrowser, SIGNAL(activePartChanged(ObjectPtr)), this,
1014           SLOT(changeCurrentDocument(ObjectPtr)));
1015   aObjDock->setWidget(myObjectBrowser);
1016
1017   myContextMenuMgr->connectObjectBrowser();
1018   return aObjDock;
1019 }
1020
1021 //******************************************************
1022 /*
1023  * Creates dock widgets, places them in corresponding area
1024  * and tabifies if necessary.
1025  */
1026 void XGUI_Workshop::createDockWidgets()
1027 {
1028   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1029   QDockWidget* aObjDock = createObjectBrowser(aDesktop);
1030   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, aObjDock);
1031   myPropertyPanel = new XGUI_PropertyPanel(aDesktop);
1032   myPropertyPanel->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
1033   aDesktop->addDockWidget(Qt::LeftDockWidgetArea, myPropertyPanel);
1034   hidePropertyPanel();  //<! Invisible by default
1035   hideObjectBrowser();
1036   aDesktop->tabifyDockWidget(aObjDock, myPropertyPanel);
1037   myPropertyPanel->installEventFilter(myOperationMgr);
1038
1039   QPushButton* aOkBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_OK);
1040   connect(aOkBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onCommitOperation()));
1041   QPushButton* aCancelBtn = myPropertyPanel->findChild<QPushButton*>(XGUI::PROP_PANEL_CANCEL);
1042   connect(aCancelBtn, SIGNAL(clicked()), myOperationMgr, SLOT(onAbortOperation()));
1043   connect(myPropertyPanel, SIGNAL(keyReleased(QKeyEvent*)), myOperationMgr,
1044           SLOT(onKeyReleased(QKeyEvent*)));
1045   connect(myOperationMgr, SIGNAL(operationValidated(bool)), myPropertyPanel,
1046           SLOT(setAcceptEnabled(bool)));
1047
1048 }
1049
1050 //******************************************************
1051 void XGUI_Workshop::showPropertyPanel()
1052 {
1053   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1054   //<! Restore ability to close panel from the window's menu
1055   aViewAct->setEnabled(true);
1056   myPropertyPanel->show();
1057   myPropertyPanel->raise();
1058 }
1059
1060 //******************************************************
1061 void XGUI_Workshop::hidePropertyPanel()
1062 {
1063   QAction* aViewAct = myPropertyPanel->toggleViewAction();
1064   //<! Do not allow to show empty property panel
1065   aViewAct->setEnabled(false);
1066   myPropertyPanel->hide();
1067 }
1068
1069 //******************************************************
1070 void XGUI_Workshop::showObjectBrowser()
1071 {
1072   myObjectBrowser->parentWidget()->show();
1073 }
1074
1075 //******************************************************
1076 void XGUI_Workshop::hideObjectBrowser()
1077 {
1078   myObjectBrowser->parentWidget()->hide();
1079 }
1080
1081 //******************************************************
1082 void XGUI_Workshop::onFeatureTriggered()
1083 {
1084   QAction* aCmd = dynamic_cast<QAction*>(sender());
1085   if (aCmd) {
1086     QString aId = salomeConnector()->commandId(aCmd);
1087     if (!aId.isNull())
1088       myModule->launchOperation(aId);
1089   }
1090 }
1091
1092 //******************************************************
1093 void XGUI_Workshop::changeCurrentDocument(ObjectPtr theObj)
1094 {
1095   SessionPtr aMgr = ModelAPI_Session::get();
1096   if (theObj) {
1097     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theObj);
1098     if (aPart) {
1099       DocumentPtr aPartDoc = aPart->partDoc();
1100       if (aPartDoc) {
1101         aMgr->setActiveDocument(aPartDoc);
1102         return;
1103       }
1104     }
1105   }
1106   aMgr->setActiveDocument(aMgr->moduleDocument());
1107 }
1108
1109 //******************************************************
1110 void XGUI_Workshop::salomeViewerSelectionChanged()
1111 {
1112   emit salomeViewerSelection();
1113 }
1114
1115 //**************************************************************
1116 ModuleBase_IViewer* XGUI_Workshop::salomeViewer() const
1117 {
1118   return mySalomeConnector->viewer();
1119 }
1120
1121 //**************************************************************
1122 void XGUI_Workshop::onContextMenuCommand(const QString& theId, bool isChecked)
1123 {
1124   QObjectPtrList aObjects = mySelector->selection()->selectedObjects();
1125   if ((theId == "ACTIVATE_PART_CMD") && (aObjects.size() > 0)) {
1126     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObjects.first());
1127     activatePart(aPart);
1128   } else if (theId == "DEACTIVATE_PART_CMD")
1129     activatePart(ResultPartPtr());
1130   else if (theId == "DELETE_CMD")
1131     deleteObjects(aObjects);
1132   else if (theId == "SHOW_CMD")
1133     showObjects(aObjects, true);
1134   else if (theId == "HIDE_CMD")
1135     showObjects(aObjects, false);
1136   else if (theId == "SHOW_ONLY_CMD")
1137     showOnlyObjects(aObjects);
1138   else if (theId == "SHADING_CMD")
1139     setDisplayMode(aObjects, XGUI_Displayer::Shading);
1140   else if (theId == "WIREFRAME_CMD")
1141     setDisplayMode(aObjects, XGUI_Displayer::Wireframe);
1142   else if (theId == "HIDEALL_CMD")
1143     myDisplayer->eraseAll();
1144   else if (theId == "EDIT_CMD") {
1145     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObjects.first());
1146     if (aFeature)
1147       myModule->editFeature(aFeature);
1148   }
1149 }
1150
1151 //**************************************************************
1152 void XGUI_Workshop::onWidgetValuesChanged()
1153 {
1154   ModuleBase_Operation* anOperation = myOperationMgr->currentOperation();
1155   FeaturePtr aFeature = anOperation->feature();
1156
1157   ModuleBase_ModelWidget* aSenderWidget = dynamic_cast<ModuleBase_ModelWidget*>(sender());
1158   //if (aCustom)
1159   //  aCustom->storeValue(aFeature);
1160
1161   const QList<ModuleBase_ModelWidget*>& aWidgets = myPropertyPanel->modelWidgets();
1162   QList<ModuleBase_ModelWidget*>::const_iterator anIt = aWidgets.begin(), aLast = aWidgets.end();
1163   for (; anIt != aLast; anIt++) {
1164     ModuleBase_ModelWidget* aCustom = *anIt;
1165     if (aCustom && (/*!aCustom->isInitialized(aFeature) ||*/aCustom == aSenderWidget)) {
1166       //aCustom->storeValue(aFeature);
1167       aCustom->storeValue();
1168     }
1169   }
1170 }
1171
1172 //**************************************************************
1173 void XGUI_Workshop::activatePart(ResultPartPtr theFeature)
1174 {
1175   if (!myPartActivating) {
1176     myPartActivating = true;
1177     if (theFeature)
1178       theFeature->activate();
1179     changeCurrentDocument(theFeature);
1180     myObjectBrowser->activatePart(theFeature);
1181     myPartActivating = false;
1182   }
1183 }
1184
1185 //**************************************************************
1186 void XGUI_Workshop::activateLastPart()
1187 {
1188   SessionPtr aMgr = ModelAPI_Session::get();
1189   DocumentPtr aDoc = aMgr->moduleDocument();
1190   std::string aGrpName = ModelAPI_ResultPart::group();
1191   ObjectPtr aLastPart = aDoc->object(aGrpName, aDoc->size(aGrpName) - 1);
1192   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aLastPart);
1193   if (aPart) {
1194     activatePart(aPart);
1195   }
1196 }
1197
1198 //**************************************************************
1199 void XGUI_Workshop::deleteObjects(const QObjectPtrList& theList)
1200 {
1201   QMainWindow* aDesktop = isSalomeMode() ? salomeConnector()->desktop() : myMainWindow;
1202   QMessageBox::StandardButton aRes = QMessageBox::warning(
1203       aDesktop, tr("Delete features"), tr("Seleted features will be deleted. Continue?"),
1204       QMessageBox::No | QMessageBox::Yes, QMessageBox::No);
1205   // ToDo: definbe deleting method
1206   if (aRes == QMessageBox::Yes) {
1207     SessionPtr aMgr = ModelAPI_Session::get();
1208     aMgr->startOperation();
1209     foreach (ObjectPtr aObj, theList)
1210     {
1211       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObj);
1212       if (aPart) {
1213         DocumentPtr aDoc = aPart->document();
1214         if (aDoc == aMgr->activeDocument()) {
1215           aDoc->close();
1216         }
1217         //aMgr->moduleDocument()->removeFeature(aPart->owner());
1218       } else {
1219         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
1220         if (aFeature)
1221           aObj->document()->removeFeature(aFeature);
1222       }
1223     }
1224     myDisplayer->updateViewer();
1225     aMgr->finishOperation();
1226   }
1227 }
1228
1229 //**************************************************************
1230 void XGUI_Workshop::showObjects(const QObjectPtrList& theList, bool isVisible)
1231 {
1232   foreach (ObjectPtr aObj, theList)
1233   {
1234     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
1235     if (aRes) {
1236       if (isVisible) {
1237         myDisplayer->display(aRes, false);
1238       } else {
1239         myDisplayer->erase(aRes, false);
1240       }
1241     }
1242   }
1243   myDisplayer->updateViewer();
1244 }
1245
1246 //**************************************************************
1247 void XGUI_Workshop::showOnlyObjects(const QObjectPtrList& theList)
1248 {
1249   myDisplayer->eraseAll(false);
1250   showObjects(theList, true);
1251 }
1252
1253
1254 //**************************************************************
1255 void XGUI_Workshop::updateCommandsOnViewSelection()
1256 {
1257   XGUI_Selection* aSelection = mySelector->selection();
1258   if (aSelection->getSelected().size() == 0)
1259     return;
1260
1261   // Restrict validators to manage only nested (child) features
1262   // of the current feature i.e. if current feature is Sketch -
1263   // Sketch Features & Constraints can be validated.
1264   QStringList aNestedIds;
1265   if(myOperationMgr->hasOperation()) {
1266     FeaturePtr aFeature = myOperationMgr->currentOperation()->feature();
1267     if(aFeature) {
1268       aNestedIds << myActionsMgr->nestedCommands(QString::fromStdString(aFeature->getKind()));
1269     }
1270   }
1271   SessionPtr aMgr = ModelAPI_Session::get();
1272   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1273   QList<QAction*> aActions = getModuleCommands();
1274   foreach(QAction* aAction, aActions) {
1275     QString aId = aAction->data().toString();
1276     if(!aNestedIds.contains(aId))
1277       continue;
1278     std::list<ModelAPI_Validator*> aValidators;
1279     std::list<std::list<std::string> > anArguments;
1280     aFactory->validators(aId.toStdString(), aValidators, anArguments);
1281     std::list<ModelAPI_Validator*>::iterator aValidator = aValidators.begin();
1282     for (; aValidator != aValidators.end(); aValidator++) {
1283       if (*aValidator) {
1284         const ModuleBase_SelectionValidator* aSelValidator =
1285             dynamic_cast<const ModuleBase_SelectionValidator*>(*aValidator);
1286         if (aSelValidator) {
1287           aAction->setEnabled(aSelValidator->isValid(aSelection));
1288         }
1289       }
1290     }
1291   }
1292 }
1293
1294 //**************************************************************
1295 void XGUI_Workshop::registerValidators() const
1296 {
1297   SessionPtr aMgr = ModelAPI_Session::get();
1298   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
1299 }
1300
1301 //**************************************************************
1302 void XGUI_Workshop::displayAllResults()
1303 {
1304   SessionPtr aMgr = ModelAPI_Session::get();
1305   DocumentPtr aRootDoc = aMgr->moduleDocument();
1306   displayDocumentResults(aRootDoc);
1307   for (int i = 0; i < aRootDoc->size(ModelAPI_ResultPart::group()); i++) {
1308     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
1309     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
1310     displayDocumentResults(aPart->partDoc());
1311   }
1312   myDisplayer->updateViewer();
1313 }
1314
1315 //**************************************************************
1316 void XGUI_Workshop::displayDocumentResults(DocumentPtr theDoc)
1317 {
1318   if (!theDoc)
1319     return;
1320   displayGroupResults(theDoc, ModelAPI_ResultConstruction::group());
1321   displayGroupResults(theDoc, ModelAPI_ResultBody::group());
1322 }
1323
1324 //**************************************************************
1325 void XGUI_Workshop::displayGroupResults(DocumentPtr theDoc, std::string theGroup)
1326 {
1327   for (int i = 0; i < theDoc->size(theGroup); i++)
1328     myDisplayer->display(theDoc->object(theGroup, i), false);
1329 }
1330
1331 //**************************************************************
1332 void XGUI_Workshop::setDisplayMode(const QObjectPtrList& theList, int theMode)
1333 {
1334   foreach(ObjectPtr aObj, theList) {
1335     myDisplayer->setDisplayMode(aObj, (XGUI_Displayer::DisplayMode)theMode, false);
1336   }
1337   if (theList.size() > 0)
1338     myDisplayer->updateViewer();
1339 }
1340
1341 //**************************************************************
1342 void XGUI_Workshop::closeDocument()
1343 {
1344   myDisplayer->closeLocalContexts();
1345   myDisplayer->eraseAll();
1346   objectBrowser()->clearContent();
1347
1348   SessionPtr aMgr = ModelAPI_Session::get();
1349   aMgr->closeAll();
1350   objectBrowser()->clearContent();
1351 }