Exemplo n.º 1
0
 def add_footer(self):
     self.elements.content.append(
         E.footer(
             E.a(self.T('Wuff Signal'),
                 href=self.handler.reverse_url('textshow.index')),
             ' ',
             E.a(self.T('About'),
                 href=self.handler.reverse_url('textshow.about'))
         )
     )
Exemplo n.º 2
0
Arquivo: html.py Projeto: chfoo/wuff
 def _build_html_footer(self):
     '''Adds the site visual footer links'''
     self.elements.footer.extend([
         E.nav(
             E.a(self.handler.application.settings['application_name'],
                 href=self.handler.reverse_url('index')),
             ' ',
             E.a(self.T('About'),
                 href=self.handler.reverse_url('index.about'))
         )
     ])
Exemplo n.º 3
0
    def replace_youtube_videos_with_links(self, doc):
        """Replace any iframe elements found with a link to the src and a
        placeholder image from youtube"""

        def get_yt_id(src):
            """Return the youtube video id"""
            split_src = src.split("/")
            if "embed" in split_src:
                yt_id_index = split_src.index("embed") + 1
                return split_src[yt_id_index]

        iframes = doc.xpath("//iframe")

        for iframe in iframes:
            src = iframe.get("src")
            yt_id = get_yt_id(src)
            if not yt_id:
                continue
            else:
                yt_img = "https://img.youtube.com/vi/{0}/0.jpg".format(yt_id)
                yt_href = "https://youtu.be/{0}".format(yt_id)
                yt_link = E.a(
                    E.img(
                        src=yt_img,
                        width="480",
                        height="360",
                    ),
                    href=yt_href,
                    target="_blank",
                )
                parent = iframe.getparent()
                parent.replace(iframe, yt_link)
Exemplo n.º 4
0
    def build_title_content(self):
        content = E.table(
            E.tr(
                E.th(self.T('Time')),
                E.th(self.T('Message')),
                E.th(self.T('Count'))
            )
        )

        for message in self._messages:
            message_dict = dict(message.data_iter)

            row = E.tr(
                E.td(self.handler.locale.format_date(message.datetime),
                    rowspan=str(len(message_dict)))
            )

            for key, count in sorted(message_dict.items()):
                row.extend([E.td(to_hex(key)), E.td(str(count))])
                content.append(row)
                row = E.tr()

        self.elements.content.append(content)

        if self._pager_next:
            self.elements.content.append(
                E.a(self.T('Older'), href='?before=' + str(self._pager_next))
            )

        self.add_footer()
Exemplo n.º 5
0
    def replace_youtube_videos_with_links(self, doc):
        """Replace any iframe elements found with a link to the src and a
        placeholder image from youtube"""
        def get_yt_id(src):
            """Return the youtube video id"""
            split_src = src.split("/")
            if "embed" in split_src:
                yt_id_index = split_src.index("embed") + 1
                return split_src[yt_id_index]

        iframes = doc.xpath("//iframe")

        for iframe in iframes:
            src = iframe.get("src")
            yt_id = get_yt_id(src)
            if not yt_id:
                continue
            else:
                yt_img = "https://img.youtube.com/vi/{0}/0.jpg".format(yt_id)
                yt_href = "https://youtu.be/{0}".format(yt_id)
                yt_link = E.a(
                    E.img(
                        src=yt_img,
                        width="480",
                        height="360",
                    ),
                    href=yt_href,
                    target="_blank",
                )
                parent = iframe.getparent()
                parent.replace(iframe, yt_link)
Exemplo n.º 6
0
Arquivo: _base.py Projeto: pxiol/spyne
    def anyuri_to_parent(self, ctx, cls, inst, parent, name, **kwargs):
        assert name is not None
        href = getattr(inst, 'href', None)
        if href is None:  # this is not a AnyUri.Value instance.
            href = inst
            text = getattr(cls.Attributes, 'text', name)
            content = None

        else:
            text = getattr(inst, 'text', None)
            if text is None:
                text = getattr(cls.Attributes, 'text', name)
            content = getattr(inst, 'content', None)

        if text is None:
            text = name

        retval = E.a(text)

        if href is not None:
            retval.attrib['href'] = href

        if content is not None:
            retval.append(content)

        parent.write(retval)
Exemplo n.º 7
0
def _subvalue_to_html(cls, value):
    if issubclass(cls.type, AnyUri):
        href = getattr(value, 'href', None)
        if href is None:  # this is not a AnyUri.Value instance.
            href = value
            text = getattr(cls.type.Attributes, 'text', None)
            content = None

        else:
            text = getattr(value, 'text', None)
            if text is None:
                text = getattr(cls.type.Attributes, 'text', None)

            content = getattr(value, 'content', None)

        if issubclass(cls.type, ImageUri):
            retval = E.img(src=href)

            if text is not None:
                retval.attrib['alt'] = text
            # content is ignored with ImageUri.

        else:
            retval = E.a(href=href)
            retval.text = text
            if content is not None:
                retval.append(content)

    else:
        retval = cls.type.to_string(value)

    return retval
Exemplo n.º 8
0
    def anyuri_to_parent(self, ctx, cls, inst, parent, name, **kwargs):
        assert name is not None
        href = getattr(inst, 'href', None)
        if href is None: # this is not a AnyUri.Value instance.
            href = inst
            text = getattr(cls.Attributes, 'text', name)
            content = None

        else:
            text = getattr(inst, 'text', None)
            if text is None:
                text = getattr(cls.Attributes, 'text', name)
            content = getattr(inst, 'content', None)

        if text is None:
            text = name

        retval = E.a(text)

        if href is not None:
            retval.attrib['href'] = href

        if content is not None:
            retval.append(content)

        parent.write(retval)
Exemplo n.º 9
0
    def gen_anchor(self, cls, inst, name, anchor_class=None):
        assert name is not None
        cls_attrs = self.get_cls_attrs(cls)

        href = getattr(inst, 'href', None)
        if href is None:  # this is not a AnyUri.Value instance.
            href = inst

            content = None
            text = cls_attrs.text

        else:
            content = getattr(inst, 'content', None)
            text = getattr(inst, 'text', None)
            if text is None:
                text = cls_attrs.text

        if anchor_class is None:
            anchor_class = cls_attrs.anchor_class

        if text is None:
            text = name

        retval = E.a(text)

        if href is not None:
            retval.attrib['href'] = href

        if anchor_class is not None:
            retval.attrib['class'] = anchor_class

        if content is not None:
            retval.append(content)

        return retval
Exemplo n.º 10
0
def _subvalue_to_html(cls, value):
    if issubclass(cls.type, AnyUri):
        href = getattr(value, 'href', None)
        if href is None: # this is not a AnyUri.Value instance.
            href = value
            text = getattr(cls.type.Attributes, 'text', None)
            content = None

        else:
            text = getattr(value, 'text', None)
            if text is None:
                text = getattr(cls.type.Attributes, 'text', None)

            content = getattr(value, 'content', None)

        if issubclass(cls.type, ImageUri):
            retval = E.img(src=href)

            if text is not None:
                retval.attrib['alt'] = text
            # content is ignored with ImageUri.

        else:
            retval = E.a(href=href)
            retval.text = text
            if content is not None:
                retval.append(content)

    else:
        retval = cls.type.to_string(value)

    return retval
Exemplo n.º 11
0
Arquivo: _base.py Projeto: plq/spyne
    def gen_anchor(self, cls, inst, name, anchor_class=None):
        assert name is not None
        cls_attrs = self.get_cls_attrs(cls)

        href = getattr(inst, 'href', None)
        if href is None: # this is not a AnyUri.Value instance.
            href = inst

            content = None
            text = cls_attrs.text

        else:
            content = getattr(inst, 'content', None)
            text = getattr(inst, 'text', None)
            if text is None:
                text = cls_attrs.text

        if anchor_class is None:
            anchor_class = cls_attrs.anchor_class

        if text is None:
            text = name

        retval = E.a(text)

        if href is not None:
            retval.attrib['href'] = href

        if anchor_class is not None:
            retval.attrib['class'] = anchor_class

        if content is not None:
            retval.append(content)

        return retval
Exemplo n.º 12
0
            def to_parent(self, ctx, cls, inst, parent, name, **kwargs):
                s = self.to_unicode(cls._type_info['query'], inst.query)
                q = urlencode({"q": s})

                parent.write(
                    E.a("Search %s" % inst.query,
                        href="{}?{}".format(inst.uri, q)))
Exemplo n.º 13
0
Arquivo: html.py Projeto: chfoo/wuff
    def _build_html_header(self):
        '''Add banner and account links'''
        header = self.elements.header
        index_url = self.links.get(
            'index', self.handler.reverse_url('index'))

        header.append(E.div(
            E.a(self.meta.app_name, href=index_url, id='logo-link'),
            id='logo-wrapper'
        ))
Exemplo n.º 14
0
    def build_title_content(self):
        self.elements.content.extend([
            E.p('''Wuff Signal allows you to share messages without revealing
            the contents of your message. It lossily scrambles your message
            and shows them as points on the page. These points are called
            Signals.
            '''),
            E.p('You can view a ', E.a('complete list of recent Signals',
                href=self.handler.reverse_url('textshow.recent')), '.'),
        ])

        self.add_footer()
Exemplo n.º 15
0
    def _gen_row(self,
                 ctx,
                 cls,
                 inst,
                 parent,
                 name,
                 from_arr=False,
                 array_index=None,
                 **kwargs):

        # because HtmlForm* protocols don't use the global null handler, it's
        # possible for null values to reach here.
        if inst is None:
            return

        print("Generate row for", cls)

        with parent.element('tr'):
            for k, v in cls.get_flat_type_info(cls).items():
                attr = get_cls_attrs(self, v)
                if attr.exc:
                    print("\tExclude table cell %r type %r" % (k, v), "for",
                          cls)
                    continue
                if not attr.get('read', True):
                    continue

                print("\tGenerate table cell %r type %r" % (k, v), "for", cls)

                try:
                    sub_value = getattr(inst, k, None)
                except:  # e.g. SQLAlchemy could throw NoSuchColumnError
                    sub_value = None

                sub_name = attr.sub_name
                if sub_name is None:
                    sub_name = k
                if self.hier_delim is not None:
                    if array_index is None:
                        sub_name = "%s%s%s" % (name, self.hier_delim, sub_name)
                    else:
                        sub_name = "%s[%d]%s%s" % (name, array_index,
                                                   self.hier_delim, sub_name)

                td_attrs = {}
                if self.field_name_attr is not None:
                    td_attrs[self.field_name_attr] = attr.sub_name or k

                with parent.element('td', td_attrs):
                    if attr.href is not None:
                        try:
                            attrib = {'href': attr.href % sub_value}
                        except:
                            attrib = {'href': attr.href}

                        with parent.element('a', attrib=attrib):
                            ret = self.to_parent(ctx,
                                                 v,
                                                 sub_value,
                                                 parent,
                                                 sub_name,
                                                 from_arr=from_arr,
                                                 array_index=array_index,
                                                 **kwargs)
                    else:
                        ret = self.to_parent(ctx,
                                             v,
                                             sub_value,
                                             parent,
                                             sub_name,
                                             from_arr=from_arr,
                                             array_index=array_index,
                                             **kwargs)

                    if isgenerator(ret):
                        try:
                            while True:
                                sv2 = (yield)
                                ret.send(sv2)
                        except Break as b:
                            try:
                                ret.throw(b)
                            except StopIteration:
                                pass

            m = cls.Attributes.methods
            if m is not None and len(m) > 0:
                with parent.element('td'):
                    first = True
                    mrpc_delim = html.fromstring(" | ").text

                    for mn, md in self._methods(cls, inst):
                        if first:
                            first = False
                        else:
                            parent.write(mrpc_delim)

                        pd = {}
                        for k, v in cls.get_flat_type_info(cls).items():
                            if getattr(v.Attributes, 'primary_key', None):
                                r = self.to_unicode(v, getattr(inst, k, None))
                                if r is not None:
                                    pd[k] = r

                        params = urlencode(pd)

                        mdid2key = ctx.app.interface.method_descriptor_id_to_key
                        href = mdid2key[id(md)].rsplit("}", 1)[-1]
                        text = md.translate(ctx.locale,
                                            md.in_message.get_type_name())
                        parent.write(E.a(text, href="%s?%s" % (href, params)))

            print("Generate row for %r done." % cls)
            self.extend_data_row(ctx,
                                 cls,
                                 inst,
                                 parent,
                                 name,
                                 array_index=array_index,
                                 **kwargs)
Exemplo n.º 16
0
Arquivo: index.py Projeto: chfoo/wuff
 def build_content(self):
     self.elements.content.append(
         E.a('Wuff Signal',
             href=self.handler.reverse_url('textshow.index')))
Exemplo n.º 17
0
def main():
    # TODO: combine command-line and option file.
    # TODO: option to generate a default configuration file
    parser = argparse.ArgumentParser()  # TODO: doc
    parser.add_argument("-s", "--standalone", action="store_true")  # TODO: doc
    args = parser.parse_args()
    standalone = args.standalone

    conf = json.load((DATA / "artdoc.js").open())

    if Path("artdoc.js").exists():
        user_conf = json.load(Path("artdoc.js").open())
        conf.update(user_conf)

    info("Document:")
    doc_patterns = conf["doc"]
    if isinstance(doc_patterns, basestring):
        doc_patterns = [doc_patterns]
    docs = []
    for pattern in doc_patterns:
        matches = list(WORKDIR.glob(pattern))
        #subinfo("matching {!r}:".format(pattern))
        for match in matches:
            subinfo(str(match))
        docs.extend(matches)
    if not docs:
        sys.exit("error: no document found")

#    info("HTML template:")
#    template_file = HTML / "index.html"
#    subinfo(str(template_file))
#    template = template_file.open().read().encode("utf-8")

    info("Bibliography:")
    bib_patterns = conf["bib"]
    if isinstance(bib_patterns, basestring):
        bib_patterns = [bib_patterns]
    bibs = []
    for pattern in bib_patterns:
        matches = list(WORKDIR.glob(pattern))
        #subinfo("matching {!r}:".format(pattern))
        for match in matches:
            subinfo(str(match))
        bibs.extend(matches)
    if not bibs:
        print()

    info("JS:")
    cmd = coffee["-c", str(JS / "main.coffee")]
    subinfo(cmd)
    cmd()

    info("CSS:")
    cmd = stylus[str(CSS / "style.styl")]
    subinfo(str(cmd))
    cmd()

    # TODO: copy only what is required.
    shutil.copytree(str(DATA), str(ARTDOC))

    for doc in docs:
        pass

        info("PANDOC: generate JSON file")
        args = ["-t", "json", "--smart"]
        for bib in bibs:
            args.extend(["--bibliography", str(bib)])
        args.append(str(doc))
        cmd = pandoc[args]
        subinfo(cmd, "> json")
        json_str = cmd()

        info("Convert raw TeX to raw HTML")
        cmd = local[str(BIN / "rawHTML.hs")]
        subinfo(cmd, "< json > json")
        json_str = (cmd << json_str)()

        #        info("Flag/Box Proofs")
        #        cmd = local[str(BIN / "proof.hs")]
        #        subinfo(cmd, "< json > json")
        #        try:
        #            json_str = (cmd << json_str)()
        #        except Exception as error:
        #            print(repr(error))

        #        info("Wrap Section-Like Sequence of Blocks")
        #        cmd = local[str(BIN / "div.hs")]
        #        subinfo(cmd, "< json > json")
        #        try:
        #            json_str = (cmd << json_str)()
        #        except Exception as error:
        #            print(repr(error))

        info("Wrap Section-Like Sequence of Blocks")
        cmd = local[str(BIN / "section.hs")]
        subinfo(cmd, "< json > json")
        try:
            json_str = (cmd << json_str)()
        except Exception as error:
            print(repr(error))

        info("Flag Tombstones (end of proofs)")
        cmd = local[str(BIN / "tombstone.hs")]
        subinfo(cmd, "< json > json")
        try:
            json_str = (cmd << json_str)()
        except Exception as error:
            print(repr(error))

        info("Convert Images to SVG Images")
        cmd = local[str(BIN / "svg.hs")]
        subinfo(cmd, "< json > json")
        json_str = (cmd << json_str)()

        info("Generate HTML body from markdown")
        args = [
            "--email-obfuscation", "none", "-f", "json", "--mathjax", "-t",
            "html5", "--section-divs"
        ]
        cmd = pandoc[args]
        subinfo(cmd, "< json > body")
        pandoc_body_str = (cmd << json_str)()
        pandoc_html = lxml.html.document_fromstring(pandoc_body_str)
        pandoc_body = pandoc_html.cssselect("body")[0]

        info("Generate standalone HTML doc")
        html = HTML.html(HTML.head, HTML.body)
        body = html.cssselect("body")[0]
        head = html.cssselect("head")[0]
        head.append(HTML.meta(charset="utf-8"))
        body.attrib.update(pandoc_body.attrib)
        body.extend(pandoc_body[:])

        # ----------------------------------------------------------------------
        info("Add JQuery")
        head.extend(jquery(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Velocity")
        head.extend(velocity(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Clipboard.js")
        head.extend(clipboard(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Highlight.js")
        head.extend(highlight(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Google Fonts support")
        head.extend(
            google_fonts(["Alegreya", "Alegreya SC"], standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Mathjax support")
        head.extend(mathjax(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Font Awesome support")
        head.extend(font_awesome(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add artdoc css & js files")
        head.extend(artdoc())

        # ----------------------------------------------------------------------
        info("Setting language to english (required for hyphens)")
        html.set("lang", "en")

        # ----------------------------------------------------------------------
        info("Ensure ids uniqueness")
        id_count = {}
        for elt in html.iter():
            _id = elt.get("id")
            if _id is not None:
                count = id_count.get(_id, 0)
                if count > 0:
                    elt.set("id", _id + "-" + str(count))
                id_count[_id] = count + 1

        # ----------------------------------------------------------------------
        info("Turning headers into self-links")
        sections = html.cssselect("section")
        for section in sections:
            id_ = section.get("id")
            heading = None
            if len(section):
                first = section[0]
                if first.tag in "h1 h2 h3 h4 h5 h6".split():
                    heading = first
            if id_ and heading is not None:
                contents = [heading.text or ""] + heading[:]
                heading.text, heading[:] = None, []
                href = {"href": "#" + id_}
                link = HTML.a(href, *contents)
                heading.insert(0, link)

        # ----------------------------------------------------------------------

        # TODO: deal with metadata & insert a document header with:
        #   - title,
        #   - date (format: Month Day, Year), autoformat, autogen ?
        #   - author(s) (with mail & affiliation when available ?).
        #     Assume custom metadata or parse the author field ?
        #     Representation of multiple authors ? MMm eLIFEsciences use
        #     popup for author info. Ex: http://elifesciences.org/content/4/e06356 !
        #     here, use hints from http://dtd.nlm.nih.gov/book/tag-library/:
        #
        #       - name (don't be more precise)
        #       - affiliation (concatenate)
        #       - address ???
        #       - email  --> Font Awesome Icon
        #       - url / uri ?
        #       - form of ID ? (like HAL ? or ZBlatt ?)

        # TODO: look at the rendering of
        #       http://kieranhealy.org/blog/archives/2014/01/23/plain-text/:
        #         - small grey date on top, bold title, bold author name,
        #           italics affiliation, repeat.

        metadata = get_metadata(str(doc))

        items = []

        date = parse_html(metadata.get("date"))
        if date is not None:
            items.append(HTML.p({"class": "date"}, *date))

#        def textify(item):
#          if isinstance(item, basestring):
#              return item
#          elif hasattr(item, "text"):
#              return item.text
#          else:
#              return "".join([textify(it) or "" for it in item])

        title = parse_html(metadata.get("title"))
        title_id = None
        if title is not None:
            #title_id = textify(title).lower().replace(" ", "-")
            items.append(
                HTML.h1({"class": "title"}, HTML.a({"href": "#"}, *title)))
            head.insert(0, HTML.title(*title))

        authors = metadata.get("author") or []

        for author in authors:
            if isinstance(author, basestring):
                name = parse_html(author)
                email = None
                affiliation = None
            else:
                name = parse_html(author.get("name"))
                email = parse_html(author.get("email"))
                affiliation = parse_html(author.get("affiliation"))

            if name is not None:
                if email is not None:
                    name = [HTML.a({"href": "mailto:" + email[0]}, *name)]
                name = HTML.p({"class": "author"}, *name)
                items.append(name)
                if affiliation is not None:
                    affiliation = HTML.p({"class": "affiliation"},
                                         *affiliation)
                    items.append(affiliation)

        header_attr = {"class": "main"}
        #        if title_id is not None:
        #          header_attr["id"] = title_id
        header = HTML.header(header_attr, *items)
        #        print("HEADER", lxml.html.tostring(header))
        body.insert(0, header)
        #        print("BODY", lxml.html.tostring(body))
        #        print("HTML", lxml.html.tostring(html))

        # ----------------------------------------------------------------------
        info("Generate the standalone HTML file")
        html_str = lxml.html.tostring(html,
                                      encoding="utf-8",
                                      doctype="<!DOCTYPE html>")
        doc.with_suffix(".html").open("wb").write(html_str)

    sys.exit(0)
Exemplo n.º 18
0
def _write_new_card_link(ctx, cls, inst, parent, name, *kwargs):
    parent.write(E.a("New Card", href="/new_card"))
Exemplo n.º 19
0
def main():
    # TODO: combine command-line and option file.
    # TODO: option to generate a default configuration file
    parser = argparse.ArgumentParser() # TODO: doc
    parser.add_argument("-s", "--standalone", action="store_true") # TODO: doc
    args = parser.parse_args()
    standalone = args.standalone

    conf = json.load((DATA / "artdoc.js").open())

    if Path("artdoc.js").exists():
        user_conf = json.load(Path("artdoc.js").open())
        conf.update(user_conf)

    info("Document:")
    doc_patterns = conf["doc"]
    if isinstance(doc_patterns, basestring):
        doc_patterns = [doc_patterns]
    docs = []
    for pattern in doc_patterns:
        matches = list(WORKDIR.glob(pattern))
        #subinfo("matching {!r}:".format(pattern))
        for match in matches:
            subinfo(str(match))
        docs.extend(matches)
    if not docs:
        sys.exit("error: no document found")

#    info("HTML template:")
#    template_file = HTML / "index.html"
#    subinfo(str(template_file))
#    template = template_file.open().read().encode("utf-8")

    info("Bibliography:")
    bib_patterns = conf["bib"]
    if isinstance(bib_patterns, basestring):
        bib_patterns = [bib_patterns]
    bibs = []
    for pattern in bib_patterns:
        matches = list(WORKDIR.glob(pattern))
        #subinfo("matching {!r}:".format(pattern))
        for match in matches:
          subinfo(str(match))
        bibs.extend(matches)
    if not bibs:
        print()

    info("JS:")
    cmd = coffee["-c", str(JS / "main.coffee")]
    subinfo(cmd)
    cmd()    

    info("CSS:")
    cmd = stylus[str(CSS / "style.styl")]
    subinfo(str(cmd))
    cmd()

    # TODO: copy only what is required.
    shutil.copytree(str(DATA), str(ARTDOC))

    for doc in docs:
        pass

        info("PANDOC: generate JSON file")
        args = ["-t", "json", "--smart"]
        for bib in bibs:
            args.extend(["--bibliography", str(bib)])
        args.append(str(doc))
        cmd = pandoc[args]
        subinfo(cmd, "> json")
        json_str = cmd()

        info("Convert raw TeX to raw HTML")
        cmd = local[str(BIN / "rawHTML.hs")]
        subinfo(cmd, "< json > json")
        json_str = (cmd << json_str)()

#        info("Flag/Box Proofs")
#        cmd = local[str(BIN / "proof.hs")]
#        subinfo(cmd, "< json > json")
#        try:
#            json_str = (cmd << json_str)()
#        except Exception as error:
#            print(repr(error))

#        info("Wrap Section-Like Sequence of Blocks")
#        cmd = local[str(BIN / "div.hs")]
#        subinfo(cmd, "< json > json")
#        try:
#            json_str = (cmd << json_str)()
#        except Exception as error:
#            print(repr(error))

        info("Wrap Section-Like Sequence of Blocks")
        cmd = local[str(BIN / "section.hs")]
        subinfo(cmd, "< json > json")
        try:
            json_str = (cmd << json_str)()
        except Exception as error:
            print(repr(error))

        info("Flag Tombstones (end of proofs)")
        cmd = local[str(BIN / "tombstone.hs")]
        subinfo(cmd, "< json > json")
        try:
            json_str = (cmd << json_str)()
        except Exception as error:
            print(repr(error))

        info("Convert Images to SVG Images")
        cmd = local[str(BIN / "svg.hs")]
        subinfo(cmd, "< json > json")
        json_str = (cmd << json_str)()

        info("Generate HTML body from markdown")
        args = ["--email-obfuscation", "none",
                "-f", "json", 
                "--mathjax", 
                "-t", "html5", "--section-divs"]
        cmd = pandoc[args]
        subinfo(cmd, "< json > body")
        pandoc_body_str = (cmd << json_str)()
        pandoc_html = lxml.html.document_fromstring(pandoc_body_str)
        pandoc_body = pandoc_html.cssselect("body")[0]

        info("Generate standalone HTML doc")
        html = HTML.html(HTML.head, HTML.body)
        body = html.cssselect("body")[0]
        head = html.cssselect("head")[0]
        head.append(HTML.meta(charset="utf-8"))
        body.attrib.update(pandoc_body.attrib)
        body.extend(pandoc_body[:])

        # ----------------------------------------------------------------------
        info("Add JQuery")
        head.extend(jquery(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Velocity")
        head.extend(velocity(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Clipboard.js")
        head.extend(clipboard(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Highlight.js")
        head.extend(highlight(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Google Fonts support")
        head.extend(google_fonts(["Alegreya", "Alegreya SC"], standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Mathjax support")
        head.extend(mathjax(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add Font Awesome support")
        head.extend(font_awesome(standalone=standalone))

        # ----------------------------------------------------------------------
        info("Add artdoc css & js files")
        head.extend(artdoc())

        # ----------------------------------------------------------------------
        info("Setting language to english (required for hyphens)")
        html.set("lang", "en") 

        # ----------------------------------------------------------------------
        info("Ensure ids uniqueness")
        id_count = {}
        for elt in html.iter():
          _id = elt.get("id")
          if _id is not None:
             count = id_count.get(_id, 0)
             if count > 0:
                 elt.set("id", _id + "-" + str(count))
             id_count[_id] = count + 1

        # ----------------------------------------------------------------------
        info("Turning headers into self-links")
        sections = html.cssselect("section")
        for section in sections:
            id_ = section.get("id")
            heading = None
            if len(section):
                first = section[0]
                if first.tag in "h1 h2 h3 h4 h5 h6".split():
                    heading = first
            if id_ and heading is not None:
                contents = [heading.text or ""] + heading[:]
                heading.text, heading[:] = None, []
                href = {"href": "#" + id_}
                link = HTML.a(href, *contents)
                heading.insert(0, link)

        # ----------------------------------------------------------------------


        # TODO: deal with metadata & insert a document header with:
        #   - title, 
        #   - date (format: Month Day, Year), autoformat, autogen ? 
        #   - author(s) (with mail & affiliation when available ?).
        #     Assume custom metadata or parse the author field ?
        #     Representation of multiple authors ? MMm eLIFEsciences use
        #     popup for author info. Ex: http://elifesciences.org/content/4/e06356 !
        #     here, use hints from http://dtd.nlm.nih.gov/book/tag-library/:
        #
        #       - name (don't be more precise)
        #       - affiliation (concatenate)
        #       - address ???
        #       - email  --> Font Awesome Icon
        #       - url / uri ?
        #       - form of ID ? (like HAL ? or ZBlatt ?)



        # TODO: look at the rendering of
        #       http://kieranhealy.org/blog/archives/2014/01/23/plain-text/:
        #         - small grey date on top, bold title, bold author name,
        #           italics affiliation, repeat.


        metadata = get_metadata(str(doc))

        items = []

        date = parse_html(metadata.get("date"))
        if date is not None:
            items.append(HTML.p({"class": "date"}, *date))

#        def textify(item):
#          if isinstance(item, basestring):
#              return item
#          elif hasattr(item, "text"):
#              return item.text
#          else:
#              return "".join([textify(it) or "" for it in item])

        title = parse_html(metadata.get("title"))
        title_id = None
        if title is not None:
            #title_id = textify(title).lower().replace(" ", "-")
            items.append(
              HTML.h1(
                {"class": "title"}, 
                HTML.a(
                  {"href": "#"},
                  *title
                )
              )
            )
            head.insert(0, HTML.title(*title))

        authors = metadata.get("author") or []

        for author in authors:
            if isinstance(author, basestring):
                name = parse_html(author)
                email = None
                affiliation = None
            else:
                name = parse_html(author.get("name"))
                email = parse_html(author.get("email"))
                affiliation = parse_html(author.get("affiliation"))

            if name is not None:
                if email is not None:
                    name = [HTML.a({"href": "mailto:" + email[0]}, *name)]
                name = HTML.p({"class": "author"}, *name)
                items.append(name)
                if affiliation is not None:
                    affiliation = HTML.p({"class": "affiliation"}, *affiliation)
                    items.append(affiliation)
        
        header_attr = {"class": "main"}
#        if title_id is not None:
#          header_attr["id"] = title_id
        header = HTML.header(header_attr, *items)
#        print("HEADER", lxml.html.tostring(header))
        body.insert(0, header)
#        print("BODY", lxml.html.tostring(body))
#        print("HTML", lxml.html.tostring(html))


        # ----------------------------------------------------------------------
        info("Generate the standalone HTML file")
        html_str = lxml.html.tostring(html, encoding="utf-8", doctype="<!DOCTYPE html>")
        doc.with_suffix(".html").open("wb").write(html_str)

    sys.exit(0)
Exemplo n.º 20
0
    def _gen_row(self,
                 ctx,
                 cls,
                 inst,
                 parent,
                 name,
                 from_arr=False,
                 array_index=None,
                 **kwargs):

        # because HtmlForm* protocols don't use the global null handler, it's
        # possible for null values to reach here.
        if inst is None:
            return

        logger.debug("Generate row for %r", cls)

        mrpc_delim_elt = ''
        if self.mrpc_delim_text is not None:
            mrpc_delim_elt = E.span(self.mrpc_delim_text,
                                    **{'class': 'mrpc-delimiter'})
            mrpc_delim_elt.tail = ' '

        with parent.element('tr'):
            for k, v in self.sort_fields(cls):
                cls_attr = self.get_cls_attrs(v)
                if cls_attr.exc:
                    logger.debug("\tExclude table cell %r type %r for %r", k,
                                 v, cls)
                    continue

                try:
                    sub_value = getattr(inst, k, None)
                except:  # e.g. SQLAlchemy could throw NoSuchColumnError
                    sub_value = None

                sub_name = cls_attr.sub_name
                if sub_name is None:
                    sub_name = k

                if self.hier_delim is not None:
                    if array_index is None:
                        sub_name = "%s%s%s" % (name, self.hier_delim, sub_name)
                    else:
                        sub_name = "%s[%d]%s%s" % (name, array_index,
                                                   self.hier_delim, sub_name)

                logger.debug("\tGenerate table cell %r type %r for %r",
                             sub_name, v, cls)

                td_attrs = {}

                self.add_field_attrs(td_attrs, cls_attr.sub_name or k, v)

                if cls_attr.hidden:
                    self.add_style(td_attrs, 'display:None')

                with parent.element('td', td_attrs):
                    ret = self.to_parent(ctx,
                                         v,
                                         sub_value,
                                         parent,
                                         sub_name,
                                         from_arr=from_arr,
                                         array_index=array_index,
                                         **kwargs)

                    if isgenerator(ret):
                        try:
                            while True:
                                sv2 = (yield)
                                ret.send(sv2)

                        except Break as b:
                            try:
                                ret.throw(b)
                            except StopIteration:
                                pass

            m = cls.Attributes.methods
            if m is not None and len(m) > 0:
                td_attrs = {'class': 'mrpc-cell'}

                with parent.element('td', td_attrs):
                    first = True

                    for mn, md in self._methods(ctx, cls, inst):
                        if first:
                            first = False
                        elif mrpc_delim_elt is not None:
                            parent.write(" ")
                            parent.write(mrpc_delim_elt)

                        pd = {}
                        for k, v in self.sort_fields(cls):
                            if getattr(v.Attributes, 'primary_key', None):
                                r = self.to_unicode(v, getattr(inst, k, None))
                                if r is not None:
                                    pd[k] = r

                        params = urlencode(pd)

                        mdid2key = ctx.app.interface.method_descriptor_id_to_key
                        href = mdid2key[id(md)].rsplit("}", 1)[-1]
                        text = md.translate(ctx.locale,
                                            md.in_message.get_type_name())
                        parent.write(
                            E.a(text,
                                href="%s?%s" % (href, params),
                                **{'class': 'mrpc-operation'}))

            logger.debug("Generate row for %r done.", cls)
            self.extend_data_row(ctx,
                                 cls,
                                 inst,
                                 parent,
                                 name,
                                 array_index=array_index,
                                 **kwargs)
Exemplo n.º 21
0
 def index(self):
     return E.div(
         E.p(E.a("Cards", href="/get_all_card")),
         E.p(E.a("Sip Buddies", href="/get_all_sip_buddy")),
         E.p(E.a("Extensions", href="/get_all_extension")),
     )
Exemplo n.º 22
0
Arquivo: html.py Projeto: 66ru/spyne
    def serialize_complex_model(self, cls, value, locale):
        sti = None
        fti = cls.get_flat_type_info(cls)
        is_array = False

        first_child = iter(fti.values()).next()
        if len(fti) == 1:
            fti = first_child.get_flat_type_info(first_child)
            first_child_2 = iter(fti.values()).next()

            if len(fti) == 1 and first_child_2.Attributes.max_occurs > 1:
                if issubclass(first_child_2, ComplexModelBase):
                    sti = first_child_2.get_simple_type_info(first_child_2)
                is_array = True

            else:
                if issubclass(first_child, ComplexModelBase):
                    sti = first_child.get_simple_type_info(first_child)
            
            value = value[0]

        else:
            raise NotImplementedError("Can only serialize single return types")

        tr = {}
        if self.row_class is not None:
            tr['class'] = self.row_class

        td = {}
        if self.cell_class is not None:
            td['class'] = self.cell_class

        th = {}
        if self.header_cell_class is not None:
            th['class'] = self.header_cell_class

        class_name = first_child.get_type_name()
        if sti is None:
            if self.field_name_attr is not None:
                td[self.field_name_attr] = class_name

            if is_array:
                for val in value:
                    yield E.tr(E.td(first_child_2.to_string(val), **td), **tr)
            else:
                yield E.tr(E.td(first_child_2.to_string(value), **td), **tr)

        else:
            for k, v in sti.items():
                row = E.tr(**tr)
                subvalue = value
                for p in v.path:
                    subvalue = getattr(subvalue, p, None)

                if subvalue is None:
                    if v.type.Attributes.min_occurs == 0:
                        continue
                    else:
                        subvalue = ""
                else:
                    subvalue = v.type.to_string(subvalue)

                    text = getattr(v.type.Attributes,'text', None)
                    if issubclass(v.type, ImageUri):
                        subvalue = E.img(src=subvalue)
                        if text is not None:
                            subvalue.attrib['alt']=text

                    elif issubclass(v.type, AnyUri):
                        if text is None:
                            text = subvalue
                        subvalue = E.a(text, href=subvalue)

                if self.produce_header:
                    header_text = translate(v.type, locale, k)
                    if self.field_name_attr is None:
                        row.append(E.th(header_text, **th))
                    else:
                        th[self.field_name_attr] = k
                        row.append(E.th(header_text, **th))

                if self.field_name_attr is None:
                    row.append(E.td(subvalue, **td))

                else:
                    td[self.field_name_attr] = k
                    row.append(E.td(subvalue, **td))

                yield row
Exemplo n.º 23
0
            def to_parent(self, ctx, cls, inst, parent, name, **kwargs):
                s = self.to_unicode(cls._type_info['query'], inst.query)
                q = urlencode({"q": s})

                parent.write(E.a("Search %s" % inst.query,
                                              href="{}?{}".format(inst.uri, q)))
Exemplo n.º 24
0
def _write_new_card_link(ctx, cls, inst, parent, name, *kwargs):
    parent.write(E.a("New Card", href="/new_card"))
Exemplo n.º 25
0
    def _gen_row(self, ctx, cls, inst, parent, name, from_arr=False,
                                                    array_index=None, **kwargs):

        # because HtmlForm* protocols don't use the global null handler, it's
        # possible for null values to reach here.
        if inst is None:
            return

        logger.debug("Generate row for %r", cls)

        with parent.element('tr'):
            for k, v in self.sort_fields(cls):
                attr = self.get_cls_attrs(v)
                if attr.exc:
                    logger.debug("\tExclude table cell %r type %r for %r",
                                                                      k, v, cls)
                    continue

                try:
                    sub_value = getattr(inst, k, None)
                except:  # e.g. SQLAlchemy could throw NoSuchColumnError
                    sub_value = None

                sub_name = attr.sub_name
                if sub_name is None:
                    sub_name = k

                if self.hier_delim is not None:
                    if array_index is None:
                        sub_name = "%s%s%s" % (name, self.hier_delim, sub_name)
                    else:
                        sub_name = "%s[%d]%s%s" % (name, array_index,
                                                     self.hier_delim, sub_name)

                logger.debug("\tGenerate table cell %r type %r for %r",
                                                               sub_name, v, cls)

                td_attrs = {}
                if self.field_name_attr is not None:
                    td_attrs[self.field_name_attr] = attr.sub_name or k
                if attr.hidden:
                    td_attrs['style'] = 'display:None'

                with parent.element('td', td_attrs):
                    ret = self.to_parent(ctx, v, sub_value, parent,
                                              sub_name, from_arr=from_arr,
                                              array_index=array_index, **kwargs)

                    if isgenerator(ret):
                        try:
                            while True:
                                sv2 = (yield)
                                ret.send(sv2)
                        except Break as b:
                            try:
                                ret.throw(b)
                            except StopIteration:
                                pass

            m = cls.Attributes.methods
            if m is not None and len(m) > 0:
                td_attrs = {}

                with parent.element('td', td_attrs):
                    first = True
                    mrpc_delim = html.fromstring("&nbsp;|&nbsp;").text

                    for mn, md in self._methods(cls, inst):
                        if first:
                            first = False
                        else:
                            parent.write(mrpc_delim)

                        pd = { }
                        for k, v in self.sort_fields(cls):
                            if getattr(v.Attributes, 'primary_key', None):
                                r = self.to_unicode(v, getattr(inst, k, None))
                                if r is not None:
                                    pd[k] = r

                        params = urlencode(pd)

                        mdid2key = ctx.app.interface.method_descriptor_id_to_key
                        href = mdid2key[id(md)].rsplit("}",1)[-1]
                        text = md.translate(ctx.locale,
                                                  md.in_message.get_type_name())
                        parent.write(E.a(text, href="%s?%s" % (href, params)))

            logger.debug("Generate row for %r done.", cls)
            self.extend_data_row(ctx, cls, inst, parent, name,
                                              array_index=array_index, **kwargs)
Exemplo n.º 26
0
def _write_new_sip_buddy_link(ctx, cls, inst, parent, name, *kwargs):
    parent.write(E.a("New SipBuddy", href="/new_sip_buddy"))
Exemplo n.º 27
0
def _write_new_ext_link(ctx, cls, inst, parent, name, *kwargs):
    parent.write(E.a("New Extension", href="/new_ext"))