#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/cidfonts.py
#$Header $
__version__=''' $Id$ '''
__doc__="""CID (Asian multi-byte) font support.

This defines classes to represent CID fonts.  They know how to calculate
their own width and how to write themselves into PDF files."""

import os
import marshal
import time
try:
    from hashlib import md5
except ImportError:
    from md5 import md5

import reportlab
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase._cidfontdata import allowedTypeFaces, allowedEncodings, CIDFontInfo, \
     defaultUnicodeEncodings, widthsByUnichar
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfdoc
from reportlab.lib.rl_accel import escapePDF
from reportlab.rl_config import CMapSearchPath
from reportlab.lib.utils import isSeq, isBytes

#quick hackery for 2.0 release.  Now we always do unicode, and have built in
#the CMAP data, any code to load CMap files is not needed.
DISABLE_CMAP = True


def findCMapFile(name):
    "Returns full filename, or raises error"
    for dirname in CMapSearchPath:
        cmapfile = dirname + os.sep + name
        if os.path.isfile(cmapfile):
            #print "found", cmapfile
            return cmapfile
    raise IOError('CMAP file for encodings "%s" not found!' % name)

def structToPDF(structure):
    "Converts deeply nested structure to PDFdoc dictionary/array objects"
    if isinstance(structure,dict):
        newDict = {}
        for k, v in structure.items():
            newDict[k] = structToPDF(v)
        return pdfdoc.PDFDictionary(newDict)
    elif isSeq(structure):
        newList = []
        for elem in structure:
            newList.append(structToPDF(elem))
        return pdfdoc.PDFArray(newList)
    else:
        return structure

class CIDEncoding(pdfmetrics.Encoding):
    """Multi-byte encoding.  These are loaded from CMAP files.

    A CMAP file is like a mini-codec.  It defines the correspondence
    between code points in the (multi-byte) input data and Character
    IDs. """
    # aims to do similar things to Brian Hooper's CMap class,
    # but I could not get it working and had to rewrite.
    # also, we should really rearrange our current encoding
    # into a SingleByteEncoding since many of its methods
    # should not apply here.

    def __init__(self, name, useCache=1):
        self.name = name
        self._mapFileHash = None
        self._codeSpaceRanges = []
        self._notDefRanges = []
        self._cmap = {}
        self.source = None
        if not DISABLE_CMAP:
            if useCache:
                from reportlab.lib.utils import get_rl_tempdir
                fontmapdir = get_rl_tempdir('FastCMAPS')
                if os.path.isfile(fontmapdir + os.sep + name + '.fastmap'):
                    self.fastLoad(fontmapdir)
                    self.source = fontmapdir + os.sep + name + '.fastmap'
                else:
                    self.parseCMAPFile(name)
                    self.source = 'CMAP: ' + name
                    self.fastSave(fontmapdir)
            else:
                self.parseCMAPFile(name)

    def _hash(self, text):
        hasher = md5()
        hasher.update(text)
        return hasher.digest()

    def parseCMAPFile(self, name):
        """This is a tricky one as CMAP files are Postscript
        ones.  Some refer to others with a 'usecmap'
        command"""
        #started = time.clock()
        cmapfile = findCMapFile(name)
        # this will CRAWL with the unicode encodings...
        rawdata = open(cmapfile, 'r').read()

        self._mapFileHash = self._hash(rawdata)
        #if it contains the token 'usecmap', parse the other
        #cmap file first....
        usecmap_pos = rawdata.find('usecmap')
        if  usecmap_pos > -1:
            #they tell us to look in another file
            #for the code space ranges. The one
            # to use will be the previous word.
            chunk = rawdata[0:usecmap_pos]
            words = chunk.split()
            otherCMAPName = words[-1]
            #print 'referred to another CMAP %s' % otherCMAPName
            self.parseCMAPFile(otherCMAPName)
            # now continue parsing this, as it may
            # override some settings


        words = rawdata.split()
        while words != []:
            if words[0] == 'begincodespacerange':
                words = words[1:]
                while words[0] != 'endcodespacerange':
                    strStart, strEnd, words = words[0], words[1], words[2:]
                    start = int(strStart[1:-1], 16)
                    end = int(strEnd[1:-1], 16)
                    self._codeSpaceRanges.append((start, end),)
            elif words[0] == 'beginnotdefrange':
                words = words[1:]
                while words[0] != 'endnotdefrange':
                    strStart, strEnd, strValue = words[0:3]
                    start = int(strStart[1:-1], 16)
                    end = int(strEnd[1:-1], 16)
                    value = int(strValue)
                    self._notDefRanges.append((start, end, value),)
                    words = words[3:]
            elif words[0] == 'begincidrange':
                words = words[1:]
                while words[0] != 'endcidrange':
                    strStart, strEnd, strValue = words[0:3]
                    start = int(strStart[1:-1], 16)
                    end = int(strEnd[1:-1], 16)
                    value = int(strValue)
                    # this means that 'start' corresponds to 'value',
                    # start+1 corresponds to value+1 and so on up
                    # to end
                    offset = 0
                    while start + offset <= end:
                        self._cmap[start + offset] = value + offset
                        offset = offset + 1
                    words = words[3:]

            else:
                words = words[1:]
        #finished = time.clock()
        #print 'parsed CMAP %s in %0.4f seconds' % (self.name, finished - started)

    def translate(self, text):
        "Convert a string into a list of CIDs"
        output = []
        cmap = self._cmap
        lastChar = ''
        for char in text:
            if lastChar != '':
                #print 'convert character pair "%s"' % (lastChar + char)
                num = ord(lastChar) * 256 + ord(char)
            else:
                #print 'convert character "%s"' % char
                num = ord(char)
            lastChar = char
            found = 0
            for low, high in self._codeSpaceRanges:
                if low < num < high:
                    try:
                        cid = cmap[num]
                        #print '%d -> %d' % (num, cid)
                    except KeyError:
                        #not defined.  Try to find the appropriate
                        # notdef character, or failing that return
                        # zero
                        cid = 0
                        for low2, high2, notdef in self._notDefRanges:
                            if low2 < num < high2:
                                cid = notdef
                                break
                    output.append(cid)
                    found = 1
                    break
            if found:
                lastChar = ''
            else:
                lastChar = char
        return output

    def fastSave(self, directory):
        f = open(os.path.join(directory, self.name + '.fastmap'), 'wb')
        marshal.dump(self._mapFileHash, f)
        marshal.dump(self._codeSpaceRanges, f)
        marshal.dump(self._notDefRanges, f)
        marshal.dump(self._cmap, f)
        f.close()

    def fastLoad(self, directory):
        started = time.clock()
        f = open(os.path.join(directory, self.name + '.fastmap'), 'rb')
        self._mapFileHash = marshal.load(f)
        self._codeSpaceRanges = marshal.load(f)
        self._notDefRanges = marshal.load(f)
        self._cmap = marshal.load(f)
        f.close()
        finished = time.clock()
        #print 'loaded %s in %0.4f seconds' % (self.name, finished - started)

    def getData(self):
        """Simple persistence helper.  Return a dict with all that matters."""
        return {
            'mapFileHash': self._mapFileHash,
            'codeSpaceRanges': self._codeSpaceRanges,
            'notDefRanges': self._notDefRanges,
            'cmap': self._cmap,
            }

class CIDTypeFace(pdfmetrics.TypeFace):
    """Multi-byte type face.

    Conceptually similar to a single byte typeface,
    but the glyphs are identified by a numeric Character
    ID (CID) and not a glyph name. """
    def __init__(self, name):
        """Initialised from one of the canned dictionaries in allowedEncodings

        Or rather, it will be shortly..."""
        pdfmetrics.TypeFace.__init__(self, name)
        self._extractDictInfo(name)
    def _extractDictInfo(self, name):
        try:
            fontDict = CIDFontInfo[name]
        except KeyError:
            raise KeyError("Unable to find information on CID typeface '%s'" % name +
                            "Only the following font names work:" + repr(allowedTypeFaces))
        descFont = fontDict['DescendantFonts'][0]
        self.ascent = descFont['FontDescriptor']['Ascent']
        self.descent = descFont['FontDescriptor']['Descent']
        self._defaultWidth = descFont['DW']
        self._explicitWidths = self._expandWidths(descFont['W'])

        # should really support self.glyphWidths, self.glyphNames
        # but not done yet.


    def _expandWidths(self, compactWidthArray):
        """Expands Adobe nested list structure to get a dictionary of widths.

        Here is an example of such a structure.::
        
            (
            # starting at character ID 1, next n  characters have the widths given.
            1,  (277,305,500,668,668,906,727,305,445,445,508,668,305,379,305,539),
            # all Characters from ID 17 to 26 are 668 em units wide
            17, 26, 668,
            27, (305, 305, 668, 668, 668, 566, 871, 727, 637, 652, 699, 574, 555,
                 676, 687, 242, 492, 664, 582, 789, 707, 734, 582, 734, 605, 605,
                 641, 668, 727, 945, 609, 609, 574, 445, 668, 445, 668, 668, 590,
                 555, 609, 547, 602, 574, 391, 609, 582, 234, 277, 539, 234, 895,
                 582, 605, 602, 602, 387, 508, 441, 582, 562, 781, 531, 570, 555,
                 449, 246, 449, 668),
            # these must be half width katakana and the like.
            231, 632, 500
            )