From 4474a42767851c09f6492d6db9009a7c0a26bebc Mon Sep 17 00:00:00 2001 From: Nebuleon Fumika Date: Wed, 18 Jun 2014 06:52:33 +0000 Subject: [PATCH] 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. --- src/font.cpp | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/font.cpp b/src/font.cpp index 3c9b6ba..049a518 100644 --- a/src/font.cpp +++ b/src/font.cpp @@ -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() { - TTF_CloseFont(font); - TTF_Quit(); + if (font) { + TTF_CloseFont(font); + TTF_Quit(); + } } int Font::getTextWidth(const char *text) { - int w, h; - TTF_SizeUTF8(font, text, &w, &h); - return w; + 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;