From f8dc4c7bb81ec1211fc7d74546d4438be8b6fe5a Mon Sep 17 00:00:00 2001 From: Maarten ter Huurne Date: Sun, 4 Aug 2013 00:58:32 +0200 Subject: [PATCH] Don't construct non-functional Font objects Replaced Font constructor with factory method, so that if the TTF cannot be loaded, the Font object is not constructed. The normal C++ way of handling this is with exceptions, but we're compiling with -fno-exceptions. --- src/font.cpp | 14 ++++++++++---- src/font.h | 8 +++++++- src/gmenu2x.cpp | 13 ++++--------- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/font.cpp b/src/font.cpp index 31eca49..a508d1e 100644 --- a/src/font.cpp +++ b/src/font.cpp @@ -14,19 +14,25 @@ using namespace std; -Font::Font(const string &path) +Font *Font::defaultFont() { if (!TTF_WasInit() && TTF_Init() < 0) { ERROR("Unable to init SDL_ttf library\n"); - return; + return nullptr; } - font = TTF_OpenFont(TTF_FONT, TTF_FONT_SIZE); + TTF_Font *font = TTF_OpenFont(TTF_FONT, TTF_FONT_SIZE); if (!font) { ERROR("Unable to open font\n"); - return; + return nullptr; } + return new Font(font); +} + +Font::Font(TTF_Font *font) + : font(font) +{ fontheight = TTF_FontHeight(font); } diff --git a/src/font.h b/src/font.h index 31b9dc0..4f76962 100644 --- a/src/font.h +++ b/src/font.h @@ -14,7 +14,11 @@ public: enum HAlign { HAlignLeft, HAlignRight, HAlignCenter }; enum VAlign { VAlignTop, VAlignBottom, VAlignMiddle }; - Font(const std::string &font); + /** + * Returns a newly created Font object for the default font, + * or nullptr if there was a problem creating it. + */ + static Font *defaultFont(); ~Font(); int getTextWidth(const char *text); @@ -34,6 +38,8 @@ public: HAlign halign = HAlignLeft, VAlign valign = VAlignTop); private: + Font(TTF_Font *font); + void writeLine(Surface *surface, const char *text, int x, int y, HAlign halign, VAlign valign); diff --git a/src/gmenu2x.cpp b/src/gmenu2x.cpp index ed72a5e..1768710 100644 --- a/src/gmenu2x.cpp +++ b/src/gmenu2x.cpp @@ -356,18 +356,13 @@ void GMenu2X::initBG() { } void GMenu2X::initFont() { - if (font != NULL) { - delete font; - font = NULL; - } - - string fontFile = sc.getSkinFilePath("imgs/font.png"); - if (fontFile.empty()) { - ERROR("Font png not found!\n"); + delete font; + font = Font::defaultFont(); + if (!font) { + ERROR("Cannot function without font; aborting...\n"); quit(); exit(-1); } - font = new Font(fontFile); } void GMenu2X::initMenu() {