text:
/*  GRAPHITE2 LICENSING

    Copyright 2010, SIL International
    All rights reserved.

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should also have received a copy of the GNU Lesser General Public
    License along with this library in the file named "LICENSE".
    If not, write to the Free Software Foundation, 51 Franklin Street,
    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
    internet at http://www.fsf.org/licenses/lgpl.html.

Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "graphite2/Font.h"
#include "inc/Face.h"
#include "inc/FileFace.h"
#include "inc/GlyphCache.h"
#include "inc/CmapCache.h"
#include "inc/Silf.h"
#include "inc/json.h"

using namespace graphite2;

#if !defined GRAPHITE2_NTRACING
extern json *global_log;
#endif

namespace
{
    bool load_face(Face & face, unsigned int options)
    {
#ifdef GRAPHITE2_TELEMETRY
        telemetry::category _misc_cat(face.tele.misc);
#endif
        Face::Table silf(face, Tag::Silf, 0x00050000);
        if (!silf)
            return false;

        if (!face.readGlyphs(options))
            return false;

        if (silf)
        {
            if (!face.readFeatures() || !face.readGraphite(silf))
            {
#if !defined GRAPHITE2_NTRACING
                if (global_log)
                {
                    *global_log << json::object
                        << "type" << "fontload"
                        << "failure" << face.error()
                        << "context" << face.error_context()
                    << json::close;
                }
#endif
                return false;
            }
            else
                return true;
        }
        else
            return false;
    }

    inline
    uint32 zeropad(const uint32 x)
    {
        if (x == 0x20202020)                    return 0;
        if ((x & 0x00FFFFFF) == 0x00202020)     return x & 0xFF000000;
        if ((x & 0x0000FFFF) == 0x00002020)     return x & 0xFFFF0000;
        if ((x & 0x000000FF) == 0x00000020)     return x & 0xFFFFFF00;
        return x;
    }
}

extern "C" {

gr_face* gr_make_face_with_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int faceOptions)
                  //the appFaceHandle must stay alive all the time when the gr_face is alive. When finished with the gr_face, call destroy_face
{
    if (ops == 0)   return 0;

    Face *res = new Face(appFaceHandle, *ops);
    if (res && load_face(*res, faceOptions))
        return static_cast<gr_face *>(res);

    delete res;
    return 0;
}

gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int faceOptions)
{
    const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
    return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
}

gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int , unsigned int faceOptions)
{
  return gr_make_face_with_ops(appFaceHandle, ops, faceOptions);
}

gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int, unsigned int faceOptions)
{
  const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
  return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
}

gr_uint32 gr_str_to_tag(const char *str)
{
    uint32 res = 0;
    switch(max(strlen(str),size_t(4)))
    {
        case 4: res |= str[3];       GR_FALLTHROUGH;
        case 3: res |= str[2] << 8;  GR_FALLTHROUGH;
        case 2: res |= str[1] << 16; GR_FALLTHROUGH;
        case 1: res |= str[0] << 24; GR_FALLTHROUGH;
        default:  break;
    }
    return res;
}

void gr_tag_to_str(gr_uint32 tag, char *str)
{
    if (!str) return;

    *str++ = char(tag >> 24);
    *str++ = char(tag >> 16);
    *str++ = char(tag >> 8);
    *str++ = char(tag);
    *str = '\0';
}

gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname/*0 means clone default*/) //clones the features. if none for language, clones the default
{
    assert(pFace);
    langname = zeropad(langname);
    return static_cast<gr_feature_val *>(pFace->theSill().cloneFeatures(langname));
}

const gr_feature_ref* gr_face_find_fref(const gr_face* pFace, gr_uint32 featId)  //When finished with the FeatureRef, call destroy_FeatureRef
{
    assert(pFace);
    featId = zeropad(featId);
    const FeatureRef* pRef = pFace->featureById(featId);
    return static_cast<const gr_feature_ref*>(pRef);
}

unsigned short gr_face_n_fref(const gr_face* pFace)
{
    assert(pFace);
    int res = 0;
    for (int i = 0; i < pFace->numFeatures(); ++i)
        if (!(pFace->feature(i)->getFlags() & FeatureRef::HIDDEN))
            ++res;
    return res;
}

const gr_feature_ref* gr_face_fref(const gr_face* pFace, gr_uint16 i) //When finished with the FeatureRef, call destroy_FeatureRef
{
    assert(pFace);
    int count = 0;
    for (int j = 0; j < pFace->numFeatures(); ++j)
    {
        const FeatureRef* pRef = pFace->feature(j);
        if (!(pRef->getFlags() & FeatureRef::HIDDEN))
            if (count++ == i)
                return static_cast<const gr_feature_ref*>(pRef);
    }
    return 0;
}

unsigned short gr_face_n_languages(const gr_face* pFace)
{
    assert(pFace);
    return pFace->theSill().numLanguages();
}

gr_uint32 gr_face_lang_by_index(const gr_face* pFace, gr_uint16 i)
{
    assert(pFace);
    return pFace->theSill().getLangName(i);
}

void gr_face_destroy(gr_face *face)
{
    delete static_cast<Face*>(face);
}

gr_uint16 gr_face_name_lang_for_locale(gr_face *face, const char * locale)
{
    if (face)
    {
        return face->languageForLocale(locale);
    }
    return 0;
}

unsigned short gr_face_n_glyphs(const gr_face* pFace)
{
    return pFace->glyphs().numGlyphs();
}

const gr_faceinfo *gr_face_info(const gr_face *pFace, gr_uint32 script)
{
    if (!pFace) return 0;
    const Silf *silf = pFace->chooseSilf(script);
    if (silf) return silf->silfInfo();
    return 0;
}

int gr_face_is_char_supported(const gr_face* pFace, gr_uint32 usv, gr_uint32 script)
{
    const Cmap & cmap = pFace->cmap();
    gr_uint16 gid = cmap[usv];
    if (!gid)
    {
        const Silf * silf = pFace->chooseSilf(script);
        gid = silf->findPseudo(usv);
    }
    return (gid != 0);
}

#ifndef GRAPHITE2_NFILEFACE
gr_face* gr_make_file_face(const char *filename, unsigned int faceOptions)
{
    FileFace* pFileFace = new FileFace(filename);
    if (*pFileFace)
    {
      gr_face* pRes = gr_make_face_with_ops(pFileFace, &FileFace::ops, faceOptions);
      if (pRes)
      {
        pRes->takeFileFace(pFileFace);        //takes ownership
        return pRes;
      }
    }

    //error when loading

    delete pFileFace;
    return NULL;
}

gr_face* gr_make_file_face_with_seg_cache(const char* filename, unsigned int, unsigned int faceOptions)   //returns NULL on failure. //TBD better error handling
                  //when finished with, call destroy_face
{
    return gr_make_file_face(filename, faceOptions);
}
#endif      //!GRAPHITE2_NFILEFACE

} // extern "C"


text:
/*  GRAPHITE2 LICENSING

    Copyright 2012, SIL International
    All rights reserved.

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should also have received a copy of the GNU Lesser General Public
    License along with this library in the file named "LICENSE".
    If not, write to the Free Software Foundation, 51 Franklin Street,
    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
    internet at http://www.fsf.org/licenses/lgpl.html.

Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "graphite2/Font.h"

#include "inc/Main.h"
#include "inc/Face.h"     //for the tags
#include "inc/GlyphCache.h"
#include "inc/GlyphFace.h"
#include "inc/Endian.h"
#include "inc/bits.h"

using namespace graphite2;

namespace
{
    // Iterator over version 1 or 2 glat entries which consist of a series of
    //    +-+-+-+-+-+-+-+-+-+-+                +-+-+-+-+-+-+-+-+-+-+-+-+
    // v1 |k|n|v1 |v2 |...|vN |     or    v2   | k | n |v1 |v2 |...|vN |
    //    +-+-+-+-+-+-+-+-+-+-+                +-+-+-+-+-+-+-+-+-+-+-+-+
    // variable length structures.

    template<typename W>
    class _glat_iterator : public std::iterator<std::input_iterator_tag, std::pair<sparse::key_type, sparse::mapped_type> >
    {
        unsigned short  key() const             { return uint16(be::peek<W>(_e) + _n); }
        unsigned int    run() const             { return be::peek<W>(_e+sizeof(W)); }
        void            advance_entry()         { _n = 0; _e = _v; be::skip<W>(_v,2); }
    public:
        _glat_iterator(const void * glat=0) : _e(reinterpret_cast<const byte *>(glat)), _v(_e+2*sizeof(W)), _n(0) {}

        _glat_iterator<W> & operator ++ () {
            ++_n; be::skip<uint16>(_v);
            if (_n == run()) advance_entry();
            return *this;
        }
        _glat_iterator<W>   operator ++ (int)   { _glat_iterator<W> tmp(*this); operator++(); return tmp; }

        // This is strictly a >= operator. A true == operator could be
        // implemented that test for overlap but it would be more expensive a
        // test.
        bool operator == (const _glat_iterator<W> & rhs) { return _v >= rhs._e - 1; }
        bool operator != (const _glat_iterator<W> & rhs) { return !operator==(rhs); }

        value_type          operator * () const {
            return value_type(key(), be::peek<uint16>(_v));
        }

    protected:
        const byte     * _e, * _v;
        size_t        _n;
    };

    typedef _glat_iterator<uint8>   glat_iterator;
    typedef _glat_iterator<uint16>  glat2_iterator;
}

const SlantBox SlantBox::empty = {0,0,0,0};

class GlyphCache::Loader
{
public:
    Loader(const Face & face);    //return result indicates success. Do not use if failed.

    operator bool () const throw();
    unsigned short int units_per_em() const throw();
    unsigned short int num_glyphs() const throw();
    unsigned short int num_attrs() const throw();
    bool has_boxes() const throw();

    const GlyphFace * read_glyph(unsigned short gid, GlyphFace &, int *numsubs) const throw();
    GlyphBox * read_box(uint16 gid, GlyphBox *curr, const GlyphFace & face) const throw();

    CLASS_NEW_DELETE;
private:
    Face::Table _head,
                _hhea,
                _hmtx,
                _glyf,
                _loca,
                m_pGlat,
                m_pGloc;

    bool            _long_fmt;
    bool            _has_boxes;
    unsigned short  _num_glyphs_graphics,        //i.e. boundary box and advance
                    _num_glyphs_attributes,
                    _num_attrs;                    // number of glyph attributes per glyph
};

GlyphCache::GlyphCache(const Face & face, const uint32 face_options)
: _glyph_loader(new Loader(face)),
  _glyphs(_glyph_loader && *_glyph_loader && _glyph_loader->num_glyphs()
        ? grzeroalloc<const GlyphFace *>(_glyph_loader->num_glyphs()) : 0),
  _boxes(_glyph_loader && _glyph_loader->has_boxes() && _glyph_loader->num_glyphs()
        ? grzeroalloc<GlyphBox *>(_glyph_loader->num_glyphs()) : 0),
  _num_glyphs(_glyphs ? _glyph_loader->num_glyphs() : 0),
  _num_attrs(_glyphs ? _glyph_loader->num_attrs() : 0),
  _upem(_glyphs ? _glyph_loader->units_per_em() : 0)
{
    if ((face_options & gr_face_preloadGlyphs) && _glyph_loader && _glyphs)
    {
        int numsubs = 0;
        GlyphFace * const glyphs = new GlyphFace [_num_glyphs];
        if (!glyphs)
            return;

        // The 0 glyph is definately required.
        _glyphs[0] = _glyph_loader->read_glyph(0, glyphs[0], &numsubs);

        // glyphs[0] has the same address as the glyphs array just allocated,
        //  thus assigning the &glyphs[0] to _glyphs[0] means _glyphs[0] points
        //  to the entire array.
        const GlyphFace * loaded = _glyphs[0];
        for (uint16 gid = 1; loaded && gid != _num_glyphs; ++gid)
            _glyphs[gid] = loaded = _glyph_loader->read_glyph(gid, glyphs[gid], &numsubs);

        if (!loaded)
        {
            _glyphs[0] = 0;
            delete [] glyphs;
        }
        else if (numsubs > 0 && _boxes)
        {
            GlyphBox * boxes = (GlyphBox *)gralloc<char>(_num_glyphs * sizeof(GlyphBox) + numsubs * 8 * sizeof(float));
            GlyphBox * currbox = boxes;

            for (uint16 gid = 0; currbox && gid != _num_glyphs; ++gid)
            {
                _boxes[gid] = currbox;
                currbox = _glyph_loader->read_box(gid, currbox, *_glyphs[gid]);
            }
            if (!currbox)
            {
                free(boxes);
                _boxes[0] = 0;
            }
        }
        delete _glyph_loader;
        _glyph_loader = 0;
	// coverity[leaked_storage : FALSE] - calling read_glyph on index 0 saved
	// glyphs as _glyphs[0]. Setting _glyph_loader to nullptr here flags that
	// the dtor needs to call delete[] on _glyphs[0] to release what was allocated
	// as glyphs
    }

    if (_glyphs && glyph(0) == 0)
    {
        free(_glyphs);
        _glyphs = 0;
        if (_boxes)
        {
            free(_boxes);
            _boxes = 0;
        }
        _num_glyphs = _num_attrs = _upem = 0;
    }
}

GlyphCache::~GlyphCache()
{
    if (_glyphs)
    {
        if (_glyph_loader)
        {
            const GlyphFace *  * g = _glyphs;
            for(unsigned short n = _num_glyphs; n; --n, ++g)
                delete *g;
        }
        else
            delete [] _glyphs[0];
        free(_glyphs);
    }
    if (_boxes)
    {
        if (_glyph_loader)
        {
            GlyphBox *  * g = _boxes;
            for (uint16 n = _num_glyphs; n; --n, ++g)
                free(*g);
        }
        else
            free(_boxes[0]);
        free(_boxes);
    }
    delete _glyph_loader;
}

const GlyphFace *GlyphCache::glyph(unsigned short glyphid) const      //result may be changed by subsequent call with a different glyphid
{
    if (glyphid >= numGlyphs())
        return _glyphs[0];
    const GlyphFace * & p = _glyphs[glyphid];
    if (p == 0 && _glyph_loader)
    {
        int numsubs = 0;
        GlyphFace * g = new GlyphFace();
        if (g)  p = _glyph_loader->read_glyph(glyphid, *g, &numsubs);
        if (!p)
        {
            delete g;
            return *_glyphs;
        }
        if (_boxes)
        {
            _boxes[glyphid] = (GlyphBox *)gralloc<char>(sizeof(GlyphBox) + 8 * numsubs * sizeof(float));
            if (!_glyph_loader->read_box(glyphid, _boxes[glyphid], *_glyphs[glyphid]))
            {
                free(_boxes[glyphid]);
                _boxes[glyphid] = 0;
            }
        }
    }
    return p;
}

GlyphCache::Loader::Loader(const Face & face)
: _head(face, Tag::head),
  _hhea(face, Tag::hhea),
  _hmtx(face, Tag::hmtx),
  _glyf(face, Tag::glyf),
  _loca(face, Tag::loca),
  _long_fmt(false),
  _has_boxes(false),
  _num_glyphs_graphics(0),
  _num_glyphs_attributes(0),
  _num_attrs(0)
{
    if (!operator bool())
        return;

    const Face::Table maxp = Face::Table(face, Tag::maxp);
    if (!maxp) { _head = Face::Table(); return; }

    _num_glyphs_graphics = static_cast<unsigned short>(TtfUtil::GlyphCount(maxp));
    // This will fail if the number of glyphs is wildly out of range.
    if (_glyf && TtfUtil::LocaLookup(_num_glyphs_graphics-1, _loca, _loca.size(), _head) == size_t(-2))
    {
        _head = Face::Table();
        return;
    }

    if ((m_pGlat = Face::Table(face, Tag::Glat, 0x00030000)) == NULL
        || (m_pGloc = Face::Table(face, Tag::Gloc)) == NULL
        || m_pGloc.size() < 8)
    {
        _head = Face::Table();
        return;
    }
    const byte    * p = m_pGloc;
    int       version = be::read<uint32>(p);
    const uint16    flags = be::read<uint16>(p);
    _num_attrs = be::read<uint16>(p);
    // We can accurately calculate the number of attributed glyphs by
    //  subtracting the length of the attribids array (numAttribs long if present)
    //  and dividing by either 2 or 4 depending on shor or lonf format
    _long_fmt              = flags & 1;
    ptrdiff_t tmpnumgattrs       = (m_pGloc.size()
                               - (p - m_pGloc)
                               - sizeof(uint16)*(flags & 0x2 ? _num_attrs : 0))
                                   / (_long_fmt ? sizeof(uint32) : sizeof(uint16)) - 1;

    if (version >= 0x00020000 || tmpnumgattrs < 0 || tmpnumgattrs > 65535
        || _num_attrs == 0 || _num_attrs > 0x3000  // is this hard limit appropriate?
        || _num_glyphs_graphics > tmpnumgattrs
        || m_pGlat.size() < 4)
    {
        _head = Face::Table();
        return;
    }

    _num_glyphs_attributes = static_cast<unsigned short>(tmpnumgattrs);
    p = m_pGlat;
    version = be::read<uint32>(p);
    if (version >= 0x00040000 || (version >= 0x00030000 && m_pGlat.size() < 8))       // reject Glat tables that are too new
    {
        _head = Face::Table();
        return;
    }
    else if (version >= 0x00030000)
    {
        unsigned int glatflags = be::read<uint32>(p);
        _has_boxes = glatflags & 1;
        // delete this once the compiler is fixed
        _has_boxes = true;
    }
}

inline
GlyphCache::Loader::operator bool () const throw()
{
    return _head && _hhea && _hmtx && !(bool(_glyf) != bool(_loca));
}

inline
unsigned short int GlyphCache::Loader::units_per_em() const throw()
{
    return _head ? TtfUtil::DesignUnits(_head) : 0;
}

inline
unsigned short int GlyphCache::Loader::num_glyphs() const throw()
{
    return max(_num_glyphs_graphics, _num_glyphs_attributes);
}

inline
unsigned short int GlyphCache::Loader::num_attrs() const throw()
{
    return _num_attrs;
}

inline
bool GlyphCache::Loader::has_boxes () const throw()
{
    return _has_boxes;
}

const GlyphFace * GlyphCache::Loader::read_glyph(unsigned short glyphid, GlyphFace & glyph, int *numsubs) const throw()
{
    Rect        bbox;
    Position    advance;

    if (glyphid < _num_glyphs_graphics)
    {
        int nLsb;
        unsigned int nAdvWid;
        if (_glyf)
        {
            int xMin, yMin, xMax, yMax;
            size_t locidx = TtfUtil::LocaLookup(glyphid, _loca, _loca.size(), _head);
            void *pGlyph = TtfUtil::GlyfLookup(_glyf, locidx, _glyf.size());

            if (pGlyph && TtfUtil::GlyfBox(pGlyph, xMin, yMin, xMax, yMax))
            {
                if ((xMin > xMax) || (yMin > yMax))
                    return 0;
                bbox = Rect(Position(static_cast<float>(xMin), static_cast<float>(yMin)),
                    Position(static_cast<float>(xMax), static_cast<float>(yMax)));
            }
        }
        if (TtfUtil::HorMetrics(glyphid, _hmtx, _hmtx.size(), _hhea, nLsb, nAdvWid))
            advance = Position(static_cast<float>(nAdvWid), 0);
    }

    if (glyphid < _num_glyphs_attributes)
    {
        const byte * gloc = m_pGloc;
        size_t      glocs = 0, gloce = 0;

        be::skip<uint32>(gloc);
        be::skip<uint16>(gloc,2);
        if (_long_fmt)
        {
            if (8 + glyphid * sizeof(uint32) > m_pGloc.size())
                return 0;
            be::skip<uint32>(gloc, glyphid);
            glocs = be::read<uint32>(gloc);
            gloce = be::peek<uint32>(gloc);
        }
        else
        {
            if (8 + glyphid * sizeof(uint16) > m_pGloc.size())
                return 0;
            be::skip<uint16>(gloc, glyphid);
            glocs = be::read<uint16>(gloc);
            gloce = be::peek<uint16>(gloc);
        }

        if (glocs >= m_pGlat.size() - 1 || gloce > m_pGlat.size())
            return 0;

        const uint32 glat_version = be::peek<uint32>(m_pGlat);
        if (glat_version >= 0x00030000)
        {
            if (glocs >= gloce)
                return 0;
            const byte * p = m_pGlat + glocs;
            uint16 bmap = be::read<uint16>(p);
            int num = bit_set_count((uint32)bmap);
            if (numsubs) *numsubs += num;
            glocs += 6 + 8 * num;
            if (glocs > gloce)
                return 0;
        }
        if (glat_version < 0x00020000)
        {
            if (gloce - glocs < 2*sizeof(byte)+sizeof(uint16)
                || gloce - glocs > _num_attrs*(2*sizeof(byte)+sizeof(uint16)))
                    return 0;
            new (&glyph) GlyphFace(bbox, advance, glat_iterator(m_pGlat + glocs), glat_iterator(m_pGlat + gloce));
        }
        else
        {
            if (gloce - glocs < 3*sizeof(uint16)        // can a glyph have no attributes? why not?
                || gloce - glocs > _num_attrs*3*sizeof(uint16)
                || glocs > m_pGlat.size() - 2*sizeof(uint16))
                    return 0;
            new (&glyph) GlyphFace(bbox, advance, glat2_iterator(m_pGlat + glocs), glat2_iterator(m_pGlat + gloce));
        }
        if (!glyph.attrs() || glyph.attrs().capacity() > _num_attrs)
            return 0;
    }
    return &glyph;
}

inline float scale_to(uint8 t, float zmin, float zmax)
{
    return (zmin + t * (zmax - zmin) / 255);
}

Rect readbox(Rect &b, uint8 zxmin, uint8 zymin, uint8 zxmax, uint8 zymax)
{
    return Rect(Position(scale_to(zxmin, b.bl.x, b.tr.x), scale_to(zymin, b.bl.y, b.tr.y)),
                Position(scale_to(zxmax, b.bl.x, b.tr.x), scale_to(zymax, b.bl.y, b.tr.y)));
}

GlyphBox * GlyphCache::Loader::read_box(uint16 gid, GlyphBox *curr, const GlyphFace & glyph) const throw()
{
    if (gid >= _num_glyphs_attributes) return 0;

    const byte * gloc = m_pGloc;
    size_t      glocs = 0, gloce = 0;

    be::skip<uint32>(gloc);
    be::skip<uint16>(gloc,2);
    if (_long_fmt)
    {
        be::skip<uint32>(gloc, gid);
        glocs = be::read<uint32>(gloc);
        gloce = be::peek<uint32>(gloc);
    }
    else
    {
        be::skip<uint16>(gloc, gid);
        glocs = be::read<uint16>(gloc);
        gloce = be::peek<uint16>(gloc);
    }

    if (gloce > m_pGlat.size() || glocs + 6 >= gloce)
        return 0;

    const byte * p = m_pGlat + glocs;
    uint16 bmap = be::read<uint16>(p);
    int num = bit_set_count((uint32)bmap);

    Rect bbox = glyph.theBBox();
    Rect diamax(Position(bbox.bl.x + bbox.bl.y, bbox.bl.x - bbox.tr.y),
                Position(bbox.tr.x + bbox.tr.y, bbox.tr.x - bbox.bl.y));
    Rect diabound = readbox(diamax, p[0], p[2], p[1], p[3]);
    ::new (curr) GlyphBox(num, bmap, &diabound);
    be::skip<uint8>(p, 4);
    if (glocs + 6 + num * 8 >= gloce)
        return 0;

    for (int i = 0; i < num * 2; ++i)
    {
        Rect box = readbox((i & 1) ? diamax : bbox, p[0], p[2], p[1], p[3]);
        curr->addSubBox(i >> 1, i & 1, &box);
        be::skip<uint8>(p, 4);
    }
    return (GlyphBox *)((char *)(curr) + sizeof(GlyphBox) + 2 * num * sizeof(Rect));
}

repo_language: C

mime_type: text/x-c


text:
/*  GRAPHITE2 LICENSING

    Copyright 2010, SIL International
    All rights reserved.

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should also have received a copy of the GNU Lesser General Public
    License along with this library in the file named "LICENSE".
    If not, write to the Free Software Foundation, 51 Franklin Street,
    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
    internet at http://www.fsf.org/licenses/lgpl.html.

Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "inc/Main.h"
#include "inc/Endian.h"

#include "inc/NameTable.h"
#include "inc/UtfCodec.h"

using namespace graphite2;

NameTable::NameTable(const void* data, size_t length, uint16 platformId, uint16 encodingID)
 : m_platformId(0), m_encodingId(0), m_languageCount(0),
   m_platformOffset(0), m_platformLastRecord(0), m_nameDataLength(0),
   m_table(0), m_nameData(NULL)
{
    void *pdata = gralloc<byte>(length);
    if (!pdata) return;
    memcpy(pdata, data, length);
    m_table = reinterpret_cast<const TtfUtil::Sfnt::FontNames*>(pdata);

    if ((length > sizeof(TtfUtil::Sfnt::FontNames)) &&
        (length > sizeof(TtfUtil::Sfnt::FontNames) +
         sizeof(TtfUtil::Sfnt::NameRecord) * ( be::swap<uint16>(m_table->count) - 1)))
    {
        uint16 offset = be::swap<uint16>(m_table->string_offset);
        if (offset < length)
        {
            m_nameData = reinterpret_cast<const uint8*>(pdata) + offset;
            setPlatformEncoding(platformId, encodingID);
            m_nameDataLength = uint16(length - offset);
            return;
        }
    }
    free(const_cast<TtfUtil::Sfnt::FontNames*>(m_table));
    m_table = NULL;
}

uint16 NameTable::setPlatformEncoding(uint16 platformId, uint16 encodingID)
{
    if (!m_nameData) return 0;
    uint16 i = 0;
    uint16 count = be::swap<uint16>(m_table->count);
    for (; i < count; i++)
    {
        if (be::swap<uint16>(m_table->name_record[i].platform_id) == platformId &&
            be::swap<uint16>(m_table->name_record[i].platform_specific_id) == encodingID)
        {
            m_platformOffset = i;
            break;
        }
    }
    while ((++i < count) &&
           (be::swap<uint16>(m_table->name_record[i].platform_id) == platformId) &&
           (be::swap<uint16>(m_table->name_record[i].platform_specific_id) == encodingID))
    {
        m_platformLastRecord = i;
    }
    m_encodingId = encodingID;
    m_platformId = platformId;
    return 0;
}

void* NameTable::getName(uint16& languageId, uint16 nameId, gr_encform enc, uint32& length)
{
    uint16 anyLang = 0;
    uint16 enUSLang = 0;
    uint16 bestLang = 0;
    if (!m_table)
    {
        languageId = 0;
        length = 0;
        return NULL;
    }
    for (uint16 i = m_platformOffset; i <= m_platformLastRecord; i++)
    {
        if (be::swap<uint16>(m_table->name_record[i].name_id) == nameId)
        {
            uint16 langId = be::swap<uint16>(m_table->name_record[i].language_id);
            if (langId == languageId)
            {
                bestLang = i;
                break;
            }
            // MS language tags have the language in the lower byte, region in the higher
            else if ((langId & 0xFF) == (languageId & 0xFF))
            {
                bestLang = i;
            }
            else if (langId == 0x409)
            {
                enUSLang = i;
            }
            else
            {
                anyLang = i;
            }
        }
    }
    if (!bestLang)
    {
        if (enUSLang) bestLang = enUSLang;
        else
        {
            bestLang = anyLang;
            if (!anyLang)
            {
                languageId = 0;
                length = 0;
                return NULL;
            }
        }
    }
    const TtfUtil::Sfnt::NameRecord & nameRecord = m_table->name_record[bestLang];
    languageId = be::swap<uint16>(nameRecord.language_id);
    uint16 utf16Length = be::swap<uint16>(nameRecord.length);
    uint16 offset = be::swap<uint16>(nameRecord.offset);
    if(offset + utf16Length > m_nameDataLength)
    {
        languageId = 0;
        length = 0;
        return NULL;
    }
    utf16Length >>= 1; // in utf16 units
    utf16::codeunit_t * utf16Name = gralloc<utf16::codeunit_t>(utf16Length + 1);
    if (!utf16Name)
    {
        languageId = 0;
        length = 0;
        return NULL;
    }
    const uint8* pName = m_nameData + offset;
    for (size_t i = 0; i < utf16Length; i++)
    {
        utf16Name[i] = be::read<uint16>(pName);
    }
    utf16Name[utf16Length] = 0;
    if (!utf16::validate(utf16Name, utf16Name + utf16Length))
    {
        free(utf16Name);
        languageId = 0;
        length = 0;
        return NULL;
    }
    switch (enc)
    {
    case gr_utf8:
    {
        utf8::codeunit_t* uniBuffer = gralloc<utf8::codeunit_t>(3 * utf16Length + 1);
        if (!uniBuffer)
        {
            free(utf16Name);
            languageId = 0;
            length = 0;
            return NULL;
        }
        utf8::iterator d = uniBuffer;
        for (utf16::const_iterator s = utf16Name, e = utf16Name + utf16Length; s != e; ++s, ++d)
            *d = *s;
        length = uint32(d - uniBuffer);
        uniBuffer[length] = 0;
        free(utf16Name);
        return uniBuffer;
    }
    case gr_utf16:
        length = utf16Length;
        return utf16Name;
    case gr_utf32:
    {
        utf32::codeunit_t * uniBuffer = gralloc<utf32::codeunit_t>(utf16Length  + 1);
        if (!uniBuffer)
        {
            free(utf16Name);
            languageId = 0;
            length = 0;
            return NULL;
        }
        utf32::iterator d = uniBuffer;
        for (utf16::const_iterator s = utf16Name, e = utf16Name + utf16Length; s != e; ++s, ++d)
            *d = *s;
        length = uint32(d - uniBuffer);
        uniBuffer[length] = 0;
        free(utf16Name);
        return uniBuffer;
    }
    }
    free(utf16Name);
    languageId = 0;
    length = 0;
    return NULL;
}

uint16 NameTable::getLanguageId(const char * bcp47Locale)
{
    size_t localeLength = strlen(bcp47Locale);
    uint16 localeId = m_locale2Lang.getMsId(bcp47Locale);
    if (m_table && (be::swap<uint16>(m_table->format) == 1))
    {
        const uint8 * pLangEntries = reinterpret_cast<const uint8*>(m_table) +
            sizeof(TtfUtil::Sfnt::FontNames)
            + sizeof(TtfUtil::Sfnt::NameRecord) * ( be::swap<uint16>(m_table->count) - 1);
        uint16 numLangEntries = be::read<uint16>(pLangEntries);
        const TtfUtil::Sfnt::LangTagRecord * langTag =
            reinterpret_cast<const TtfUtil::Sfnt::LangTagRecord*>(pLangEntries);
        if (pLangEntries + numLangEntries * sizeof(TtfUtil::Sfnt::LangTagRecord) <= m_nameData)
        {
            for (uint16 i = 0; i < numLangEntries; i++)
            {
                uint16 offset = be::swap<uint16>(langTag[i].offset);
                uint16 length = be::swap<uint16>(langTag[i].length);
                if ((offset + length <= m_nameDataLength) && (length == 2 * localeLength))
                {
                    const uint8* pName = m_nameData + offset;
                    bool match = true;
                    for (size_t j = 0; j < localeLength; j++)
                    {
                        uint16 code = be::read<uint16>(pName);
                        if ((code > 0x7F) || (code != bcp47Locale[j]))
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match)
                        return 0x8000 + i;
                }
            }
        }
    }
    return localeId;
}


text:
/*  GRAPHITE2 LICENSING

    Copyright 2010, SIL International
    All rights reserved.

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should also have received a copy of the GNU Lesser General Public
    License along with this library in the file named "LICENSE".
    If not, write to the Free Software Foundation, 51 Franklin Street,
    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
    internet at http://www.fsf.org/licenses/lgpl.html.

Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "inc/Segment.h"
#include "inc/Slot.h"
#include "inc/Silf.h"
#include "inc/CharInfo.h"
#include "inc/Rule.h"
#include "inc/Collider.h"

using namespace graphite2;

Slot::Slot(int16 *user_attrs) :
    m_next(NULL), m_prev(NULL),
    m_glyphid(0), m_realglyphid(0), m_original(0), m_before(0), m_after(0),
    m_index(0), m_parent(NULL), m_child(NULL), m_sibling(NULL),
    m_position(0, 0), m_shift(0, 0), m_advance(0, 0),
    m_attach(0, 0), m_with(0, 0), m_just(0.),
    m_flags(0), m_attLevel(0), m_bidiCls(-1), m_bidiLevel(0),
    m_userAttr(user_attrs), m_justs(NULL)
{
}

// take care, this does not copy any of the GrSlot pointer fields
void Slot::set(const Slot & orig, int charOffset, size_t sizeAttr, size_t justLevels, size_t numChars)
{
    // leave m_next and m_prev unchanged
    m_glyphid = orig.m_glyphid;
    m_realglyphid = orig.m_realglyphid;
    m_original = orig.m_original + charOffset;
    if (charOffset + int(orig.m_before) < 0)
        m_before = 0;
    else
        m_before = orig.m_before + charOffset;
    if (charOffset <= 0 && orig.m_after + charOffset >= numChars)
        m_after = int(numChars) - 1;
    else
        m_after = orig.m_after + charOffset;
    m_parent = NULL;
    m_child = NULL;
    m_sibling = NULL;
    m_position = orig.m_position;
    m_shift = orig.m_shift;
    m_advance = orig.m_advance;
    m_attach = orig.m_attach;
    m_with = orig.m_with;
    m_flags = orig.m_flags;
    m_attLevel = orig.m_attLevel;
    m_bidiCls = orig.m_bidiCls;
    m_bidiLevel = orig.m_bidiLevel;
    if (m_userAttr && orig.m_userAttr)
        memcpy(m_userAttr, orig.m_userAttr, sizeAttr * sizeof(*m_userAttr));
    if (m_justs && orig.m_justs)
        memcpy(m_justs, orig.m_justs, SlotJustify::size_of(justLevels));
}

void Slot::update(int /*numGrSlots*/, int numCharInfo, Position &relpos)
{
    m_before += numCharInfo;
    m_after += numCharInfo;
    m_position = m_position + relpos;
}

Position Slot::finalise(const Segment *seg, const Font *font, Position & base, Rect & bbox, uint8 attrLevel, float & clusterMin, bool rtl, bool isFinal, int depth)
{
    SlotCollision *coll = NULL;
    if (depth > 100 || (attrLevel && m_attLevel > attrLevel)) return Position(0, 0);
    float scale = font ? font->scale() : 1.0f;
    Position shift(m_shift.x * (rtl * -2 + 1) + m_just, m_shift.y);
    float tAdvance = m_advance.x + m_just;
    if (isFinal && (coll = seg->collisionInfo(this)))
    {
        const Position &collshift = coll->offset();
        if (!(coll->flags() & SlotCollision::COLL_KERN) || rtl)
            shift = shift + collshift;
    }
    const GlyphFace * glyphFace = seg->getFace()->glyphs().glyphSafe(glyph());
    if (font)
    {
        scale = font->scale();
        shift *= scale;
        if (font->isHinted() && glyphFace)
            tAdvance = (m_advance.x - glyphFace->theAdvance().x + m_just) * scale + font->advance(glyph());
        else
            tAdvance *= scale;
    }
    Position res;

    m_position = base + shift;
    if (!m_parent)
    {
        res = base + Position(tAdvance, m_advance.y * scale);
        clusterMin = m_position.x;
    }
    else
    {
        float tAdv;
        m_position += (m_attach - m_with) * scale;
        tAdv = m_advance.x >= 0.5f ? m_position.x + tAdvance - shift.x : 0.f;
        res = Position(tAdv, 0);
        if ((m_advance.x >= 0.5f || m_position.x < 0) && m_position.x < clusterMin) clusterMin = m_position.x;
    }

    if (glyphFace)
    {
        Rect ourBbox = glyphFace->theBBox() * scale + m_position;
        bbox = bbox.widen(ourBbox);
    }

    if (m_child && m_child != this && m_child->attachedTo() == this)
    {
        Position tRes = m_child->finalise(seg, font, m_position, bbox, attrLevel, clusterMin, rtl, isFinal, depth + 1);
        if ((!m_parent || m_advance.x >= 0.5f) && tRes.x > res.x) res = tRes;
    }

    if (m_parent && m_sibling && m_sibling != this && m_sibling->attachedTo() == m_parent)
    {
        Position tRes = m_sibling->finalise(seg, font, base, bbox, attrLevel, clusterMin, rtl, isFinal, depth + 1);
        if (tRes.x > res.x) res = tRes;
    }

    if (!m_parent && clusterMin < base.x)
    {
        Position adj = Position(m_position.x - clusterMin, 0.);
        res += adj;
        m_position += adj;
        if (m_child) m_child->floodShift(adj);
    }
    return res;
}

int32 Slot::clusterMetric(const Segment *seg, uint8 metric, uint8 attrLevel, bool rtl)
{
    Position base;
    if (glyph() >= seg->getFace()->glyphs().numGlyphs())
        return 0;
    Rect bbox = seg->theGlyphBBoxTemporary(glyph());
    float clusterMin = 0.;
    Position res = finalise(seg, NULL, base, bbox, attrLevel, clusterMin, rtl, false);

    switch (metrics(metric))
    {
    case kgmetLsb :
        return int32(bbox.bl.x);
    case kgmetRsb :
        return int32(res.x - bbox.tr.x);
    case kgmetBbTop :
        return int32(bbox.tr.y);
    case kgmetBbBottom :
        return int32(bbox.bl.y);
    case kgmetBbLeft :
        return int32(bbox.bl.x);
    case kgmetBbRight :
        return int32(bbox.tr.x);
    case kgmetBbWidth :
        return int32(bbox.tr.x - bbox.bl.x);
    case kgmetBbHeight :
        return int32(bbox.tr.y - bbox.bl.y);
    case kgmetAdvWidth :
        return int32(res.x);
    case kgmetAdvHeight :
        return int32(res.y);
    default :
        return 0;
    }
}

#define SLOTGETCOLATTR(x) { SlotCollision *c = seg->collisionInfo(this); return c ? int(c-> x) : 0; }

int Slot::getAttr(const Segment *seg, attrCode ind, uint8 subindex) const
{
    if (ind >= gr_slatJStretch && ind < gr_slatJStretch + 20 && ind != gr_slatJWidth)
    {
        int indx = ind - gr_slatJStretch;
        return getJustify(seg, indx / 5, indx % 5);
    }

    switch (ind)
    {
    case gr_slatAdvX :      return int(m_advance.x);
    case gr_slatAdvY :      return int(m_advance.y);
    case gr_slatAttTo :     return m_parent ? 1 : 0;
    case gr_slatAttX :      return int(m_attach.x);
    case gr_slatAttY :      return int(m_attach.y);
    case gr_slatAttXOff :
    case gr_slatAttYOff :   return 0;
    case gr_slatAttWithX :  return int(m_with.x);
    case gr_slatAttWithY :  return int(m_with.y);
    case gr_slatAttWithXOff:
    case gr_slatAttWithYOff:return 0;
    case gr_slatAttLevel :  return m_attLevel;
    case gr_slatBreak :     return seg->charinfo(m_original)->breakWeight();
    case gr_slatCompRef :   return 0;
    case gr_slatDir :       return seg->dir() & 1;
    case gr_slatInsert :    return isInsertBefore();
    case gr_slatPosX :      return int(m_position.x); // but need to calculate it
    case gr_slatPosY :      return int(m_position.y);
    case gr_slatShiftX :    return int(m_shift.x);
    case gr_slatShiftY :    return int(m_shift.y);
    case gr_slatMeasureSol: return -1; // err what's this?
    case gr_slatMeasureEol: return -1;
    case gr_slatJWidth:     return int(m_just);
    case gr_slatUserDefnV1: subindex = 0; GR_FALLTHROUGH;
      // no break
    case gr_slatUserDefn :  return subindex < seg->numAttrs() ?  m_userAttr[subindex] : 0;
    case gr_slatSegSplit :  return seg->charinfo(m_original)->flags() & 3;
    case gr_slatBidiLevel:  return m_bidiLevel;
    case gr_slatColFlags :		{ SlotCollision *c = seg->collisionInfo(this); return c ? c->flags() : 0; }
    case gr_slatColLimitblx:SLOTGETCOLATTR(limit().bl.x)
    case gr_slatColLimitbly:SLOTGETCOLATTR(limit().bl.y)
    case gr_slatColLimittrx:SLOTGETCOLATTR(limit().tr.x)
    case gr_slatColLimittry:SLOTGETCOLATTR(limit().tr.y)
    case gr_slatColShiftx :	SLOTGETCOLATTR(offset().x)
    case gr_slatColShifty :	SLOTGETCOLATTR(offset().y)
    case gr_slatColMargin :	SLOTGETCOLATTR(margin())
    case gr_slatColMarginWt:SLOTGETCOLATTR(marginWt())
    case gr_slatColExclGlyph:SLOTGETCOLATTR(exclGlyph())
    case gr_slatColExclOffx:SLOTGETCOLATTR(exclOffset().x)
    case gr_slatColExclOffy:SLOTGETCOLATTR(exclOffset().y)
    case gr_slatSeqClass :	SLOTGETCOLATTR(seqClass())
    case gr_slatSeqProxClass:SLOTGETCOLATTR(seqProxClass())
    case gr_slatSeqOrder :	SLOTGETCOLATTR(seqOrder())
    case gr_slatSeqAboveXoff:SLOTGETCOLATTR(seqAboveXoff())
    case gr_slatSeqAboveWt: SLOTGETCOLATTR(seqAboveWt())
    case gr_slatSeqBelowXlim:SLOTGETCOLATTR(seqBelowXlim())
    case gr_slatSeqBelowWt:	SLOTGETCOLATTR(seqBelowWt())
    case gr_slatSeqValignHt:SLOTGETCOLATTR(seqValignHt())
    case gr_slatSeqValignWt:SLOTGETCOLATTR(seqValignWt())
    default : return 0;
    }
}

#define SLOTCOLSETATTR(x) { \
        SlotCollision *c = seg->collisionInfo(this); \
        if (c) { c-> x ; c->setFlags(c->flags() & ~SlotCollision::COLL_KNOWN); } \
        break; }
#define SLOTCOLSETCOMPLEXATTR(t, y, x) { \
        SlotCollision *c = seg->collisionInfo(this); \
        if (c) { \
        const t &s = c-> y; \
        c-> x ; c->setFlags(c->flags() & ~SlotCollision::COLL_KNOWN); } \
        break; }

void Slot::setAttr(Segment *seg, attrCode ind, uint8 subindex, int16 value, const SlotMap & map)
{
    if (ind == gr_slatUserDefnV1)
    {
        ind = gr_slatUserDefn;
        subindex = 0;
        if (seg->numAttrs() == 0)
            return;
    }
    else if (ind >= gr_slatJStretch && ind < gr_slatJStretch + 20 && ind != gr_slatJWidth)
    {
        int indx = ind - gr_slatJStretch;
        return setJustify(seg, indx / 5, indx % 5, value);
    }

    switch (ind)
    {
    case gr_slatAdvX :  m_advance.x = value; break;
    case gr_slatAdvY :  m_advance.y = value; break;
    case gr_slatAttTo :
    {
        const uint16 idx = uint16(value);
        if (idx < map.size() && map[idx])
        {
            Slot *other = map[idx];
            if (other == this || other == m_parent || other->isCopied()) break;
            if (m_parent) { m_parent->removeChild(this); attachTo(NULL); }
            Slot *pOther = other;
            int count = 0;
            bool foundOther = false;
            while (pOther)
            {
                ++count;
                if (pOther == this) foundOther = true;
                pOther = pOther->attachedTo();
            }
            for (pOther = m_child; pOther; pOther = pOther->m_child)
                ++count;
            for (pOther = m_sibling; pOther; pOther = pOther->m_sibling)
                ++count;
            if (count < 100 && !foundOther && other->child(this))
            {
                attachTo(other);
                if ((map.dir() != 0) ^ (idx > subindex))
                    m_with = Position(advance(), 0);
                else        // normal match to previous root
                    m_attach = Position(other->advance(), 0);
            }
        }
        break;
    }
    case gr_slatAttX :          m_attach.x = value; break;
    case gr_slatAttY :          m_attach.y = value; break;
    case gr_slatAttXOff :
    case gr_slatAttYOff :       break;
    case gr_slatAttWithX :      m_with.x = value; break;
    case gr_slatAttWithY :      m_with.y = value; break;
    case gr_slatAttWithXOff :
    case gr_slatAttWithYOff :   break;
    case gr_slatAttLevel :
        m_attLevel = byte(value);
        break;
    case gr_slatBreak :
        seg->charinfo(m_original)->breakWeight(value);
        break;
    case gr_slatCompRef :   break;      // not sure what to do here
    case gr_slatDir : break;
    case gr_slatInsert :
        markInsertBefore(value? true : false);
        break;
    case gr_slatPosX :      break; // can't set these here
    case gr_slatPosY :      break;
    case gr_slatShiftX :    m_shift.x = value; break;
    case gr_slatShiftY :    m_shift.y = value; break;
    case gr_slatMeasureSol :    break;
    case gr_slatMeasureEol :    break;
    case gr_slatJWidth :    just(value); break;
    case gr_slatSegSplit :  seg->charinfo(m_original)->addflags(value & 3); break;
    case gr_slatUserDefn :  m_userAttr[subindex] = value; break;
    case gr_slatColFlags :  {
        SlotCollision *c = seg->collisionInfo(this);
        if (c)
            c->setFlags(value);
        break; }
    case gr_slatColLimitblx :	SLOTCOLSETCOMPLEXATTR(Rect, limit(), setLimit(Rect(Position(value, s.bl.y), s.tr)))
    case gr_slatColLimitbly :	SLOTCOLSETCOMPLEXATTR(Rect, limit(), setLimit(Rect(Position(s.bl.x, value), s.tr)))
    case gr_slatColLimittrx :	SLOTCOLSETCOMPLEXATTR(Rect, limit(), setLimit(Rect(s.bl, Position(value, s.tr.y))))
    case gr_slatColLimittry :	SLOTCOLSETCOMPLEXATTR(Rect, limit(), setLimit(Rect(s.bl, Position(s.tr.x, value))))
    case gr_slatColMargin :		SLOTCOLSETATTR(setMargin(value))
    case gr_slatColMarginWt :	SLOTCOLSETATTR(setMarginWt(value))
    case gr_slatColExclGlyph :	SLOTCOLSETATTR(setExclGlyph(value))
    case gr_slatColExclOffx :	SLOTCOLSETCOMPLEXATTR(Position, exclOffset(), setExclOffset(Position(value, s.y)))
    case gr_slatColExclOffy :	SLOTCOLSETCOMPLEXATTR(Position, exclOffset(), setExclOffset(Position(s.x, value)))
    case gr_slatSeqClass :		SLOTCOLSETATTR(setSeqClass(value))
	case gr_slatSeqProxClass :	SLOTCOLSETATTR(setSeqProxClass(value))
    case gr_slatSeqOrder :		SLOTCOLSETATTR(setSeqOrder(value))
    case gr_slatSeqAboveXoff :	SLOTCOLSETATTR(setSeqAboveXoff(value))
    case gr_slatSeqAboveWt :	SLOTCOLSETATTR(setSeqAboveWt(value))
    case gr_slatSeqBelowXlim :	SLOTCOLSETATTR(setSeqBelowXlim(value))
    case gr_slatSeqBelowWt :	SLOTCOLSETATTR(setSeqBelowWt(value))
    case gr_slatSeqValignHt :	SLOTCOLSETATTR(setSeqValignHt(value))
    case gr_slatSeqValignWt :	SLOTCOLSETATTR(setSeqValignWt(value))
    default :
        break;
    }
}

int Slot::getJustify(const Segment *seg, uint8 level, uint8 subindex) const
{
    if (level && level >= seg->silf()->numJustLevels()) return 0;

    if (m_justs)
        return m_justs->values[level * SlotJustify::NUMJUSTPARAMS + subindex];

    if (level >= seg->silf()->numJustLevels()) return 0;
    Justinfo *jAttrs = seg->silf()->justAttrs() + level;

    switch (subindex) {
        case 0 : return seg->glyphAttr(gid(), jAttrs->attrStretch());
        case 1 : return seg->glyphAttr(gid(), jAttrs->attrShrink());
        case 2 : return seg->glyphAttr(gid(), jAttrs->attrStep());
        case 3 : return seg->glyphAttr(gid(), jAttrs->attrWeight());
        case 4 : return 0;      // not been set yet, so clearly 0
        default: return 0;
    }
}

void Slot::setJustify(Segment *seg, uint8 level, uint8 subindex, int16 value)
{
    if (level && level >= seg->silf()->numJustLevels()) return;
    if (!m_justs)
    {
        SlotJustify *j = seg->newJustify();
        if (!j) return;
        j->LoadSlot(this, seg);
        m_justs = j;
    }
    m_justs->values[level * SlotJustify::NUMJUSTPARAMS + subindex] = value;
}

bool Slot::child(Slot *ap)
{
    if (this == ap) return false;
    else if (ap == m_child) return true;
    else if (!m_child)
        m_child = ap;
    else
        return m_child->sibling(ap);
    return true;
}

bool Slot::sibling(Slot *ap)
{
    if (this == ap) return false;
    else if (ap == m_sibling) return true;
    else if (!m_sibling || !ap)
        m_sibling = ap;
    else
        return m_sibling->sibling(ap);
    return true;
}

bool Slot::removeChild(Slot *ap)
{
    if (this == ap || !m_child || !ap) return false;
    else if (ap == m_child)
    {
        Slot *nSibling = m_child->nextSibling();
        m_child->nextSibling(NULL);
        m_child = nSibling;
        return true;
    }
    for (Slot *p = m_child; p; p = p->m_sibling)
    {
        if (p->m_sibling && p->m_sibling == ap)
        {
            p->m_sibling = p->m_sibling->m_sibling;
            ap->nextSibling(NULL);
            return true;
        }
    }
    return false;
}

void Slot::setGlyph(Segment *seg, uint16 glyphid, const GlyphFace * theGlyph)
{
    m_glyphid = glyphid;
    m_bidiCls = -1;
    if (!theGlyph)
    {
        theGlyph = seg->getFace()->glyphs().glyphSafe(glyphid);
        if (!theGlyph)
        {
            m_realglyphid = 0;
            m_advance = Position(0.,0.);
            return;
        }
    }
    m_realglyphid = theGlyph->attrs()[seg->silf()->aPseudo()];
    if (m_realglyphid > seg->getFace()->glyphs().numGlyphs())
        m_realglyphid = 0;
    const GlyphFace *aGlyph = theGlyph;
    if (m_realglyphid)
    {
        aGlyph = seg->getFace()->glyphs().glyphSafe(m_realglyphid);
        if (!aGlyph) aGlyph = theGlyph;
    }
    m_advance = Position(aGlyph->theAdvance().x, 0.);
    if (seg->silf()->aPassBits())
    {
        seg->mergePassBits(uint8(theGlyph->attrs()[seg->silf()->aPassBits()]));
        if (seg->silf()->numPasses() > 16)
            seg->mergePassBits(theGlyph->attrs()[seg->silf()->aPassBits()+1] << 16);
    }
}

void Slot::floodShift(Position adj, int depth)
{
    if (depth > 100)
        return;
    m_position += adj;
    if (m_child) m_child->floodShift(adj, depth + 1);
    if (m_sibling) m_sibling->floodShift(adj, depth + 1);
}

void SlotJustify::LoadSlot(const Slot *s, const Segment *seg)
{
    for (int i = seg->silf()->numJustLevels() - 1; i >= 0; --i)
    {
        Justinfo *justs = seg->silf()->justAttrs() + i;
        int16 *v = values + i * NUMJUSTPARAMS;
        v[0] = seg->glyphAttr(s->gid(), justs->attrStretch());
        v[1] = seg->glyphAttr(s->gid(), justs->attrShrink());
        v[2] = seg->glyphAttr(s->gid(), justs->attrStep());
        v[3] = seg->glyphAttr(s->gid(), justs->attrWeight());
    }
}

Slot * Slot::nextInCluster(const Slot *s) const
{
    Slot *base;
    if (s->firstChild())
        return s->firstChild();
    else if (s->nextSibling())
        return s->nextSibling();
    while ((base = s->attachedTo()))
    {
        // if (base->firstChild() == s && base->nextSibling())
        if (base->nextSibling())
            return base->nextSibling();
        s = base;
    }
    return NULL;
}

bool Slot::isChildOf(const Slot *base) const
{
    for (Slot *p = m_parent; p; p = p->m_parent)
        if (p == base)
            return true;
    return false;
}


text:
/*  GRAPHITE2 LICENSING

    Copyright 2010, SIL International
    All rights reserved.

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should also have received a copy of the GNU Lesser General Public
    License along with this library in the file named "LICENSE".
    If not, write to the Free Software Foundation, 51 Franklin Street,
    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
    internet at http://www.fsf.org/licenses/lgpl.html.

Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "inc/Position.h"
#include <cmath>

using namespace graphite2;

bool Rect::hitTest(Rect &other)
{
    if (bl.x > other.tr.x) return false;
    if (tr.x < other.bl.x) return false;
    if (bl.y > other.tr.y) return false;
    if (tr.y < other.bl.y) return false;
    return true;
}

Position Rect::overlap(Position &offset, Rect &other, Position &othero)
{
    float ax = (bl.x + offset.x) - (other.tr.x + othero.x);
    float ay = (bl.y + offset.y) - (other.tr.y + othero.y);
    float bx = (other.bl.x + othero.x) - (tr.x + offset.x);
    float by = (other.bl.y + othero.y) - (tr.y + offset.y);
    return Position((ax > bx ? ax : bx), (ay > by ? ay : by));
}

float boundmin(float move, float lim1, float lim2, float &error)
{
    // error is always positive for easy comparison
    if (move < lim1 && move < lim2)
    { error = 0.; return move; }
    else if (lim1 < lim2)
    { error = std::fabs(move - lim1); return lim1; }
    else
    { error = std::fabs(move - lim2); return lim2; }
}

#if 0
Position Rect::constrainedAvoid(Position &offset, Rect &box, Rect &sdbox, Position &other, Rect &obox, Rect &osdbox)
{
    // a = max, i = min, s = sum, d = diff
    float eax, eay, eix, eiy, eas, eis, ead, eid;
    float beste = INF;
    Position res;
    // calculate the movements in each direction and the error (amount of remaining overlap)
    // first param is movement, second and third are movement over the constraining box
    float ax = boundmin(obox.tr.x + other.x - box.bl.x - offset.x + 1, tr.x - offset.x, INF, &eax);
    float ay = boundmin(obox.tr.y + other.y - box.bl.y - offset.y + 1, tr.y - offset.y, INF, &eay);
    float ix = boundmin(obox.bl.x + other.x - box.tr.x - offset.x + 1, bl.x - offset.x, INF, &eix);
    float iy = boundmin(obox.bl.y + other.y - box.tr.y - offset.y + 1, bl.y - offset.y, INF, &eiy);
    float as = boundmin(ISQRT2 * (osdbox.tr.x + other.x + other.y - sdbox.bl.x - offset.x - offset.y) + 1, tr.x - offset.x, tr.y - offset.y, &eas);
    float is = boundmin(ISQRT2 * (osdbox.bl.x + other.x + other.y - sdbox.tr.x - offset.x - offset.y) + 1, bl.x - offset.x, bl.y - offset.y, &eis);
    float ad = boundmin(ISQRT2 * (osdbox.tr.y + other.x - other.y - sdbox.bl.y - offset.x + offset.y) + 1, tr.y - offset.y, tr.x - offset.x, &ead);
    float id = boundmin(ISQRT2 * (osdbox.bl.y + other.x - other.y - sdbox.tr.y - offset.x + offset.y) + 1, bl.y - offset.y, bl.x - offset.x, &eid);

    if (eax < beste)
    { res = Position(ax, 0); beste = eax; }
    if (eay < beste)
    { res = Position(0, ay); beste = eay; }
    if (eix < beste)
    { res = Position(ix, 0); beste = eix; }
    if (eiy < beste)
    { res = Position(0, iy); beste = eiy; }
    if (SQRT2 * (eas) < beste)
    { res = Position(as, ad); beste = SQRT2 * (eas); }
    if (SQRT2 * (eis) < beste)
    { res = Position(is, is); beste = SQRT2 * (eis); }
    if (SQRT2 * (ead) < beste)
    { res = Position(ad, ad); beste = SQRT2 * (ead); }
    if (SQRT2 * (eid) < beste)
    { res = Position(id, id); beste = SQRT2 * (eid); }
    return res;
}
#endif