[Mpuls-commits] r4606 - in base/trunk: . mpulsweb/lib

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Feb 10 17:20:34 CET 2011


Author: bh
Date: 2011-02-10 17:20:33 +0100 (Thu, 10 Feb 2011)
New Revision: 4606

Removed:
   base/trunk/mpulsweb/lib/renderer.py
Modified:
   base/trunk/ChangeLog
Log:
* mpulsweb/lib/renderer.py: Removed. The old renderer is not used
anymore.


Modified: base/trunk/ChangeLog
===================================================================
--- base/trunk/ChangeLog	2011-02-10 16:17:55 UTC (rev 4605)
+++ base/trunk/ChangeLog	2011-02-10 16:20:33 UTC (rev 4606)
@@ -1,5 +1,10 @@
 2011-02-10  Bernhard Herzog  <bh at intevation.de>
 
+	* mpulsweb/lib/renderer.py: Removed. The old renderer is not used
+	anymore.
+
+2011-02-10  Bernhard Herzog  <bh at intevation.de>
+
 	* mpulsweb/lib/formedrenderer.py (UrlFactory.icon): Inline the
 	code of the icon function imported from the old renderer
 	module. That function was not used anywhere else anyway.

Deleted: base/trunk/mpulsweb/lib/renderer.py
===================================================================
--- base/trunk/mpulsweb/lib/renderer.py	2011-02-10 16:17:55 UTC (rev 4605)
+++ base/trunk/mpulsweb/lib/renderer.py	2011-02-10 16:20:33 UTC (rev 4606)
@@ -1,1205 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2007, 2008 Intevation GmbH, Germany, <info at intevation.de>
-#
-# This file is part of mpuls WASKA (CoMPUter-based case fiLeS -
-# Web-Anwendungs-Server fuer Kompetenzagenturen).
-#
-# mpuls WASKA is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Affero General Public License as published by the
-# Free Software Foundation, either version 3 of the License, or (at your
-# option) any later version.
-#
-# mpuls WASKA is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
-# License for more details.
-#
-# You should have received a copy of the GNU Affero General Public
-# License along with mpuls WASKA. If not, see <http://www.gnu.org/licenses/>.
-#
-# mpuls WASKA has been developed on behalf of the
-# Projekttraeger im Deutschen Zentrum fuer Luft- und Raumfahrt e.V. (PT-DLR)
-# within the programme Kompetenzagenturen (Durchfuehrungsphase) funded by
-# the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and
-# European Social Fund resources.
-#
-# Authors:
-# Sascha L. Teichmann <teichmann at intevation.de>
-#
-
-import re
-from cgi import escape
-import logging
-import decimal
-
-from mpulsweb.lib.translation import _, ungettext
-
-import formed.meta.data as data
-from formed.meta.nodecomponents import Node, NodeComponent as MetaNodeComponent
-from formed.instance.tree import RepeatInstanceContainerNode
-from formed.instance.backends.common import RuleEvalContext
-
-from mpulsweb.lib.helper.filters import NA, nl_to_br
-from mpulsweb.lib.helpers import tag, url_for, dd_mm_YYYY as format_date, \
-    format_number
-
-
-log = logging.getLogger(__name__)
-
-TARGET = re.compile(r"(\w+)(?:|:(.+))$")
-WEIGHTS = frozenset([15, 25, 30, 40, 45, 50, 55, 60, 75])
-SET_MODIFICATION_ATTRS = {"onchange": "setModification();"}
-
-def is_required(flags):
-    return flags.find("required:") >= 0
-
-def is_evaluation_relevant(flags):
-    return flags.find("evaluation:") >= 0
-
-def digits(n):
-    d, c = 10, 1
-    while n >= d:
-        d *= 10
-        c += 1
-    return c
-
-def visibleDepth(c):
-    depth = -1
-    while c:
-        if not (isinstance(c, data.GroupNode) and not c.isInvisible()):
-            depth += 1
-        c = c.parent
-    return depth
-
-def get_child_num(child):
-    '''Returns which place in sequence of the children the given child is'''
-    parent = child.parent
-    for num, c in enumerate(parent.children):
-        if c.getIdentifier() == child.getIdentifier():
-            return num + 1
-    return 0
-
-
-def hidden_bool_tag(id):
-    """Return the hidden HTML input tag for the plain boolean field given by id.
-
-    This hidden input field will have a name derived from id by
-    prepending the id with 'bool-'.  The hidden field can be used to
-    determine which booleans are present to detect which have been
-    unckecked by the user.
-    """
-    return tag("input", type="hidden", name="bool-" + id)
-
-def apply_hidden_booleans(form_result):
-    """Set the boolean values in form results using the hidden fields.
-
-    In HTML-Forms, check boxes that are noch checked when the user
-    submits the form are not included in the form results.  The need to
-    be included the form results, though, so that their values are
-    updated properly.  This function uses the hidden fields created by
-    hidden_bool_tag to determine which booleans are present in the form
-    and adds all booleans which have a hidden field but are not included
-    in form_result, to an empty string.  The hidden fields are removed
-    from form_result.
-
-    The form_result parameter should be a dictionary mapping HTML form
-    field names to values.
-    """
-    for key in [key for key in form_result.keys() if key.startswith("bool-")]:
-        del form_result[key]
-        fieldid = key[5:]
-        if fieldid not in form_result:
-            form_result[fieldid] = ""
-
-
-def icon(name):
-    """Return the url for the icon given by name."""
-    return url_for("/images/icons/" + name)
-
-
-class Text:
-
-    def __init__(self, txt):
-        self.txt = txt
-
-    def render(self, target, weight=None):
-        return self.txt
-
-
-class Div(Text):
-
-    def render(self, target, width=""):
-        return '<td width="%s">%s</td>\n' % ("%s%%" % width, self.txt)
-
-
-class Item(Text):
-
-    def render(self, target, width="100"):
-        if width:
-            return '<td width="%s">%s</td>\n' % ("%s%%" % width, self.txt)
-        else:
-            return '<td>%s</td>\n' % (self.txt)
-
-
-class Container:
-
-    def __init__(self, target):
-        self.target = target
-        self.items = []
-
-    def append(self, item, weight=1.0):
-        self.items.append((item, weight))
-
-    def render(self, doBreak=True):
-        out = []
-        if self.items:
-            out.append('<table>')
-            out.append('<tr>')
-            for col, w in self.items:
-                data = col.render(self.target, w or "")
-                if not data:
-                    data = "<td></td>"
-                out.append(data)
-            out.append('</tr>')
-            out.append('</table>')
-        return "".join(out)
-
-
-class ChoiceContainer(Container):
-
-    def render(self, doBreak=True):
-        return "".join([col.render(self.target, w or "")
-                        for col, w in self.items])
-
-
-class ViewRenderer:
-
-    def __init__(self, it=None, page=None, ro_mode=True):
-        self.it = it # instancetree
-        self.page = page
-        self.stateStack = None
-        self.containersStack = None
-        self.ro_mode = ro_mode
-        self.tabindex = 3
-        self.warnings = {}
-        self.notices = {}
-        self.widget_order = []
-        self.current_identifier = None
-
-    def next_tabindex(self):
-        tabindex = self.tabindex
-        self.tabindex += 1
-        return str(tabindex)
-
-    def render(self, showNext=False):
-        out = []
-        if not self.ro_mode:
-            out.append(tag("form", id="formularpage",
-                           action=url_for(controller="/formularpage",
-                                          action="save"),
-                           accept_charset="UTF-8",
-                           method="POST"))
-            # Add submitbutton at the top of the page too
-            out.append('<div class="widget formbuttons">')
-            out.append(tag("input", type="submit", name="save",
-                           class_="submit_button", value=_('Save'),
-                           tabindex=self.next_tabindex()))
-            if showNext:
-                out.append("&nbsp;")
-                out.append(tag("input", type="submit", name="savenext",
-                               class_="submit_button",
-                               value=_('Save and proceed'),
-                               tabindex=self.next_tabindex()))
-            out.append('</div>')
-        out.append('<div>')
-        #out.append('<div class="widget formfields">')
-        out.append(tag("input", type="hidden", name="page",
-                       value=self.page.getIdentifier()))
-
-        self.stateStack = []
-        self.containersStack = [[Container(None)]]
-        self._renderPage(self.page)
-
-        out.append(self.containersStack[-1][0].render())
-
-        out.append('</div>')
-        if not self.ro_mode:
-            out.append('<div class="widget formbuttons">')
-            out.append(tag("input", type="submit", class_="submit_button",
-                           name="save", value=_('Save'),
-                           tabindex=self.next_tabindex()))
-            if showNext:
-                out.append("&nbsp;")
-                out.append(tag("input", type="submit", name="savenext",
-                               class_="submit_button",
-                               value=_('Save and proceed'),
-                               tabindex=self.next_tabindex()))
-            out.append('</div>')
-            out.append('</form>\n')
-
-        return "".join(out)
-
-    def toTarget(self, item, target):
-        weight = None
-        if target:
-            m = TARGET.match(target)
-            if m:
-                target = m.group(1)
-                try:
-                   weight = m.group(2)
-                except (TypeError, ValueError):
-                   pass
-
-        for container in self.containersStack[-1]:
-            if not container.target or container.target == target:
-                container.append(item, weight)
-                return
-
-    def _getMeta(self, node):
-        if isinstance(node, MetaNodeComponent):
-            return node
-        else:
-            return node.getMeta()
-
-    def _renderLabel(self, node, labeltag=True):
-        meta = self._getMeta(node)
-        out = []
-        warning = self._has_warnings(node) and "warning" or ""
-        error = node.hasErrors() and "error" or ""
-        if labeltag:
-            out.append(tag("label", for_=node.getIdentifier()))
-            out.append(tag("a", class_=error or warning,
-                           name="f_%s" % node.getIdentifier()))
-            out.append(escape(meta.getDescription()))
-            out.append("</a>")
-            out.append("</label>")
-        else:
-            out.append(escape(meta.getDescription()))
-        out.append(' ')
-        return "".join(out)
-
-    def _renderAttributes(self, node):
-        meta = self._getMeta(node)
-
-        out = []
-        if meta.hasHelp():
-            out.append(tag("a", target="_blank",
-                           href=url_for(controller="/annotations",
-                                        action="help", id=meta.getName())))
-            out.append(tag("img", src=icon("formular/help.png"), alt="help",
-                        width=12,
-                        height=12))
-            out.append('</a>')
-        if is_required(meta.getFlags()):
-            out.append(tag("a", target="_blank",
-                           href=url_for(controller="/annotations",
-                                        action="required", id=meta.getName())))
-            out.append(tag("img", src=icon("formular/required.png"),
-                           width="12", height="12", alt="required"))
-            out.append('</a>')
-        if is_evaluation_relevant(meta.getFlags()):
-            out.append(tag("a", target="_blank",
-                           href=url_for(controller="/annotations",
-                                        action="evaluation",
-                                        id=meta.getName())))
-            out.append(tag("img", src=icon("formular/evaluation.png"),
-                           alt="evaluation",
-                           width=12,
-                           height=12))
-            out.append('</a>')
-        return "".join(out)
-
-    def _renderErrors(self, node):
-        """
-        Render errors and warnings
-        """
-        meta = self._getMeta(node)
-        out = []
-        if self._has_warnings(node) and not node.hasErrors():
-            spanClass = 'warning'
-        else:
-            spanClass = 'error'
-
-        out.append('<span class="%s">' % spanClass)
-        out.append(tag("form:%s" % spanClass, name=node.getIdentifier(),
-                       format=''))
-        out.append('</span>')
-
-        return "".join(out)
-
-    def _has_warnings(self, node):
-        """Return whether there are known warnings for the node"""
-        identifier = node.getIdentifier()
-        return identifier in self.warnings or identifier in self.notices
-
-    def _checkWarnings(self, node):
-        """Check node for warnings by evaluating the relevant warning rules.
-        Only rules that are warnings, as determined by the rule's
-        isWarning method, and that would mark the field corresponding to
-        node are evaluated.  If such a rule is violated the warning
-        message is added to the self.warnings dictionary.
-        """
-        meta = self._getMeta(node)
-        if meta is node:
-            # This method is called from _renderChild for all child
-            # object, some of which are actually meta tree components.
-            # We cannot check warnings on meta components, so abort
-            # early in this case.
-            return
-
-        name = meta.getName()
-        id = node.getIdentifier()
-
-        # add all checked widgets to warning_order, even if they have no
-        # warnings or no warning rules so that the widget_order list can
-        # be used to order the errors too.
-        self.widget_order.append(id)
-
-        formed = self.it.getFormEd()
-        rules = [rule for rule in formed.name2markingrules.get(name, ())
-                      if rule.isWarning()]
-        if not rules:
-            return
-
-        context = RuleEvalContext(self.it, id)
-        for rule in rules:
-            if not self.it.rule_available(rule, context):
-                continue
-            for result, variables in rule.getExpr().evaluate_instances(context):
-                if not result and id in variables:
-                    if rule.getMark().startswith("notice"):
-                        collection = self.notices
-                    else:
-                        collection = self.warnings
-                    collection.setdefault(id, []).append(rule.getValue())
-
-    def _renderGroup(self, node):
-        meta = self._getMeta(node)
-        description = meta.getDescription()
-
-        out = []
-
-        if meta.isInvisible():
-            if description:
-                out.append("<!-- %s -->\n" % escape(description))
-        else:
-            out.append("<fieldset>\n")
-            if description:
-                out.append("<legend>%s %s</legend>\n"
-                           % (self._renderLabel(node, False),
-                              self._renderAttributes(node)))
-            out.append(self._renderRecursive(node))
-            out.append("</fieldset>\n")
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderRepeatContainer(self, node):
-        meta = self._getMeta(node)
-        description = meta.getDescription()
-        out = []
-        out.append('<fieldset>')
-        out.append('<legend>%s %s</legend>'
-                   % (escape(description), self._renderAttributes(node)))
-        out.append('<table class="repeatgroup">')
-        if True:
-            out.extend(self._renderRepeatList(node))
-        else:
-            out.extend(self._renderRepeatNav(node))
-        out.append('</table>')
-        out.append('</fieldset>')
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderRepeatList(self, node):
-        out = []
-        for child in node.getChildren():
-            out.append('<tr>')
-            out.append('<td class="container">')
-            out.append(self._renderRecursive(child))
-            out.append('</td>')
-            out.append('<td class="vcontrol" width="17">')
-            if not self.ro_mode:
-                out.append(tag("input",
-                               name="del_rg|%s" % child.getIdentifier(),
-                               type="submit",
-                               class_="pseudo_imagebutton del_rg",
-                               style=('background-image:url("%s")'
-                                      % icon("delete_active_16.png")),
-                               title=_('Delete RG')))
-
-            out.append('</td>')
-            out.append('</tr>')
-        if self.ro_mode:
-            out.append('<tr><td class="hcontrol" style="text-align: right;"'
-                       ' colspan="2">&nbsp;</td></tr>')
-        else:
-            out.append('<tr>')
-            out.append('<td class="hcontrol" style="text-align: right;"'
-                       ' colspan="2">')
-            out.append(tag("input",
-                           name="add_rg|%s" % node.getIdentifier(),
-                           type="submit",
-                           class_="pseudo_imagebutton add_rg",
-                           style=('background-image:url("%s")'
-                                  % icon("new_16.png")),
-                           title=_('Add new RG')))
-            out.append("</td>")
-            out.append("</tr>")
-        return out
-
-    def _renderRepeatNav(self, node):
-        out = []
-        for child in node.getChildren():
-            out.append('<tr>')
-            out.append('<td class="container">')
-            out.append(self._renderRecursive(child))
-            out.append('</td>')
-            out.append('</tr>')
-            break
-
-        child_id = child.getIdentifier()
-        out.append('<tr>')
-        out.append('<td class="hcontrol">')
-
-        out.append(tag("a", name=_('Select first'),
-                       href=url_for(controller="/repeatgroup",
-                                    action="select_first", id=child_id)))
-        out.append(tag("img", src=icon("go_first_16.png")))
-        out.append('</a>')
-
-        out.append(tag("a", name=_('Select previous'),
-                       href=url_for(controller="/repeatgroup",
-                                    action="select_prev", id=child_id)))
-        out.append(tag("img", src=icon("go_previous_16.png")))
-        out.append('</a>')
-
-        out.append(tag("a", name=_('Select next'),
-                       href=url_for(controller="/repeatgroup",
-                                    action="select_next", id=child_id)))
-        out.append(tag("img", src=icon("go_next_16.png")))
-        out.append('</a>')
-
-        out.append(tag("a", name=_('Select last'),
-                       href=url_for(controller="/repeatgroup",
-                                    action="select_last", id=child_id)))
-        out.append(tag("img", src=icon("go_last_16.png")))
-        out.append('</a>')
-
-        out.append(' | ?/? | ')
-
-        if not self.ro_mode:
-            out.append(tag("a", name=_('Create new'),
-                           href=url_for(controller="/repeatgroup", action="new",
-                                        id=child_id)))
-            out.append(tag("img", src=icon("formular/rg_new.png")))
-            out.append('</a>')
-
-            out.append(tag("a", name=_('Delete'),
-                           href=url_for(controller="/repeatgroup",
-                                        action="delete", id=child_id)))
-            out.append(tag("img", src=icon("formular/rg_delete.png")))
-            out.append('</a>')
-
-        out.append('</td>')
-        out.append('</tr>')
-        return out
-
-    def _renderConditional(self, conditional):
-        if isinstance(conditional, MetaNodeComponent):
-            valid = self.it.evaluate_conditional(conditional, self.current_identifier)
-        else:
-            valid = self.it.evaluate_conditional(conditional)
-        if not valid:
-            meta = self._getMeta(conditional)
-            ro = not meta.isInvisible()
-            if ro:
-                old_ro = self.ro_mode
-                self.ro_mode = True
-                for child in conditional.getChildren():
-                    self._renderChild(child)
-                self.ro_mode = old_ro
-            else:
-                pass # do nothing when it is invisible
-        else:
-            for child in conditional.getChildren():
-                self._renderChild(child)
-
-    def _renderInfo(self, node):
-        meta = self._getMeta(node)
-        out = []
-        if meta.isInvisible():
-            return
-        text = meta.getValue()
-        depth = 1 #visibleDepth(node)
-        if text:
-            out.append('<p class="text">')
-            out.append(tag("img", src=icon("formular/info.png"), width="12",
-                        height="12"))
-            out.append(escape(text))
-            out.append('</p>')
-            self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderText(self, node):
-        meta = self._getMeta(node)
-        out = []
-        id = node.getIdentifier()
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-        out.append(tag("input", name=id, id=id, value=node.getValue(),
-                       type="text", size=meta.getSize(),
-                       maxlength=meta.getMaxLength(), disabled=self.ro_mode,
-                       **SET_MODIFICATION_ATTRS))
-        out.append('<br>')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-
-    def _renderDate(self, node):
-
-        def uformat_date(value):
-            if value == "01.01.1":
-                return "unbekannt"
-            return value
-
-        meta = self._getMeta(node)
-        out = []
-        id = node.getIdentifier()
-        size = "10"
-        maxlength = "10"
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-        value = node.getValue()
-        out.append(tag("input", name=id, id=id,
-                       value=uformat_date(format_date(value)),
-                       type="text", size=size, maxlength=maxlength,
-                       disabled=self.ro_mode, class_="datefield",
-                       **SET_MODIFICATION_ATTRS))
-        out.append('<br>')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderInt(self, node):
-
-        def uformat_int(value):
-            if value == -9999999:
-                return "unbekannt"
-            return value
-
-        meta = self._getMeta(node)
-        out = []
-        id = node.getIdentifier()
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-        out.append(tag("input", name=id, id=id,
-                       value=uformat_int(node.getValue()),
-                       type="text", disabled=self.ro_mode,
-                       **SET_MODIFICATION_ATTRS))
-        out.append('<br>')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderNumeric(self, node):
-
-        def uformat_numeric(value):
-            if value == decimal.Decimal(-9999999):
-                return "unbekannt"
-            if value is not None:
-                value = format_number(float(str(value)))
-            return value
-
-        meta = self._getMeta(node)
-        out = []
-        id = node.getIdentifier()
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-        out.append(tag("input", name=id, id=id,
-                       value=uformat_numeric(node.getValue()),
-                       type="text", disabled=self.ro_mode,
-                       **SET_MODIFICATION_ATTRS))
-        out.append('<br>')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderTextArea(self, node):
-        meta = self._getMeta(node)
-        out = []
-        id = node.getIdentifier()
-        value = node.getValue() or ""
-        cols = meta.getCols() or "0"
-        rows = meta.getRows() or "0"
-        out.append(self._renderLabel(node, not self.ro_mode))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-
-        if not self.ro_mode:
-            out.append(tag("textarea", id=id, name=id, rows=rows, cols=cols,
-                           **SET_MODIFICATION_ATTRS))
-            out.append(escape(value))
-            out.append("</textarea>")
-            out.append("<br>\n")
-        else:
-            out.append('<p class="readonly">%s</p>'
-                       % (NA(nl_to_br(escape(value)))))
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderRadio(self, node):
-        meta = self._getMeta(node)
-        id = node.getIdentifier()
-        current_value = node.getValue()
-        out = []
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append("<br>\n")
-        for child in meta.getChildren():
-            value = child.getValue()
-            radio_id = child.getName()
-            out.append(tag("input", type="radio", id=radio_id, name=id,
-                           value=value, disabled=self.ro_mode,
-                           checked=(current_value == value),
-                           tabindex=self.next_tabindex(),
-                           **SET_MODIFICATION_ATTRS))
-            out.append(" ")
-            out.append(tag("label", for_=radio_id))
-            out.append(tag("a", name="f_" + radio_id))
-            out.append(escape(child.getDescription()))
-            out.append("</a>")
-            out.append("</label>")
-            out.append('<br>\n')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderPlainBool(self, node):
-        meta = self._getMeta(node)
-        id = node.getIdentifier()
-        value = node.getValue()
-        out = []
-        out.append(tag("input", type="checkbox", class_="checkbox",
-                       id=id, name=id, value="1", disabled=self.ro_mode,
-                       checked=(value == 1),
-                       tabindex=self.next_tabindex(),
-                       **SET_MODIFICATION_ATTRS))
-        out.append(hidden_bool_tag(id))
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        errors = self._renderErrors(node)
-        if errors:
-            out.append('<br>')
-            out.append(errors)
-        out.append('<br>')
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderChoice(self, node):
-        meta = self._getMeta(node)
-        id = node.getIdentifier()
-
-        out = []
-        out.append(self._renderLabel(node))
-        out.append(self._renderAttributes(node))
-        out.append('<br>')
-        out.append(tag("select", id=id, name=id, size=meta.getSize() or "1",
-                       multiple=bool(meta.getMultiple()), disabled=self.ro_mode,
-                       **SET_MODIFICATION_ATTRS))
-        self.stateStack.append(node.getValue())
-        out.append(self._renderRecursive(meta, False, ChoiceContainer))
-        self.stateStack.pop()
-        out.append('</select>')
-        out.append('<br>')
-        out.append(self._renderErrors(node))
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderChoiceGroup(self, choice):
-        meta = self._getMeta(choice)
-        out = []
-        if not self.ro_mode:
-            out.append(tag("optgroup", label=meta.getDescription()))
-            out.append("\n")
-        out.append(self._renderRecursive(meta, False, ChoiceContainer))
-        if not self.ro_mode:
-            out.append("</optgroup>\n")
-        self.toTarget(Text("".join(out)), meta.getTarget())
-
-    def _renderChoiceBool(self, bool):
-        meta = self._getMeta(bool)
-        value = meta.getValue()
-        selected = value == self.stateStack[-1]
-        out = []
-        if not self.ro_mode and not meta.isInvisible() or selected:
-            out.append(tag("option", selected=selected, value=value))
-            out.append(escape(meta.getDescription()))
-            out.append("</option>")
-
-        self.toTarget(Text("".join(out)), meta.getTarget())
-
-    def _renderMatrix(self, node):
-        meta = self._getMeta(node)
-        out = []
-        legend = []
-        out.append('<table class="radiomatrix">')
-
-        # write table header
-        nr_of_children = len(self._getMeta(node.getChildren()[0]).children) + 1
-
-        out.append('<thead>')
-        out.append('<tr>')
-        out.append(tag("th", class_="label", colspan=nr_of_children))
-        out.append(self._renderLabel(node, False))
-        out.append(self._renderAttributes(node))
-        out.append('</th>')
-        out.append('</tr>')
-
-        out.append('<tr>')
-        out.append('<th></th>')
-        for hcol in self._getMeta(node.getChildren()[0]).children:
-            hcolmeta = hcol
-            alternative = hcolmeta.getAlternative()
-            description = hcolmeta.getDescription()
-            if alternative == '':
-                header = description
-            else:
-                header = alternative
-                legend.append("<strong>%s</strong>:%s"
-                              % (escape(alternative), escape(description)))
-            out.append('<th>%s</th>' % escape(header))
-        out.append('</tr>')
-        out.append('</thead>')
-
-        # write table body
-        out.append('<tbody>')
-        for num, row in enumerate(node.getChildren()):
-            self._checkWarnings(row)
-            out.append('<tr>')
-            out.append(tag("td", class_=("label %s"
-                                         % (num % 2 and "hl" or ""))))
-            out.append(self._renderLabel(row))
-            out.extend(self._renderAttributes(row))
-            out.append('</td>')
-            self.stateStack.append(row.getValue())
-            for col in self._getMeta(row).children:
-                value = col.getValue()
-                out.append(tag("td", class_=(num%2 and "hl" or "")))
-                out.append(tag("input", type="radio", name=row.getIdentifier(),
-                               value=value, disabled=self.ro_mode,
-                               checked=(value == self.stateStack[-1]),
-                               tabindex=self.next_tabindex(),
-                               **SET_MODIFICATION_ATTRS))
-                out.append('</td>')
-            self.stateStack.pop()
-            out.append("</tr>")
-
-        # write legend
-        length = len(self._getMeta(node.getChildren()[0]).children)+1
-        out.append('<tr>')
-        out.append(tag("td", colspan=length))
-        out.append('</td></tr>')
-        if legend:
-            out.append('<tr>')
-            out.append(tag("td", class_="legend", colspan=length))
-            out.append(" ".join(legend))
-            out.append('</td>')
-            out.append('</tr>')
-        out.append('<tr>')
-        out.append(tag("td", class_="label", colspan=length))
-        out.append(self._renderErrors(node))
-        out.append('</td>')
-        out.append('</tr>')
-        out.append('</tbody>')
-        out.append('</table>')
-        out.append('<br>')
-        self.toTarget(Item("".join(out)), meta.getTarget())
-
-    def _renderPage(self, page):
-        out = []
-        out.append(self._renderRecursive(page))
-        self.toTarget(Item("\n".join(out)), self._getMeta(page).getTarget())
-
-    def _renderBool(self, bool):
-        meta = self._getMeta(bool)
-        parent = meta.parent
-        parentparent = meta.parent.parent
-
-        # Check if the bool is within a choicelist
-        if (isinstance(self._getMeta(parent), data.ChoiceNode)
-            or (isinstance(self._getMeta(parent), data.GroupNode)
-            or isinstance(self._getMeta(parent), data.ConditionalNode))
-            and isinstance(self._getMeta(parentparent), data.ChoiceNode)):
-            self._renderChoiceBool(bool)
-
-        elif isinstance(self._getMeta(parent), data.RadioNode):
-            self._renderRadioBool(bool)
-
-        else:
-            self._renderPlainBool(bool)
-
-    def _renderExternalChoiceList(self, choiceList):
-        out = []
-
-        # Sort the list according to the target
-        children = sorted(choiceList.getChildren(),
-                          key=lambda child: child.getTarget(),
-                          reverse=True)
-
-        if children:
-            for child in children:
-                value = child.getValue()
-                out.append(tag("option", value=value,
-                               selected=(value == self.stateStack[-1])))
-                out.append(escape(child.getDescription()))
-                out.append("</option>")
-        self.toTarget(Text("\n".join(out)),
-                      self._getMeta(choiceList).getTarget())
-
-    def _renderChild(self, child):
-        try:
-            # Try to get the identiefier for the current element.
-            self.current_identifier = child.getIdentifier()
-        except Exception, e:
-            # May fail in case of meta objects.
-            pass
-        self._checkWarnings(child)
-        meta = self._getMeta(child)
-        if isinstance(child, RepeatInstanceContainerNode):
-            self._renderRepeatContainer(child)
-        elif isinstance(meta, Node):
-            if isinstance(meta, data.MatrixNode):
-                self._renderMatrix(child)
-            elif (isinstance(meta, data.GroupNode)
-                  and isinstance(meta.parent, data.ChoiceNode)):
-                self._renderChoiceGroup(child)
-            elif isinstance(meta, data.GroupNode):
-                self._renderGroup(child)
-            elif isinstance(meta, data.ChoiceNode):
-                self._renderChoice(child)
-            elif isinstance(meta, data.RadioNode):
-                self._renderRadio(child)
-            elif isinstance(meta, data.PageNode):
-                self._renderPage(child)
-            elif isinstance(meta, data.ConditionalNode):
-                #if not self.it.evaluate_conditional(child):
-                #    meta = self._getMeta(child)
-                #    if not meta.isInvisible():
-                #        self._renderConditional(child)
-                #    else:
-                #        pass
-                #else:
-                #    self._renderConditional(child)
-                self._renderConditional(child)
-            else:
-                self.toTarget(Item(self._renderRecursive(child)),
-                              meta.getTarget())
-
-        elif isinstance(meta, data.InfoLeaf):
-            self._renderInfo(child)
-        elif isinstance(meta, data.BoolLeaf):
-            self._renderBool(child)
-        elif isinstance(meta, data.TextLeaf):
-            self._renderText(child)
-        elif isinstance(meta, data.TextAreaLeaf):
-            self._renderTextArea(child)
-        elif isinstance(meta, data.IntLeaf):
-            self._renderInt(child)
-        elif isinstance(meta, data.NumericLeaf):
-            self._renderNumeric(child)
-        elif isinstance(meta, data.DateLeaf):
-            self._renderDate(child)
-        elif isinstance(meta, data.ExternalChoiceListLeaf):
-            self._renderExternalChoiceList(child)
-        else:
-            log.debug("Unhandled child %r", child)
-
-    def _renderRecursive(self, node, doBreak=True, Cont=Container):
-        meta = self._getMeta(node)
-        self.containersStack.append([Cont(c)
-                                     for c in meta.getParsedContainers()]
-                                    + [Cont(None)])
-
-        for child in node.getChildren():
-            self._renderChild(child)
-
-        out = []
-        for c in self.containersStack.pop():
-            txt = c.render(doBreak)
-            if txt:
-                out.append(txt)
-        return "".join(out)
-
-
-class RepeatGroupRenderer(ViewRenderer):
-
-    def __init__(self, it=None, page=None, ro_mode=True, digests=None):
-        ViewRenderer.__init__(self, it, page, ro_mode)
-        if digests is None:
-            digests = {}
-        self.rg_digests = digests
-
-    def render_digest(self, rg, fields):
-        out = []
-        case_id = rg.getIdentifier().split(':')[-1]
-
-        out.append('<table class="rgdigest">')
-        if not fields:
-            log.warning("No digest specification for repeat group %r",
-                        rg.getIdentifier())
-            out.append('<tr><td>%s</td></tr>' % escape(rg.getIdentifier()))
-        else:
-            child_identifier = rg.getChildren()[0].getIdentifier()
-            rg_identifier = rg.getInternalIdentifier()
-            for field in fields:
-                description, value = self.get_field_info(case_id, rg_identifier,
-                                                         field)
-                if description is None:
-                    continue
-                out.append('<tr>')
-                out.append('<td class="label">')
-                out.append(tag("a", href=url_for(controller="/navigation",
-                                                 action="select_branch",
-                                                 id=child_identifier)))
-                out.append(escape(description))
-                out.append('</a>')
-                out.append('</td>')
-                out.append('<td>')
-                out.append(tag("a", href=url_for(controller="/navigation",
-                                                 action="select_branch",
-                                                 id=child_identifier)))
-                out.append('%s' % NA(value))
-                out.append('</a>')
-                out.append('</td>')
-                out.append('</tr>')
-        out.append('</table>')
-        return "".join(out)
-
-    def get_field_info(self, case_id, rg_identifier, field):
-        """Return description and formatted value for the given digest field.
-        If the item referred to by the field would be invisible in the
-        rendered repeat group instance due to visibility conditionals,
-        the method returns (None, None) to indicate that it shouldn't be
-        rendered in the digest either.
-        """
-        item = self.it.getItem('%s:%s:%s' % (field, rg_identifier, case_id))
-
-        # check whether the item would be visible according to the
-        # conditionals containing it.
-        for conditional in self.get_conditional_parents(item):
-            if (conditional.getMeta().isInvisible()
-                and not self.it.evaluate_conditional(conditional)):
-                return None, None
-
-        meta = self._getMeta(item)
-        value = item.getValue()
-        if isinstance(meta, data.DateLeaf):
-            value = format_date(value)
-        if isinstance(meta, data.ChoiceNode):
-            childs = []
-            for child in meta.getChildren():
-                if isinstance(child, data.GroupNode):
-                    childs.extend(child.getChildren())
-                else:
-                    childs.append(child)
-            for child in childs:
-                if str(child.getValue()) == str(value):
-                    value = child.getDescription()
-                    break
-        return (meta.getDescription(), value)
-
-    def get_conditional_parents(self, item):
-        """Return a list with the conditionals containing item.
-
-        The conditionals are the conditional nodes from the intance
-        tree.  The order of the conditionals in the return value is from
-        root to leaf.
-        """
-        conditionals = []
-        while item:
-            if isinstance(item.getMeta(), data.ConditionalNode):
-                conditionals.append(item)
-            item = item.getParent()
-        return reversed(conditionals)
-
-    def render(self, showNext=False):
-        out = []
-        out.append('<div class="widget">')
-        out.append('<table class="list" style="margin:0px;">')
-        out.append('<tr><th class="table_width_small"></th><th colspan>%s</th><th class="actions">%s</th>'
-                   % (escape(_('Description')),
-                      escape(_('Actions'))))
-        items = self.page.getChildren()
-
-        # Sorting of RG.
-        class SortDummy:
-            def __init__(self, rg, it, case_id, sort_field, fields):
-                self.rg = rg
-                self.value = unicode(it.getItem('%s:%s:%s'
-                                                % (sort_field,
-                                                   rg.getInternalIdentifier(),
-                                                   case_id)).getValue())
-                self.fields = fields
-
-        unsorted_items = []
-        reverse_order = False
-        if len(items) > 0:
-            rg = items[0]
-            case_id = rg.getIdentifier().split(':')[-1]
-            digest_spec = self.rg_digests.get(self._getMeta(rg).getName())
-            if digest_spec is None:
-                log.error("No digest specification for %r", rg)
-            else:
-                fields = digest_spec.get('fields')
-                sort_field = digest_spec.get('sort_field', fields[0])
-                sort_order = digest_spec.get('sort_order')
-                for rg in items:
-                    unsorted_items.append(SortDummy(rg, self.it, case_id,
-                                                    sort_field, fields))
-                if sort_order == "desc":
-                    reverse_order = True
-        sorted_items = sorted(unsorted_items, key=lambda rg: rg.value,
-                              reverse=reverse_order)
-
-        for num, sd in enumerate(sorted_items):
-            out.append('<tr class="%s">' % (num%2 and "hl" or ""))
-            out.append('<td align="center">')
-            out.append('<strong>')
-            out.append('(%s)' % (num+1))
-            out.append('</strong>')
-            out.append('</td>')
-            out.append('<td>')
-            out.append(self.render_digest(sd.rg, sd.fields))
-            out.append('</td>')
-            out.append('<td class="actions hcontrol">')
-            out.append(tag("a",
-                           href=url_for(controller="/navigation",
-                                        action="select_branch",
-                                   id=sd.rg.getChildren()[0].getIdentifier())))
-            out.append(tag("img", src=icon("open_active_22.png"),
-                           border="0", alt=_('view'), title=_('view'),
-                           height="22",
-                           width="22"))
-            out.append("</a>")
-            if not self.ro_mode:
-                out.append(tag("a", href=url_for(controller="/repeatgroup",
-                                                 action="delete",
-                                                 id=sd.rg.getIdentifier())))
-                out.append(tag("img", src=icon("delete_active_22.png"),
-                               border="0", alt=_('delete'), title=_('delete'),
-                               height="22",
-                               width="22"))
-                out.append("</a>")
-            out.append('</td>')
-            out.append('</tr>')
-
-        out.append('<tr class="background_slight">')
-        out.append('<td></td>')
-        out.append('<td style="text-align:right;">')
-        out.append('</td>')
-        out.append('<td class="actions">')
-        if not self.ro_mode:
-            out.append(tag("a",
-                           href=url_for(controller="/repeatgroup", action="new",
-                                        id=self.page.getIdentifier())))
-
-            out.append(tag("img", src=icon("new_22.png"),
-                           border="0", alt=_('Add new RG'),
-                           title=_('Add new RG'),
-                           height="22",
-                           width="22"))
-            out.append("</a>")
-        out.append('</td>')
-        out.append('</tr>')
-        out.append('</table>')
-        out.append('</div>')
-        out.append('<div>%s %s</div>'
-                   % (len(self.page.getChildren()),
-                      escape(ungettext('Item found', 'Items found',
-                                       len(self.page.getChildren())))))
-
-        return "\n".join(out)
-
-
-class ErrorRenderer(object):
-
-    def __init__(self, error_items, warnings, notices, widget_order):
-        self.error_items = error_items
-        self.warnings = warnings
-        self.notices = notices
-        self.widget_order = widget_order
-
-    def in_widget_order(self, items):
-        """Generate the items in the dictionary items in widget order.
-        The dictionary should map widget ids to errors or warnings.
-        The widget order is defined by the widget_order parameter given
-        to the constructor when the ErrorRenderer was instantiated.
-        """
-        copy = items.copy()
-        for id in self.widget_order:
-            value = copy.pop(id, None)
-            if value is not None:
-                yield (id, value)
-        if copy:
-            # This shouldn't happen, but if it does happen, log a debug
-            # message and yield the rest of the items in an arbitrary
-            # order, so that all are at least shown to the user.
-            log.debug("ErrorRenderer: not all items occur in the widget_order"
-                      " list")
-            for key, value in copy.iteritems():
-                yield (key, value)
-
-    def render(self, page):
-        tree = page.getInstanceTree()
-
-        out = []
-        out.append(self.render_items(self.error_items, _('Formular errors'),
-                                     icon("info/alert.png"), tree))
-        out.append(self.render_items(self.notices, _('Formular notices'),
-                                     icon("info/info.png"), tree,
-                                     css_class='warning-box',
-                                     show_undo=False))
-        out.append(self.render_items(self.warnings, _('Formular warnings'),
-                                     icon("info/info.png"), tree,
-                                     css_class='warning-box',
-                                     show_undo=False))
-        return "".join(out)
-
-    def render_items(self, items, title, title_icon, tree, css_class="",
-                     show_undo=True, img_width=48, img_height=48):
-        if not items:
-            return ""
-
-        out = []
-        out.append(tag("div", class_=("widget dialog %s" % css_class)))
-        out.append('<h1>')
-        
-        out.append(tag("img", src=title_icon, alt='', width=img_width, height=img_height))
-        out.append(escape(title))
-        out.append('</h1>')
-        out.append('<ol>')
-
-        for k, values in self.in_widget_order(items):
-            element = tree.getFormEd().findByName(k.split(':')[0])
-            description = element.getDescription()
-            # the values in the items dict may either be strings or
-            # lists of strings.
-            if not isinstance(values, list):
-                values = [values]
-            for v in values:
-                out.append('<li>')
-                if show_undo:
-                    out.append(tag("a", href=url_for(controller="/formularpage",
-                                                     action="undo", id=k)))
-                    out.append(tag("img", src=icon("formular/undo.png"),
-                                   border="0", alt="undo",
-                                   title=_('Restore last valid value'),
-                                   _close=True))
-                    out.append('</a>')
-                out.append(tag("a", class_="error", href="#f_%s" % k))
-                out.append("%s:</a>" % escape(description))
-                out.append(" %s" % (escape(v)))
-                out.append("</li>")
-
-        out.append('</ol>')
-        out.append('</div>')
-        return "".join(out)
-
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8:



More information about the Mpuls-commits mailing list