
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from matplotlib.image import BboxImage
import numpy as np
from matplotlib.transforms import IdentityTransform

import matplotlib.patches as mpatches

from matplotlib.offsetbox import AnnotationBbox,\
     AnchoredOffsetbox, AuxTransformBox

from matplotlib.cbook import get_sample_data

from matplotlib.text import TextPath
import matplotlib.textpath as textpath


import matplotlib.dviread as dviread
from matplotlib.path import Path
from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, LOAD_NO_HINTING, LOAD_TARGET_LIGHT

class TextToPath(textpath.TextToPath):


    def get_glyphs_tex(self, prop, s, glyph_map=None,
                       return_new_glyphs_only=False):
        """
        convert the string *s* to vertices and codes using matplotlib's usetex mode.
        """

        # codes are modstly borrowed from pdf backend.

        texmanager = self.get_texmanager()

        if self.tex_font_map is None:
            self.tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))

        fontsize = prop.get_size_in_points()
        if hasattr(texmanager, "get_dvi"): #
            dvifilelike = texmanager.get_dvi(s, self.FONT_SCALE)
            dvi = dviread.DviFromFileLike(dvifilelike, self.DPI)
        else:
            dvifile = texmanager.make_dvi(s, self.FONT_SCALE)
            dvi = dviread.Dvi(dvifile, self.DPI)
        page = iter(dvi).next()
        dvi.close()


        if glyph_map is None:
            glyph_map = dict()

        if return_new_glyphs_only:
            glyph_map_new = dict()
        else:
            glyph_map_new = glyph_map

        # debug
        print "texname, type1name, enc, char_id"

        glyph_ids, xpositions, ypositions, sizes = [], [], [], []

        # Gather font information and do some setup for combining
        # characters into strings.
        #oldfont, seq = None, []
        for x1, y1, dvifont, glyph, width in page.text:
            font_and_encoding = self._ps_fontd.get(dvifont.texname)

            if font_and_encoding is None:
                font_bunch =  self.tex_font_map[dvifont.texname]
                font = FT2Font(font_bunch.filename)
                if font_bunch.encoding:
                    enc = dviread.Encoding(font_bunch.encoding)
                else:
                    enc = None
                self._ps_fontd[dvifont.texname] = font, enc

            else:
                font, enc = font_and_encoding

            ft2font_flag = LOAD_TARGET_LIGHT
            if enc:
                ng = font.get_name_index(enc.encoding[glyph])
            else:
                ng = glyph

            char_id = self._get_char_id_ps(font, ng)

            if not char_id in glyph_map:
                font.clear()
                font.set_size(self.FONT_SCALE, self.DPI)

                if ng == 0:
                    # While 0 is a valid index (e.g., "-", "\Gamma"),
                    # font.load_glyph(0) does not seem to work. This
                    # may not be a general solution.
                    glyph0 = font.load_glyph(128, flags=ft2font_flag)
                else:
                    glyph0 = font.load_glyph(ng, flags=ft2font_flag)

                glyph_map_new[char_id] = self.glyph_to_path(glyph0)

            glyph_ids.append(char_id)
            xpositions.append(x1)
            ypositions.append(y1)
            sizes.append(dvifont.size/self.FONT_SCALE)

            # debug
            print dvifont.texname, font_bunch.filename, font_bunch.encoding, char_id

        myrects = []

        for ox, oy, h, w in page.boxes:
            vert1=[(ox, oy), (ox+w, oy), (ox+w, oy+h), (ox, oy+h), (ox, oy), (0,0)]
            code1 = [Path.MOVETO,
                     Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
                     Path.CLOSEPOLY]
            myrects.append((vert1, code1))


        return zip(glyph_ids, xpositions, ypositions, sizes), glyph_map, myrects

textpath.text_to_path = TextToPath()

if 1:

    usetex = True

    fig = plt.figure(1)

    # EXAMPLE 2

    ax = plt.subplot(111)

    if usetex:
        s = r"$\displaystyle\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
    else:
        s = r"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
    text_path = TextPath((0, 0), s, size=40, usetex=usetex)
    text_patch = mpatches.PathPatch(text_path, ec="none",
                                    transform=IdentityTransform())

    offsetbox = AuxTransformBox(IdentityTransform())
    offsetbox.add_artist(text_patch)

    # place the anchored offset box using AnnotationBbox
    ab = AnnotationBbox(offsetbox, (0.5, 0.5),
                        xycoords='data',
                        boxcoords="offset points",
                        box_alignment=(0.5,0.5),
                        )
    #text_path.set_size(10)

    ax.add_artist(ab)

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)


    plt.draw()
    plt.show()
