Пример #1
0
def on_update(sender=None, watcher=None, request=None, **kw):
    """
    Log a Change if there is a `change_watcher_spec`.
    """
    master = get_master(watcher.watched)
    if master is None:
        # No master, nothing to log
        return

    cs = watcher.watched.change_watcher_spec
    if False:  # html version
        changes = list(watcher.get_updates_html(cs.ignored_fields))
        if len(changes) == 0:
            msg = '(no changes)'
        elif len(changes) == 1:
            msg = E.tostring(changes[0])
        else:
            msg = E.tostring(E.ul(*changes))
    else:
        changes = []
        for k, old, new in watcher.get_updates(cs.ignored_fields):
            changes.append("%s : %s --> %s" %
                           (k, dd.obj2str(old), dd.obj2str(new)))
        if len(changes) == 0:
            msg = '(no changes)'
        elif len(changes) == 1:
            msg = changes[0]
        else:
            msg = '- ' + ('\n- '.join(changes))
    log_change(ChangeTypes.update, request, master, watcher.watched, msg)
Пример #2
0
def plain_response(ui, request, tplname, context):
    "Deserves a docstring"
    u = request.subst_user or request.user
    lang = get_language()
    k = (u.profile, lang)
    menu = PLAIN_MENUS.get(k, None)
    if menu is None:
        menu = settings.SITE.get_site_menu(ui, u.profile)
        #~ url = settings.SITE.plain_prefix + '/'
        plain = settings.SITE.plugins.plain
        assert plain.renderer is not None
        url = plain.build_plain_url()
        menu.add_url_button(url, label=_("Home"))
        menu = menu.as_bootstrap_html(plain.renderer, request)
        menu = E.tostring(menu)
        PLAIN_MENUS[k] = menu
    context.update(menu=menu, E=E)
    web.extend_context(context)
    template = settings.SITE.jinja_env.get_template(tplname)

    response = http.HttpResponse(
        template.render(**context),
        content_type='text/html;charset="utf-8"')

    return response
Пример #3
0
    def to_rst(cls, ar, column_names=None, header_level=None, **kwargs):
        "Better name would be table2rst (analog to table2xhtml())"
        fields, headers, widths = ar.get_field_info(column_names)
        # ~ # in case column_names contains remote fields
        #~ settings.SITE.startup()
        #~ settings.SITE.resolve_virtual_fields()

        #~ grid = ar.ah.list_layout.main

        sums = [fld.zero for fld in fields]
        rows = []
        recno = 0
        #~ for row in ar:
        for row in ar.sliced_data_iterator:
            recno += 1
            rows.append([x for x in ar.row2text(fields, row, sums)])
            #~ rows.append([x for x in grid.row2html(ar,fields,row,sums)])

        has_sum = False
        for i in sums:
            if i:
                #~ print '20120914 zero?', repr(i)
                has_sum = True
                break
        if has_sum:
            rows.append([x for x in ar.sums2html(fields, sums)])

        t = RstTable(headers, **kwargs)
        s = t.to_rst(rows)
        if header_level is not None:
            s = E.tostring(E.h2(ar.get_title())) + s
        return s
Пример #4
0
    def as_button(self, *args, **kwargs):
        """Return a HTML chunk with a "button" which, when clicked, will
        execute this action on this instance.  This is being used in
        the :ref:`lino.tutorial.polls`.

        """
        return E.tostring(self.as_button_elem(*args, **kwargs))
Пример #5
0
 def as_ul(action_spec):
     a = settings.SITE.modules.resolve(action_spec)
     ar = a.request(user=AnonymousUser.instance())
     # 20150810
     ar.renderer = self
     # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
     return E.tostring(E.ul(*[obj.as_list_item(ar) for obj in ar]))
Пример #6
0
    def render(self, ar):
        T = self.actor
        sar = ar.spawn(T, limit=T.preview_limit)
        if sar.get_total_count():
            if self.header_level is None:
                s = ''
            else:
                s = E.tostring(E.h2(
                    T.label, ' ', ar.window_action_button(
                        T.default_action,
                        label="🗗",
                        style="text-decoration:none; font-size:80%;",
                        title=_("Show this table in own window"))))

            s += E.tostring(ar.show(sar))
            return s
Пример #7
0
    def get_change_body(self, ar, cw):
        """Returns the text of the notification message to emit.

        The default implementation returns a message of style
        "{object} has been modified by {user}" followed by a summary
        of the changes.  

        Application code can override this. Returning None or an empty
        string means to suppress notification.

        """
        if cw is None:
            elems = [
                E.p(ar.obj2memo(self), ' ',
                    _("has been created by {user}").format(user=ar.get_user()))
            ]
        else:
            items = list(cw.get_updates_html())
            if len(items) == 0:
                return
            elems = [
                E.p(
                    ar.obj2memo(self), ' ',
                    _("has been modified by {user}").format(
                        user=ar.get_user()), ":")
            ]
            elems.append(E.ul(*items))
        return E.tostring(E.div(*elems))
Пример #8
0
    def get_address_html(self, *args, **kwargs):
        """Returns the full postal address a a string containing html
        markup of style::
        
            <p>line1<br/>line2...</p>

        This returns always exactly one paragraph, even if the address
        is empty (in which case the paragraph is empty):

        >>> print(TestAddress().get_address_html())
        <p />

        Optional attributes for the enclosing `<p>` tag can be
        specified as keyword arguments. Example:

        >>> addr = TestAddress('line1', 'line2')
        >>> print(addr.get_address_html(class_="Recipient"))
        <p class="Recipient">line1<br />line2</p>
          
        If `min_height` is specified, makes sure that the string
        contains at least that many lines. Adds as many empty lines
        (``<br/>``) as needed.  This is useful in a template which
        wants to get a given height for every address.

        >>> print(addr.get_address_html(min_height=5))
        <p>line1<br />line2<br /><br /><br /></p>

        Any arguments are forwarded to :meth:`lines2p
        <lino.utils.xmlgen.html.lines2p>` which is used to pack the address
        lines into a paragraph (see there for more examples).

        """
        lines = list(self.get_address_lines())
        return E.tostring(lines2p(lines, *args, **kwargs))
Пример #9
0
    def get_address_html(self, *args, **kwargs):
        """Returns the full postal address a a string containing html
        markup of style::
        
            <p>line1<br/>line2...</p>

        This returns always exactly one paragraph, even if the address
        is empty (in which case the paragraph is empty):

        >>> print(TestAddress().get_address_html())
        <p />

        Optional attributes for the enclosing `<p>` tag can be
        specified as keyword arguments. Example:

        >>> addr = TestAddress('line1', 'line2')
        >>> print(addr.get_address_html(class_="Recipient"))
        <p class="Recipient">line1<br />line2</p>
          
        If `min_height` is specified, makes sure that the string
        contains at least that many lines. Adds as many empty lines
        (``<br/>``) as needed.  This is useful in a template which
        wants to get a given height for every address.

        >>> print(addr.get_address_html(min_height=5))
        <p>line1<br />line2<br /><br /><br /></p>

        Any arguments are forwarded to :meth:`lines2p
        <lino.utils.xmlgen.html.lines2p>` which is used to pack the address
        lines into a paragraph (see there for more examples).

        """
        lines = list(self.get_address_lines())
        return E.tostring(lines2p(lines, *args, **kwargs))
Пример #10
0
    def resolve_conflicts(self, we, ar, rset, until):
        """Check whether given event `we` conflicts with other events and move
        it to a new date if necessary. Returns (a) the event's
        start_date if there is no conflict, (b) the next available
        alternative date if the event conflicts with other existing
        events and should be moved, or (c) None if there are conflicts
        but no alternative date could be found.

        `ar` is the action request who asks for this.
        `rset` is the `RecurrenceSet`.

        """

        date = we.start_date
        if not self.care_about_conflicts(we):
            return date
        # ar.debug("20140310 resolve_conflicts %s", we.start_date)
        while we.has_conflicting_events():
            qs = we.get_conflicting_events()
            date = rset.get_next_alt_date(ar, date)
            ar.debug("%s wants %s but conflicts with %s, moving to %s. ",
                     we.summary, we.start_date, qs, date)
            if date is None or date > until:
                ar.debug("Failed to get next date for %s (%s > %s).", we, date,
                         until)
                conflicts = [E.tostring(ar.obj2html(o)) for o in qs]
                msg = ', '.join(conflicts)
                ar.warning("%s conflicts with %s. ", we, msg)
                return None

            rset.move_event_to(we, date)
        return date
Пример #11
0
    def as_button(self, *args, **kwargs):
        """Return a HTML chunk with a "button" which, when clicked, will
        execute this action on this instance.  This is being used in
        the :ref:`lino.tutorial.polls`.

        """
        return E.tostring(self.as_button_elem(*args, **kwargs))
Пример #12
0
    def to_rst(cls, ar, column_names=None, header_level=None, **kwargs):
        "Better name would be table2rst (analog to table2xhtml())"
        fields, headers, widths = ar.get_field_info(column_names)

        sums = [fld.zero for fld in fields]
        rows = []
        recno = 0
        for row in ar.sliced_data_iterator:
            recno += 1
            rows.append([x for x in ar.row2text(fields, row, sums)])

        has_sum = False
        for i in sums:
            if i:
                #~ print '20120914 zero?', repr(i)
                has_sum = True
                break
        if has_sum:
            rows.append([x for x in ar.sums2html(fields, sums)])

        t = RstTable(headers, **kwargs)
        s = t.to_rst(rows)
        if header_level is not None:
            s = E.tostring(E.h2(ar.get_title())) + s
        return s
Пример #13
0
def http_response(ar, tplname, context):
    "Deserves a docstring"
    u = ar.get_user()
    lang = get_language()
    k = (u.profile, lang)
    menu = MENUS.get(k, None)
    if menu is None:
        menu = settings.SITE.get_site_menu(None, u.profile)
        bs3 = settings.SITE.plugins.bootstrap3
        if False:  # 20150803 home button now in base.html
            assert bs3.renderer is not None
            url = bs3.build_plain_url()
            menu.add_url_button(url, label=_("Home"))
        e = bs3.renderer.show_menu(ar, menu)
        menu = E.tostring(e)
        MENUS[k] = menu
    context.update(menu=menu)
    context = ar.get_printable_context(**context)
    context['ar'] = ar
    context['memo'] = MEMO_PARSER.parse
    env = settings.SITE.plugins.jinja.renderer.jinja_env
    template = env.get_template(tplname)

    response = http.HttpResponse(
        template.render(**context),
        content_type='text/html;charset="utf-8"')

    return response
Пример #14
0
    def elem2rec_detailed(ar, elem, **rec):
        """Adds additional information for this record, used only by
    detail views.

        The "navigation information" is a set of pointers to the next,
        previous, first and last record relative to this record in
        this report.  (This information can be relatively expensive
        for records that are towards the end of the report.  See
        `/blog/2010/0716`, `/blog/2010/0721`, `/blog/2010/1116`,
        `/blog/2010/1207`.)

        recno 0 means "the requested element exists but is not
        contained in the requested queryset".  This can happen after
        changing the quick filter (search_change) of a detail view.

        """
        rh = ar.ah
        rec = ar.elem2rec1(rh, elem, **rec)
        if ar.actor.hide_top_toolbar:
            rec.update(title=ar.get_detail_title(elem))
        else:
            #~ print(ar.get_title())
            #~ print(dd.obj2str(elem))
            #~ print(repr(unicode(elem)))
            if True:  # before 20131017
                rec.update(title=ar.get_title() + u" » " +
                           ar.get_detail_title(elem))
            else:  # todo
                rec.update(title=E.tostring(ar.href_to_request(ar))
                           + u" » " + ar.get_detail_title(elem))
        rec.update(id=elem.pk)
        rec.update(disable_delete=rh.actor.disable_delete(elem, ar))
        if rh.actor.show_detail_navigator:
            rec.update(navinfo=navinfo(ar.data_iterator, elem))
        return rec
Пример #15
0
 def resolve_conflicts(self, we, ar, rset, until):
     """
     Check whether given event conflicts with other events and move it
     to a new date if necessary. Returns the new date, or None if
     no alternative could be found.
     """
 
     date = we.start_date
     if not self.care_about_conflicts(we):
         return date
     # ar.debug("20140310 resolve_conflicts %s", we.start_date)
     while we.has_conflicting_events():
         qs = we.get_conflicting_events()
         # ar.debug("20140310 %s conflicts with %s. ", we,
         #          we.get_conflicting_events())
         date = rset.get_next_alt_date(ar, date)
         if date is None or date > until:
             ar.debug(
                 "Failed to get next date for %s (%s > %s).",
                 we, date, until)
             conflicts = [E.tostring(ar.obj2html(o)) for o in qs]
             msg = ', '.join(conflicts)
             ar.warning("%s conflicts with %s. ", we, msg)
             return None
     
         rset.move_event_to(we, date)
     return date
Пример #16
0
 def as_ul(action_spec):
     a = settings.SITE.modules.resolve(action_spec)
     ar = a.request(user=AnonymousUser.instance())
     # 20150810
     ar.renderer = self
     # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
     return E.tostring(E.ul(*[obj.as_list_item(ar) for obj in ar]))
Пример #17
0
 def fmt(obj):
     s = E.tostring(ar.action_button(ba, obj))
     s += fds(obj.created) + " " + obj.created.strftime(
         settings.SITE.time_format_strftime) + " "
     s += ar.parse_memo(obj.body)
     # s += obj.body
     return "<li>{}</li>".format(s)
Пример #18
0
    def get_notify_message(self, ar, cw):
        """Returns the text of the notification message to emit.

        The default implementation returns a message of style
        "{object} has been modified by {user}" followed by a summary
        of the changes.  

        Application code can override this. Returning None or an empty
        string means to suppress notification.

        """
        if cw is None:
            return
        items = list(cw.get_updates_html())
        if len(items) == 0:
            return
        elems = [E.p(
            ar.obj2html(self),
            ' ', _("has been modified by {user}").format(
                user=ar.get_user()),
            ":")]
        elems.append(E.ul(*items))
        if False:
            elems.append(E.p(_(
                "Subsequent changes to {obj} will not be notified "
                "until you visit {url} and mark this notification "
                "as seen.").format(
                url=settings.SITE.server_url or "Lino",
                obj=self.get_notify_owner(ar))))
        return E.tostring(E.div(*elems))
Пример #19
0
 def resolve_conflicts(self, we, ar, rset, until):
     """
     Check whether given event conflicts with other events and move it
     to a new date if necessary. Returns the new date, or None if
     no alternative could be found.
     """
 
     date = we.start_date
     # ar.debug("20140310 resolve_conflicts %s", we.start_date)
     while we.has_conflicting_events():
         qs = we.get_conflicting_events()
         # ar.debug("20140310 %s conflicts with %s. ", we,
         #          we.get_conflicting_events())
         date = rset.get_next_alt_date(ar, date)
         if date is None or date > until:
             ar.debug(
                 "Failed to get next date for %s (%s > %s).",
                 we, date, until)
             conflicts = [E.tostring(ar.obj2html(o)) for o in qs]
             msg = ', '.join(conflicts)
             ar.warning("%s conflicts with %s. ", we, msg)
             return None
     
         rset.move_event_to(we, date)
     return date
Пример #20
0
 def ticket2html(parser, s):
     ar = parser.context['ar']
     # dd.logger.info("20161019 %s", ar.renderer)
     pk = int(s)
     obj = sender.site.models.tickets.Ticket.objects.get(pk=pk)
     text = "#{0}".format(obj.id)
     e = ar.obj2html(obj, text, title=obj.summary)
     return E.tostring(e)
Пример #21
0
        def as_table2(ar):
            # 20150810
            # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
            ar.renderer = self

            t = xghtml.Table()
            ar.dump2html(t, ar.sliced_data_iterator)

            #~ print ar.get_total_count()
            return E.tostring(t.as_element())
Пример #22
0
        def as_table2(ar):
            # 20150810
            # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
            ar.renderer = self

            t = xghtml.Table()
            ar.dump2html(t, ar.sliced_data_iterator)

            #~ print ar.get_total_count()
            return E.tostring(t.as_element())
Пример #23
0
 def get_address_html(self, *args, **kwargs):
     """
     Return the address of the :attr:`recipient` of this object.
     See
     :meth:`Addressable.get_address_html
     <lino.utils.addressable.Addressable.get_address_html>`.
     """
     rec = self.get_recipient()
     if rec is None:
         return E.tostring(lines2p([], *args, **kwargs))
     return rec.get_address_html(*args, **kwargs)
Пример #24
0
 def get_address_html(self, *args, **kwargs):
     """
     Return the address of the :attr:`recipient` of this object.
     See
     :meth:`Addressable.get_address_html
     <lino.utils.addressable.Addressable.get_address_html>`.
     """
     rec = self.get_recipient()
     if rec is None:
         return E.tostring(lines2p([], *args, **kwargs))
     return rec.get_address_html(*args, **kwargs)
Пример #25
0
        def as_table(action_spec):
            a = settings.SITE.modules.resolve(action_spec)
            ar = a.request(user=AnonymousUser.instance())
            # 20150810
            # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
            ar.renderer = self

            t = xghtml.Table()
            ar.dump2html(t, ar.sliced_data_iterator)

            #~ print ar.get_total_count()
            return E.tostring(t.as_element())
Пример #26
0
    def as_li(self, ar):
        """Return this comment as a list item. 

        """
        chunks = [ar.parse_memo(self.short_text)]
        by = _("{0} by {1}").format(naturaltime(self.created), str(self.user)),
        chunks += [" (", E.tostring(ar.obj2html(self, by)), ")"]
        if self.more_text:
            chunks.append(" (...)")

        html = ''.join(chunks)
        return "<li>" + html + "</li>"
Пример #27
0
        def as_table(action_spec):
            a = settings.SITE.modules.resolve(action_spec)
            ar = a.request(user=AnonymousUser.instance())
            # 20150810
            # ar.renderer = settings.SITE.plugins.bootstrap3.renderer
            ar.renderer = self

            t = xghtml.Table()
            ar.dump2html(t, ar.sliced_data_iterator)

            #~ print ar.get_total_count()
            return E.tostring(t.as_element())
Пример #28
0
 def notify_done(self, ar, bm, leaf, url, **kw):
     help_url = ar.get_help_url("print", target='_blank')
     msg = _("Your printable document (filename %(doc)s) "
             "should now open in a new browser window. "
             "If it doesn't, please consult %(help)s "
             "or ask your system administrator.")
     msg %= dict(doc=leaf, help=E.tostring(help_url))
     kw.update(message=msg, alert=True)
     if bm.use_webdav and has_davlink and ar.request is not None:
         kw.update(open_davlink_url=ar.request.build_absolute_uri(url))
     else:
         kw.update(open_url=url)
     ar.success(**kw)
     return
Пример #29
0
    def as_li(self, ar):
        """Return this comment as a list item. 

        """
        chunks = [ar.parse_memo(self.short_text)]
        by = _("{0} by {1}").format(
            naturaltime(self.created), str(self.user)),
        chunks += [
            " (", E.tostring(ar.obj2html(self, by)), ")"
        ]
        if self.more_text:
            chunks.append(" (...)")

        html = ''.join(chunks)
        return "<li>" + html + "</li>"
Пример #30
0
    def render(self, ar):
        """Render this table to the dashboard.

        - Do nothing if there is no data.

        - If :attr:`header_level` is not None, add a header

        - Render the table itself by calling
          :meth:`lino.core.requests.BaseRequest.show`

        """
        T = self.actor
        sar = ar.spawn(T, limit=T.preview_limit)
        if not sar.get_total_count():
            return ''
        if self.header_level is None:
            s = ''
        else:
            s = E.tostring(
                E.h2(
                    T.label,
                    ' ',
                    ar.window_action_button(
                        T.default_action,
                        # label="🗗",
                        # label="☌",  # conjunction
                        # label="◱", # 25F1
                        # label="◳", # 25F3
                        # label="⏍", # 23CD
                        label="⍐",  # 2350
                        # style="text-decoration:none; font-size:80%;",
                        style="text-decoration:none;",
                        title=_("Show this table in own window"))))

        s += E.tostring(ar.show(sar))
        return s
Пример #31
0
 def notify_done(self, ar, bm, leaf, url, **kw):
     help_url = ar.get_help_url("print", target='_blank')
     msg = _("Your printable document (filename %(doc)s) "
             "should now open in a new browser window. "
             "If it doesn't, please consult %(help)s "
             "or ask your system administrator.")
     msg %= dict(doc=leaf, help=E.tostring(help_url))
     kw.update(message=msg, alert=True)
     if bm.use_webdav and has_davlink and ar.request is not None:
         kw.update(
             open_davlink_url=ar.request.build_absolute_uri(url))
     else:
         kw.update(open_url=url)
     ar.success(**kw)
     return
Пример #32
0
def on_update(sender=None, watcher=None, request=None, **kw):
    """
    Log a Change if there is a `change_watcher_spec`.
    `watcher` is a :class:`lino.core.diff.ChangeWatcher` instance.
    """
    master = get_master(watcher.watched)
    if master is None:
        # No master, nothing to log
        return

    cs = watcher.watched.change_watcher_spec
    changed_fields = ''
    if False:  # I tried a html version, but it doesn't help to make
        # things more end-user firiendly. And it caused
        # problems when being rendered in a grid.
        changes = list(watcher.get_updates_html(cs.ignored_fields))
        if len(changes) == 0:
            msg = '(no changes)'
        elif len(changes) == 1:
            msg = E.tostring(changes[0])
        else:
            msg = E.tostring(E.ul(*changes))
    else:
        changes = []
        for k, old, new in watcher.get_updates(cs.ignored_fields):
            changed_fields += k + " "
            changes.append("%s : %s --> %s" %
                           (k, dd.obj2str(old), dd.obj2str(new)))
        if len(changes) == 0:
            msg = '(no changes)'
        elif len(changes) == 1:
            msg = changes[0]
        else:
            msg = '- ' + ('\n- '.join(changes))
    log_change(ChangeTypes.update, request, master, watcher.watched, msg,
               changed_fields)
Пример #33
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`CommentsByController`.

        """
        sar = self.request_from(ar, master_instance=obj)

        html = obj.description
        items = [o.as_li(ar) for o in sar]
        if len(items) > 0:
            html += u"<ul>{0}</ul>".format(''.join(items))

        sar = self.insert_action.request_from(sar)
        if ar.renderer.is_interactive and sar.get_permission():
            btn = sar.ar2button(None, _("Write comment"), icon_name=None)
            html += "<p>" + E.tostring(btn) + "</p>"
        return u"""<div class="htmlText">{0}</div>""".format(html)
Пример #34
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`CommentsByController`.

        """
        sar = self.request_from(ar, master_instance=obj)

        html = obj.description
        items = [o.as_li(ar) for o in sar]
        if len(items) > 0:
            html += u"<ul>{0}</ul>".format("".join(items))

        sar = self.insert_action.request_from(sar)
        if ar.renderer.is_interactive and sar.get_permission():
            btn = sar.ar2button(None, _("Write comment"), icon_name=None)
            html += "<p>" + E.tostring(btn) + "</p>"
        return u"""<div class="htmlText">{0}</div>""".format(html)
Пример #35
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`CommentsByRFC`.

        """
        sar = self.request_from(ar, master_instance=obj)

        html = obj.get_rfc_description(ar)
        sar = self.insert_action.request_from(sar)
        if sar.get_permission():
            btn = sar.ar2button(None, _("Write comment"), icon_name=None)
            html += "<p>" + E.tostring(btn) + "</p>"

        items = [o.as_li(ar) for o in sar]
        if len(items) > 0:
            html += u"<ul>{0}</ul>".format(''.join(items))

        return ar.html_text(html)
Пример #36
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`CommentsByRFC`.

        """
        sar = self.request_from(ar, master_instance=obj)

        html = obj.get_rfc_description(ar)
        sar = self.insert_action.request_from(sar)
        if sar.get_permission():
            btn = sar.ar2button(None, _("Write comment"), icon_name=None)
            html += "<p>" + E.tostring(btn) + "</p>"

        items = [o.as_li(ar) for o in sar]
        if len(items) > 0:
            html += u"<ul>{0}</ul>".format(''.join(items))

        return ar.html_text(html)
Пример #37
0
    def as_li(self, ar):
        """Return this comment as a list item. If `bleach
        <http://bleach.readthedocs.org/en/latest/>`_ is installed, all
        tags except some will be removed when

        """
        if bleach is None:
            chunks = [self.short_text]
        else:
            chunks = [bleach.clean(self.short_text, tags=self.ALLOWED_TAGS, strip=True)]

        by = (_("{0} by {1}").format(naturaltime(self.created), unicode(self.user)),)
        chunks += [" (", E.tostring(ar.obj2html(self, by)), ")"]
        if self.more_text:
            chunks.append(" (...)")

        html = "".join(chunks)
        return "<li>" + html + "</li>"
Пример #38
0
 def resolve_conflicts(self, we, ar, rset, until):
     date = we.start_date
     # ar.debug("20140310 resolve_conflicts %s", we.start_date)
     while we.has_conflicting_events():
         qs = we.get_conflicting_events()
         # ar.debug("20140310 %s conflicts with %s. ", we,
         #          we.get_conflicting_events())
         date = rset.get_next_alt_date(ar, date)
         if date is None or date > until:
             ar.debug(
                 "Failed to get next date for %s (%s > %s).",
                 we, date, until)
             conflicts = [E.tostring(ar.obj2html(o)) for o in qs]
             msg = ', '.join(conflicts)
             ar.warning("%s conflicts with %s. ", we, msg)
             return None
     
         rset.move_event_to(we, date)
     return date
Пример #39
0
    def as_li(self, ar):
        """Return this comment as a list item. If `bleach
        <http://bleach.readthedocs.org/en/latest/>`_ is installed, all
        tags except some will be removed when

        """
        if bleach is None:
            chunks = [self.short_text]
        else:
            chunks = [bleach.clean(
                self.short_text, tags=self.ALLOWED_TAGS, strip=True)]

        by = _("{0} by {1}").format(
            naturaltime(self.created), unicode(self.user)),
        chunks += [
            " (", E.tostring(ar.obj2html(self, by)), ")"
        ]
        if self.more_text:
            chunks.append(" (...)")

        html = ''.join(chunks)
        return "<li>" + html + "</li>"
Пример #40
0
 def html_func(self, html, **kw):
     """
     Render a string that is in HTML (not XHTML).
     """
     if not html:
         return ''
     if E.iselement(html):
         html = E.tostring(html)
     try:
         html = html2xhtml(html)
     except Exception as e:
         print(20150923, e)
     # logger.debug("20141210 html_func() got:<<<\n%s\n>>>", html)
     # print __file__, ">>>"
     # print html
     # print "<<<", __file__
     if isinstance(html, str):
         # some sax parsers refuse unicode strings.
         # appy.pod always expects utf-8 encoding.
         # See /blog/2011/0622.
         html = html.encode('utf-8')
         #~ logger.info("20120726 html_func() %r",html)
     return self.renderXhtml(html, **kw)
Пример #41
0
 def html_func(self, html, **kw):
     """
     Render a string that is in HTML (not XHTML).
     """
     if not html:
         return ''
     if E.iselement(html):
         html = E.tostring(html)
     try:
         html = html2xhtml(html)
     except Exception as e:
         print 20150923, e
     # logger.debug("20141210 html_func() got:<<<\n%s\n>>>", html)
     # print __file__, ">>>"
     # print html
     # print "<<<", __file__
     if isinstance(html, unicode):
         # some sax parsers refuse unicode strings.
         # appy.pod always expects utf-8 encoding.
         # See /blog/2011/0622.
         html = html.encode('utf-8')
         #~ logger.info("20120726 html_func() %r",html)
     return self.renderXhtml(html, **kw)
Пример #42
0
 def get_address_html(self,**attrs):
     """
     Returns the full postal address a a string containing html 
     markup of style::
     
         <p>line1<br />line2...</p>
       
     Optional attributes for the enclosing `<p>` tag can be 
     specified as keyword arguments. Example::
     
         >>> class MyAddr(Addressable):
         ...     def __init__(self,*lines): self.lines = lines
         ...     def address_person_lines(self): return []
         ...     def address_location_lines(self): return self.lines
         ...     
         >>> addr = MyAddr('line1','line2')
         >>> print(addr.get_address_html(class_="Recipient"))
         <p class="Recipient">line1<br />line2</p>
       
     See :mod:`lino.utils.xmlgen.html`.
       
     """
     lines = join_elems(self.address_lines(),E.br)
     return E.tostring(E.p(*lines,**attrs))
Пример #43
0
    def elem2rec_detailed(ar, elem, **rec):
        """Adds additional information for this record, used only by detail
        views.

        The "navigation information" is a set of pointers to the next,
        previous, first and last record relative to this record in
        this report.  (This information can be relatively expensive
        for records that are towards the end of the queryset.  See
        `/blog/2010/0716`, `/blog/2010/0721`, `/blog/2010/1116`,
        `/blog/2010/1207`.)

        recno 0 means "the requested element exists but is not
        contained in the requested queryset".  This can happen after
        changing the quick filter (search_change) of a detail view.

        """
        rh = ar.ah
        rec = ar.elem2rec1(rh, elem, **rec)
        if ar.actor.hide_top_toolbar:
            rec.update(title=ar.get_detail_title(elem))
        else:
            #~ print(ar.get_title())
            #~ print(dd.obj2str(elem))
            #~ print(repr(unicode(elem)))
            if True:  # before 20131017
                rec.update(title=ar.get_title() + u" » " +
                           ar.get_detail_title(elem))
            else:  # todo
                rec.update(title=E.tostring(ar.href_to_request(ar)) + u" » " +
                           ar.get_detail_title(elem))
        rec.update(id=elem.pk)
        if ar.actor.editable:
            rec.update(disable_delete=rh.actor.disable_delete(elem, ar))
        if rh.actor.show_detail_navigator:
            rec.update(navinfo=navinfo(ar.data_iterator, elem))
        return rec
Пример #44
0
    def html_func(self, html, **kw):
        """
        Insert a chunk of HTML (not XHTML).
        This might be provided as a string or as an etree element.
        """

        if html is None or html == '':
            # Testing for `if not html:` caused a FutureWarning: The
            # behavior of this method will change in future versions.
            # Use specific 'len(elem)' or 'elem is not None' test
            # instead.
            return ''

        if E.iselement(html):
            html = E.tostring(html)

        try:
            html = html2xhtml(html)
        except Exception as e:
            raise Exception(
                "20150923 html2xhtml(%r) failed: %s" % (html, e))
        # logger.info("20160330 html_func() got:<<<\n%s\n>>>", html)
        # print(__file__, ">>>")
        # print(html)
        # print("<<<", __file__)
        try:
            return self.renderXhtml(html, **kw)
        except Exception as e:
            if not isinstance(html, six.string_types):
                raise
            # some sax parsers refuse unicode strings.
            # appy.pod always expects utf-8 encoding.
            # See /blog/2011/0622.
            html = html.encode('utf-8')
            # logger.info("20120726 renderXhtml(%r) failed : %s", html, e)
            return self.renderXhtml(html, **kw)
Пример #45
0
    def test_this(self):

        Person = rt.modules.contacts.Person
        Link = rt.modules.humanlinks.Link
        LinkTypes = rt.modules.humanlinks.LinkTypes
        LinksByHuman = rt.modules.humanlinks.LinksByHuman

        father = create(Person,
                        first_name="John",
                        last_name="Doe",
                        gender="M",
                        birth_date='1980-07-31')
        try:
            son = create(Person,
                         first_name="Joseph",
                         last_name="Doe",
                         gender="M",
                         birth_date=IncompleteDate(2009, 2, 30))
        except ValidationError:
            pass
        else:
            self.fail("Expected ValidationError")
        son = create(Person,
                     first_name="Joseph",
                     last_name="Doe",
                     gender="M",
                     birth_date='2009-02-28')
        create(Link, parent=father, child=son, type=LinkTypes.parent)

        mary = create(Person,
                      first_name="Mary",
                      last_name="Doe",
                      gender="F",
                      birth_date='2010-01-30')
        create(Link, parent=father, child=mary, type=LinkTypes.parent)

        self.assertEqual(Person.objects.count(), 3)

        ar = LinksByHuman.request(father)
        s = ar.to_rst()
        # print(s)
        self.assertEquivalent(
            """

        John is Father of *Mary* (4 years) Father of *Joseph* (5
        years) """, s)

        # Create relationship as **Father**/**Son** **Adoptive
        # father**/**Adopted son** **Foster father**/**Foster son**
        # **Husband** **Partner** **Stepfather**/**Stepson** **Brother**
        # **Cousin** **Uncle**/**Nephew** **Relative** **Other** """, s)

        with translation.override('de'):
            ar = LinksByHuman.request(father)
            s = ar.to_rst()
            # print(s)
            self.assertEquivalent(
                """
            
            John ist Vater von *Mary* (4 Jahre) Vater von *Joseph* (5
            Jahre) """, s)

            # Beziehung erstellen als **Vater**/**Sohn**
            # **Adoptivvater**/**Adoptivsohn**
            # **Pflegevater**/**Pflegesohn** **Ehemann** **Partner**
            # **Stiefvater**/**Stiefsohn** **Bruder** **Vetter**
            # **Onkel**/**Neffe** **Verwandter** **Sonstiger** """, s)

        with translation.override('fr'):
            ar = LinksByHuman.request(father)
            s = ar.to_rst()
            # print(s)
            self.assertEquivalent(
                u"""

            John est Père de *Mary* (4 ans) Père de *Joseph* (5
            ans) """, s)

            # Créer lien de parenté en tant que **Père**/**Fils** **Père
            # adoptif**/**Fils adoptif** **Père nourricier**/**Fils
            # nourricier** **Mari** **Partenaire**
            # **Beau-père**/**Beau-fils** **Frère** **Cousin**
            # **Oncle**/**Nephew** **Parent** **Autre** """, s)

        # Here we are just testing whether no exception is risen. The
        # ouptut itself is more thoroughly tested elsewhere.
        html = LinksByHuman.get_slave_summary(father, ar)
        s = E.tostring(html)
        self.assertEqual(s[:5], '<div>')
Пример #46
0
 def obj2str(self, ar, obj, text=None, **kwargs):
     return E.tostring(self.obj2html(ar, obj, text, **kwargs))
Пример #47
0
 def show_table(self, *args, **kwargs):
     return E.tostring(self.table2story(*args, **kwargs))
Пример #48
0
 def obj2str(self, ar, obj, text=None, **kwargs):
     return E.tostring(self.obj2html(ar, obj, text, **kwargs))
Пример #49
0
 def show_table(self, *args, **kwargs):
     return E.tostring(self.table2story(*args, **kwargs))
Пример #50
0
 def show_table(self, *args, **kwargs):
     e = super(JinjaRenderer, self).show_table(*args, **kwargs)
     return E.tostring(e)
Пример #51
0
 def show_request(self, ar, **kw):
     """
     Returns a HTML element representing this request as a table.
     """
     #~ return ar.table2xhtml(**kw)
     return E.tostring(ar.table2xhtml(**kw))
Пример #52
0
 def overview(self, ar):
     context = dict(obj=E.tostring(ar.obj2html(self.owner)),
                    user=E.tostring(ar.obj2html(self.user)))
     return _(self.message).format(**context)
Пример #53
0
 def to_html(self, **kw):
     """
     """
     #~ settings.SITE.startup()
     return E.tostring(self.request(**kw).table2xhtml())
Пример #54
0
 def fmt(e):
     if isinstance(e, basestring):
         return e
     return E.tostring(e)
Пример #55
0
 def to_html(self, **kw):
     """
     """
     #~ settings.SITE.startup()
     return E.tostring(self.request(**kw).table2xhtml())
Пример #56
0
 def get_address_html(self, **attrs):
     """
     """
     lines = join_elems(self.address_lines(), E.br)
     return E.tostring(E.p(*lines, **attrs))
Пример #57
0
 def fmt(e):
     if isinstance(e, basestring):
         return e
     return E.tostring(e)