Skip to content

Instantly share code, notes, and snippets.

@Groogy
Last active December 13, 2015 18:09
Show Gist options
  • Save Groogy/4953503 to your computer and use it in GitHub Desktop.
Save Groogy/4953503 to your computer and use it in GitHub Desktop.
namespace GUI
{
class BOOK_MENUS_API Button : public GUI::Component
{
public:
Button(const std::string& text, const FontHolder& fonts, const TextureHolder& textures, std::function<void> callback);
bool isSelectable() const;
void handleEvent(const sf::Event& event);
protected:
void draw(sf::RenderTarget& target, sf::RenderStates& states) const;
private:
std::function<void> mCallback;
const sf::Texture& mNormalTexture;
const sf::Texture& mSelectedTexture;
const sf::Texture& mPressedTexture;
sf::Sprite mSprite;
};
}
#include <Book/Menus/Container.hpp>
GUI::Container::Container()
: mChildren()
, mSelectedChild(-1)
{
}
void GUI::Container::pack(std::shared_ptr<GUI::Componenet> component)
{
mChildren.push_back(component);
if (!hasSelection() && component->isSelectable())
select(mChildren.size() - 1);
}
bool GUI::Container::isSelectable() const
{
return false;
}
void GUI::Container::handleEvent(const sf::Event& event)
{
if (hasSelection() && mChildren[mSelectedChild]->isActive())
{
mChildren[mSelectedChild]->handleEvent(event);
}
else
{
if (event.type == sf::Event::KeyReleased)
{
if (event.key.code == sf::Keyboard::W || event.key.code == sf::Keyboard::Up)
{
selectPrevious();
}
else if (event.key.code == sf::Keyboard::S || event.key.code == sf::Keyboard::Down)
{
selectNext();
}
else if (event.key.code == sf::Keyboard::Enter || event.key.code == sf::Keyboard::Space)
{
if(hasSelection())
mChildren[mSelectedChild]->activate();
}
}
}
}
void GUI::Container::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform.combine(getTransform());
std::for_each(mChildren.begin(), mChildren.end(), [&target, &states](const std::unique_ptr<GUI::Component>& child) {
target.draw(*child, states);
});
}
bool GUI::Container::hasSelection() const
{
return mSelectedChild >= 0;
}
void GUI::Container::select(unsigned int index)
{
if (mChildren[index]->isSelectable())
{
if (hasSelection())
mChildren[mSelectedChild]->deselect();
mChildren[index]->select();
mSelectedChild = index;
}
}
void GUI::Container::selectNext()
{
int selectedChild = mSelectedChild;
while (hasSelection())
{
selectedChild = selectedChild + 1 >= mChildren.size() ? 0 : selectedChild + 1;
if (mChildren[selectedChild]->isSelectable())
break;
}
if (hasSelection())
select(selectedChild);
}
void GUI::Container::selectPrevious()
{
int selectedChild = mSelectedChild;
while (hasSelection())
{
selectedChild = selectedChild - 1 < 0 ? mChildren.size() : selectedChild - 1;
if (mChildren[selectedChild]->isSelectable())
break;
}
if (hasSelection())
select(selectedChild);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment