コード例 #1
0
def embed_iframe(media, width=400, height=225, frameborder=0, **kwargs):
    """Return an <iframe> tag that loads our universal player.

    :type media: :class:`mediadrop.model.media.Media`
    :param media: The media object that is being rendered, to be passed
        to all instantiated player objects.
    :rtype: :class:`genshi.builder.Element`
    :returns: An iframe element stream.

    """
    src = url_for(controller='/media',
                  action='embed_player',
                  slug=media.slug,
                  qualified=True)
    tag = Element('iframe',
                  src=src,
                  width=width,
                  height=height,
                  frameborder=frameborder,
                  **kwargs)
    # some software is known not to work with self-closing iframe tags
    # ('<iframe ... />'). Several WordPress instances are affected as well as
    # TWiki http://mediadrop.video/community/topic/embed-iframe-closing-tag
    tag.append('')
    return tag
コード例 #2
0
ファイル: export.py プロジェクト: ryanpetrello/draughtcraft
    def render(self, xml=True):
        """
        Returns a genshi.builder.Element, or raw rendered XML, depending on the
        value of `xml`.
        """

        # Keep a namespace of XML nodes to render
        ns = dict()

        # Look at every key/value pair passed into the constructor...
        for key, value in self.__values__.items():

            # If the value is a list, it's a set of Nodes.
            if isinstance(value, list):
                # Update the namespace with {NodeSet.name: [Element, Element]}
                ns.update({
                    key: [node.render(xml=False) for node in value]
                })
            elif isinstance(value, Node):
                #
                # If the value is already a singular node, just add it to the
                # existing list of values.
                #
                ns.update({
                    key: value.render(xml=False)
                })
            elif key.lower() in self.__fields__:
                field = self.__fields__[key.lower()]
                # Get the `transform`'ed value and store it in the namespace.
                fval = field.get_value(value)
                ns.update(fval)

        # The tagname is the class name in uppercase, e.g., `Hop` -> `<HOP>`
        name = self.__class__.__name__.upper()

        # Sort the keys for consistency
        items = sorted(
            ns.items(), lambda x, y: cmp(x[0].lower(), y[0].lower()))

        #
        # Create an `Element` for this node.
        # Its value should be the accumulated collection of its child
        # `Element`s.
        #
        element = Element(name)(*[
            v if isinstance(v, Element) else Element(k.upper())(v)
            for k, v in items
        ])

        # Return xml or a raw `Element`.
        if xml is False:
            return element
        return element.generate().render('xml')
コード例 #3
0
    def render_object(self, error_text=None):
        swf_url = self.swf_url()
        flashvars = urlencode(self.flashvars())

        tag = Element('object', type='application/x-shockwave-flash',
                      width=self.adjusted_width, height=self.adjusted_height,
                      data=swf_url, id=self.elem_id)
        tag(Element('param', name='movie', value=swf_url))
        tag(Element('param', name='flashvars', value=flashvars))
        tag(Element('param', name='allowfullscreen', value='true'))
        tag(Element('param', name='allowscriptaccess', value='always'))
        if error_text:
            tag(error_text)
        return tag
コード例 #4
0
    def filter_stream(self, req, method, filename, stream, data):

        found = False
        for pattern in self.insert_into:
            if filename == pattern:
                add_stylesheet(req, 'calendarpopup/css/CalendarPopUp.css')
                add_script(req, 'calendarpopup/js/CalendarPopUp.js')
                found = True

        calendarPopUpArrayOfIDs = ""
        calendarPopUpArrayOfIDsFormat = ""
        for element in self.watch_ids:
            if element.find('=') != -1:
                (one, two) = element.split('=', 2)
                if one and two:
                    if calendarPopUpArrayOfIDs == "":
                        calendarPopUpArrayOfIDs = "\"%s\"" % one
                        calendarPopUpArrayOfIDsFormat = "\"%s\"" % two
                    else:
                        calendarPopUpArrayOfIDs = "%s, \"%s\"" % (
                            calendarPopUpArrayOfIDs, one)
                        calendarPopUpArrayOfIDsFormat = "%s, \"%s\"" % (
                            calendarPopUpArrayOfIDsFormat, two)
            else:
                if element:
                    if calendarPopUpArrayOfIDs == "":
                        calendarPopUpArrayOfIDs = "\"%s\"" % element
                        calendarPopUpArrayOfIDsFormat = "\"yyyy/MM/dd\""
                    else:
                        calendarPopUpArrayOfIDs = "%s, \"%s\"" % (
                            calendarPopUpArrayOfIDs, element)
                        calendarPopUpArrayOfIDsFormat = "%s, \"yyyy/MM/dd\"" % calendarPopUpArrayOfIDsFormat

        insertDIV = Element(
            'div',
            id="CalendarPopUpDiv",
            style=
            "position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"
        )
        insertScript = Element(
            'script', type="text/javascript"
        )('var calendarPopUpArrayOfIDs = new Array(%s); var calendarPopUpArrayOfIDsFormat = new Array(%s)'
          % (calendarPopUpArrayOfIDs, calendarPopUpArrayOfIDsFormat))

        if found:
            return stream | Transformer('//div[@id="footer"]').after(
                insertDIV) | Transformer('body').before(insertScript)

        return stream
コード例 #5
0
    def render(self, xml=True):
        """
        Returns a genshi.builder.Element, or raw rendered XML, depending on the
        value of `xml`.
        """

        # Keep a namespace of XML nodes to render
        ns = dict()

        # Look at every key/value pair passed into the constructor...
        for key, value in self.__values__.items():

            # If the value is a list, it's a set of Nodes.
            if isinstance(value, list):
                # Update the namespace with {NodeSet.name: [Element, Element]}
                ns.update({key: [node.render(xml=False) for node in value]})
            elif isinstance(value, Node):
                #
                # If the value is already a singular node, just add it to the
                # existing list of values.
                #
                ns.update({key: value.render(xml=False)})
            elif key.lower() in self.__fields__:
                field = self.__fields__[key.lower()]
                # Get the `transform`'ed value and store it in the namespace.
                fval = field.get_value(value)
                ns.update(fval)

        # The tagname is the class name in uppercase, e.g., `Hop` -> `<HOP>`
        name = self.__class__.__name__.upper()

        # Sort the keys for consistency
        items = sorted(ns.items(),
                       lambda x, y: cmp(x[0].lower(), y[0].lower()))

        #
        # Create an `Element` for this node.
        # Its value should be the accumulated collection of its child
        # `Element`s.
        #
        element = Element(name)(*[
            v if isinstance(v, Element) else Element(k.upper())(v)
            for k, v in items
        ])

        # Return xml or a raw `Element`.
        if xml is False:
            return element
        return element.generate().render('xml')
コード例 #6
0
    def render_markup(self, error_text=None):
        """Render the XHTML markup for this player instance.

        :param error_text: Optional error text that should be included in
            the final markup if appropriate for the player.
        :rtype: ``unicode`` or :class:`genshi.core.Markup`
        :returns: XHTML that will not be escaped by Genshi.

        """
        uri = self.uris[0]
        
        data = self.data.copy()
        wmode = data.pop('wmode', 0)
        if wmode:
            # 'wmode' is subject to a lot of myths and half-true statements, 
            # these are the best resources I could find:
            # http://stackoverflow.com/questions/886864/differences-between-using-wmode-transparent-opaque-or-window-for-an-embed
            # http://kb2.adobe.com/cps/127/tn_12701.html#main_Using_Window_Mode__wmode__values_
            data['wmode'] = 'opaque'
        data_qs = urlencode(data)
        tag = Element('iframe', src='%s?%s' % (uri, data_qs), frameborder=0,
                      width=self.adjusted_width, height=self.adjusted_height,
                      allowfullscreen='allowfullscreen')
        if error_text:
            tag(error_text)
        return tag
コード例 #7
0
ファイル: transform.py プロジェクト: egilchri/tweetapp
class WrapTransformation(object):
    """Wrap selection in an element."""

    def __init__(self, element):
        if isinstance(element, Element):
            self.element = element
        else:
            self.element = Element(element)

    def __call__(self, stream):
        for mark, event in stream:
            if mark:
                element = list(self.element.generate())
                for prefix in element[:-1]:
                    yield None, prefix
                yield mark, event
                start = mark
                stopped = False
                for mark, event in stream:
                    if start is ENTER and mark is EXIT:
                        yield mark, event
                        stopped = True
                        break
                    if not mark:
                        break
                    yield mark, event
                else:
                    stopped = True
                yield None, element[-1]
                if not stopped:
                    yield mark, event
            else:
                yield mark, event
コード例 #8
0
ファイル: players.py プロジェクト: isaleem/cumin
    def render_markup(self, error_text=None):
        """Render the XHTML markup for this player instance.

        :param error_text: Optional error text that should be included in
            the final markup if appropriate for the player.
        :rtype: ``unicode`` or :class:`genshi.core.Markup`
        :returns: XHTML that will not be escaped by Genshi.

        """
        uri = self.uris[0]
        data = urlencode({
            'width': 560,  # XXX: The native height for this width is 420
            'theme': 'none',
            'iframe': 1,
            'autoPlay': 0,
            'hideInfos': 1,
            'additionalInfos': 1,
            'foreground': '#F7FFFD',
            'highlight': '#FFC300',
            'background': '#171D1B',
        })
        tag = Element('iframe',
                      src='%s?%s' % (uri, data),
                      frameborder=0,
                      width=self.adjusted_width,
                      height=self.adjusted_height)
        if error_text:
            tag(error_text)
        return tag
コード例 #9
0
class WrapTransformation(object):
    """Wrap selection in an element."""

    def __init__(self, element):
        if isinstance(element, Element):
            self.element = element
        else:
            self.element = Element(element)

    def __call__(self, stream):
        for mark, event in stream:
            if mark:
                element = list(self.element.generate())
                for prefix in element[:-1]:
                    yield None, prefix
                yield mark, event
                start = mark
                stopped = False
                for mark, event in stream:
                    if start is ENTER and mark is EXIT:
                        yield mark, event
                        stopped = True
                        break
                    if not mark:
                        break
                    yield mark, event
                else:
                    stopped = True
                yield None, element[-1]
                if not stopped:
                    yield mark, event
            else:
                yield mark, event
コード例 #10
0
ファイル: macro.py プロジェクト: pombredanne/trachacks
    def expand_macro(self, formatter, macro, args):

        # dictionary file

        section = macro.lower()  # [abbr]
        option = 'file'  # file = /path/to/dictionary/file
        dict = {}

        if self.config.has_option(section, option):
            dict = build_dict(self.config.get(section, option), self.tags)

        args, kw = parse_args(args)

        try:
            for key in self.keys:
                kw[key] = kw[key].strip()
        except KeyError:
            if key == 'title' and kw['key'] in dict:
                kw['title'] = dict[kw['key']][0]
                kw['tag'] = dict[kw['key']][1]
            else:
                return system_message('%s: Missing required keyword "%s."' %
                                      (macro, key))
        # tag keyword is optional

        if 'tag' in kw:
            tag = kw['tag'].strip()
            if tag not in self.tags: tag = self.default
        else:
            tag = self.default

        return Element(tag)(kw['key'], title="%s" % kw['title'])
コード例 #11
0
 def test_wrap_with_element(self):
     element = Element('a', href='http://localhost')
     self.assertEqual(
         _transform('foo', Transformer('.').wrap(element), with_attrs=True),
         [(None, START, ('a', {'href': 'http://localhost'})),
          (OUTSIDE, TEXT, 'foo'),
          (None, END, 'a')]
         )
コード例 #12
0
def embed_iframe(media, width=400, height=225, frameborder=0, **kwargs):
    """Return an <iframe> tag that loads our universal player.

    :type media: :class:`mediadrop.model.media.Media`
    :param media: The media object that is being rendered, to be passed
        to all instantiated player objects.
    :rtype: :class:`genshi.builder.Element`
    :returns: An iframe element stream.

    """
    src = url_for(controller="/media", action="embed_player", slug=media.slug, qualified=True)
    tag = Element("iframe", src=src, width=width, height=height, frameborder=frameborder, **kwargs)
    # some software is known not to work with self-closing iframe tags
    # ('<iframe ... />'). Several WordPress instances are affected as well as
    # TWiki http://mediadrop.net/community/topic/embed-iframe-closing-tag
    tag.append("")
    return tag
コード例 #13
0
    def render_embed(self, error_text=None):
        swf_url = self.swf_url()
        flashvars = urlencode(self.flashvars())

        tag = Element('embed', type='application/x-shockwave-flash',
                      allowfullscreen='true', allowscriptaccess='always',
                      width=self.adjusted_width, height=self.adjusted_height,
                      src=swf_url, flashvars=flashvars, id=self.elem_id)
        if error_text:
            tag(error_text)
        return tag
コード例 #14
0
ファイル: players.py プロジェクト: isaleem/cumin
    def render_markup(self, error_text=None):
        """Render the XHTML markup for this player instance.

        :param error_text: Optional error text that should be included in
            the final markup if appropriate for the player.
        :rtype: ``unicode`` or :class:`genshi.core.Markup`
        :returns: XHTML that will not be escaped by Genshi.

        """
        attrs = self.html5_attrs()
        tag = Element(self.media.type, **attrs)
        for uri in self.uris:
            # Providing a type attr breaks for m3u8 breaks iPhone playback.
            # Tried: application/x-mpegURL, vnd.apple.mpegURL, video/MP2T
            if uri.file.container == 'm3u8':
                mimetype = None
            else:
                mimetype = uri.file.mimetype
            tag(Element('source', src=uri, type=mimetype))
        if error_text:
            tag(error_text)
        return tag
コード例 #15
0
    def render_markup(self, error_text=None):
        """Render the XHTML markup for this player instance.

        :param error_text: Optional error text that should be included in
            the final markup if appropriate for the player.
        :rtype: ``unicode`` or :class:`genshi.core.Markup`
        :returns: XHTML that will not be escaped by Genshi.

        """
        uri = self.uris[0]
        tag = Element('iframe', src=uri, frameborder=0,
                      width=self.adjusted_width, height=self.adjusted_height)
        return tag
コード例 #16
0
def embed_iframe(media, width=400, height=225, frameborder=0, **kwargs):
    """Return an <iframe> tag that loads our universal player.

    :type media: :class:`mediacore.model.media.Media`
    :param media: The media object that is being rendered, to be passed
        to all instantiated player objects.
    :rtype: :class:`genshi.builder.Element`
    :returns: An iframe element stream.

    """
    src = url_for(controller='/media',
                  action='embed_player',
                  slug=media.slug,
                  qualified=True)
    tag = Element('iframe',
                  src=src,
                  width=width,
                  height=height,
                  frameborder=frameborder,
                  **kwargs)
    return tag
コード例 #17
0
    def filter_stream(self, req, method, filename, stream, data):

        if filename != "ticket.html" and filename != 'ticket_preview.html':
            return stream

        if 'ticket' in data:

            add_script(req, 'CategorizedFields/js/bundle.js')
            add_stylesheet(req, 'CategorizedFields/css/base.css')

            ticket = data['ticket']

            self.categories = self.build_category()
            self.map_fields_to_category(self.categories)

            for index in list(self.categories.keys()):
                if self.category_is_hidden(self.categories[index], ticket):
                    del self.categories[index]

            cat_ticket = Element(
                'cat-ticket', **{
                    ':categories': 'categories',
                    ':ticket': 'ticket'
                })
            cat_modify = Element(
                'cat-modify', **{
                    ':categories': 'categories',
                    ':ticket': 'ticket'
                })

            stream |= Transformer('//div[@id="ticket"]').attr("id", "ticket1")
            stream |= Transformer('//div[@id="ticket1"]').after(
                tag.div(cat_ticket, id='ticket', class_='trac-content'))
            stream |= Transformer('//fieldset[@id="properties"]').attr(
                "id", "properties1")
            stream |= Transformer('//fieldset[@id="properties1"]').after(
                tag.fieldset(cat_modify, id='properties'))

            stream |= Transformer('//body').append(
                tag.script(
                    """
                            (function () {
                            var app1 = new Vue$({
                                el: '#ticket',
                                data: {
                                    categories: %s,
                                    ticket: %s,
                                }
                            });
                            var app2 = new Vue$({
                                el: '#properties',
                                data: {
                                    categories: %s,
                                    ticket: %s,
                                }
                            });
                            })(); 
                        """ %
                    (json.dumps(self.categories, cls=CategoryEncoder),
                     json.dumps(ticket.values, cls=DateTimeJSONEncoder),
                     json.dumps(self.categories, cls=CategoryEncoder),
                     json.dumps(ticket.values, cls=DateTimeJSONEncoder))))

        return stream
コード例 #18
0
 def __init__(self, element):
     if isinstance(element, Element):
         self.element = element
     else:
         self.element = Element(element)
コード例 #19
0
ファイル: present.py プロジェクト: fnogcps/pkgs.void
def render_link(href, text):
    return Element('a', href=href)(text)
コード例 #20
0
 def __init__(self, tag_, *args, **kwargs):
     Element.__init__(self, tag_, **kwargs)
     self(*args)
コード例 #21
0
ファイル: transform.py プロジェクト: egilchri/tweetapp
 def __init__(self, element):
     if isinstance(element, Element):
         self.element = element
     else:
         self.element = Element(element)
コード例 #22
0
def create_headers_html(level, content):
    """
    Create internal headers of block (Heading 2 to Heading 10 in odt)
    It uses h1 to h10 html headers
    """
    return Element('h' + str(level - 1))(content)