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

#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$

# See LICENSE.txt for licensing terms

'''
This module contains sphinx-specific node handlers.  An import
of this module will apparently fail if sphinx.roles hasn't been
imported.

This module creates a sphinx-specific dispatch dictionary,
which is kept separate from the regular one.

When the SphinxHandler class is instantiated, the two dictionaries
are combined into the instantiated object.
'''

from copy import copy

from log import nodeid
from flowables import  Spacer, MyIndenter, Reference

from opt_imports import Paragraph, sphinx

from nodehandlers import NodeHandler, FontHandler, HandleEmphasis
import math_flowable

################## NodeHandler subclasses ###################

class SphinxHandler(NodeHandler):
    sphinxmode = True
    dispatchdict = {}

    def __init__(self):
        ''' This is where the magic happens.  Make a copy of the elements
            in the non-sphinx dispatch dictionary, setting sphinxmode on
            every element, and then overwrite that dictionary with any
            sphinx-specific handlers.
        '''
        mydict = {}
        for key, value in self._baseclass.dispatchdict.iteritems():
            value = copy(value)
            value.sphinxmode = True
            mydict[key] = value
        mydict.update(self.dispatchdict)
        self.dispatchdict = mydict


class SphinxFont(SphinxHandler, FontHandler):
    pass

class HandleSphinxDefaults(SphinxHandler, sphinx.addnodes.glossary,
                                        sphinx.addnodes.start_of_file,
                                        sphinx.addnodes.compact_paragraph,
                                        sphinx.addnodes.pending_xref):
    pass

class SphinxListHandler(SphinxHandler):
    def get_text(self, client, node, replaceEnt):
        t = client.gather_pdftext(node)
        while t and t[0] in ', ':
            t=t[1:]
        return t

class HandleSphinxDescAddname(SphinxFont,  sphinx.addnodes.desc_addname):
    fontstyle = "descclassname"

class HandleSphinxDescName(SphinxFont, sphinx.addnodes.desc_name):
    fontstyle = "descname"

class HandleSphinxDescReturn(SphinxFont, sphinx.addnodes.desc_returns):
    def get_font_prefix(self, client, node, replaceEnt):
        return ' &rarr; ' + client.styleToFont("returns")

class HandleSphinxDescType(SphinxFont, sphinx.addnodes.desc_type):
    fontstyle = "desctype"

class HandleSphinxDescParamList(SphinxListHandler, sphinx.addnodes.desc_parameterlist):
    pre=' ('
    post=')'

class HandleSphinxDescParam(SphinxFont, sphinx.addnodes.desc_parameter):
    fontstyle = "descparameter"
    def get_pre_post(self, client, node, replaceEnt):
        pre, post = FontHandler.get_pre_post(self, client, node, replaceEnt)
        if node.hasattr('noemph'):
            pre = ', ' + pre
        else:
            pre = ', <i>' + pre
            post += '</i>'
        return pre, post

class HandleSphinxDescOpt(SphinxListHandler, SphinxFont, sphinx.addnodes.desc_optional):
    fontstyle = "optional"
    def get_pre_post(self, client, node, replaceEnt):
        prepost = FontHandler.get_pre_post(self, client, node, replaceEnt)
        return '%s[%s, ' % prepost, '%s]%s' % prepost

class HandleDescAnnotation(SphinxHandler, HandleEmphasis, sphinx.addnodes.desc_annotation):
    pass

class HandleSphinxIndex(SphinxHandler, sphinx.addnodes.index):
    def gather_elements(self, client, node, style):
        try:
            client.pending_targets.append(node['entries'][0][2])
        except IndexError:
            if node['entries']:
                log.error("Can't process index entry: %s [%s]",
                    node['entries'], nodeid(node))
        return []

class HandleSphinxModule(SphinxHandler, sphinx.addnodes.module):
    def gather_elements(self, client, node, style):
        return [Reference('module-'+node['modname'])]

# custom SPHINX nodes.
# FIXME: make sure they are all here, and keep them all together

class HandleSphinxCentered(SphinxHandler, sphinx.addnodes.centered):
    def gather_elements(self, client, node, style):
        return [Paragraph(client.gather_pdftext(node),
                client.styles['centered'])]

class HandleSphinxDesc(SphinxHandler, sphinx.addnodes.desc):
    def gather_elements(self, client, node, style):
        st=client.styles[node['desctype']]
        if st==client.styles['normal']:
            st=copy(client.styles['desc'])
            st.spaceBefore=0
        pre=[Spacer(0,client.styles['desc'].spaceBefore)]
        return pre + client.gather_elements(node, st)

class HandleSphinxDescSignature(SphinxHandler, sphinx.addnodes.desc_signature):
    def gather_elements(self, client, node, style):
        # Need to add ids as targets, found this when using one of the
        # django docs extensions
        targets=[i.replace(' ','') for i in node['ids']]
        pre=''
        for i in targets:
            if i not in client.targets:
                pre+='<a name="%s" />'% i
                client.targets.append(i)
        return [Paragraph(pre+client.gather_pdftext(node),style)]

class HandleSphinxDescContent(SphinxHandler, sphinx.addnodes.desc_content):
    def gather_elements(self, client, node, style):
        return [MyIndenter(left=10)] +\
                client.gather_elements(node, client.styles["definition"]) +\
                [MyIndenter(left=-10)]

from sphinx.ext import mathbase

class HandleSphinxMath(SphinxHandler, mathbase.math, mathbase.displaymath):
    def gather_elements(self, client, node, style):
        return [math_flowable.Math(node.get('latex',''))]

    def get_text(self, client, node, replaceEnt):
        mf = math_flowable.Math(node.get('latex',''))
        w, h = mf.wrap(0, 0)
        descent = mf.descent()
        img = mf.genImage()
        client.to_unlink.append(img)
        return '<img src="%s" width=%f height=%f valign=%f/>' % (
            img, w, h, -descent)

sphinxhandlers = SphinxHandler()

@@ -5632,16 +5632,39 @@
 tex','')
+,node.get('label',None)
 )%5D%0A%0A    
@@ -5988,16 +5988,248 @@
 scent)%0A%0A
+class HandleSphinxEq(SphinxHandler, mathbase.eqref):%0A%0A    def get_text(self, client, node, replaceEnt):%0A        return '%3Ca href=%22equation-%25s%22 color=%22%25s%22%3E%25s%3C/a%3E'%25(node%5B'target'%5D, %0A            client.styles.linkColor, node.astext())%0A%0A
 sphinxha

Make eq role work in sphinx