Add support for TrueType fonts

* Keeps original font system in place
* Uses the same API as original font system:
   - You can render only one line at a time
   - You can only use one font and color for one gr_text* call
* Caches all rendered text, with a string cache limited to 400
  entries, then it trucates to 250, which results in memory
  usage hovering around 5-10MB

Change-Id: I36107b9dcd8d57bae4486fce8b8f64e49ef3d906
Signed-off-by: Vojtech Bocek <vbocek@gmail.com>
diff --git a/gui/resources.cpp b/gui/resources.cpp
index 8d430b1..4fce0ca 100644
--- a/gui/resources.cpp
+++ b/gui/resources.cpp
@@ -65,27 +65,82 @@
  : Resource(node, pZip)
 {
 	std::string file;
+	xml_attribute<>* attr;
 
 	mFont = NULL;
 	if (!node)
 		return;
 
-	if (node->first_attribute("filename"))
-		file = node->first_attribute("filename")->value();
+	attr = node->first_attribute("filename");
+	if (!attr)
+		return;
 
-	if (ExtractResource(pZip, "fonts", file, ".dat", TMP_RESOURCE_NAME) == 0)
+	file = attr->value();
+
+#ifndef TW_DISABLE_TTF
+	if(file.size() >= 4 && file.compare(file.size()-4, 4, ".ttf") == 0)
 	{
-		mFont = gr_loadFont(TMP_RESOURCE_NAME);
-		unlink(TMP_RESOURCE_NAME);
+		m_type = TYPE_TTF;
+
+		attr = node->first_attribute("size");
+		if(!attr)
+			return;
+
+		int size = atoi(attr->value());
+		int dpi = 300;
+
+		attr = node->first_attribute("dpi");
+		if(attr)
+			dpi = atoi(attr->value());
+
+		if (ExtractResource(pZip, "fonts", file, "", TMP_RESOURCE_NAME) == 0)
+		{
+			mFont = gr_ttf_loadFont(TMP_RESOURCE_NAME, size, dpi);
+			unlink(TMP_RESOURCE_NAME);
+		}
+		else
+		{
+			file = std::string("/res/fonts/") + file;
+			mFont = gr_ttf_loadFont(file.c_str(), size, dpi);
+		}
 	}
 	else
+#endif
 	{
-		mFont = gr_loadFont(file.c_str());
+		m_type = TYPE_TWRP;
+
+		if(file.size() >= 4 && file.compare(file.size()-4, 4, ".ttf") == 0)
+		{
+			attr = node->first_attribute("fallback");
+			if (!attr)
+				return;
+
+			file = attr->value();
+		}
+
+		if (ExtractResource(pZip, "fonts", file, ".dat", TMP_RESOURCE_NAME) == 0)
+		{
+			mFont = gr_loadFont(TMP_RESOURCE_NAME);
+			unlink(TMP_RESOURCE_NAME);
+		}
+		else
+		{
+			mFont = gr_loadFont(file.c_str());
+		}
 	}
 }
 
 FontResource::~FontResource()
 {
+	if(mFont)
+	{
+#ifndef TW_DISABLE_TTF
+		if(m_type == TYPE_TTF)
+			gr_ttf_freeFont(mFont);
+		else
+#endif
+			gr_freeFont(mFont);
+	}
 }
 
 ImageResource::ImageResource(xml_node<>* node, ZipArchive* pZip)