Salome HOME
Issue #1005: To improve user-friendship of error-messages for features and attributes
[modules/shaper.git] / src / ModuleBase / ModuleBase_ModelWidget.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        ModuleBase_ModelWidget.cpp
4 // Created:     25 Apr 2014
5 // Author:      Natalia ERMOLAEVA
6
7 #include "ModuleBase_ModelWidget.h"
8 #include "ModuleBase_ViewerPrs.h"
9 #include "ModuleBase_Tools.h"
10 #include "ModuleBase_WidgetValidator.h"
11
12 #include <Events_InfoMessage.h>
13
14 #include <ModelAPI_Data.h>
15 #include <ModelAPI_Attribute.h>
16 #include <ModelAPI_Events.h>
17 #include <ModelAPI_Session.h>
18 #include <ModelAPI_Validator.h>
19
20 #include <Config_Keywords.h>
21 #include <Config_WidgetAPI.h>
22 #include <Config_Translator.h>
23 #include <Config_PropManager.h>
24
25 #include <Events_Loop.h>
26
27 #include <QEvent>
28 #include <QLabel>
29 #include <QFocusEvent>
30 #include <QTextCodec>
31
32 //#define DEBUG_VALUE_STATE
33
34 //#define DEBUG_WIDGET_INSTANCE
35 //#define DEBUG_ENABLE_SKETCH_INPUT_FIELDS
36
37 ModuleBase_ModelWidget::ModuleBase_ModelWidget(QWidget* theParent,
38                                                const Config_WidgetAPI* theData)
39     : QWidget(theParent),
40       myIsEditing(false),
41       myState(Stored),
42       myIsValueStateBlocked(false),
43       myFlushUpdateBlocked(false),
44       myWidgetValidator(0)
45 {
46 #ifdef DEBUG_WIDGET_INSTANCE
47   qDebug("ModuleBase_ModelWidget::ModuleBase_ModelWidget");
48 #endif
49
50   myFeatureId = theData->featureId();
51
52   myIsInternal = theData->getBooleanAttribute(ATTR_INTERNAL, false);
53
54   myDefaultValue = theData->getProperty(ATTR_DEFAULT);
55   myUseReset = theData->getBooleanAttribute(ATTR_USE_RESET, true);
56   myIsComputedDefault = theData->getProperty(ATTR_DEFAULT) == DOUBLE_WDG_DEFAULT_COMPUTED;
57   myAttributeID = theData ? theData->widgetId() : "";
58   myIsObligatory = theData->getBooleanAttribute(ATTR_OBLIGATORY, true);
59
60   myIsValueEnabled = On; // not defined or "true"
61   std::string anEnableValue = theData->getProperty(DOUBLE_WDG_ENABLE_VALUE);
62   if (anEnableValue == "false")
63     myIsValueEnabled = Off;
64   if (anEnableValue == DOUBLE_WDG_ENABLE_VALUE_BY_PREFERENCES)
65     myIsValueEnabled = DefinedInPreferences;
66
67   connect(this, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
68   connect(this, SIGNAL(valuesModified()), this, SLOT(onWidgetValuesModified()));
69 }
70
71 ModuleBase_ModelWidget::~ModuleBase_ModelWidget()
72 {
73 #ifdef DEBUG_WIDGET_INSTANCE
74   qDebug("ModuleBase_ModelWidget::~ModuleBase_ModelWidget");
75 #endif
76 }
77
78 bool ModuleBase_ModelWidget::reset()
79 {
80   bool aResult = resetCustom();
81   if (aResult)
82     setValueState(Reset);
83
84   return aResult;
85 }
86
87 bool ModuleBase_ModelWidget::isInitialized(ObjectPtr theObject) const
88 {
89   return theObject->data()->attribute(attributeID())->isInitialized();
90 }
91
92 bool ModuleBase_ModelWidget::isValueEnabled() const
93 {
94   bool anEnabled = true;
95   if (myIsValueEnabled == DefinedInPreferences) {
96 #ifdef DEBUG_ENABLE_SKETCH_INPUT_FIELDS
97     bool aCanDisable = false;
98 #else
99     //Config_PropManager::boolean(SKETCH_TAB_NAME, "disable_input_fields", "true");
100     bool aCanDisable = true;
101 #endif
102     if (aCanDisable)
103       anEnabled = false;
104   }
105   else if (myIsValueEnabled == Off)
106     anEnabled = false;
107   return anEnabled;
108 }
109
110 void ModuleBase_ModelWidget::processValueState()
111 {
112   if (myState == ModifiedInPP || myState == ModifiedInViewer)
113     storeValue();
114 }
115
116 Events_InfoMessage ModuleBase_ModelWidget::getValueStateError() const
117 {
118   Events_InfoMessage aMessage;
119
120   ModuleBase_ModelWidget::ValueState aState = getValueState();
121   if (aState != ModuleBase_ModelWidget::Stored) {
122     AttributePtr anAttr = feature()->attribute(attributeID());
123     if (anAttr.get()) {
124       const std::string& anAttributeName = anAttr->id();
125       switch (aState) {
126         case ModuleBase_ModelWidget::ModifiedInViewer:
127           aMessage = "Attribute \"%1\" is locked by modification value in the viewer.";
128           aMessage.addParameter(anAttributeName);
129           break;
130         case ModuleBase_ModelWidget::Reset:
131           aMessage = "Attribute \"%1\" is not initialized.";
132           aMessage.addParameter(anAttributeName);
133           break;
134         case ModuleBase_ModelWidget::ModifiedInPP: // Apply should be enabled in this mode
135         default:
136           break;
137       }
138     }
139   }
140   return aMessage;
141 }
142
143 QString ModuleBase_ModelWidget::getError(const bool theValueStateChecked) const
144 {
145   QString anError;
146
147   if (!feature().get())
148     return anError;
149
150   std::string aFeatureID = feature()->getKind();
151   std::string anAttributeID = attributeID();
152   AttributePtr anAttribute = feature()->attribute(anAttributeID);
153   if (!anAttribute.get())
154     return anError;
155
156   std::string aValidatorID;
157   Events_InfoMessage anErrorMsg;
158
159   static ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
160   if (!aValidators->validate(anAttribute, aValidatorID, anErrorMsg)) {
161     if (anErrorMsg.empty())
162       anErrorMsg = "Unknown error.";
163
164     if (anErrorMsg.context().empty()) {
165       anErrorMsg.setContext(aFeatureID + ":" + anAttributeID + ":" + aValidatorID);
166     }
167   }
168
169   if (anErrorMsg.empty() && theValueStateChecked) {
170     anErrorMsg = getValueStateError();
171   }
172
173   if (!anErrorMsg.empty()) {
174     anError = ModuleBase_Tools::translate(anErrorMsg);
175   }
176
177   return anError;
178 }
179
180 void ModuleBase_ModelWidget::enableFocusProcessing()
181 {
182   QList<QWidget*> aMyControls = getControls();
183   foreach(QWidget*  eachControl, aMyControls) {
184       eachControl->setFocusPolicy(Qt::StrongFocus);
185       eachControl->installEventFilter(this);
186   }
187 }
188
189 void ModuleBase_ModelWidget::setHighlighted(bool isHighlighted)
190 {
191   QList<QWidget*> aWidgetList = getControls();
192   foreach(QWidget* aWidget, aWidgetList) {
193     QLabel* aLabel = qobject_cast<QLabel*>(aWidget);
194     // We won't set the effect to QLabels - it looks ugly
195     if(aLabel) continue;
196     // If effect is the installed on a different widget, setGraphicsEffect() will
197     // remove the effect from the widget and install it on this widget.
198     // That's why we create a new effect for each widget
199     ModuleBase_Tools::setShadowEffect(aWidget, isHighlighted);
200   }
201 }
202
203 void ModuleBase_ModelWidget::setFeature(const FeaturePtr& theFeature, const bool theToStoreValue,
204                                         const bool isUpdateFlushed)
205 {
206   /// it is possible to give this flag as parameter in storeValue/storeCustomValue
207   /// after debug, it may be corrected
208   myFlushUpdateBlocked = !isUpdateFlushed;
209   myFeature = theFeature;
210   if (theToStoreValue) {
211     /// it is possible that the attribute is filled before the operation is started,
212     /// e.g. by reentrant operation case some attributes are filled by values of
213     /// feature of previous operation, we should not lost them here
214     if (!theFeature->data()->attribute(attributeID())->isInitialized())
215       storeValue();
216   }
217   myFlushUpdateBlocked = false;
218 }
219
220 bool ModuleBase_ModelWidget::focusTo()
221 {
222 #ifdef DEBUG_WIDGET_INSTANCE
223   qDebug("ModuleBase_ModelWidget::focusTo");
224 #endif
225   QList<QWidget*> aControls = getControls();
226   QList<QWidget*>::const_iterator anIt = aControls.begin(), aLast = aControls.end();
227   bool isFocusAccepted = false;
228   for (; anIt != aLast && !isFocusAccepted; anIt++) {
229     QWidget* aWidget = *anIt;
230     if (aWidget && aWidget->focusPolicy() != Qt::NoFocus) {
231       ModuleBase_Tools::setFocus(aWidget, "ModuleBase_ModelWidget::focusTo()");
232       isFocusAccepted = true;
233     }
234   }
235   return isFocusAccepted;
236 }
237
238 void ModuleBase_ModelWidget::activate()
239 {
240 #ifdef DEBUG_WIDGET_INSTANCE
241   qDebug("ModuleBase_ModelWidget::activate");
242 #endif
243   // the control value is stored to the mode by the focus in on the widget
244   // we need the value is initialized in order to enable the apply button in the property panel.
245   // It should happens in the creation mode only because all fields are filled in the edition mode
246   if (!isEditingMode()) {
247     AttributePtr anAttribute = myFeature->data()->attribute(myAttributeID);
248     if (anAttribute.get() != NULL && !anAttribute->isInitialized())
249       initializeValueByActivate();
250   }
251
252   if (myWidgetValidator)
253     myWidgetValidator->activateFilters(true);
254
255   activateCustom();
256 }
257
258 void ModuleBase_ModelWidget::deactivate()
259 {
260 #ifdef DEBUG_WIDGET_INSTANCE
261   qDebug("ModuleBase_ModelWidget::deactivate");
262 #endif
263   myIsValueStateBlocked = false;
264   myState = Stored;
265   if (myWidgetValidator)
266     myWidgetValidator->activateFilters(false);
267 }
268
269 void ModuleBase_ModelWidget::initializeValueByActivate()
270 {
271   if (isComputedDefault()) {
272     if (myFeature->compute(myAttributeID)) {
273       restoreValue();
274     }
275   }
276   else {
277     storeValue();
278   }
279 }
280
281 QWidget* ModuleBase_ModelWidget::getControlAcceptingFocus(const bool isFirst)
282 {
283   QWidget* aControl = 0;
284
285   QList<QWidget*> aControls = getControls();
286   int aSize = aControls.size();
287
288   if (isFirst) {
289     for (int i = 0; i < aSize && !aControl; i++)  {
290       if (aControls[i]->focusPolicy() != Qt::NoFocus)
291         aControl = aControls[i];
292     }
293   }
294   else {
295     for (int i = aSize - 1; i >= 0 && !aControl; i--)  {
296       if (aControls[i]->focusPolicy() != Qt::NoFocus)
297         aControl = aControls[i];
298     }
299   }
300   return aControl;
301 }
302
303 void ModuleBase_ModelWidget::setDefaultValue(const std::string& theValue)
304 {
305   myDefaultValue = theValue;
306 }
307
308 bool ModuleBase_ModelWidget::storeValue()
309 {
310   setValueState(Stored);
311
312   emit beforeValuesChanged();
313   bool isDone = storeValueCustom();
314   emit afterValuesChanged();
315
316   return isDone;
317 }
318 #ifdef DEBUG_VALUE_STATE
319 std::string getDebugInfo(const ModuleBase_ModelWidget::ValueState& theState)
320 {
321   std::string anInfo;
322   switch (theState) {
323     case ModuleBase_ModelWidget::Stored:           anInfo = "Stored          "; break;
324     case ModuleBase_ModelWidget::ModifiedInPP:     anInfo = "ModifiedInPP    "; break;
325     case ModuleBase_ModelWidget::ModifiedInViewer: anInfo = "ModifiedInViewer"; break;
326     case ModuleBase_ModelWidget::Reset:            anInfo = "Reset           "; break;
327     default: break;
328   }
329   return anInfo;
330 }
331
332 #endif
333 ModuleBase_ModelWidget::ValueState ModuleBase_ModelWidget::setValueState
334                                          (const ModuleBase_ModelWidget::ValueState& theState)
335 {
336   ValueState aState = myState;
337
338   if (myState != theState && !myIsValueStateBlocked) {
339 #ifdef DEBUG_VALUE_STATE
340     qDebug(QString("setValueState: previous state = %1,\t new state = %2")
341            .arg(getDebugInfo(myState).c_str())
342            .arg(getDebugInfo(theState).c_str()).toStdString().c_str());
343 #endif
344     myState = theState;
345     emit valueStateChanged(aState);
346   }
347   return aState;
348 }
349
350 bool ModuleBase_ModelWidget::blockValueState(const bool theBlocked)
351 {
352   bool isBlocked = myIsValueStateBlocked;
353   myIsValueStateBlocked = theBlocked;
354   return isBlocked;
355 }
356
357 bool ModuleBase_ModelWidget::restoreValue()
358 {
359   emit beforeValuesRestored();
360   bool isDone = restoreValueCustom();
361   emit afterValuesRestored();
362
363   return isDone;
364 }
365
366 void ModuleBase_ModelWidget::updateObject(ObjectPtr theObject)
367 {
368   if (!myFlushUpdateBlocked) {
369 #ifdef DEBUG_WIDGET_INSTANCE
370     qDebug("ModuleBase_ModelWidget::updateObject");
371 #endif
372     ModuleBase_Tools::flushUpdated(theObject);
373     emit objectUpdated();
374   }
375 }
376
377 void ModuleBase_ModelWidget::moveObject(ObjectPtr theObj)
378 {
379   //blockUpdateViewer(true);
380 #ifdef DEBUG_WIDGET_INSTANCE
381   qDebug("ModuleBase_ModelWidget::moveObject");
382 #endif
383
384   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
385   ModelAPI_EventCreator::get()->sendUpdated(theObj, anEvent);
386   Events_Loop::loop()->flush(anEvent);
387
388   //blockUpdateViewer(false);
389 }
390
391 bool ModuleBase_ModelWidget::processEnter()
392 {
393   return false;
394 }
395
396 bool ModuleBase_ModelWidget::processDelete()
397 {
398   // we consider that model objects eats delete key in order to
399   // do nothing by for example symbol delete in line edit or spin box
400   return true;
401 }
402
403 bool ModuleBase_ModelWidget::eventFilter(QObject* theObject, QEvent *theEvent)
404 {
405   QWidget* aWidget = qobject_cast<QWidget*>(theObject);
406   if (theEvent->type() == QEvent::FocusIn) {
407     #ifdef _DEBUG
408     // The following two lines are for debugging purpose only
409     QFocusEvent* aFocusEvent = dynamic_cast<QFocusEvent*>(theEvent);
410     bool isWinFocus = aFocusEvent->reason() == Qt::ActiveWindowFocusReason;
411     #endif
412     if (getControls().contains(aWidget)) {
413       emit focusInWidget(this);
414     }
415   }
416   else if (theEvent->type() == QEvent::FocusOut) {
417     QFocusEvent* aFocusEvent = dynamic_cast<QFocusEvent*>(theEvent);
418
419     Qt::FocusReason aReason = aFocusEvent->reason();
420     bool aMouseOrKey = aReason == Qt::MouseFocusReason ||
421                         aReason == Qt::TabFocusReason ||
422                         aReason == Qt::BacktabFocusReason ||
423                         aReason == Qt::OtherFocusReason; // to process widget->setFocus()
424     if (aMouseOrKey && getControls().contains(aWidget)) {
425       if (getValueState() == ModifiedInPP) {
426         storeValue();
427       }
428     }
429   }
430   // pass the event on to the parent class
431
432   return QObject::eventFilter(theObject, theEvent);
433 }
434
435 //**************************************************************
436 void ModuleBase_ModelWidget::onWidgetValuesChanged()
437 {
438   storeValue();
439 }
440
441 //**************************************************************
442 void ModuleBase_ModelWidget::onWidgetValuesModified()
443 {
444   setValueState(ModifiedInPP);
445 }
446
447 QString ModuleBase_ModelWidget::translate(const std::string& theStr) const
448 {
449   return ModuleBase_Tools::translate(context(), theStr);
450 }