-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextBox.cpp
More file actions
109 lines (93 loc) · 2.33 KB
/
TextBox.cpp
File metadata and controls
109 lines (93 loc) · 2.33 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "TextBox.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
TextBox::TextBox() : limit(100), cursorID(0), str("|")
{
}
TextBox::TextBox(const sf::Vector2f& pos, int textSize, sf::Color textColor, const sf::Font& font, size_t characteLimit) :
limit(characteLimit), font(font), cursorID(0), str("|")
{
setPosition(pos);
text.setFont(font);
text.setCharacterSize(textSize);
text.setFillColor(textColor);
text.setPosition(pos);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
void TextBox::update(sf::RenderWindow& window, const sf::Vector2f& mousePos, const UserInput& userInput)
{
if (active)
{
if (userInput.event == Event::TextEntered)
{
char ch = userInput.character;
if (ch > 31 && ch < 127)
{
if (str.length() < limit)
{
str = str.substr(0, cursorID) + ch + '|' + str.substr(cursorID + 1, str.length());
cursorID++;
}
}
else if (ch == DELETE_KEY)
{
if (cursorID > 0)
{
str = str.substr(0, cursorID - 1) + '|' + str.substr(cursorID + 1, str.length());
cursorID--;
}
}
}
if (userInput.event == Event::KeyLeftPressed)
{
if (cursorID > 0)
{
str[cursorID] = str[cursorID - 1];
str[--cursorID] = '|';
}
}
else if (userInput.event == Event::KeyRightPressed)
{
if (cursorID < str.length() - 1)
{
str[cursorID] = str[cursorID + 1];
str[++cursorID] = '|';
}
}
text.setString(str);
}
}
void TextBox::draw(sf::RenderWindow& window) const
{
window.draw(text);
}
void TextBox::reset()
{
str.clear();
setActive(false);
}
void TextBox::setActive(bool value)
{
active = value;
if (!active)
{
text.setString(getString());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
void TextBox::setString(const std::string& str)
{
cursorID = str.length();
this->str = str + '|';
if (active) text.setString(this->str);
else text.setString(str);
}
void TextBox::setPosition(const sf::Vector2f& position)
{
text.setPosition(position);
this->position = position;
}
std::string TextBox::getString()
{
return str.substr(0, cursorID) + str.substr(cursorID + 1, str.length());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////