/**
 * We buffer the rendered text instead of calculating it each frame
 * This function refreshes the buffer.
 */
void WidgetLabel::recacheTextSprite() {
    Image *image;

    if (label) {
        delete label;
        label = NULL;
    }

    if (text.empty())
        return;

    std::string temp_text = text;

    font->setFont(font_style);
    bounds.w = font->calc_width(temp_text);
    bounds.h = font->getFontHeight();

    if (max_width > 0 && bounds.w > max_width) {
        temp_text = font->trimTextToWidth(text, max_width, true);
        bounds.w = font->calc_width(temp_text);
    }

    image = render_device->createImage(bounds.w, bounds.h);
    if (!image) return;

    font->renderShadowed(temp_text, 0, 0, JUSTIFY_LEFT, image, 0, color);
    label = image->createSprite();
    image->unref();

    applyOffsets();
}
/**
 * A shortcut function to set all attributes simultaneously.
 */
void WidgetLabel::set(int _x, int _y, int _justify, int _valign, const std::string& _text, const Color& _color, const std::string& _font) {

	bool changed = false;
	bool changed_pos = false;

	if (justify != _justify) {
		justify = _justify;
		changed = true;
	}
	if (valign != _valign) {
		valign = _valign;
		changed = true;
	}
	if (text != _text) {
		text = _text;
		changed = true;
	}
	if (color.r != _color.r || color.g != _color.g || color.b != _color.b) {
		color = _color;
		changed = true;
	}
	if (pos.x != _x) {
		pos.x = _x;
		changed_pos = true;
	}
	if (pos.y != _y) {
		pos.y = _y;
		changed_pos = true;
	}
	if (font_style != _font) {
		font_style = _font;
		changed = true;
	}

	if (changed) {
		recacheTextSprite();
	}
	else if (changed_pos) {
		applyOffsets();
	}
}
/**
 * We buffer the rendered text instead of calculating it each frame
 * This function refreshes the buffer.
 */
void WidgetLabel::recacheTextSprite() {
	Image *image;

	if (label) {
		delete label;
		label = NULL;
	}

	font->setFont(font_style);
	bounds.w = font->calc_width(text);
	bounds.h = font->getFontHeight();

	image = render_device->createImage(bounds.w, bounds.h);
	if (!image) return;

	font->renderShadowed(text, 0, 0, JUSTIFY_LEFT, image, color);
	label = image->createSprite();
	image->unref();

	applyOffsets();
}
void WidgetLabel::setPos(int offset_x, int offset_y) {
	Widget::setPos(offset_x, offset_y);
	applyOffsets();
}
/**
 * Set initial Y position of label.
 */
void WidgetLabel::setY(int _y) {
	if (pos.y != _y) {
		pos.y = _y;
		applyOffsets();
	}
}
/**
 * Set initial X position of label.
 */
void WidgetLabel::setX(int _x) {
	if (pos.x != _x) {
		pos.x = _x;
		applyOffsets();
	}
}