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