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