1
0
mirror of git://projects.qi-hardware.com/gmenu2x.git synced 2024-11-17 21:10:39 +02:00

Do not construct Font objects that crash gmenu2x if font loading fails.

This commit ensures that a fully constructed Font object will not crash
gmenu2x when it is used, even if loading the font or initialising SDL_ttf
altogether has failed. Instead, it will render no text, but icons and
images are still drawn.

The proper way to signal an error would be to throw an exception and fail
to construct the Font object. However, gmenu2x does not use exceptions.
This commit is contained in:
Nebuleon Fumika 2014-06-18 06:52:33 +00:00 committed by Maarten ter Huurne
parent 738c296c67
commit 4474a42767

View File

@ -21,6 +21,9 @@ Font *Font::defaultFont()
Font::Font(const std::string &path, unsigned int size)
{
font = nullptr;
fontheight = 1;
/* Note: TTF_Init and TTF_Quit perform reference counting, so call them
* both unconditionally for each font. */
if (TTF_Init() < 0) {
@ -31,6 +34,7 @@ Font::Font(const std::string &path, unsigned int size)
font = TTF_OpenFont(path.c_str(), size);
if (!font) {
ERROR("Unable to open font\n");
TTF_Quit();
return;
}
@ -39,20 +43,29 @@ Font::Font(const std::string &path, unsigned int size)
Font::~Font()
{
if (font) {
TTF_CloseFont(font);
TTF_Quit();
}
}
int Font::getTextWidth(const char *text)
{
if (font) {
int w, h;
TTF_SizeUTF8(font, text, &w, &h);
return w;
}
else return 1;
}
void Font::write(Surface *surface, const string &text,
int x, int y, HAlign halign, VAlign valign)
{
if (!font) {
return;
}
if (text.find("\n", 0) == string::npos) {
writeLine(surface, text.c_str(), x, y, halign, valign);
return;
@ -70,6 +83,10 @@ void Font::write(Surface *surface, const string &text,
void Font::writeLine(Surface *surface, const char *text,
int x, int y, HAlign halign, VAlign valign)
{
if (!font) {
return;
}
switch (halign) {
case HAlignLeft:
break;