Salome HOME
50c7734d280c69e7af1b38b516efb322c6be5353
[modules/shaper.git] / src / ModuleBase / ModuleBase_ModelWidget.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "ModuleBase_ModelWidget.h"
22 #include "ModuleBase_IPropertyPanel.h"
23 #include "ModuleBase_ViewerPrs.h"
24 #include "ModuleBase_Tools.h"
25 #include "ModuleBase_WidgetValidator.h"
26
27 #include <Events_InfoMessage.h>
28
29 #include <ModelAPI_Data.h>
30 #include <ModelAPI_Attribute.h>
31 #include <ModelAPI_Events.h>
32 #include <ModelAPI_Session.h>
33 #include <ModelAPI_Validator.h>
34
35 #include <Config_Keywords.h>
36 #include <Config_WidgetAPI.h>
37 #include <Config_Translator.h>
38 #include <Config_PropManager.h>
39
40 #include <Events_Loop.h>
41
42 #include <QEvent>
43 #include <QLabel>
44 #include <QFocusEvent>
45 #include <QTextCodec>
46
47 //#define DEBUG_VALUE_STATE
48
49 //#define DEBUG_WIDGET_INSTANCE
50 //#define DEBUG_ENABLE_SKETCH_INPUT_FIELDS
51
52 //**************************************************************
53 ModuleBase_ModelWidget::ModuleBase_ModelWidget(QWidget* theParent,
54                                                const Config_WidgetAPI* theData)
55     : QWidget(theParent),
56       myIsEditing(false),
57       myState(Stored),
58       myIsValueStateBlocked(false),
59       myFlushUpdateBlocked(false),
60       myWidgetValidator(0)
61 {
62 #ifdef DEBUG_WIDGET_INSTANCE
63   qDebug("ModuleBase_ModelWidget::ModuleBase_ModelWidget");
64 #endif
65
66   myFeatureId = theData->featureId();
67
68   myIsInternal = theData->getBooleanAttribute(ATTR_INTERNAL, false);
69
70   myIsModifiedInEdit = theData->getProperty(ATTR_MODIFIED_IN_EDIT);
71
72   myDefaultValue = theData->getProperty(ATTR_DEFAULT);
73   myUseReset = theData->getBooleanAttribute(ATTR_USE_RESET, true);
74   myIsComputedDefault = theData->getProperty(ATTR_DEFAULT) == DOUBLE_WDG_DEFAULT_COMPUTED;
75   myAttributeID = theData ? theData->widgetId() : "";
76   myIsObligatory = theData->getBooleanAttribute(ATTR_OBLIGATORY, true);
77
78   myIsValueEnabled = On; // not defined or "true"
79   std::string anEnableValue = theData->getProperty(DOUBLE_WDG_ENABLE_VALUE);
80   if (anEnableValue == "false")
81     myIsValueEnabled = Off;
82   if (anEnableValue == DOUBLE_WDG_ENABLE_VALUE_BY_PREFERENCES)
83     myIsValueEnabled = DefinedInPreferences;
84
85   connect(this, SIGNAL(valuesChanged()), this, SLOT(onWidgetValuesChanged()));
86   connect(this, SIGNAL(valuesModified()), this, SLOT(onWidgetValuesModified()));
87 }
88
89 //**************************************************************
90 ModuleBase_ModelWidget::~ModuleBase_ModelWidget()
91 {
92 #ifdef DEBUG_WIDGET_INSTANCE
93   qDebug("ModuleBase_ModelWidget::~ModuleBase_ModelWidget");
94 #endif
95 }
96
97 //**************************************************************
98 bool ModuleBase_ModelWidget::reset()
99 {
100   bool aResult = resetCustom();
101   if (aResult)
102     setValueState(Reset);
103
104   return aResult;
105 }
106
107 //**************************************************************
108 bool ModuleBase_ModelWidget::isInitialized(ObjectPtr theObject) const
109 {
110   return theObject->data()->attribute(attributeID())->isInitialized();
111 }
112
113 //**************************************************************
114 void ModuleBase_ModelWidget::selectionModes(int& theModuleSelectionModes, QIntList& theModes)
115 {
116   theModuleSelectionModes = -1;
117   if (myWidgetValidator)
118     myWidgetValidator->selectionModes(theModuleSelectionModes, theModes);
119 }
120
121 //**************************************************************
122 void ModuleBase_ModelWidget::selectionFilters(QIntList& theModuleSelectionFilters,
123                                               SelectMgr_ListOfFilter& theSelectionFilters)
124 {
125   if (myWidgetValidator)
126     myWidgetValidator->selectionFilters(theModuleSelectionFilters, theSelectionFilters);
127 }
128
129 //**************************************************************
130 bool ModuleBase_ModelWidget::isValueEnabled() const
131 {
132   bool anEnabled = true;
133   if (myIsValueEnabled == DefinedInPreferences) {
134 #ifdef DEBUG_ENABLE_SKETCH_INPUT_FIELDS
135     bool aCanDisable = false;
136 #else
137     //Config_PropManager::boolean(SKETCH_TAB_NAME, "disable_input_fields", "true");
138     bool aCanDisable = true;
139 #endif
140     if (aCanDisable)
141       anEnabled = false;
142   }
143   else if (myIsValueEnabled == Off)
144     anEnabled = false;
145   return anEnabled;
146 }
147
148 //**************************************************************
149 void ModuleBase_ModelWidget::processValueState()
150 {
151   if (myState == ModifiedInPP || myState == ModifiedInViewer)
152     storeValue();
153 }
154
155 //**************************************************************
156 Events_InfoMessage ModuleBase_ModelWidget::getValueStateError() const
157 {
158   Events_InfoMessage aMessage;
159
160   ModuleBase_ModelWidget::ValueState aState = getValueState();
161   if (aState != ModuleBase_ModelWidget::Stored) {
162     AttributePtr anAttr = feature()->attribute(attributeID());
163     if (anAttr.get()) {
164       const std::string& anAttributeName = anAttr->id();
165       switch (aState) {
166         case ModuleBase_ModelWidget::ModifiedInViewer:
167           aMessage = "Attribute \"%1\" is locked by modification value in the viewer.";
168           aMessage.addParameter(anAttributeName);
169           break;
170         case ModuleBase_ModelWidget::Reset:
171           aMessage = "Attribute \"%1\" is not initialized.";
172           aMessage.addParameter(anAttributeName);
173           break;
174         case ModuleBase_ModelWidget::ModifiedInPP: // Apply should be enabled in this mode
175         default:
176           break;
177       }
178     }
179   }
180   return aMessage;
181 }
182
183 //**************************************************************
184 QString ModuleBase_ModelWidget::getError(const bool theValueStateChecked) const
185 {
186   QString anError;
187
188   if (!feature().get())
189     return anError;
190
191   std::string aFeatureID = feature()->getKind();
192   std::string anAttributeID = attributeID();
193   AttributePtr anAttribute = feature()->attribute(anAttributeID);
194   if (!anAttribute.get())
195     return anError;
196
197   std::string aValidatorID;
198   Events_InfoMessage anErrorMsg;
199
200   static ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
201   if (!aValidators->validate(anAttribute, aValidatorID, anErrorMsg)) {
202     if (anErrorMsg.empty())
203       anErrorMsg = "Unknown error.";
204
205     if (anErrorMsg.context().empty()) {
206       anErrorMsg.setContext(aFeatureID + ":" + anAttributeID + ":" + aValidatorID);
207     }
208   }
209
210   if (anErrorMsg.empty() && theValueStateChecked) {
211     anErrorMsg = getValueStateError();
212   }
213
214   if (!anErrorMsg.empty()) {
215     anError = ModuleBase_Tools::translate(anErrorMsg);
216   }
217
218   return anError;
219 }
220
221 //**************************************************************
222 void ModuleBase_ModelWidget::enableFocusProcessing()
223 {
224   QList<QWidget*> aMyControls = getControls();
225   foreach(QWidget*  eachControl, aMyControls) {
226       eachControl->setFocusPolicy(Qt::StrongFocus);
227       eachControl->installEventFilter(this);
228   }
229 }
230
231 //**************************************************************
232 void ModuleBase_ModelWidget::setHighlighted(bool isHighlighted)
233 {
234   QList<QWidget*> aWidgetList = getControls();
235   foreach(QWidget* aWidget, aWidgetList) {
236     QLabel* aLabel = qobject_cast<QLabel*>(aWidget);
237     // We won't set the effect to QLabels - it looks ugly
238     if(aLabel) continue;
239     // If effect is the installed on a different widget, setGraphicsEffect() will
240     // remove the effect from the widget and install it on this widget.
241     // That's why we create a new effect for each widget
242     ModuleBase_Tools::setShadowEffect(aWidget, isHighlighted);
243   }
244 }
245
246 //**************************************************************
247 void ModuleBase_ModelWidget::setFeature(const FeaturePtr& theFeature, const bool theToStoreValue,
248                                         const bool isUpdateFlushed)
249 {
250   /// it is possible to give this flag as parameter in storeValue/storeCustomValue
251   /// after debug, it may be corrected
252   myFlushUpdateBlocked = !isUpdateFlushed;
253   myFeature = theFeature;
254   if (theToStoreValue) {
255     /// it is possible that the attribute is filled before the operation is started,
256     /// e.g. by reentrant operation case some attributes are filled by values of
257     /// feature of previous operation, we should not lost them here
258     if (!theFeature->data()->attribute(attributeID())->isInitialized())
259       storeValue();
260   }
261   myFlushUpdateBlocked = false;
262 }
263
264 //**************************************************************
265 bool ModuleBase_ModelWidget::focusTo()
266 {
267 #ifdef DEBUG_WIDGET_INSTANCE
268   qDebug("ModuleBase_ModelWidget::focusTo");
269 #endif
270   QList<QWidget*> aControls = getControls();
271   QList<QWidget*>::const_iterator anIt = aControls.begin(), aLast = aControls.end();
272   bool isFocusAccepted = false;
273   for (; anIt != aLast && !isFocusAccepted; anIt++) {
274     QWidget* aWidget = *anIt;
275     if (aWidget && aWidget->focusPolicy() != Qt::NoFocus) {
276       ModuleBase_Tools::setFocus(aWidget, "ModuleBase_ModelWidget::focusTo()");
277       isFocusAccepted = true;
278     }
279   }
280   return isFocusAccepted;
281 }
282
283 //**************************************************************
284 void ModuleBase_ModelWidget::activate()
285 {
286 #ifdef DEBUG_WIDGET_INSTANCE
287   qDebug("ModuleBase_ModelWidget::activate");
288 #endif
289   // the control value is stored to the mode by the focus in on the widget
290   // we need the value is initialized in order to enable the apply button in the property panel.
291   // It should happens in the creation mode only because all fields are filled in the edition mode
292   if (!isEditingMode()) {
293     AttributePtr anAttribute = myFeature->data()->attribute(myAttributeID);
294     if (anAttribute.get() != NULL && !anAttribute->isInitialized())
295       initializeValueByActivate();
296   }
297   activateCustom();
298 }
299
300 //**************************************************************
301 void ModuleBase_ModelWidget::deactivate()
302 {
303 #ifdef DEBUG_WIDGET_INSTANCE
304   qDebug("ModuleBase_ModelWidget::deactivate");
305 #endif
306   myIsValueStateBlocked = false;
307   myState = Stored;
308   if (myWidgetValidator)
309     myWidgetValidator->clearValidatedCash();
310 }
311
312 //**************************************************************
313 void ModuleBase_ModelWidget::initializeValueByActivate()
314 {
315   if (isComputedDefault()) {
316     if (myFeature->compute(myAttributeID)) {
317       restoreValue();
318     }
319   }
320   else {
321     storeValue();
322   }
323 }
324
325 //**************************************************************
326 QWidget* ModuleBase_ModelWidget::getControlAcceptingFocus(const bool isFirst)
327 {
328   QWidget* aControl = 0;
329
330   QList<QWidget*> aControls = getControls();
331   int aSize = aControls.size();
332
333   if (isFirst) {
334     for (int i = 0; i < aSize && !aControl; i++)  {
335       if (aControls[i]->focusPolicy() != Qt::NoFocus)
336         aControl = aControls[i];
337     }
338   }
339   else {
340     for (int i = aSize - 1; i >= 0 && !aControl; i--)  {
341       if (aControls[i]->focusPolicy() != Qt::NoFocus)
342         aControl = aControls[i];
343     }
344   }
345   return aControl;
346 }
347
348 //**************************************************************
349 void ModuleBase_ModelWidget::setDefaultValue(const std::string& theValue)
350 {
351   myDefaultValue = theValue;
352 }
353
354 //**************************************************************
355 bool ModuleBase_ModelWidget::storeValue()
356 {
357   setValueState(Stored);
358
359   emit beforeValuesChanged();
360   bool isDone = false;
361   // value is stored only in creation mode and in edition if there is not
362   // XML flag prohibited modification in edit mode(macro feature circle/arc)
363   if (!isEditingMode() || isModifiedInEdit().empty())
364     isDone = storeValueCustom();
365   else {
366     /// store value in an alternative attribute if possible(attribute has the same type)
367     std::string aWidgetAttribute = attributeID();
368     myAttributeID = isModifiedInEdit();
369     storeValueCustom();
370     myAttributeID = aWidgetAttribute;
371     // operation will be restarted but if isDone == true, PagedContainer will try to set focus
372     // to the current widget, but will be already deleted
373     isDone = false;
374   }
375
376   emit afterValuesChanged();
377
378   return isDone;
379 }
380 #ifdef DEBUG_VALUE_STATE
381
382 //**************************************************************
383 std::string getDebugInfo(const ModuleBase_ModelWidget::ValueState& theState)
384 {
385   std::string anInfo;
386   switch (theState) {
387     case ModuleBase_ModelWidget::Stored:           anInfo = "Stored          "; break;
388     case ModuleBase_ModelWidget::ModifiedInPP:     anInfo = "ModifiedInPP    "; break;
389     case ModuleBase_ModelWidget::ModifiedInViewer: anInfo = "ModifiedInViewer"; break;
390     case ModuleBase_ModelWidget::Reset:            anInfo = "Reset           "; break;
391     default: break;
392   }
393   return anInfo;
394 }
395 #endif
396
397 //**************************************************************
398 ModuleBase_ModelWidget::ValueState ModuleBase_ModelWidget::setValueState
399                                          (const ModuleBase_ModelWidget::ValueState& theState)
400 {
401   ValueState aState = myState;
402
403   if (myState != theState && !myIsValueStateBlocked) {
404 #ifdef DEBUG_VALUE_STATE
405     qDebug(QString("setValueState: previous state = %1,\t new state = %2")
406            .arg(getDebugInfo(myState).c_str())
407            .arg(getDebugInfo(theState).c_str()).toStdString().c_str());
408 #endif
409     myState = theState;
410     emit valueStateChanged(aState);
411   }
412   return aState;
413 }
414
415 //**************************************************************
416 bool ModuleBase_ModelWidget::blockValueState(const bool theBlocked)
417 {
418   bool isBlocked = myIsValueStateBlocked;
419   myIsValueStateBlocked = theBlocked;
420   return isBlocked;
421 }
422
423 //**************************************************************
424 bool ModuleBase_ModelWidget::restoreValue()
425 {
426   emit beforeValuesRestored();
427   bool isDone = restoreValueCustom();
428   emit afterValuesRestored();
429
430   return isDone;
431 }
432
433 //**************************************************************
434 void ModuleBase_ModelWidget::updateObject(ObjectPtr theObject)
435 {
436   if (!myFlushUpdateBlocked) {
437 #ifdef DEBUG_WIDGET_INSTANCE
438     qDebug("ModuleBase_ModelWidget::updateObject");
439 #endif
440     ModuleBase_Tools::flushUpdated(theObject);
441     emit objectUpdated();
442   }
443 }
444
445 //**************************************************************
446 bool ModuleBase_ModelWidget::canProcessAction(ModuleBase_ActionType theActionType,
447                                               bool& isActionEnabled)
448 {
449   isActionEnabled = false;
450   switch (theActionType) {
451     case ActionEnter: return false;
452     case ActionEscape: return false;
453     case ActionDelete: return true;
454     case ActionSelection: return true;
455     case ActionUndo:
456     case ActionRedo:
457     default:
458       return false;
459   }
460 }
461
462 //**************************************************************
463 bool ModuleBase_ModelWidget::processAction(ModuleBase_ActionType theActionType,
464                                            const ActionParamPtr& theParam)
465 {
466   switch (theActionType) {
467     case ActionEnter:
468       return processEnter();
469     case ActionEscape:
470       return processEscape();
471     case ActionDelete:
472       return processDelete();
473     case ActionSelection:
474       processSelection();
475     case ActionUndo:
476     case ActionRedo:
477     default:
478       return false;
479   }
480 }
481
482 //**************************************************************
483 bool ModuleBase_ModelWidget::processEnter()
484 {
485   return false;
486 }
487
488 //**************************************************************
489 bool ModuleBase_ModelWidget::processEscape()
490 {
491   return false;
492 }
493
494 //**************************************************************
495 bool ModuleBase_ModelWidget::processDelete()
496 {
497   // we consider that model objects eats delete key in order to
498   // do nothing by for example symbol delete in line edit or spin box
499   return true;
500 }
501
502 //**************************************************************
503 bool ModuleBase_ModelWidget::processSelection()
504 {
505   return false;
506 }
507
508 //**************************************************************
509 bool ModuleBase_ModelWidget::eventFilter(QObject* theObject, QEvent *theEvent)
510 {
511   QWidget* aWidget = qobject_cast<QWidget*>(theObject);
512   if (theEvent->type() == QEvent::FocusIn) {
513     QFocusEvent* aFocusEvent = dynamic_cast<QFocusEvent*>(theEvent);
514     Qt::FocusReason aReason = aFocusEvent->reason();
515     bool aMouseOrKey = aReason == Qt::MouseFocusReason ||
516                         /*aReason == Qt::TabFocusReason ||
517                         //aReason == Qt::BacktabFocusReason ||*/
518                         aReason == Qt::OtherFocusReason; // to process widget->setFocus()
519     if (aMouseOrKey && getControls().contains(aWidget)) {
520     //if (getControls().contains(aWidget)) {
521       emitFocusInWidget();
522     }
523   }
524   else if (theEvent->type() == QEvent::FocusOut) {
525     QFocusEvent* aFocusEvent = dynamic_cast<QFocusEvent*>(theEvent);
526
527     Qt::FocusReason aReason = aFocusEvent->reason();
528     bool aMouseOrKey = aReason == Qt::MouseFocusReason ||
529                         aReason == Qt::TabFocusReason ||
530                         aReason == Qt::BacktabFocusReason ||
531                         aReason == Qt::OtherFocusReason; // to process widget->setFocus()
532     if (aMouseOrKey && getControls().contains(aWidget)) {
533       if (getValueState() == ModifiedInPP) {
534         storeValue();
535       }
536     }
537   }
538   // pass the event on to the parent class
539
540   return QObject::eventFilter(theObject, theEvent);
541 }
542
543 //**************************************************************
544 void ModuleBase_ModelWidget::onWidgetValuesChanged()
545 {
546   storeValue();
547 }
548
549 //**************************************************************
550 void ModuleBase_ModelWidget::onWidgetValuesModified()
551 {
552   setValueState(ModifiedInPP);
553 }
554
555 //**************************************************************
556 QString ModuleBase_ModelWidget::translate(const std::string& theStr) const
557 {
558   return ModuleBase_Tools::translate(context(), theStr);
559 }
560
561 //**************************************************************
562 ModuleBase_ModelWidget* ModuleBase_ModelWidget::findModelWidget(ModuleBase_IPropertyPanel* theProp,
563                                                                 QWidget* theWidget)
564 {
565   ModuleBase_ModelWidget* aModelWidget = 0;
566   if (!theWidget)
567     return aModelWidget;
568
569   QObject* aParent = theWidget->parent();
570   while (aParent) {
571     aModelWidget = qobject_cast<ModuleBase_ModelWidget*>(aParent);
572     if (aModelWidget)
573       break;
574     aParent = aParent->parent();
575   }
576   return aModelWidget;
577 }