Salome HOME
Separation of Workshop and events listener in order to make XGUI_Workshop is a child...
[modules/shaper.git] / src / XGUI / XGUI_WorkshopListener.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 #include "XGUI_WorkshopListener.h"
4 #include "XGUI_Workshop.h"
5 #include "XGUI_Displayer.h"
6 #include "XGUI_OperationMgr.h"
7 #include "XGUI_SalomeConnector.h"
8 #include "XGUI_ActionsMgr.h"
9 #include "XGUI_PropertyPanel.h"
10 #include "XGUI_ModuleConnector.h"
11 #include "XGUI_QtEvents.h"
12
13 #include <AppElements_Workbench.h>
14 #include <AppElements_Command.h>
15 #include <AppElements_MainMenu.h>
16 #include <AppElements_MainWindow.h>
17 #include <AppElements_MenuGroupPanel.h>
18 #include <AppElements_Button.h>
19
20 #include <ModuleBase_IModule.h>
21
22 #include <ModelAPI_Object.h>
23 #include <ModelAPI_Events.h>
24 #include <ModelAPI_Session.h>
25 #include <ModelAPI_Result.h>
26 #include <ModelAPI_Feature.h>
27 #include <ModelAPI_Data.h>
28 #include <ModelAPI_ResultBody.h>
29
30 #include <Events_Loop.h>
31 #include <Events_Error.h>
32 #include <Events_LongOp.h>
33
34 #include <ModuleBase_IWorkshop.h>
35
36 #include <ModuleBase_Operation.h>
37 #include <ModuleBase_OperationDescription.h>
38 #include <ModuleBase_Tools.h>
39 #include <ModuleBase_IViewer.h>
40 #include <ModuleBase_FilterFactory.h>
41
42 #include <Config_FeatureMessage.h>
43 #include <Config_PointerMessage.h>
44 #include <Config_SelectionFilterMessage.h>
45
46 #include <QApplication>
47 #include <QMainWindow>
48 #include <QThread>
49 #include <QAction>
50
51 #ifdef _DEBUG
52 #include <QDebug>
53 #include <iostream>
54 #endif
55
56 //#define DEBUG_FEATURE_CREATED
57 //#define DEBUG_FEATURE_REDISPLAY
58
59 XGUI_WorkshopListener::XGUI_WorkshopListener(ModuleBase_IWorkshop* theWorkshop)
60   : myWorkshop(theWorkshop),
61     myUpdatePrefs(false)
62 {
63 }
64
65 //******************************************************
66 XGUI_WorkshopListener::~XGUI_WorkshopListener(void)
67 {
68 }
69
70 //******************************************************
71 void XGUI_WorkshopListener::initializeEventListening()
72 {
73   //Initialize event listening
74   Events_Loop* aLoop = Events_Loop::loop();
75   aLoop->registerListener(this, Events_Error::errorID());  //!< Listening application errors.
76   aLoop->registerListener(this, Events_Loop::eventByName(Config_FeatureMessage::GUI_EVENT()));
77   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OPERATION_LAUNCHED));
78   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
79   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
80   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
81   aLoop->registerListener(this, Events_LongOp::eventID());
82   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_PLUGIN_LOADED));
83   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_SELFILTER_LOADED));
84
85   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED));
86   aLoop->registerListener(this, Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED));
87 }
88
89 //******************************************************
90 void XGUI_WorkshopListener::processEvent(const std::shared_ptr<Events_Message>& theMessage)
91 {
92   if (QApplication::instance()->thread() != QThread::currentThread()) {
93     #ifdef _DEBUG
94     std::cout << "XGUI_Workshop::processEvent: " << "Working in another thread." << std::endl;
95     #endif
96     SessionPtr aMgr = ModelAPI_Session::get();
97     PostponeMessageQtEvent* aPostponeEvent = new PostponeMessageQtEvent(theMessage);
98     QApplication::postEvent(this, aPostponeEvent);
99     return;
100   }
101
102   //A message to start feature creation received.
103   if (theMessage->eventID() == Events_Loop::loop()->eventByName(Config_FeatureMessage::GUI_EVENT())) {
104     std::shared_ptr<Config_FeatureMessage> aFeatureMsg =
105        std::dynamic_pointer_cast<Config_FeatureMessage>(theMessage);
106     if (!aFeatureMsg->isInternal()) {
107       addFeature(aFeatureMsg);
108     }
109   }
110   // Process creation of Part
111   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)) {
112     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
113         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
114     onFeatureCreatedMsg(aUpdMsg);
115     if (myUpdatePrefs) {
116       XGUI_SalomeConnector* aSalomeConnector = workshop()->salomeConnector();
117       if (aSalomeConnector)
118         aSalomeConnector->createPreferences();
119       myUpdatePrefs = false;
120     }
121   }
122   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_PLUGIN_LOADED)) {
123     myUpdatePrefs = true;
124   }
125   // Redisplay feature
126   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY)) {
127     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> aUpdMsg =
128         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
129     onFeatureRedisplayMsg(aUpdMsg);
130   }
131   //Update property panel on corresponding message. If there is no current operation (no
132   //property panel), or received message has different feature to the current - do nothing.
133   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED)) {
134     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
135         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
136     onFeatureUpdatedMsg(anUpdateMsg);
137   } else if (theMessage->eventID() == Events_LongOp::eventID()) {
138     if (Events_LongOp::isPerformed()) {
139       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
140     } else {
141       QApplication::restoreOverrideCursor();
142     }
143   }
144   //An operation passed by message. Start it, process and commit.
145   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OPERATION_LAUNCHED)) {
146     std::shared_ptr<Config_PointerMessage> aPartSetMsg =
147         std::dynamic_pointer_cast<Config_PointerMessage>(theMessage);
148     //myPropertyPanel->cleanContent();
149     ModuleBase_Operation* anOperation = (ModuleBase_Operation*) aPartSetMsg->pointer();
150     XGUI_OperationMgr* anOperationMgr = workshop()->operationMgr();
151
152     if (anOperationMgr->startOperation(anOperation)) {
153       workshop()->propertyPanel()->updateContentWidget(anOperation->feature());
154       if (!anOperation->getDescription()->hasXmlRepresentation()) {
155         if (anOperation->commit())
156           workshop()->updateCommandStatus();
157       }
158     }
159   } 
160   else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_SELFILTER_LOADED)) {
161     std::shared_ptr<Config_SelectionFilterMessage> aMsg = 
162       std::dynamic_pointer_cast<Config_SelectionFilterMessage>(theMessage);
163     if (aMsg) {
164       ModuleBase_FilterFactory* aFactory = myWorkshop->selectionFilters();
165       if (!aMsg->attributeId().empty()) {
166         aFactory->assignFilter(aMsg->selectionFilterId(), aMsg->featureId(), aMsg->attributeId(),
167                                aMsg->parameters());
168       }
169     }
170   } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_BLOCKED)) {
171     // the viewer's update context will not happens until viewer updated is emitted
172       workshop()->displayer()->enableUpdateViewer(false);
173   } else if (theMessage->eventID() == Events_Loop::eventByName(EVENT_UPDATE_VIEWER_UNBLOCKED)) {
174     // the viewer's update context is unblocked, the viewer's update works
175     XGUI_Displayer* aDisplayer = workshop()->displayer();
176     aDisplayer->enableUpdateViewer(true);
177     aDisplayer->updateViewer();
178   } else {
179     //Show error dialog if error message received.
180     std::shared_ptr<Events_Error> anAppError = std::dynamic_pointer_cast<Events_Error>(theMessage);
181     if (anAppError) {
182       emit errorOccurred(QString::fromLatin1(anAppError->description()));
183     }
184     return;
185   }
186   if (!workshop()->isSalomeMode()) {
187     SessionPtr aMgr = ModelAPI_Session::get();
188     AppElements_MainWindow* aMainWindow = workshop()->mainWindow();
189     if (aMgr->isModified() != aMainWindow->isModifiedState())
190       aMainWindow->setModifiedState(aMgr->isModified());
191   }
192 }
193
194 //******************************************************
195 void XGUI_WorkshopListener::onFeatureUpdatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
196 {
197   std::set<ObjectPtr> aFeatures = theMsg->objects();
198   XGUI_OperationMgr* anOperationMgr = workshop()->operationMgr();
199   if (anOperationMgr->hasOperation()) {
200     FeaturePtr aCurrentFeature = anOperationMgr->currentOperation()->feature();
201     std::set<ObjectPtr>::const_iterator aIt;
202     for (aIt = aFeatures.begin(); aIt != aFeatures.end(); ++aIt) {
203       ObjectPtr aNewFeature = (*aIt);
204       if (aNewFeature == aCurrentFeature) {
205         workshop()->propertyPanel()->updateContentWidget(aCurrentFeature);
206         break;
207       }
208     }
209   }
210   anOperationMgr->onValidateOperation();
211   //if (myObjectBrowser)
212   //  myObjectBrowser->processEvent(theMsg);
213 }
214
215 //******************************************************
216 void XGUI_WorkshopListener::onFeatureRedisplayMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
217 {
218   std::set<ObjectPtr> aObjects = theMsg->objects();
219   std::set<ObjectPtr>::const_iterator aIt;
220
221 #ifdef DEBUG_FEATURE_REDISPLAY
222   QStringList anInfo;
223   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
224     anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
225   }
226   QString anInfoStr = anInfo.join(", ");
227   qDebug(QString("onFeatureRedisplayMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
228 #endif
229
230   XGUI_Workshop* aWorkshop = workshop();
231   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
232   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
233     ObjectPtr aObj = (*aIt);
234
235     // Hide the object if it is invalid or concealed one
236     bool aHide = !aObj->data() || !aObj->data()->isValid() || 
237       aObj->isDisabled() || (!aObj->isDisplayed());
238     if (!aHide) { // check that this is not hidden result
239       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
240       aHide = aRes && aRes->isConcealed();
241     }
242     if (aHide)
243       aDisplayer->erase(aObj, false);
244     else {
245       // Redisplay the visible object or the object of the current operation
246       bool isVisibleObject = aDisplayer->isVisible(aObj);
247       #ifdef DEBUG_FEATURE_REDISPLAY
248       //QString anObjInfo = ModuleBase_Tools::objectInfo((aObj));
249       //qDebug(QString("visible=%1 : display= %2").arg(isVisibleObject).arg(anObjInfo).toStdString().c_str());
250       #endif
251
252       if (isVisibleObject)  { // redisplay visible object
253         //displayObject(aObj);  // In order to update presentation
254         // in order to avoid the check whether the object can be redisplayed, the exact method
255         // of redisplay is called. This modification is made in order to have the line is updated
256         // by creation of a horizontal constraint on the line by preselection
257         aDisplayer->redisplay(aObj, false);
258         // Deactivate object of current operation from selection
259         aWorkshop->deactivateActiveObject(aObj, false);
260       } else { // display object if the current operation has it
261         if (displayObject(aObj)) {
262           // Deactivate object of current operation from selection
263           aWorkshop->deactivateActiveObject(aObj, false);
264         }
265       }
266     }
267   }
268   aDisplayer->updateViewer();
269 }
270 //******************************************************
271 void XGUI_WorkshopListener::onFeatureCreatedMsg(const std::shared_ptr<ModelAPI_ObjectUpdatedMessage>& theMsg)
272 {
273   std::set<ObjectPtr> aObjects = theMsg->objects();
274   std::set<ObjectPtr>::const_iterator aIt;
275 #ifdef DEBUG_FEATURE_CREATED
276   QStringList anInfo;
277   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
278     anInfo.append(ModuleBase_Tools::objectInfo((*aIt)));
279   }
280   QString anInfoStr = anInfo.join(", ");
281   qDebug(QString("onFeatureCreatedMsg: %1, %2").arg(aObjects.size()).arg(anInfoStr).toStdString().c_str());
282 #endif
283
284   //bool aHasPart = false;
285   bool isDisplayed = false;
286   for (aIt = aObjects.begin(); aIt != aObjects.end(); ++aIt) {
287     ObjectPtr anObject = *aIt;
288     // the validity of the data should be checked here in order to avoid display of the objects,
289     // which were created, then deleted, but flush for the creation event happens after that
290     // we should not display disabled objects
291     bool aHide = !anObject->data()->isValid() || 
292                  anObject->isDisabled() ||
293                  !anObject->isDisplayed();
294     if (!aHide) {
295       // setDisplayed has to be called in order to synchronize internal state of the object 
296       // with list of displayed objects
297       if (myWorkshop->module()->canDisplayObject(anObject)) {
298         anObject->setDisplayed(true);
299         isDisplayed = displayObject(*aIt);
300       } else 
301         anObject->setDisplayed(false);
302     }
303   }
304   //if (myObjectBrowser)
305   //  myObjectBrowser->processEvent(theMsg);
306   if (isDisplayed)
307     workshop()->displayer()->updateViewer();
308   //if (aHasPart) { // TODO: Avoid activate last part on loading of document
309   //  activateLastPart();
310   //}
311 }
312
313 bool XGUI_WorkshopListener::event(QEvent * theEvent)
314 {
315   PostponeMessageQtEvent* aPostponedEv = dynamic_cast<PostponeMessageQtEvent*>(theEvent);
316   if (aPostponedEv) {
317     std::shared_ptr<Events_Message> aEventPtr = aPostponedEv->postponedMessage();
318     processEvent(aEventPtr);
319     return true;
320   }
321   return false;
322 }
323
324 void XGUI_WorkshopListener::addFeature(const std::shared_ptr<Config_FeatureMessage>& theMessage)
325 {
326   if (!theMessage) {
327 #ifdef _DEBUG
328     qDebug() << "XGUI_WorkshopListener::addFeature: NULL message.";
329 #endif
330     return;
331   }
332   ActionInfo aFeatureInfo;
333   aFeatureInfo.initFrom(theMessage);
334
335   XGUI_Workshop* aWorkshop = workshop();
336
337   QString aWchName = QString::fromStdString(theMessage->workbenchId());
338   QStringList aNestedFeatures =
339       QString::fromStdString(theMessage->nestedFeatures()).split(" ", QString::SkipEmptyParts);
340   QString aDocKind = QString::fromStdString(theMessage->documentKind());
341   QList<QAction*> aNestedActList;
342   bool isColumnButton = !aNestedFeatures.isEmpty();
343   if (isColumnButton) {
344     QString aNestedActions = QString::fromStdString(theMessage->actionsWhenNested());
345     XGUI_OperationMgr* anOperationMgr = aWorkshop->operationMgr();
346     XGUI_ActionsMgr* anActionsMgr = aWorkshop->actionsMgr();
347     if (aNestedActions.contains("accept")) {
348       QAction* anAction = anActionsMgr->operationStateAction(XGUI_ActionsMgr::AcceptAll, NULL);
349       connect(anAction, SIGNAL(triggered()), anOperationMgr, SLOT(commitAllOperations()));
350       aNestedActList << anAction;
351     }
352     if (aNestedActions.contains("abort")) {
353       QAction* anAction = anActionsMgr->operationStateAction(XGUI_ActionsMgr::AbortAll, NULL);
354       connect(anAction, SIGNAL(triggered()), anOperationMgr, SLOT(abortAllOperations()));
355       aNestedActList << anAction;
356     }
357   }
358
359   if (aWorkshop->isSalomeMode()) {
360     XGUI_SalomeConnector* aSalomeConnector = aWorkshop->salomeConnector();
361     QAction* aAction;
362     if (isColumnButton) {
363       aAction = aSalomeConnector->addNestedFeature(aWchName, aFeatureInfo, aNestedActList);
364     } else {
365       aAction = aSalomeConnector->addFeature(aWchName, aFeatureInfo);
366     }
367     aSalomeConnector->setNestedActions(aFeatureInfo.id, aNestedFeatures);
368     aSalomeConnector->setDocumentKind(aFeatureInfo.id, aDocKind);
369
370     aWorkshop->actionsMgr()->addCommand(aAction);
371     aWorkshop->module()->actionCreated(aAction);
372   } else {
373     //Find or create Workbench
374     AppElements_MainMenu* aMenuBar = aWorkshop->mainWindow()->menuObject();
375     AppElements_Workbench* aPage = aMenuBar->findWorkbench(aWchName);
376     if (!aPage) {
377       aPage = aWorkshop->addWorkbench(aWchName);
378     }
379     //Find or create Group
380     QString aGroupName = QString::fromStdString(theMessage->groupId());
381     AppElements_MenuGroupPanel* aGroup = aPage->findGroup(aGroupName);
382     if (!aGroup) {
383       aGroup = aPage->addGroup(aGroupName);
384     }
385     // Check if hotkey sequence is already defined:
386     XGUI_ActionsMgr* anActionsMgr = aWorkshop->actionsMgr();
387     QKeySequence aHotKey = anActionsMgr->registerShortcut(aFeatureInfo.shortcut);
388     if(aHotKey != aFeatureInfo.shortcut) {
389       aFeatureInfo.shortcut = aHotKey;
390     }
391     // Create feature...
392     AppElements_Command* aCommand = aGroup->addFeature(aFeatureInfo,
393                                                        aDocKind,
394                                                        aNestedFeatures);
395     // Enrich created button with accept/abort buttons if necessary
396     AppElements_Button* aButton = aCommand->button();
397     if (aButton->isColumnButton()) {
398       aButton->setAdditionalButtons(aNestedActList);
399     }
400     aWorkshop->actionsMgr()->addCommand(aCommand);
401     aWorkshop->module()->actionCreated(aCommand);
402   }
403 }
404
405
406 //**************************************************************
407 bool XGUI_WorkshopListener::displayObject(ObjectPtr theObj)
408 {
409    XGUI_Workshop* aWorkshop = workshop();
410   if (!aWorkshop->module()->canDisplayObject(theObj))
411     return false;
412
413   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
414   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theObj);
415   if (aBody.get() != NULL) {
416     int aNb = aDisplayer->objectsCount();
417     aDisplayer->display(theObj, false);
418     if (aNb == 0)
419       myWorkshop->viewer()->fitAll();
420   } else if (!aWorkshop->isLoadingData())
421     aDisplayer->display(theObj, false);
422
423   return true;
424 }
425
426 XGUI_Workshop* XGUI_WorkshopListener::workshop() const
427 {
428   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myWorkshop);
429   return aConnector->workshop();
430 }