//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.1
// Copyright (C) 2002-2004 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software 
// is granted provided this copyright notice appears in all copies. 
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
//          mcseemagg@yahoo.com
//          http://www.antigrain.com
//----------------------------------------------------------------------------


#include <stdio.h>
#include "agg_font_freetype.h"
#include "agg_bitset_iterator.h"


namespace agg
{

    //------------------------------------------------------------------------
    inline double conv_coord_64(int v)
    {
        return double(v) / 64.0;
    }


    //------------------------------------------------------------------------
    inline int conv_coord_none(int v)
    {
        return v;
    }


    //------------------------------------------------------------------------
    template<class PathStorage, class ConvCoord>
    bool decompose_ft_outline(const FT_Outline& outline,
                              bool flip_y,
                              PathStorage& path, 
                              ConvCoord conv)
    {   
        FT_Vector   v_last;
        FT_Vector   v_control;
        FT_Vector   v_start;

        FT_Vector*  point;
        FT_Vector*  limit;
        char*       tags;

        int   n;         // index of contour in outline
        int   first;     // index of first point in contour
        char  tag;       // current point's state

        first = 0;

        for(n = 0; n < outline.n_contours; n++)
        {
            int  last;  // index of last point in contour

            last  = outline.contours[n];
            limit = outline.points + last;

            v_start = outline.points[first];
            v_last  = outline.points[last];

            v_control = v_start;

            point = outline.points + first;
            tags  = outline.tags  + first;
            tag   = FT_CURVE_TAG(tags[0]);

            // A contour cannot start with a cubic control point!
            if(tag == FT_CURVE_TAG_CUBIC) return false;

            // check first point to determine origin
            if( tag == FT_CURVE_TAG_CONIC)
            {
                // first point is conic control.  Yes, this happens.
                if(FT_CURVE_TAG(outline.tags[last]) == FT_CURVE_TAG_ON)
                {
                    // start at last point if it is on the curve
                    v_start = v_last;
                    limit--;
                }
                else
                {
                    // if both first and last points are conic,
                    // start at their middle and record its position
                    // for closure
                    v_start.x = (v_start.x + v_last.x) / 2;
                    v_start.y = (v_start.y + v_last.y) / 2;

                    v_last = v_start;
                }
                point--;
                tags--;
            }

            path.move_to(conv(v_start.x), flip_y ? -conv(v_start.y) : conv(v_start.y));

            while(point < limit)
            {
                point++;
                tags++;

                tag = FT_CURVE_TAG(tags[0]);
                switch(tag)
                {
                    case FT_CURVE_TAG_ON:  // emit a single line_to
                    {
                        path.line_to(conv(point->x), flip_y ? -conv(point->y) : conv(point->y));
                        continue;
                    }

                    case FT_CURVE_TAG_CONIC:  // consume conic arcs
                    {
                        v_control.x = point->x;
                        v_control.y = point->y;

                    Do_Conic:
                        if(point < limit)
                        {
                            FT_Vector vec;
                            FT_Vector v_middle;

                            point++;
                            tags++;
                            tag = FT_CURVE_TAG(tags[0]);

                            vec.x = point->x;
                            vec.y = point->y;

                            if(tag == FT_CURVE_TAG_ON)
                            {
                                path.curve3(conv(v_control.x), 
                                            flip_y ? -conv(v_control.y) : conv(v_control.y), 
                                            conv(vec.x), 
                                            flip_y ? -conv(vec.y) : conv(vec.y));
                                continue;
                            }

                            if(tag != FT_CURVE_TAG_CONIC) return false;

                            v_middle.x = (v_control.x + vec.x) / 2;
                            v_middle.y = (v_control.y + vec.y) / 2;

                            path.curve3(conv(v_control.x), 
                                        flip_y ? -conv(v_control.y) : conv(v_control.y), 
                                        conv(v_middle.x), 
                                        flip_y ? -conv(v_middle.y) : conv(v_middle.y));

                            v_control = vec;
                            goto Do_Conic;
                        }
                        path.curve3(conv(v_control.x), 
                                    flip_y ? -conv(v_control.y) : conv(v_control.y), 
                                    conv(v_start.x), 
                                    flip_y ? -conv(v_start.y) : conv(v_start.y));
                        goto Close;
                    }

                    default:  // FT_CURVE_TAG_CUBIC
                    {
                        FT_Vector vec1, vec2;

                        if(point + 1 > limit || FT_CURVE_TAG(tags[1]) != FT_CURVE_TAG_CUBIC)
                        {
                            return false;
                        }

                        vec1.x = point[0].x; 
                        vec1.y = point[0].y;
                        vec2.x = point[1].x; 
                        vec2.y = point[1].y;

                        point += 2;
                        tags  += 2;

                        if(point <= limit)
                        {
                            FT_Vector vec;

                            vec.x = point->x;
                            vec.y = point->y;

                            path.curve4(conv(vec1.x), 
                                        flip_y ? -conv(vec1.y) : conv(vec1.y), 
                                        conv(vec2.x), 
                                        flip_y ? -conv(vec2.y) : conv(vec2.y),
                                        conv(vec.x), 
                                        flip_y ? -conv(vec.y) : conv(vec.y));
                            continue;
                        }

                        path.curve4(conv(vec1.x), 
                                    flip_y ? -conv(vec1.y) : conv(vec1.y), 
                                    conv(vec2.x), 
                                    flip_y ? -conv(vec2.y) : conv(vec2.y),
                                    conv(v_start.x), 
                                    flip_y ? -conv(v_start.y) : conv(v_start.y));
                        goto Close;
                    }
                }
            }

            path.close_polygon();

       Close:
            first = last + 1; 
        }

        return true;
    }



    //------------------------------------------------------------------------
    template<class Scanline, class ScanlineStorage>
    void decompose_ft_bitmap_mono(const FT_Bitmap& bitmap,
                                  int x, int y,
                                  bool flip_y,
                                  Scanline& sl,
                                  ScanlineStorage& storage)
    {
        int i;
        const int8u* buf = (const int8u*)bitmap.buffer;
        int pitch = bitmap.pitch;
        sl.reset(x, x + bitmap.width);
        storage.prepare(bitmap.width + 2);
        if(flip_y)
        {
            buf += bitmap.pitch * (bitmap.rows - 1);
            y += bitmap.rows;
            pitch = -pitch;
        }
        for(i = 0; i < bitmap.rows; i++)
        {
            sl.reset_spans();
            bitset_iterator bits(buf, 0);
            int j;
            for(j = 0; j < bitmap.width; j++)
            {
                if(bits.bit()) sl.add_cell(x + j, cover_full);
                ++bits;
            }
            buf += pitch;
            if(sl.num_spans())
            {
                sl.finalize(y - i - 1);
                storage.render(sl);
            }
        }
    }



    //------------------------------------------------------------------------
    template<class Scanline, class ScanlineStorage>
    void decompose_ft_bitmap_gray8(const FT_Bitmap& bitmap,
                                   int x, int y,
                                   bool flip_y,
                                   Scanline& sl,
                                   ScanlineStorage& storage)
    {
        int i, j;
        const int8u* buf = (const int8u*)bitmap.buffer;
        int pitch = bitmap.pitch;
        sl.reset(x, x + bitmap.width);
        storage.prepare(bitmap.width + 2);
        if(flip_y)
        {
            buf += bitmap.pitch * (bitmap.rows - 1);
            y += bitmap.rows;
            pitch = -pitch;
        }
        for(i = 0; i < bitmap.rows; i++)
        {
            sl.reset_spans();
            const int8u* p = buf;
            for(j = 0; j < bitmap.width; j++)
            {
                if(*p) sl.add_cell(x + j, *p);
                ++p;
            }
            buf += pitch;
            if(sl.num_spans())
            {
                sl.finalize(y - i - 1);
                storage.render(sl);
            }
        }
    }













    //------------------------------------------------------------------------
    font_engine_freetype::~font_engine_freetype()
    {
        unsigned i;
        for(i = 0; i < m_num_faces; ++i)
        {
            delete [] m_face_names[i];
            FT_Done_Face(m_faces[i]);
        }
        delete [] m_face_names;
        delete [] m_faces;
        delete [] m_signature;
        if(m_library_initialized) FT_Done_FreeType(m_library);
    }


    //------------------------------------------------------------------------
    font_engine_freetype::font_engine_freetype(unsigned max_faces) :
        m_change_stamp(0),
        m_last_error(0),
        m_name(0),
        m_name_len(256-16-1),
        m_face_index(0),
        m_char_map(FT_ENCODING_NONE),
        m_signature(new char [256+256-16]),
        m_height(0),
        m_width(0),
        m_hinting(true),
        m_flip_y(false),
        m_library_initialized(false),
        m_library(0),
        m_faces(new FT_Face [max_faces]),
        m_face_names(new char* [max_faces]),
        m_num_faces(0),
        m_max_faces(max_faces),
        m_cur_face(0),
        m_resolution(0),
        m_glyph_rendering(glyph_ren_native_gray8),
        m_glyph_index(0),
        m_data_size(0),
        m_data_type(glyph_data_invalid),
        m_bounds(1,1,0,0),
        m_advance_x(0.0),
        m_advance_y(0.0),

        m_path(),
        m_curves(m_path),
        m_scanline_aa(),
        m_scanline_bin(),
        m_scanlines_aa(),
        m_scanlines_bin(),
        m_rasterizer()
    {
        m_curves.approximation_scale(2.0);
        m_last_error = FT_Init_FreeType(&m_library);
        if(m_last_error == 0) m_library_initialized = true;
    }



    //------------------------------------------------------------------------
    void font_engine_freetype::resolution(unsigned dpi) 
    { 
        m_resolution = dpi;
        update_char_size();
    }


    //------------------------------------------------------------------------
    int font_engine_freetype::find_face(const char* face_name) const
    {
        unsigned i;
        for(i = 0; i < m_num_faces; ++i)
        {
            if(strcmp(face_name, m_face_names[i]) == 0) return i;
        }
        return -1;
    }


    //------------------------------------------------------------------------
    bool font_engine_freetype::load_font(const char* font_name, 
                                         unsigned face_index,
                                         glyph_rendering ren_type)
    {
        bool ret = false;

        if(m_library_initialized)
        {
            m_last_error = 0;

            int idx = find_face(font_name);
            if(idx >= 0)
            {
                m_cur_face = m_faces[idx];
                m_name     = m_face_names[idx];
            }
            else
            {
                if(m_num_faces >= m_max_faces)
                {
                    delete [] m_face_names[0];
                    FT_Done_Face(m_faces[0]);
                    memcpy(m_faces, 
                           m_faces + 1, 
                           (m_max_faces - 1) * sizeof(FT_Face));
                    memcpy(m_face_names, 
                           m_face_names + 1, 
                           (m_max_faces - 1) * sizeof(char*));
                    m_num_faces = m_max_faces - 1;
                }

                m_last_error = FT_New_Face(m_library,
                                           font_name,
                                           face_index,
                                           &m_faces[m_num_faces]);
                if(m_last_error == 0)
                {
                    m_face_names[m_num_faces] = new char [strlen(font_name) + 1];
                    strcpy(m_face_names[m_num_faces], font_name);
                    m_cur_face = m_faces[m_num_faces];
                    m_name     = m_face_names[m_num_faces];
                    ++m_num_faces;
                }
                else
                {
                    m_face_names[m_num_faces] = 0;
                    m_cur_face = 0;
                    m_name = 0;
                }
            }


            if(m_last_error == 0)
            {
                ret = true;

                switch(ren_type)
                {
                case glyph_ren_native_mono:
                    m_glyph_rendering = glyph_ren_native_mono;
                    break;

                case glyph_ren_native_gray8:
                    m_glyph_rendering = glyph_ren_native_gray8;
                    break;

                case glyph_ren_outline:
                    if(FT_IS_SCALABLE(m_cur_face))
                    {
                        m_glyph_rendering = glyph_ren_outline;
                    }
                    else
                    {
                        m_glyph_rendering = glyph_ren_native_gray8;
                    }
                    break;

                case glyph_ren_agg_mono:
                    if(FT_IS_SCALABLE(m_cur_face))
                    {
                        m_glyph_rendering = glyph_ren_agg_mono;
                    }
                    else
                    {
                        m_glyph_rendering = glyph_ren_native_mono;
                    }
                    break;

                case glyph_ren_agg_gray8:
                    if(FT_IS_SCALABLE(m_cur_face))
                    {
                        m_glyph_rendering = glyph_ren_agg_gray8;
                    }
                    else
                    {
                        m_glyph_rendering = glyph_ren_native_gray8;
                    }
                    break;
                }

                update_signature();
            }
        }
        return ret;
    }


    //------------------------------------------------------------------------
    bool font_engine_freetype::attach(const char* file_name)
    {
        if(m_cur_face)
        {
            m_last_error = FT_Attach_File(m_cur_face, file_name);
            return m_last_error == 0;
        }
        return false;
    }

    //------------------------------------------------------------------------
    unsigned font_engine_freetype::num_faces() const
    {
        if(m_cur_face)
        {
            return m_cur_face->num_faces;
        }
        return 0;
    }

    //------------------------------------------------------------------------
    bool font_engine_freetype::char_map(FT_Encoding char_map)
    {
        if(m_cur_face)
        {
            m_last_error = FT_Select_Charmap(m_cur_face, m_char_map);
            if(m_last_error == 0)
            {
                update_signature();
                return true;
            }
        }
        return false;
    }

    //------------------------------------------------------------------------
    bool font_engine_freetype::height(double h)
    {
        m_height = int(h * 64.0);
        if(m_cur_face)
        {
            update_char_size();
            return true;
        }
        return false;
    }

    //------------------------------------------------------------------------
    bool font_engine_freetype::width(double w)
    {
        m_width = int(w * 64.0);
        if(m_cur_face)
        {
            update_char_size();
            return true;
        }
        return false;
    }

    //------------------------------------------------------------------------
    void font_engine_freetype::hinting(bool h)
    { 
        m_hinting = h; 
        if(m_cur_face)
        {
            update_signature();
        }
    }

    //------------------------------------------------------------------------
    void font_engine_freetype::flip_y(bool f)
    { 
        m_flip_y = f; 
        if(m_cur_face)
        {
            update_signature();
        }
    }

    //------------------------------------------------------------------------
    void font_engine_freetype::update_signature()
    {
        if(m_cur_face && m_name)
        {
            unsigned name_len = strlen(m_name);
            if(name_len > m_name_len)
            {
                delete [] m_signature;
                m_signature = new char [name_len + 32 + 256];
                m_name_len = name_len + 32 - 1;
            }
            sprintf(m_signature, 
                    "%s,%u,%d,%d,%d:%dx%d,%d,%d", 
                    m_name,
                    m_char_map,
                    m_face_index,
                    int(m_glyph_rendering),
                    m_resolution,
                    m_height,
                    m_width,
                    int(m_hinting),
                    int(m_flip_y));
            ++m_change_stamp;
        }
    }


    //------------------------------------------------------------------------
    void font_engine_freetype::update_char_size()
    {
        if(m_cur_face)
        {
            if(m_resolution)
            {
                FT_Set_Char_Size(m_cur_face, 
                                 m_width,       // char_width in 1/64th of points
                                 m_height,      // char_height in 1/64th of points
                                 m_resolution,  // horizontal device resolution 
                                 m_resolution); // vertical device resolution 
            }
            else
            {
                FT_Set_Pixel_Sizes(m_cur_face,    
                                   m_width >> 6,    // pixel_width
                                   m_height >> 6);  // pixel_height
            }
            update_signature();
        }
    }





    //------------------------------------------------------------------------
    bool font_engine_freetype::prepare_glyph(unsigned glyph_code)
    {
        m_glyph_index = FT_Get_Char_Index(m_cur_face, glyph_code);
        m_last_error = FT_Load_Glyph(m_cur_face, 
                                     m_glyph_index, 
                                     m_hinting ? FT_LOAD_DEFAULT : FT_LOAD_NO_HINTING);
//                                     m_hinting ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_NO_HINTING);
        if(m_last_error == 0)
        {
            switch(m_glyph_rendering)
            {
            case glyph_ren_native_mono:
                m_last_error = FT_Render_Glyph(m_cur_face->glyph, FT_RENDER_MODE_MONO);
                if(m_last_error == 0)
                {
                    decompose_ft_bitmap_mono(m_cur_face->glyph->bitmap, 
                                             m_cur_face->glyph->bitmap_left,
                                             m_flip_y ? -m_cur_face->glyph->bitmap_top : 
                                                         m_cur_face->glyph->bitmap_top,
                                             m_flip_y,
                                             m_scanline_bin,
                                             m_scanlines_bin);
                    m_bounds.x1 = m_scanlines_bin.min_x();
                    m_bounds.y1 = m_scanlines_bin.min_y();
                    m_bounds.x2 = m_scanlines_bin.max_x();
                    m_bounds.y2 = m_scanlines_bin.max_y();
                    m_data_size = m_scanlines_bin.byte_size(); 
                    m_data_type = glyph_data_mono;
                    m_advance_x = double(m_cur_face->glyph->advance.x) / 64.0;
                    m_advance_y = double(m_cur_face->glyph->advance.y) / 64.0;
                    return true;
                }
                break;


            case glyph_ren_native_gray8:
                m_last_error = FT_Render_Glyph(m_cur_face->glyph, FT_RENDER_MODE_NORMAL);
                if(m_last_error == 0)
                {
                    decompose_ft_bitmap_gray8(m_cur_face->glyph->bitmap, 
                                              m_cur_face->glyph->bitmap_left,
                                              m_flip_y ? -m_cur_face->glyph->bitmap_top : 
                                                          m_cur_face->glyph->bitmap_top,
                                              m_flip_y,
                                              m_scanline_aa,
                                              m_scanlines_aa);
                    m_bounds.x1 = m_scanlines_aa.min_x();
                    m_bounds.y1 = m_scanlines_aa.min_y();
                    m_bounds.x2 = m_scanlines_aa.max_x();
                    m_bounds.y2 = m_scanlines_aa.max_y();
                    m_data_size = m_scanlines_aa.byte_size(); 
                    m_data_type = glyph_data_gray8;
                    m_advance_x = double(m_cur_face->glyph->advance.x) / 64.0;
                    m_advance_y = double(m_cur_face->glyph->advance.y) / 64.0;
                    return true;
                }
                break;


            case glyph_ren_outline:
                if(m_last_error == 0)
                {
                    m_path.remove_all();
                    if(decompose_ft_outline(m_cur_face->glyph->outline,
                                            m_flip_y, 
                                            m_path, 
                                            conv_coord_none))
                    {
                        rect_d bnd  = m_path.bounding_rect();
                        m_data_size = m_path.byte_size();
                        m_data_type = glyph_data_outline;
                        m_bounds.x1 = int(floor(bnd.x1));
                        m_bounds.y1 = int(floor(bnd.y1));
                        m_bounds.x2 = int(ceil(bnd.x2));
                        m_bounds.y2 = int(ceil(bnd.y2));
                        m_advance_x = double(m_cur_face->glyph->advance.x) / 64.0;
                        m_advance_y = double(m_cur_face->glyph->advance.y) / 64.0;
                        return true;
                    }
                }
                return false;

            case glyph_ren_agg_mono:
            case glyph_ren_agg_gray8:
                if(m_last_error == 0)
                {
                    m_path.remove_all();
                    if(decompose_ft_outline(m_cur_face->glyph->outline,
                                            m_flip_y, 
                                            m_path, 
                                            conv_coord_none))
                    {
                        m_rasterizer.reset();
                        m_rasterizer.add_path(m_curves);
                        if(m_glyph_rendering == glyph_ren_agg_mono)
                        {
                            m_scanlines_bin.prepare(1); // Remove all 
                            m_rasterizer.render(m_scanline_bin, m_scanlines_bin);
                            m_bounds.x1 = m_scanlines_bin.min_x();
                            m_bounds.y1 = m_scanlines_bin.min_y();
                            m_bounds.x2 = m_scanlines_bin.max_x();
                            m_bounds.y2 = m_scanlines_bin.max_y();
                            m_data_size = m_scanlines_bin.byte_size(); 
                            m_data_type = glyph_data_mono;
                        }
                        else
                        {
                            m_scanlines_aa.prepare(1); // Remove all 
                            m_rasterizer.render(m_scanline_aa, m_scanlines_aa);
                            m_bounds.x1 = m_scanlines_aa.min_x();
                            m_bounds.y1 = m_scanlines_aa.min_y();
                            m_bounds.x2 = m_scanlines_aa.max_x();
                            m_bounds.y2 = m_scanlines_aa.max_y();
                            m_data_size = m_scanlines_aa.byte_size(); 
                            m_data_type = glyph_data_gray8;
                        }
                        m_advance_x = double(m_cur_face->glyph->advance.x) / 64.0;
                        m_advance_y = double(m_cur_face->glyph->advance.y) / 64.0;
                        return true;
                    }
                }
                return false;
            }
        }
        return false;
    }




    //------------------------------------------------------------------------
    void font_engine_freetype::write_glyph_to(int8u* data) const
    {
        if(data && m_data_size)
        {
            switch(m_data_type)
            {
            case glyph_data_mono:    m_scanlines_bin.serialize(data); break;
            case glyph_data_gray8:   m_scanlines_aa.serialize(data);  break;
            case glyph_data_outline: m_path.serialize(data);          break;
            }
        }
    }



    //------------------------------------------------------------------------
    bool font_engine_freetype::add_kerning(unsigned first, unsigned second,
                                           double* x, double* y)
    {
        if(m_cur_face && first && second && FT_HAS_KERNING(m_cur_face))
        {
            FT_Vector delta;
            FT_Get_Kerning(m_cur_face, first, second,
                           FT_KERNING_DEFAULT, &delta);
            // TO DO: Add transformations when embedded roitation is implemented
            *x += double(delta.x) / 64.0;
            *y += double(delta.y) / 64.0;
            return true;
        }
        return false;
    }



}


