コード例 #1
0
    def loadTemplates(self, document):
        """Load templates as in PageTemplate but also look for packages that
    want to override some templates and handles extra css and javascript."""

        try:
            import jinja2
        except ImportError:
            log.error(
                'Jinja2 is not available, hence the HTML5 renderer cannot be used.'
            )

        _Renderer.loadTemplates(self, document)
        rendererdata = document.rendererdata["gerby"] = dict()
        config = document.config

        # split-level must always be -2 to not create any clutter files
        config["files"]["split-level"] = -2

        rendererDir = os.path.dirname(__file__)

        srcDir = document.userdata['working-dir']
        buildDir = os.getcwd()

        for resrc in document.packageResources:
            # Next line may load templates or change
            # document.rendererdata['html5'] or copy some files to buildDir
            resrc.alter(renderer=self,
                        rendererName='gerby',
                        document=document,
                        target=buildDir)
コード例 #2
0
ファイル: __init__.py プロジェクト: jbransen/problemtools
    def render(self, document):
        templatepaths = [os.path.join(os.path.dirname(__file__), '../templates/html'),
                         os.path.join(os.path.dirname(__file__), '../../templates/html'),
                         '/usr/lib/problemtools/templates/html']
        templatepath = None
        for p in templatepaths:
            if os.path.isdir(p):
                templatepath = p
                break
        if templatepath == None:
            raise Exception('Could not find templates needed for conversion to HTML')
        
        # Ugly but unfortunately PlasTeX is quite inflexible when it comes to
        # configuring where to search for template files
        os.environ['ProblemRendererTEMPLATES'] = templatepath

        # Gigantic ugliness to cope with PlasTeX problem that prevents
        # plastex from resetting list of invalid filenames when doing multiple renderings.
        f = Filenames('blah.html', {}, {}, 'html')
        f.invalid.clear()

        # Setup our own mini-imager which just does copying and converts pdfs to png
        self.imager = ImageConverter(document)
        
        Renderer.render(self, document)
コード例 #3
0
    def render(self, document):
        templatepaths = [
            os.path.join(os.path.dirname(__file__), '../templates/html'),
            os.path.join(os.path.dirname(__file__), '../../templates/html'),
            '/usr/lib/problemtools/templates/html'
        ]
        templatepath = None
        for p in templatepaths:
            if os.path.isdir(p):
                templatepath = p
                break
        if templatepath == None:
            raise Exception(
                'Could not find templates needed for conversion to HTML')

        # Ugly but unfortunately PlasTeX is quite inflexible when it comes to
        # configuring where to search for template files
        os.environ['ProblemRendererTEMPLATES'] = templatepath

        # Gigantic ugliness to cope with PlasTeX problem that prevents
        # plastex from resetting list of invalid filenames when doing multiple renderings.
        f = Filenames('blah.html', {}, {}, 'html')
        f.invalid.clear()

        # Setup our own mini-imager which just does copying and converts pdfs to png
        self.imager = ImageConverter(document)

        Renderer.render(self, document)
コード例 #4
0
 def cleanup(self, document, files, postProcess=None):
     res = _Renderer.cleanup(self, document, files, postProcess=postProcess)
     self.doJavaHelpFiles(document, version='1')
     self.doJavaHelpFiles(document, version='2')
     self.doEclipseHelpFiles(document)
     self.doCHMFiles(document)
     return res
コード例 #5
0
ファイル: __init__.py プロジェクト: khemanta/plastex-oreilly
 def cleanup(self, document, files, postProcess=None):
     res = _Renderer.cleanup(self, document, files, postProcess=postProcess)
     self.doJavaHelpFiles(document, version='1')
     self.doJavaHelpFiles(document, version='2')
     self.doEclipseHelpFiles(document)
     self.doCHMFiles(document)
     return res
コード例 #6
0
    def cleanup(self, document, files, postProcess=None):
        """
        Cleanup method called at the end of rendering.
        Uses the base renderer cleanup but calls packages callbacks before and
        after. Callbacks should be listed in
        document.userdata['preCleanupCallbacks']
        or document.userdata['postCleanupCallbacks']. Each call back should accept the
        current document as its only argument. Pre-cleanup call back must return
        the list of path of files they created (relative to the output directory).
        """

        rendererdata = document.rendererdata.get('html5', dict())
        preCleanupCallbacks = rendererdata.get('preCleanupCallbacks', [])
        for preCleanupCallback in preCleanupCallbacks:
            files += preCleanupCallback(document)

        _Renderer.cleanup(self, document, files, postProcess)
コード例 #7
0
ファイル: __init__.py プロジェクト: PatrickMassot/plastex
    def cleanup(self, document, files, postProcess=None):
        """
        Cleanup method called at the end of rendering.
        Uses the base renderer cleanup but calls packages callbacks before and
        after. Callbacks should be listed in
        document.userdata['preCleanupCallbacks']
        or document.userdata['postCleanupCallbacks']. Each call back should accept the
        current document as its only argument. Pre-cleanup call back must return
        the list of path of files they created (relative to the output directory).
        """

        rendererdata = document.rendererdata.get('html5', dict())
        preCleanupCallbacks = rendererdata.get('preCleanupCallbacks', [])
        for preCleanupCallback in preCleanupCallbacks:
            files += preCleanupCallback(document)

        _Renderer.cleanup(self, document, files, postProcess)
コード例 #8
0
  def processFileContent(self, document, s):
    s = _Renderer.processFileContent(self, document, s)

    # remove empty paragraphs
    s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

    # Remove extra paragraph tags around displaymath
    s = re.compile(r'<p>(<div class="equation">.*?<\/div>)<\/p>', flags=re.DOTALL).sub(r'\1',s)

    return s
コード例 #9
0
    def render(self, document):
        # create the tags and labels dictionaries in the document
        loadTags(document)

        copyBibliographies(document)

        # validity check
        checkLabels(document)

        # we decorate all DOM elements with labels that appear in the tags file
        decorateTags(document, document.userdata["labels"])

        # create a linearised version of the document containing theorems and proofs in order
        linearRepresentation(document)

        tagAttendanceSheet = tagRollCall(document)
        for tag in filter(lambda t: not tagAttendanceSheet[t],
                          tagAttendanceSheet):
            log.warning("document does not contain tag %s" % tag)

        # associate parts to chapters
        parts = partsList(document)
        with open("parts.json", "w") as f:
            json.dump(parts, f)

        _Renderer.render(self, document)

        # write footnotes if there are any
        if "footnotes" in document.userdata:
            mixin(Node, Gerby.renderableClass)
            Node.renderer = self
            for footnote in document.userdata["footnotes"]:
                with open("{0}.footnote".format(footnote.id), "w") as f:
                    f.write(str(footnote))
            del Node.renderer
            unmix(Node, Gerby.renderableClass)

        # write meta information, like line count.
        with open("meta.statistics", "w") as f:
            json.dump(document.context.meta, f)
コード例 #10
0
ファイル: __init__.py プロジェクト: Chuvi-w/lisiynos
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Force XHTML syntax on empty tags
        s = re.compile(r"(<(?:hr|br|img|link|meta)\b.*?)\s*/?\s*(>)", re.I | re.S).sub(r"\1 /\2", s)

        # Remove empty paragraphs
        s = re.compile(r"<p>\s*</p>", re.I).sub(r"", s)

        # Add a non-breaking space to empty table cells
        s = re.compile(r"(<(td|th)\b[^>]*>)\s*(</\2>)", re.I).sub(r"\1&nbsp;\3", s)

        return s
コード例 #11
0
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Force XHTML syntax on empty tags
        s = re.compile(r'(<(?:hr|br|img|link|meta|col)\b.*?)\s*/?\s*(>)',
                       re.I|re.S).sub(r'\1 /\2', s)

        # Remove empty paragraphs
        s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

        # Add a non-breaking space to empty table cells
        s = re.compile(r'(<(td|th)\b[^>]*>)\s*(</\2>)', re.I).sub(r'\1&nbsp;\3', s)

        return s
コード例 #12
0
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)
        s = s.strip()

        # Force XHTML syntax on empty tags
        s = re.sub(r'(<(?:hr|br|img|link|meta|col)\b.*?)\s*/?\s*(>)',
                   r'\1 /\2',
                   s,
                   re.I|re.S)

        # replace the document header: this is an awful workaround for
        # a problem with simpleTAL where is mangles the mathml part of
        # the header (but only on recent versions of Linux
        s = re.sub(r'put_mathml_stuff_here', with_mathml, s, count=1)

        # replace xml:id with id
        s = re.sub(r'xml:id', r'id', s)

        # replace the first chapter with a preface
        s = re.sub(r'<chapter', r'<preface', s, count=1)
        s = re.sub(r'</chapter>', r'</preface>', s, count=1)

        # no space before an indexterm
        s = re.sub(r' <indexterm', r'<indexterm', s)
        s = re.sub(r'indexterm> ', r'indexterm>', s)

        # remove newlines in programlistings
        s = re.sub(r'\s*(<programlisting>)\n', r'\1', s)
        s = re.sub(r'\n(</programlisting>)\s*', r'\1', s)

        # remove para around bookinfo
        s = re.sub(r'<para>\s*(<bookinfo>)', r'\1', s)
        s = re.sub(r'(</bookinfo>)\s*</para>', r'\1', s)

        # remove pointless anchors
        s = re.sub(r'\s*(<anchor[^>]*>)\s*', r'',s)

        # get rid of empty paragraphs
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)

        # get rid of empty partintro
        s = re.sub(r'\s*<partintro>\s*</partintro>\s*',  r'', s)

        # get rid of redundant references
        s = re.sub(r'\w*.<xref',  r'<xref', s)

        return s
コード例 #13
0
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        for fun in document.rendererdata["gerby"].get('processFileContents',
                                                      []):
            s = fun(document, s)

        # remove empty paragraphs
        s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

        # Remove extra paragraph tags around displaymath
        s = re.compile(r'<p>(<div class="equation".*?<\/div>)<\/p>',
                       flags=re.DOTALL).sub(r'\1', s)

        return s
コード例 #14
0
ファイル: __init__.py プロジェクト: khemanta/plastex-oreilly
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)
        s = s.strip()

        # Force XHTML syntax on empty tags
        s = re.sub(r'(<(?:hr|br|img|link|meta|col)\b.*?)\s*/?\s*(>)',
                   r'\1 /\2', s, re.I | re.S)

        # replace the document header: this is an awful workaround for
        # a problem with simpleTAL where is mangles the mathml part of
        # the header (but only on recent versions of Linux
        s = re.sub(r'put_mathml_stuff_here', with_mathml, s, count=1)

        # replace xml:id with id
        s = re.sub(r'xml:id', r'id', s)

        # replace the first chapter with a preface
        s = re.sub(r'<chapter', r'<preface', s, count=1)
        s = re.sub(r'</chapter>', r'</preface>', s, count=1)

        # no space before an indexterm
        s = re.sub(r' <indexterm', r'<indexterm', s)
        s = re.sub(r'indexterm> ', r'indexterm>', s)

        # remove newlines in programlistings
        s = re.sub(r'\s*(<programlisting>)\n', r'\1', s)
        s = re.sub(r'\n(</programlisting>)\s*', r'\1', s)

        # remove para around bookinfo
        s = re.sub(r'<para>\s*(<bookinfo>)', r'\1', s)
        s = re.sub(r'(</bookinfo>)\s*</para>', r'\1', s)

        # remove pointless anchors
        s = re.sub(r'\s*(<anchor[^>]*>)\s*', r'', s)

        # get rid of empty paragraphs
        s = re.sub(r'\s*<para>\s*</para>\s*', r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*', r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*', r'', s)

        # get rid of empty partintro
        s = re.sub(r'\s*<partintro>\s*</partintro>\s*', r'', s)

        # get rid of redundant references
        s = re.sub(r'\w*.<xref', r'<xref', s)

        return s
コード例 #15
0
ファイル: __init__.py プロジェクト: Chuvi-w/lisiynos
 def processFileContent(self, document, s):
     s = _Renderer.processFileContent(self, document, s)
     s = re.compile(r"</partintro>\s*<partintro>", re.I).sub(r"", s)
     #
     s = re.compile(r"<para>\s*(<articleinfo>)", re.I).sub(r"\1", s)
     s = re.compile(r"(</articleinfo>)\s*</para>", re.I).sub(r"\1", s)
     #
     s = re.compile(r"(<informalfigure>)\s*<para>", re.I).sub(r"\1", s)
     s = re.compile(r"</para>\s*(</informalfigure>)", re.I).sub(r"\1", s)
     #
     s = re.compile(r"(<para>)(\s*<para>)+", re.I).sub(r"\1", s)
     s = re.compile(r"(</para>\s*)+(</para>)", re.I).sub(r"\2", s)
     #
     #        s = s.replace('&','&amp;')
     #
     s = re.compile(r"<para>\s*</para>", re.I).sub(r"", s)
     return s
コード例 #16
0
ファイル: __init__.py プロジェクト: KatiaBorges/exeLearning
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)
        s = re.compile(r'</partintro>\s*<partintro>',re.I).sub(r'',s)
        #
        s = re.compile(r'<para>\s*(<articleinfo>)',re.I).sub(r'\1',s)
        s = re.compile(r'(</articleinfo>)\s*</para>',re.I).sub(r'\1',s)
        #
        s = re.compile(r'(<informalfigure>)\s*<para>',re.I).sub(r'\1',s)
        s = re.compile(r'</para>\s*(</informalfigure>)',re.I).sub(r'\1',s)
        #
        s = re.compile(r'(<para>)\s*<para>',re.I).sub(r'\1',s)
        s = re.compile(r'</para>\s*(</para>)',re.I).sub(r'\1',s)
        #
#        s = s.replace('&','&amp;')
        #
        s = re.compile(r'<para>\s*</para>', re.I).sub(r'', s)
        return s
コード例 #17
0
ファイル: __init__.py プロジェクト: go38/exeLearning
 def processFileContent(self, document, s):
     s = _Renderer.processFileContent(self, document, s)
     s = re.compile(r'</partintro>\s*<partintro>', re.I).sub(r'', s)
     #
     s = re.compile(r'<para>\s*(<articleinfo>)', re.I).sub(r'\1', s)
     s = re.compile(r'(</articleinfo>)\s*</para>', re.I).sub(r'\1', s)
     #
     s = re.compile(r'(<informalfigure>)\s*<para>', re.I).sub(r'\1', s)
     s = re.compile(r'</para>\s*(</informalfigure>)', re.I).sub(r'\1', s)
     #
     s = re.compile(r'(<para>)\s*<para>', re.I).sub(r'\1', s)
     s = re.compile(r'</para>\s*(</para>)', re.I).sub(r'\1', s)
     #
     #        s = s.replace('&','&amp;')
     #
     s = re.compile(r'<para>\s*</para>', re.I).sub(r'', s)
     return s
コード例 #18
0
ファイル: __init__.py プロジェクト: shanhaiying/plastex
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)
        if have_lxml:
            tree = etree.fromstring(s)
            for name in ['itemizedlist', 'table', 'term', 'para']:
                tree = clean_para(tree, name)
            s = etree.tostring(tree)
        else:
            s = re.sub(r'</partintro>\s*<partintro>', '', s, flags=re.I)
            s = re.sub(r'<para>\s*(<articleinfo>)', r'\1', s, flags=re.I)
            s = re.sub(r'(</articleinfo>)\s*</para>', r'\1', s, flags=re.I)
            s = re.sub(r'<para>\s*</para>', '', s, flags=re.I)

            for name in ['itemizedlist', 'term', 'para']:
                s = re.sub(r'(<%s>)\s*<para>' % name, r'\1', s, flags=re.I)
                s = re.sub(r'</para>\s*(</%s>)' % name, r'\1', s, flags=re.I)

        return s
コード例 #19
0
ファイル: __init__.py プロジェクト: EHCliffe/plastex
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)
        if have_lxml:
            tree = etree.fromstring(s)
            for name in ['itemizedlist', 'table', 'term', 'para']:
                tree = clean_para(tree, name)
            s = etree.tostring(tree)
        else:
            s = re.sub(r'</partintro>\s*<partintro>','', s, flags=re.I)
            s = re.sub(r'<para>\s*(<articleinfo>)', r'\1', s, flags=re.I)
            s = re.sub(r'(</articleinfo>)\s*</para>', r'\1', s, flags=re.I)
            s = re.sub(r'<para>\s*</para>', '', s, flags=re.I)

            for name in ['itemizedlist', 'term', 'para']:
                s = re.sub(r'(<%s>)\s*<para>' % name, r'\1', s, flags=re.I)
                s = re.sub(r'</para>\s*(</%s>)' % name, r'\1', s, flags=re.I)

        return s
コード例 #20
0
ファイル: __init__.py プロジェクト: marcio-curl/EPUB-plasTeX
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Fecha as tags solitárias como em <br />
        s = re.compile(r'(<(?:hr|br|img|link|meta)\b.*?)\s*/?\s*(>)', 
                       re.I|re.S).sub(r'\1 /\2', s)

        # Remove os parágrafos vazios
        s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

        # Espaço nas células vazias das tabelas
        s = re.compile(r'(<(td|th)\b[^>]*>)\s*(</\2>)', re.I).sub(r'\1&nbsp;\3', s)

        # Sem ":" nos ids e nos links
#        s = re.compile(r'id="(.*?):(.*?)"', re.I).sub(r'id="\1\2"', s)
        s = re.compile(r'<(\w+) id="(.*?):(.*?)"(.*?)>', re.I | re.U).sub(r'<\1 id="\2\3"\4>', s)
        s = re.compile(r'<a href="((?:http://)?.*?)#(.*?):(.*?)"(.*?)>', re.I | re.U).sub(r'<a href="\1#\2\3"\4>', s)

        return s
コード例 #21
0
ファイル: __init__.py プロジェクト: PatrickMassot/plastex
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Remove empty paragraphs
        s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

        # Add a non-breaking space to empty table cells
        s = re.compile(r'(<(td|th)\b[^>]*>)\s*(</\2>)', re.I).sub(r'\1&nbsp;\3', s)

        for fun in document.rendererdata['html5'].get('processFileContents', []):
            s = fun(document, s)

        filters = document.config['html5']['filters']
        for filter_ in filters:
            proc = subprocess.Popen(
                    shlex.split(filter_),
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE)
            output, output_err = proc.communicate(s.encode(encoding="utf-8"))
            if not output_err:
                s = output.decode(encoding="utf-8")

        return s
コード例 #22
0
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Remove empty paragraphs
        s = re.compile(r'<p>\s*</p>', re.I).sub(r'', s)

        # Add a non-breaking space to empty table cells
        s = re.compile(r'(<(td|th)\b[^>]*>)\s*(</\2>)', re.I).sub(r'\1&nbsp;\3', s)

        for fun in document.rendererdata['html5'].get('processFileContents', []):
            s = fun(document, s)

        filters = document.config['html5']['filters']
        for filter_ in filters:
            proc = subprocess.Popen(
                    shlex.split(filter_),
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE)
            output, output_err = proc.communicate(s.encode(encoding="utf-8"))
            if not output_err:
                s = output.decode(encoding="utf-8")

        return s
コード例 #23
0
ファイル: __init__.py プロジェクト: dvbrydon/plastex-oreilly
    def processFileContent(self, document, s):
        s = _Renderer.processFileContent(self, document, s)

        # Force XHTML syntax on empty tags
        s = re.sub(r'(<(?:hr|br|img|link|meta|col)\b.*?)\s*/?\s*(>)',
                   r'\1 /\2',
                   s,
                   re.I|re.S)

        s = re.sub(r'xml:id', r'id',s)

        # replace the first chapter with a preface
        s = re.sub(r'<chapter', r'<preface', s, count=1)
        s = re.sub(r'</chapter>', r'</preface>', s, count=1)

        # no space before an indexterm
        s = re.sub(r' <indexterm', r'<indexterm', s)
        s = re.sub(r'indexterm> ', r'indexterm>', s)

        # remove newlines in programlistings
        s = re.sub(r'\s*(<programlisting>)\n', r'\1', s)
        s = re.sub(r'\n(</programlisting>)\s*', r'\1', s)

        # remove para around bookinfo
        s = re.sub(r'<para>\s*(<bookinfo>)', r'\1', s)
        s = re.sub(r'(</bookinfo>)\s*</para>', r'\1', s)

        # remove pointless anchors
        s = re.sub(r'\s*(<anchor[^>]*>)\s*', r'',s)

        # get rid of empty paragraphs
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)
        s = re.sub(r'\s*<para>\s*</para>\s*',  r'', s)

        return s
コード例 #24
0
ファイル: __init__.py プロジェクト: KatiaBorges/exeLearning
 def cleanup(self, document, files, postProcess=None):
     res = _Renderer.cleanup(self, document, files, postProcess=postProcess)
     return res
コード例 #25
0
ファイル: __init__.py プロジェクト: PatrickMassot/plastex
    def loadTemplates(self, document):
        """Load templates as in PageTemplate but also look for packages that
        want to override some templates and handles extra css and javascript."""

        try:
            import jinja2
        except ImportError:
            log.error('Jinja2 is not available, hence the HTML5 renderer cannot be used.')

        _Renderer.loadTemplates(self, document)
        rendererdata = document.rendererdata['html5'] = dict()
        config = document.config

        rendererDir = os.path.dirname(__file__)
        themeDir = os.path.join(rendererDir, 'Theme', self.loadedTheme)

        srcDir = document.userdata['working-dir']
        buildDir = os.getcwd()

        # Theme css has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create styles directory is case it's false
        try:
            os.mkdir('styles')
        except OSError:
            # This should mean the directory already exists
            pass

        # Start building the css list for use by the layout template
        if config['html5']['use-theme-css'] and config['general']['copy-theme-extras']:
            rendererdata['css'] = ['theme-' + config['html5']['theme-css'] + '.css']
        else:
            rendererdata['css'] = []

        # Theme js has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create js directory is case it's false
        try:
            os.mkdir('js')
        except OSError:
            pass

        # Start building the js list for use by the layout template
        if (config['html5']['use-theme-js'] and 
                config['general']['copy-theme-extras']):
            rendererdata['js'] = sorted(
                    os.listdir(os.path.join(themeDir, 'js')))
        else:
            rendererdata['js'] = []

        for resrc in document.packageResources:
            # Next line may load templates or change
            # document.rendererdata['html5'] or copy some files to buildDir
            resrc.alter(
                    renderer=self,
                    rendererName='html5',
                    document=document,
                    target=buildDir)

        # Last loaded files (hence overriding everything else) come from user
        # configuration
        cssBuildDir = os.path.join(buildDir, 'styles')
        for css in config['html5']['extra-css']:
            rendererdata['css'].append(css)
            shutil.copy(os.path.join(srcDir, css), cssBuildDir)

        jsBuildDir = os.path.join(buildDir, 'js')
        for js in config['html5']['extra-js']:
            rendererdata['js'].append(js)
            shutil.copy(os.path.join(srcDir, js), jsBuildDir)
コード例 #26
0
 def cleanup(self, document, files, postProcess=None):
     res = _Renderer.cleanup(self, document, files, postProcess=postProcess)
     return res
コード例 #27
0
 def processFileContent(self, document, s):
     s = _Renderer.processFileContent(self, document, s)
     return s
コード例 #28
0
ファイル: __init__.py プロジェクト: marcio-curl/EPUB-plasTeX
    def cleanup(self, document, files, postProcess=None):        
        res = _Renderer.cleanup(self, document, files, postProcess=postProcess)

        # Define uma lista de arquivos que devem ficar fora de OEBPS/,
        # e move os outros arquivos / diretórios, apagando os diretórios
        # pré-existentes em OEBPS/
        dirNaoMover = ['mimetype', 'OEBPS', 'META-INF', 'Makefile']
        moverDirs = list(set(os.listdir('.')) - set(dirNaoMover))
        for arq in moverDirs:
            if os.path.isdir('OEBPS/%s' % arq):
                shutil.rmtree('OEBPS/%s' % arq)
            shutil.move(arq, 'OEBPS/%s' % arq)

        # Move os arquivos de conteúdo para OEBPS/
#        for arq in files:
#            os.rename(arq, 'OEBPS/' + arq)

        # Mover todos os arquivos e diretórios que não sejam o META-INF/, OEBPS/ e mimetype

        latexdoc = document.getElementsByTagName('document')[0]

        # Cria uma entrada para o bookid com um UUID aleatório.
        latexdoc.setUserData('bookid', 'urn:uuid:%s' % uuid.uuid4())

        # Adiciona o mimetype do arquivo ncx
        if not mimetypes.types_map.has_key('.ncx'):
            mimetypes.add_type('application/x-dtbncx+xml', '.ncx')

        # Mimetypes dos arquivos .html, .svg e .otf
        mimetypes.add_type('application/xhtml+xml', '.html')
        mimetypes.add_type('image/svg+xml', '.svg')
        mimetypes.add_type('application/vnd.ms-opentype', '.otf')

        # Gera o arquivo ncx
        self.doNCXFiles(latexdoc)

        listaArquivos = dict() # Lista dos arquivos no manifest
        spine = [] # Lista de ids no spine (poderiamos trocar por uma função que verifica quais tipos de seção geram arquivos e incluir no userdata deles).
        for root, dirs, arquivos in os.walk('OEBPS/'):
            for nomeArquivo in arquivos:
                if (nomeArquivo == 'content.opf'):
                    continue

                if re.match('.*~$', nomeArquivo):
                    continue

                href = os.path.join(re.sub('OEBPS/?', '', root), nomeArquivo)
                # As / são substituídas por - no id
                itemid = re.sub('[/.]', '-', href)
                mediaType = mimetypes.guess_type(nomeArquivo)[0]

                # Os arquivos html são incluídos no spine
                if re.match('.*\.html', nomeArquivo):
                    spine.append(itemid)

                listaArquivos[itemid] = {'href': href, 'mediaType': mediaType}
            
        latexdoc.setUserData('listaArqs', listaArquivos)
        # A lista de ids será ordenada para a geração do content.opf
        latexdoc.setUserData('spine', sorted(spine))

        # Chamadas para geração do arquivo opf
        self.doOPFFiles(latexdoc)
        return res
コード例 #29
0
 def __init__(self, *args, **kwargs):
     _Renderer.__init__(self, *args, **kwargs)
     self.registerEngine('xml', None, '.xml', xmltemplate)
コード例 #30
0
ファイル: __init__.py プロジェクト: ugoertz/plastex
    def loadTemplates(self, document):
        """Load templates as in PageTemplate but also look for packages that
        want to override some templates and handles extra css and javascript."""

        _Renderer.loadTemplates(self, document)
        rendererdata = document.rendererdata.setdefault('html5', dict())
        config = document.config
        if 'html5' not in config:
            addConfig(config)

        srcDir = document.userdata.get('working-dir', '.')  # type: str
        buildDir = os.getcwd()

        # Theme css has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create styles directory is case it's false
        try:
            os.mkdir('styles')
        except OSError:
            # This should mean the directory already exists
            pass

        # Start building the css list for use by the layout template
        if config['html5']['use-theme-css'] and config['general'][
                'copy-theme-extras']:
            rendererdata['css'] = [
                'theme-' + config['html5']['theme-css'] + '.css'
            ]
        else:
            rendererdata['css'] = []

        # Theme js has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create js directory is case it's false
        try:
            os.mkdir('js')
        except OSError:
            pass

        # Start building the js list for use by the layout template
        if self.loadedTheme:
            theme_js_path = Path(self.loadedTheme) / 'js'
            if (config['html5']['use-theme-js']
                    and config['general']['copy-theme-extras']
                    and theme_js_path.exists()):
                rendererdata['js'] = sorted(
                    path.name for path in theme_js_path.glob('*.js'))
            else:
                rendererdata['js'] = []

        for resrc in document.packageResources:
            # Next line may load templates or change
            # document.rendererdata['html5'] or copy some files to buildDir
            resrc.alter(renderer=self,
                        rendererName='html5',
                        document=document,
                        target=Path(buildDir))

        # Last loaded files (hence overriding everything else) come from user
        # configuration
        cssBuildDir = os.path.join(buildDir, 'styles')
        for css in config['html5']['extra-css']:
            rendererdata['css'].append(css)
            shutil.copy(os.path.join(srcDir, css), cssBuildDir)

        jsBuildDir = os.path.join(buildDir, 'js')
        for js in config['html5']['extra-js']:
            rendererdata['js'].append(js)
            shutil.copy(os.path.join(srcDir, js), jsBuildDir)
コード例 #31
0
def test_rendererDir():
    assert rendererDir(Renderer()) == os.path.split(
        inspect.getfile(Renderer))[0]
コード例 #32
0
    def cleanup(self, document, files, postProcess=None):
        res = _Renderer.cleanup(self, document, files, postProcess=postProcess)

        # TODO: Convert this to named registered utilities or adapters
        self.doEclipseHelpFiles(document)
        return res
コード例 #33
0
    def loadTemplates(self, document):
        """Load templates as in PageTemplate but also look for packages that
        want to override some templates and handles extra css and javascript."""

        try:
            import jinja2
        except ImportError:
            log.error(
                'Jinja2 is not available, hence the HTML5 renderer cannot be used.'
            )

        _Renderer.loadTemplates(self, document)
        rendererdata = document.rendererdata['html5'] = dict()
        config = document.config

        rendererDir = os.path.dirname(__file__)

        srcDir = document.userdata['working-dir']
        buildDir = os.getcwd()

        # Theme css has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create styles directory is case it's false
        try:
            os.mkdir('styles')
        except OSError:
            # This should mean the directory already exists
            pass

        # Start building the css list for use by the layout template
        if config['html5']['use-theme-css'] and config['general'][
                'copy-theme-extras']:
            rendererdata['css'] = [
                'theme-' + config['html5']['theme-css'] + '.css'
            ]
        else:
            rendererdata['css'] = []

        # Theme js has already been copied by PageTemplate.loadTemplates,
        # provided config['general']['copy-theme-extras'] is true
        # Still try to create js directory is case it's false
        try:
            os.mkdir('js')
        except OSError:
            pass

        # Start building the js list for use by the layout template
        if (config['html5']['use-theme-js']
                and config['general']['copy-theme-extras']):
            rendererdata['js'] = sorted(
                os.listdir(os.path.join(self.loadedTheme, 'js')))
        else:
            rendererdata['js'] = []

        for resrc in document.packageResources:
            # Next line may load templates or change
            # document.rendererdata['html5'] or copy some files to buildDir
            resrc.alter(renderer=self,
                        rendererName='html5',
                        document=document,
                        target=buildDir)

        # Last loaded files (hence overriding everything else) come from user
        # configuration
        cssBuildDir = os.path.join(buildDir, 'styles')
        for css in config['html5']['extra-css']:
            rendererdata['css'].append(css)
            shutil.copy(os.path.join(srcDir, css), cssBuildDir)

        jsBuildDir = os.path.join(buildDir, 'js')
        for js in config['html5']['extra-js']:
            rendererdata['js'].append(js)
            shutil.copy(os.path.join(srcDir, js), jsBuildDir)
コード例 #34
0
def test_rendererDir():
    base = os.path.split(os.path.split(__file__)[0])[0]
    path = os.path.join(base, 'plasTeX', 'Renderers', 'PageTemplate')
    assert rendererDir(Renderer()) == path
コード例 #35
0
 def alterRenderer(self, renderer: Renderer) -> None:
     renderer.importDirectory(str(self.path))