#include "LineEditor.h"
namespace glan
{
LineEditor::LineEditor(sf::Texture const& boxTexture, sf::Font const& font, sf::RenderWindow *shownIn,
unsigned int characterSize, sf::Vector2f const& offset,
sf::Texture const& cursorTexture, sf::String const& str, bool numbersOnly, unsigned int charMax) :
parent(shownIn), box(boxTexture), cursor(cursorTexture), customCursor(cursorTexture.getSize() != sf::Vector2u()), text(str, font, characterSize),
textOffset(offset), maxChar(charMax), onlyNumbers(numbersOnly), hasFocus(false), isPressed(false), active(false)
{
text.setPosition(box.getPosition() + textOffset);
cursor.setOrigin( static_cast<sf::Vector2f>( (cursor.getTexture()->getSize()) / (unsigned)2 ) );
}
//////////////////////////////////////////////////////////////////////////////
void LineEditor::treatEvent(sf::Event const& event)
{
sf::Vector2f msPos(static_cast<sf::Vector2f>(sf::Mouse::getPosition(*parent)));
switch(event.type)
{
case sf::Event::MouseMoved:
cursor.setPosition(msPos);
if(box.getGlobalBounds().contains(msPos))
{
hasFocus = true;
if(customCursor)
parent->setMouseCursorVisible(false);
}
else
{
hasFocus = false;
if(customCursor)
parent->setMouseCursorVisible(true);
}
break;
case sf::Event::MouseButtonPressed:
if(hasFocus)
isPressed = true;
break;
case sf::Event::MouseButtonReleased:
if(isPressed)
active=true;
else
active=false;
isPressed=false;
break;
case sf::Event::TextEntered:
if(active)
{
sf::Uint32 chr = event.text.unicode;
sf::String temp(text.getString());
if(chr == 8 && temp.getSize() > 0) // If the user pressed backspace...
temp.erase(temp.getSize() - 1);
else if(chr > 31 && temp.getSize() < maxChar)
temp+=chr;
text.setString(temp);
}
break;
default:
break;
}
}
//////////////////////////////////////////////////////////////////////////////
void LineEditor::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(box, states);
target.draw(text, states);
if(hasFocus && customCursor)
target.draw(cursor);
}
} // namespace glan