-
Notifications
You must be signed in to change notification settings - Fork 0
/
FloatInput.cpp
70 lines (64 loc) · 2.17 KB
/
FloatInput.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "FloatInput.h"
#include "General.h"
FloatInput::FloatInput(wxWindow* parent, wxWindowID textCtrlId, std::string labelText, float initialValue, wxPoint topLeft,
TextChangeFunc textChangeFunc, FloatValidationFunc floatValidationFunc, float nullValue,
int labelWidth, int textInputWidth, int initialDecimalPlaces)
: textChangeFunc(textChangeFunc), floatValidationFunc(floatValidationFunc), nullValue(nullValue), parent(parent)
{
staticText = new wxStaticText(parent, 0, labelText, topLeft, wxSize(labelWidth, Height));
textCtrl = new wxTextCtrl(parent, textCtrlId, formatFloat(initialValue, initialDecimalPlaces, false, nullValue),
topLeft + wxSize(labelWidth, 0), wxSize(textInputWidth, Height));
parent->Bind(wxEVT_TEXT, &FloatInput::updateText, this, textCtrl->GetId());
}
float FloatInput::getValue() const
{
std::string str = textCtrl->GetValue().ToStdString();
if (str.empty()) {
if (nullValue == std::numeric_limits<float>::lowest()) return 0.0f;
return nullValue;
}
else if (str == "-") {
return 0.0f;
}
else {
return std::stof(str);
}
}
void FloatInput::updateText(wxCommandEvent & event)
{
if (currentlyUpdating) return;
currentlyUpdating = true;
float value = nullValue;
std::string str = event.GetString().ToStdString();
// updates the preliminary project data with the string from the event.
// This code effectively acts as a pseudo-validator
// (can't get the standard one to work properly with pre-initialized values)
try {
// An empty string can be interpreted as zero or the preset null value, so it's ok.
if (str.empty()) {
value = nullValue;
if (nullValue == std::numeric_limits<float>::lowest()) value = 0.0f;
}
else if (str == "-") {
value = 0.0f;
}
else {
value = std::stof(str);
float validated = floatValidationFunc(value);
if (validated != value) {
value = validated;
textCtrl->SetLabel(std::to_string(value));
}
}
// save this valid string in case the next text entry gives an error.
lastText = str;
}
catch (std::logic_error err) {
// Set the text to the last valid string.
textCtrl->SetLabel(lastText);
currentlyUpdating = false;
return;
}
textChangeFunc(value);
currentlyUpdating = false;
}