Richard Parker / EALCD

fonts/EAFontCacheEntry.cpp

Committer:
richardparker
Date:
2010-11-01
Revision:
7:6cf21b018420

File content as of revision 7:6cf21b018420:

// Copyright 2010 Richard Parker

#include "mbed.h"
#include "EAFontCacheEntry.h"

EAFontCacheEntry::EAFontCacheEntry()
:    _refs(0)
{
}

EAFontCacheEntry::~EAFontCacheEntry()
{
    // Remember to free up allocated memory.
    unload();
}

void EAFontCacheEntry::unload()
{   
    _path.clear();

    _chars.clear();
    
    _img.unload();
}

bool EAFontCacheEntry::load(const std::string& path)
{
    if (path.empty() == true)
    {
        // Invalid path passed in.
        return false;
    }

    // Try and open the file, check type and load width and height.
    FILE* fp = fopen(path.c_str(), "r");
    if (fp == NULL)
    {
        unload();
        return false;
    }
    
    int noChars = 0;
       
    // The first line contains the number of characters,
    if (fscanf(fp, "%d", &noChars) != 1)
    {
        fclose(fp);
        unload();
        return false;
    }
    
    // Store the path for later
    _path = path;
    
    // Crete the correct size.
    _chars.resize(noChars);
      
    // Now loop through loading in the values.
    for (int i = 0; i < noChars; i++)
    {   
        int v = 0;
        
        // id.
        fscanf(fp, "%d", &v);
        _chars[i].id = v;
        
        // x.
        fscanf(fp, "%d", &v);
        _chars[i].x = v;

        // y.
        fscanf(fp, "%d", &v);
        _chars[i].y = v;

        // width.
        fscanf(fp, "%d", &v);
        _chars[i].width = v;

        // height.
        fscanf(fp, "%d", &v);
        _chars[i].height = v;

        // xoffset.
        fscanf(fp, "%d", &v);
        _chars[i].xOffset = v;

        // yoffset.
        fscanf(fp, "%d", &v);
        _chars[i].yOffset = v;

        // xAdvance.
        fscanf(fp, "%d", &v);
        _chars[i].xAdvance = v;
    }
    
    fclose(fp);
    
    // Now change extension to fnb.
    _path[_path.length()-1] = 'b';

    _img.setMask(true);
    if (_img.load(_path) == false)
    {
        unload();
        return false;
    }

    _path[_path.length()-1] = 't';
    
    return true;
}

void EAFontCacheEntry::incReferences() 
{ 
    _refs++; 
    
    printf("References are now %d\r\n", _refs);
}

void EAFontCacheEntry::decReferences() 
{ 
    _refs--; 

    printf("References are now %d\r\n", _refs);
}