Widget.py 68 KB
Newer Older
Nicolas Delaby's avatar
Nicolas Delaby committed
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8
import string
from DummyField import fields
from DocumentTemplate.DT_Util import html_quote
from DateTime import DateTime
from cgi import escape
import types
from DocumentTemplate.ustr import ustr
9
from urlparse import urljoin
10
from lxml import etree
11
from lxml.etree import Element, SubElement
12
from lxml.builder import ElementMaker
13
import re
14 15 16

DRAW_URI = 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'
TEXT_URI = 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'
17 18 19
FORM_URI = 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'
OFFICE_URI = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'

20 21
NSMAP = {
          'draw': DRAW_URI,
22 23 24
          'text': TEXT_URI,
          'form': FORM_URI,
          'office': OFFICE_URI,
25
        }
26

27 28
EForm = ElementMaker(namespace=FORM_URI, nsmap=NSMAP)

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
RE_OOO_ESCAPE = re.compile(r'([\n\t])?([^\n\t]*)')
def ooo_escape(match_object):
  """Replacement function to use inside re.sub expression.
  This function replace \t by <text:tab/>
                        \n by <text:line-break/>
  - parent_node is a global variable used to carry new nodes.
  """
  match_value = match_object.group(1)
  if match_value is None:
    parent_node.text = match_object.group(2)
  elif match_value == '\n':
    line_break = SubElement(parent_node, '{%s}%s' % (TEXT_URI, 'line-break'))
    line_break.tail = match_object.group(2)
  elif match_value == '\t':
    line_break = SubElement(parent_node, '{%s}%s' % (TEXT_URI, 'tab'))
    line_break.tail = match_object.group(2)

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
class Widget:
  """A field widget that knows how to display itself as HTML.
  """

  property_names = ['title', 'description',
                    'default', 'css_class', 'alternate_name',
                    'hidden']

  title = fields.StringField('title',
                              title='Title',
                              description=(
      "The title of this field. This is the title of the field that "
      "will appear in the form when it is displayed. Required."),
                              default="",
                              required=1)

  description = fields.TextAreaField('description',
                                      title='Description',
                                      description=(
      "Description of this field. The description property can be "
      "used to add a short description of what a field does; such as "
      "this one."),
                                      default="",
                                      width="20", height="3",
                                      required=0)

  css_class = fields.StringField('css_class',
                                  title='CSS class',
                                  description=(
      "The CSS class of the field. This can be used to style your "
      "formulator fields using cascading style sheets. Not required."),
                                  default="",
                                  required=0)

  alternate_name = fields.StringField('alternate_name',
                                      title='Alternate name',
                                      description=(
      "An alternative name for this field. This name will show up in "
      "the result dictionary when doing validation, and in the REQUEST "
      "if validation goes to request. This can be used to support names "
      "that cannot be used as Zope ids."),
                                      default="",
                                      required=0)

  hidden = fields.CheckBoxField('hidden',
                                title="Hidden",
                                description=(
      "This field will be on the form, but as a hidden field. The "
      "contents of the hidden field will be the default value. "
      "Hidden fields are not visible but will be validated."),
                                default=0)

  # NOTE: for ordering reasons (we want extra at the end),
  # this isn't in the base class property_names list, but
  # instead will be referred to by the subclasses.
  extra = fields.StringField('extra',
                              title='Extra',
                              description=(
      "A string containing extra HTML code for attributes. This "
      "string will be literally included in the rendered field."
      "This property can be useful if you want "
      "to add an onClick attribute to use with JavaScript, for instance."),
                              default="",
                              required=0)

  def render(self, field, key, value, REQUEST):
      """Renders this widget as HTML using property values in field.
      """
      return "[widget]"

  def render_hidden(self, field, key, value, REQUEST, render_prefix=None):
    """Renders this widget as a hidden field.
    """
    try:
      extra = field.get_value('extra')
    except KeyError:
    # In case extra is not defined as in DateTimeWidget
      extra = ''
    result = ''
    # We must adapt the rendering to the type of the value
    # in order to get the correct type back
    if isinstance(value, (tuple, list)):
      for v in value:
        result += render_element("input",
                          type="hidden",
                          name="%s:list" % key,
                          value=v,
                          extra=extra)
    else:
      result = render_element("input",
                          type="hidden",
                          name=key,
                          value=value,
                          extra=extra)
    return result

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """Renders this widget for public viewing.
    """
    # default implementation
    if value is None:
      return ''
    return value

  render_pdf = render_view

  def render_html(self, *args, **kw):
    return self.render(*args, **kw)

  def render_htmlgrid(self, field, key, value, REQUEST, render_prefix=None):
    """
    render_htmlgrid returns a list of tuple (title, html render)
    """
    # XXX Calling _render_helper on the field is not optimized
    return ((field.get_value('title'), 
            field._render_helper(key, value, REQUEST, render_prefix=render_prefix)),)
  def render_css(self, field, REQUEST):
    """
      Default render css for widget - to be overwritten in field classes.
      Should return valid css code as string.
      The value returned by this method will be used as inline style for a field.
    """
    pass

  def get_css_list(self, field, REQUEST):
    """
      Return CSS needed by the widget - to be overwritten in field classes.
      Should return a list of CSS file names.
      These names will be appended to global css_list and included in a rendered page.
    """
    return []

  def get_javascript_list(self, field, REQUEST):
    """
      Return JS needed by the widget - to be overwritten in field classes.
      Should return a list of javascript file names.
      These names will be appended to global js_list and included in a rendered page.
    """
    return []

  def render_dict(self, field, value):
    """
    This is yet another field rendering. It is designed to allow code to
    understand field's value data by providing its type and format when
    applicable.
    """
    return None

194
  def render_odt(self, field, value, as_string, ooo_builder, REQUEST,
195 196 197
                 render_prefix, attr_dict, local_name):
    """This render dedicated to render fields inside OOo document
      (eg. editable mode)
198
    """
199 200 201 202 203 204 205 206
    # XXX By default fallback to render_odt_view
    return self.render_odt_view(field, value, as_string, ooo_builder, REQUEST,
      render_prefix, attr_dict, local_name)

  def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
                      render_prefix, attr_dict, local_name):
    """
      Return a field value rendered in odt format as read-only mode.
207 208
      - as_string return value as string or as xml object
      - attr_dict can be used for additional attributes (like style).
209 210
      - ooo_builder wrapper of ODF zipped archive usefull to insert images
      - local_name local-name of the node returned by this render
211 212 213
    """
    if attr_dict is None:
      attr_dict = {}
214 215 216
    if isinstance(value, str):
      #required by lxml
      value = value.decode('utf-8')
217
    text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
218
    text_node.text = value
219 220 221 222 223
    text_node.attrib.update(attr_dict)
    if as_string:
      return etree.tostring(text_node)
    return text_node

224
  def render_odg(self, field, value, as_string, ooo_builder, REQUEST,
225
      render_prefix, attr_dict, local_name):
226 227
    """
      Default render odg for widget - to be overwritten in field classes.
228
      Return a field node rendered in odg format.
229 230 231 232
      - as_string return value as string or as xml object
      - attr_dict can be used for additional attributes (like style).
      - ooo_builder wrapper of ODF zipped archive usefull to insert images
      - local_name local-name of the node returned by this render
233
    """
234 235
    if attr_dict is None:
      attr_dict = {}
236 237 238
    if isinstance(value, str):
      #required by lxml
      value = value.decode('utf-8')
239 240
    draw_frame_tag_name = '{%s}%s' % (DRAW_URI, 'frame')
    draw_frame_node = Element(draw_frame_tag_name, nsmap=NSMAP)
241 242
    if len(attr_dict.get(draw_frame_tag_name, {})) > 0:
      draw_frame_node.attrib.update(attr_dict.get(draw_frame_tag_name, {}).pop(0))
243

244 245
    draw_tag_name = '{%s}%s' % (DRAW_URI, 'text-box')
    draw_node = Element(draw_tag_name, nsmap=NSMAP)
246 247
    if len(attr_dict.get(draw_tag_name, {})) > 0:
      draw_node.attrib.update(attr_dict.get(draw_tag_name, {}).pop(0))
248

249
    text_p_tag_name = '{%s}%s' % (TEXT_URI, 'p')
250
    text_p_node = Element(text_p_tag_name, nsmap=NSMAP)
251 252
    if len(attr_dict.get(text_p_tag_name, {})) > 0:
      text_p_node.attrib.update(attr_dict.get(text_p_tag_name, {}).pop(0))
253

254 255
    text_span_tag_name = '{%s}%s' % (TEXT_URI, 'span')
    text_span_node =  Element(text_span_tag_name, nsmap=NSMAP)
256 257
    if len(attr_dict.get(text_span_tag_name, {})) > 0:
      text_span_node.attrib.update(attr_dict.get(text_span_tag_name, {}).pop(0))
258

259 260
    text_p_node.append(text_span_node)
    draw_node.append(text_p_node)
261
    draw_frame_node.append(draw_node)
262

263 264 265
    global parent_node
    parent_node = text_span_node
    RE_OOO_ESCAPE.sub(ooo_escape, value)
266
    if as_string:
267 268
      return etree.tostring(draw_frame_node)
    return draw_frame_node
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
class TextWidget(Widget):
  """Text widget
  """
  property_names = Widget.property_names +\
                    ['display_width', 'display_maxwidth', 'extra']

  default = fields.StringField('default',
                                title='Default',
                                description=(
      "You can place text here that will be used as the default "
      "value of the field, unless the programmer supplies an override "
      "when the form is being generated."),
                                default="",
                                required=0)

  display_width = fields.IntegerField('display_width',
                                      title='Display width',
                                      description=(
      "The width in characters. Required."),
                                      default=20,
                                      required=1)

  display_maxwidth = fields.IntegerField('display_maxwidth',
                                          title='Maximum input',
                                          description=(
      "The maximum input in characters that the widget will allow. "
      "Required. If set to 0 or is left empty, there is no maximum. "
      "Note that is client side behavior only."),
                                          default="",
                                          required=0)

  def render(self, field, key, value, REQUEST, render_prefix=None):
    """Render text input field.
    """
    display_maxwidth = field.get_value('display_maxwidth') or 0
    if display_maxwidth > 0:
      return render_element("input",
                            type="text",
                            name=key,
                            css_class=field.get_value('css_class'),
                            value=value,
                            size=field.get_value('display_width'),
                            maxlength=display_maxwidth,
                            extra=field.get_value('extra'))
    else:
      return render_element("input",
                            type="text",
                            name=key,
                            css_class=field.get_value('css_class'),
                            value=value,
                            size=field.get_value('display_width'),
                            extra=field.get_value('extra'))

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """Render text as non-editable.
      This renderer is designed to be type error resistant.
      in we get a non string value. It does escape the result
      and produces clean xhtml.
      Patch the render_view of TextField to enclose the value within <span> html tags if css class defined
    """
    if value is None:
      return ''
    if isinstance(value, types.ListType) or isinstance(value, types.TupleType):
      old_value = value
    else:
      old_value = [str(value)]
    value = []
    for line in old_value:
      value.append(escape(line))
    value = '<br/>'.join(value)
340 341 342 343 344

    extra = field.get_value('extra')
    if extra not in (None, ''):
      value = "<div %s>%s</div>" % (extra, value)

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    css_class = field.get_value('css_class')
    if css_class not in ('', None):
      # All strings should be escaped before rendering in HTML
      # except for editor field
      return "<span class='%s'>%s</span>" % (css_class, value)
    return value

TextWidgetInstance = TextWidget()

class PasswordWidget(TextWidget):

  def render(self, field, key, value, REQUEST, render_prefix=None):
      """Render password input field.
      """
      display_maxwidth = field.get_value('display_maxwidth') or 0
      if display_maxwidth > 0:
          return render_element("input",
                                type="password",
                                name=key,
                                css_class=field.get_value('css_class'),
                                value=value,
                                size=field.get_value('display_width'),
                                maxlength=display_maxwidth,
                                extra=field.get_value('extra'))
      else:
          return render_element("input",
                                type="password",
                                name=key,
                                css_class=field.get_value('css_class'),
                                value=value,
                                size=field.get_value('display_width'),
                                extra=field.get_value('extra'))

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
      return "[password]"

PasswordWidgetInstance = PasswordWidget()

class CheckBoxWidget(Widget):
  property_names = Widget.property_names + ['extra']

  default = fields.CheckBoxField('default',
                                  title='Default',
                                  description=(
      "Default setting of the widget; either checked or unchecked. "
      "(true or false)"),
                                  default=0)

  def render(self, field, key, value, REQUEST, render_prefix=None):
    """Render checkbox.
    """
    rendered = [render_element("input",
                              type="hidden",
                              name="default_%s:int" % (key, ),
                              value="0")
              ]

    if value:
      rendered.append(render_element("input",
                                    type="checkbox",
                                    name=key,
                                    css_class=field.get_value('css_class'),
                                    checked=None,
                                    extra=field.get_value('extra'))
                    )
    else:
      rendered.append(render_element("input",
                                    type="checkbox",
                                    name=key,
                                    css_class=field.get_value('css_class'),
                                    extra=field.get_value('extra'))
                    )
    return "".join(rendered)

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """Render checkbox in view mode.
    """
    if value:
      return render_element("input",
                            type="checkbox",
                            css_class=field.get_value('css_class'),
                            checked=1,
                            extra=field.get_value('extra'),
                            disabled='disabled')
    else:
      return render_element("input",
                            type="checkbox",
                            css_class=field.get_value('css_class'),
                            extra=field.get_value('extra'),
                            disabled='disabled')
435

436 437
  def render_odt(self, field, value, as_string, ooo_builder, REQUEST,
      render_prefix, attr_dict, local_name):
438 439 440
    """
    <form:checkbox form:name="is_accepted"
                   form:control-implementation="ooo:com.sun.star.form.component.CheckBox"
441
                   form:current-state="checked"
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
                   form:id="control1"
                   form:image-position="center">
      <form:properties>
        <form:property form:property-name="DefaultControl" office:value-type="string" office:string-value="com.sun.star.form.control.CheckBox"/>
        <form:property form:property-name="SecondaryRefValue" office:value-type="string" office:string-value=""/>
      </form:properties>
    </form:checkbox>
    """
    if attr_dict is None:
      attr_dict = {}
    form_node = EForm.checkbox(
                  EForm.properties(
                    EForm.property(**{'{%s}property-name' % FORM_URI: 'DefaultControl',
                                      '{%s}value-type' % OFFICE_URI: 'string',
                                      '{%s}string-value' % OFFICE_URI: 'com.sun.star.form.control.CheckBox'}),
                    EForm.property(**{'{%s}property-name' % FORM_URI: 'SecondaryRefValue',
                                      '{%s}value-type' % OFFICE_URI: 'string',
                                      '{%s}string-value' % OFFICE_URI: ''}),
                  )
                )

    current_state_attribute_name = '{%s}current-state'% FORM_URI
464
    if value:
465 466 467 468 469 470 471 472
      attr_dict.update({current_state_attribute_name: 'checked'})
    elif attr_dict.has_key(current_state_attribute_name):
      del attr_dict[current_state_attribute_name]
    form_node.attrib.update(attr_dict)
    if as_string:
      return etree.tostring(form_node)
    return form_node

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
      render_prefix, attr_dict, local_name):
    """
    """
    if attr_dict is None:
      attr_dict = {}
    if isinstance(value, int):
      value = str(value)
    if isinstance(value, str):
      #required by lxml
      value = value.decode('utf-8')
    text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
    text_node.text = value
    text_node.attrib.update(attr_dict)
    if as_string:
      return etree.tostring(text_node)
    return text_node

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
CheckBoxWidgetInstance = CheckBoxWidget()

class TextAreaWidget(Widget):
    """Textarea widget
    """
    property_names = Widget.property_names +\
                     ['width', 'height', 'extra']
    
    default = fields.TextAreaField('default',
                                   title='Default',
                                   description=(
        "Default value of the text in the widget."),
                                   default="",
                                   width=20, height=3,
                                   required=0)
    
    width = fields.IntegerField('width',
                                title='Width',
                                description=(
        "The width (columns) in characters. Required."),
                                default=40,
                                required=1)

    height = fields.IntegerField('height',
                                 title="Height",
                                 description=(
        "The height (rows) in characters. Required."),
                                 default=5,
                                 required=1)

    def render(self, field, key, value, REQUEST, render_prefix=None):
      width = field.get_value('width', REQUEST=REQUEST)
      height = field.get_value('height', REQUEST=REQUEST)

      return render_element("textarea",
                            name=key,
                            css_class=field.get_value('css_class'),
                            cols=width,
                            rows=height,
                            contents=html_quote(value),
                            extra=field.get_value('extra'))

    def render_view(self, field, value, REQUEST, render_prefix=None):
534 535 536 537
        return render_element("div",
                              css_class=field.get_value('css_class'),
                              contents=html_quote(value),
                              extra=field.get_value('extra'))
538

539
    def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
540
        render_prefix, attr_dict, local_name):
541 542
        if attr_dict is None:
            attr_dict = {}
543 544 545
        if isinstance(value, str):
            #required by lxml
            value = value.decode('utf-8')
546
        text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
547 548 549 550

        global parent_node
        parent_node = text_node
        RE_OOO_ESCAPE.sub(ooo_escape, value)
551 552 553 554 555
        text_node.attrib.update(attr_dict)
        if as_string:
            return etree.tostring(text_node)
        return text_node

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
TextAreaWidgetInstance = TextAreaWidget()

class LinesTextAreaWidget(TextAreaWidget):
  property_names = Widget.property_names +\
                    ['width', 'height', 'view_separator', 'extra']

  default = fields.LinesField('default',
                              title='Default',
                              description=(
      "Default value of the lines in the widget."),
                              default=[],
                              width=20, height=3,
                              required=0)

  view_separator = fields.StringField('view_separator',
                                      title='View separator',
                                      description=(
      "When called with render_view, this separator will be used to "
      "render individual items."),
                                      width=20,
                                      default='<br />\n',
                                      whitespace_preserve=1,
                                      required=1)

  def render(self, field, key, value, REQUEST, render_prefix=None):
    """
    If type definition is missing for LinesField, the input text will be
    splitted into list like ['f', 'o', 'o'] with original Formulator's
    implementation. So explicit conversion to list is required before
    passing to LinesTextAreaWidget's render and render_view methods.
    """
    if isinstance(value, (str, unicode)):
      value = [value]
    value = string.join(value, "\n")
    return TextAreaWidget.render(self, field, key, value, REQUEST)

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    if value is None:
      return ''
    elif isinstance(value, (str, unicode)):
      value = [value]
597 598 599 600 601 602
    return TextAreaWidget.render_view(
        self,
        field,
        string.join(value, field.get_value('view_separator')),
        REQUEST,
    )
603

604
  def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
605 606 607 608 609 610
      render_prefix, attr_dict, local_name):
    if value is None:
      value = ['']
    elif isinstance(value, (str, unicode)):
      value = [value]
    value = '\n'.join(value)
611
    return TextAreaWidget.render_odt_view(self, field, value, as_string,
612 613 614
                                     ooo_builder, REQUEST, render_prefix,
                                     attr_dict, local_name)

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
LinesTextAreaWidgetInstance = LinesTextAreaWidget()

class FileWidget(TextWidget):

    def render(self, field, key, value, REQUEST, render_prefix=None):
        """Render text input field.
        """
        display_maxwidth = field.get_value('display_maxwidth') or 0
        if display_maxwidth > 0:
            return render_element("input",
                                  type="file",
                                  name=key,
                                  css_class=field.get_value('css_class'),
                                  value=value,
                                  size=field.get_value('display_width'),
                                  maxlength=display_maxwidth,
                                  extra=field.get_value('extra'))
        else:
            return render_element("input",
                                  type="file",
                                  name=key,
                                  css_class=field.get_value('css_class'),
                                  value=value,
                                  size=field.get_value('display_width'),
                                  extra=field.get_value('extra'))

    def render_view(self, field, value, REQUEST=None, render_prefix=None):
        return "[File]"
    
FileWidgetInstance = FileWidget()

class ItemsWidget(Widget):
    """A widget that has a number of items in it.
    """
    
    items = fields.ListTextAreaField('items',
                                     title='Items',
                                     description=(
        "Items in the field. Each row should contain an "
        "item. Use the | (pipe) character to separate what is shown "
        "to the user from the submitted value. If no | is supplied, the "
        "shown value for the item will be identical to the submitted value. "
        "Internally the items property returns a list. If a list item "
        "is a single value, that will be used for both the display and "
        "the submitted value. A list item can also be a tuple consisting "
        "of two elements. The first element of the tuple should be a string "
        "that is name of the item that should be displayed. The second "
        "element of the tuple should be the value that will be submitted. "
        "If you want to override this property you will therefore have "
        "to return such a list."),

                                     default=[],
                                     width=20,
                                     height=5,
                                     required=0)

    # NOTE: for ordering reasons (we want extra at the end),
    # this isn't in the base class property_names list, but
    # instead will be referred to by the subclasses.
    extra_item = fields.StringField('extra_item',
                               title='Extra per item',
                               description=(
        "A string containing extra HTML code for attributes. This "
        "string will be literally included each of the rendered items of the "
        "field. This property can be useful if you want "
        "to add a disabled attribute to disable all contained items, for "
        "instance."),
                               default="",
                               required=0)

class SingleItemsWidget(ItemsWidget):
  """A widget with a number of items that has only a single
  selectable item.
  """
  default = fields.StringField('default',
                                title='Default',
                                description=(
      "The default value of the widget; this should be one of the "
      "elements in the list of items."),
                                default="",
                                required=0)

  first_item = fields.CheckBoxField('first_item',
                                    title="Select First Item",
                                    description=(
      "If checked, the first item will always be selected if "
      "no initial default value is supplied."),
                                    default=0)

  def render_items(self, field, key, value, REQUEST, render_prefix=None):
    # get items
    cell = getattr(REQUEST, 'cell', None)
    items = field.get_value('items', REQUEST=REQUEST, cell=cell)
    if not items:
      # single item widget should have at least one child in order to produce
      # valid XHTML; disable it so user can not select it
      return [self.render_item('', '', '', '', 'disabled="disabled"')]

    # check if we want to select first item
    if not value and field.get_value('first_item', REQUEST=REQUEST,
                                    cell=cell) and len(items) > 0:
      try:
        text, value = items[0]
      except ValueError:
        value = items[0]

    css_class = field.get_value('css_class')
    extra_item = field.get_value('extra_item')

    # if we run into multiple items with same value, we select the
    # first one only (for now, may be able to fix this better later)
    selected_found = 0
    rendered_items = []
    for item in items:
      try:
        item_text, item_value = item
      except ValueError:
        item_text = item
        item_value = item

      if item_value == value and not selected_found:
        rendered_item = self.render_selected_item(escape(ustr(item_text)),
                                                  item_value,
                                                  key,
                                                  css_class,
                                                  extra_item)
        selected_found = 1
      else:
        rendered_item = self.render_item(escape(ustr(item_text)),
                                          item_value,
                                          key,
                                          css_class,
                                          extra_item)

      rendered_items.append(rendered_item)

    # XXX We want to make sure that we always have the current value in items. -yo
    if not selected_found and value:
      value = escape(ustr(value))
      rendered_item = self.render_selected_item('??? (%s)' % value,
                                                value,
                                                key,
                                                css_class,
                                                extra_item)
      rendered_items.append(rendered_item)

    return rendered_items

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """
    This method is not as efficient as using a StringField in read only.
    Always consider to change the field in your Form.
    """
    if value is None:
        return ''
    title_list = [x[0] for x in field.get_value("items", REQUEST=REQUEST) if x[1]==value]
    if len(title_list) == 0:
      return "??? (%s)" % escape(value)
    else:
      return title_list[0]
    return value

  render_pdf = render_view

class MultiItemsWidget(ItemsWidget):
  """A widget with a number of items that has multiple selectable
  items.
  """
  default = fields.LinesField('default',
                              title='Default',
                              description=(
      "The initial selections of the widget. This is a list of "
      "zero or more values. If you override this property from Python "
      "your code should return a Python list."),
                              width=20, height=3,
                              default=[],
                              required=0)

  view_separator = fields.StringField('view_separator',
                                      title='View separator',
                                      description=(
      "When called with render_view, this separator will be used to "
      "render individual items."),
                                      width=20,
                                      default='<br />\n',
                                      whitespace_preserve=1,
                                      required=1)

  def render_items(self, field, key, value, REQUEST, render_prefix=None):
    # list is needed, not a tuple
    if isinstance(value, tuple):
      value = list(value)
    # need to deal with single item selects
    if not isinstance(value, list):
      value = [value]

    # XXX -yo
    selected_found = {}

    items = field.get_value('items', REQUEST=REQUEST, cell=getattr(REQUEST, 'cell', None)) # Added request
    from Products.ERP5Form.MultiLinkField import MultiLinkFieldWidget
    if not items and not isinstance(self, MultiLinkFieldWidget):
      # multi items widget should have at least one child in order to produce
      # valid XHTML; disable it so user can not select it.
      # This cannot be applied to MultiLinkFields, which are just some <a>
      # links
      return [self.render_item('', '', '', '', 'disabled="disabled"')]

    css_class = field.get_value('css_class')
    extra_item = field.get_value('extra_item')
    rendered_items = []

    for item in items:
      try:
        item_text, item_value = item
      except ValueError:
        item_text = item
        item_value = item

      if item_value in value:
        rendered_item = self.render_selected_item(
            escape(ustr(item_text)),
            escape(ustr(item_value)),
            key,
            css_class,
            extra_item)
        # XXX -yo
        index = value.index(item_value)
        selected_found[index] = 1
      else:
        rendered_item = self.render_item(
            escape(ustr(item_text)),
            escape(ustr(item_value)),
            key,
            css_class,
            extra_item)
      rendered_items.append(rendered_item)

    # XXX We want to make sure that we always have the current value in items. -yo
    for index in range(len(value)):
      v = value[index]
      if index not in selected_found and v:
        v = escape(v)
        rendered_item = self.render_selected_item('??? (%s)' % v,
                                                  v,
                                                  key,
                                                  css_class,
                                                  extra_item)
        rendered_items.append(rendered_item)

    # Moved marked field to Render
    # rendered_items.append(render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0"))
    return rendered_items

869
  def render_items_view(self, field, value, REQUEST):
870 871 872
      if type(value) is not type([]):
          value = [value]

873 874 875
      items = field.get_value('items',
                              REQUEST=REQUEST,
                              cell=getattr(REQUEST, 'cell', None))
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
      d = {}
      for item in items:
          try:
              item_text, item_value = item
          except ValueError:
              item_text = item
              item_value = item
          d[item_value] = item_text
      result = []
      for e in value:
          result.append(d[e])
      return result

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
      if value is None:
          return ''
892
      return string.join(self.render_items_view(field, value, REQUEST),
893 894
                          field.get_value('view_separator'))

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  def render_items_odf(self, field, value, REQUEST):
    if type(value) is not type([]):
      value = [value]

    items = field.get_value('items',
                            REQUEST=REQUEST,
                            cell=getattr(REQUEST, 'cell', None))
    d = {}
    for item in items:
      try:
        item_text, item_value = item
      except ValueError:
        item_text = item
        item_value = item
      d[item_value] = item_text
    result = []
    for e in value:
      result.append(d[e].replace('\xc2\xa0', ''))
    return result

915 916
  def render_odg(self, field, value, as_string, ooo_builder, REQUEST,
                 render_prefix, attr_dict, local_name):
917 918 919 920
    if value is None:
      return None
    value_list = self.render_items_odf(field, value, REQUEST)
    value = ', '.join(value_list).decode('utf-8')
921 922
    return Widget.render_odg(self, field, value, as_string, ooo_builder,
                             REQUEST, render_prefix, attr_dict, local_name)
923

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
class ListWidget(SingleItemsWidget):
    """List widget.
    """
    property_names = Widget.property_names +\
                     ['first_item', 'items', 'size', 'extra', 'extra_item']

    size = fields.IntegerField('size',
                               title='Size',
                               description=(
        "The display size in rows of the field. If set to 1, the "
        "widget will be displayed as a drop down box by many browsers, "
        "if set to something higher, a list will be shown. Required."),
                               default=5,
                               required=1)

    def render(self, field, key, value, REQUEST, render_prefix=None):
      rendered_items = self.render_items(field, key, value, REQUEST)
      input_hidden = render_element('input', type='hidden', 
                                    name="default_%s:int" % (key, ), value="0") 
      list_widget = render_element(
                    'select',
                    name=key,
                    css_class=field.get_value('css_class', REQUEST=REQUEST),
                    size=field.get_value('size', REQUEST=REQUEST),
                    contents=string.join(rendered_items, "\n"),
                    extra=field.get_value('extra', REQUEST=REQUEST))

      return "\n".join([list_widget, input_hidden])

    def render_item(self, text, value, key, css_class, extra_item):
        return render_element('option', contents=text, value=value, 
                              extra=extra_item)

    def render_selected_item(self, text, value, key, css_class, extra_item):
        return render_element('option', contents=text, value=value,
                              selected=None, extra=extra_item)

961 962 963 964 965 966 967 968 969 970 971 972
    def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
                        render_prefix, attr_dict, local_name):
        if attr_dict is None:
          attr_dict = {}
        if value is None:
          value = []
        if isinstance(value, (list, tuple)):
          value = '\n'.join(value)
        if isinstance(value, str):
          #required by lxml
          value = value.decode('utf-8')
        text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
Nicolas Delaby's avatar
typo  
Nicolas Delaby committed
973 974
        global parent_node
        parent_node = text_node
975 976 977 978 979 980
        RE_OOO_ESCAPE.sub(ooo_escape, value)
        text_node.attrib.update(attr_dict)
        if as_string:
            return etree.tostring(text_node)
        return text_node

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
ListWidgetInstance = ListWidget()

class MultiListWidget(MultiItemsWidget):
    """List widget with multiple select.
    """
    property_names = Widget.property_names +\
                     ['items', 'size', 'view_separator', 'extra', 'extra_item']
    
    size = fields.IntegerField('size',
                               title='Size',
                               description=(
        "The display size in rows of the field. If set to 1, the "
        "widget will be displayed as a drop down box by many browsers, "
        "if set to something higher, a list will be shown. Required."),
                               default=5,
                               required=1)

    def render(self, field, key, value, REQUEST, render_prefix=None):
      rendered_items = self.render_items(field, key, value, REQUEST)
      input_hidden = render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0")
      multi_list = render_element(
                    'select',
                    name=key,
                    multiple=None,
                    css_class=field.get_value('css_class', REQUEST=REQUEST),
                    size=field.get_value('size', REQUEST=REQUEST),
                    contents=string.join(rendered_items, "\n"),
                    extra=field.get_value('extra', REQUEST=REQUEST))

      return "\n".join([multi_list,input_hidden])

    def render_item(self, text, value, key, css_class, extra_item):
        return render_element('option', contents=text, value=value, 
                              extra=extra_item)

    def render_selected_item(self, text, value, key, css_class, extra_item):
        return render_element('option', contents=text, value=value,
                              selected=None, extra=extra_item)
    
MultiListWidgetInstance = MultiListWidget()

class RadioWidget(SingleItemsWidget):
  """radio buttons widget.
  """
  property_names = Widget.property_names +\
                    ['first_item', 'items', 'orientation', 'extra_item']
  
  orientation = fields.ListField('orientation',
                                  title='Orientation',
                                  description=(
      "Orientation of the radio buttons. The radio buttons will "
      "be drawn either vertically or horizontally."),
                                  default="vertical",
                                  required=1,
                                  size=1,
                                  items=[('Vertical', 'vertical'),
                                        ('Horizontal', 'horizontal')])
                                  
  def render(self, field, key, value, REQUEST, render_prefix=None):
    input_hidden = render_element('input', type='hidden',
                                  name="default_%s" % (key, ), value="")
    rendered_items = self.render_items(field, key, value, REQUEST)
    rendered_items.append(input_hidden)
    orientation = field.get_value('orientation')
    if orientation == 'horizontal':
      return string.join(rendered_items, "&nbsp;&nbsp;")
    else:
      return string.join(rendered_items, "<br />")

  def render_item(self, text, value, key, css_class, extra_item):
    return render_element('input',
                          type="radio",
                          css_class=css_class,
                          name=key,
                          value=value,
                          extra=extra_item) + text

  def render_selected_item(self, text, value, key, css_class, extra_item):
    return render_element('input',
                          type="radio",
                          css_class=css_class,
                          name=key,
                          value=value,
                          checked=None,
                          extra=extra_item) + text

RadioWidgetInstance = RadioWidget()

class MultiCheckBoxWidget(MultiItemsWidget):
    """multiple checkbox widget.
    """
    property_names = Widget.property_names +\
                     ['items', 'orientation', 'view_separator', 'extra_item']

    orientation = fields.ListField('orientation',
                                   title='Orientation',
                                   description=(
        "Orientation of the check boxes. The check boxes will "
        "be drawn either vertically or horizontally."),
                                   default="vertical",
                                   required=1,
                                   size=1,
                                   items=[('Vertical', 'vertical'),
                                          ('Horizontal', 'horizontal')])

    def render(self, field, key, value, REQUEST, render_prefix=None):
      rendered_items = self.render_items(field, key, value, REQUEST)
      rendered_items.append(render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0"))
      orientation = field.get_value('orientation')
      if orientation == 'horizontal':
        return string.join(rendered_items, "&nbsp;&nbsp;")
      else:
        return string.join(rendered_items, "<br />")

    def render_item(self, text, value, key, css_class, extra_item):
        return render_element('input',
                              type="checkbox",
                              css_class=css_class,
                              name=key,
                              value=value,
                              extra=extra_item) + text
    
    def render_selected_item(self, text, value, key, css_class, extra_item):
        return render_element('input',
                              type="checkbox",
                              css_class=css_class,
                              name=key,
                              value=value,
                              checked=None,
                              extra=extra_item) + text

MultiCheckBoxWidgetInstance = MultiCheckBoxWidget()

class DateTimeWidget(Widget):
  """
    Added support for key in every call to render_sub_field
  """

  sql_format_year  = '%Y'
  sql_format_month = '%m'
  sql_format_day   = '%d'
  format_to_sql_format_dict = {'dmy': (sql_format_day  , sql_format_month, sql_format_year),
                                'ymd': (sql_format_year , sql_format_month, sql_format_day ),
                                'mdy': (sql_format_month, sql_format_day  , sql_format_year),
                                'my' : (sql_format_month, sql_format_year ),
                                'ym' : (sql_format_year , sql_format_month)
                              }
  sql_format_default = format_to_sql_format_dict['ymd']

  hide_day = fields.CheckBoxField('hide_day',
                                title="Hide Day",
                                description=(
      "The day will be hidden on the output. Instead the default"
      "Day will be taken"),
                                default=0)

  hidden_day_is_last_day = fields.CheckBoxField('hidden_day_is_last_day',
                                title="Hidden Day is last day of the Month",
                                description=(
      "Defines wether hidden day means, you want the last day of the month"
      "Else it will be the first day"),
                                default=0)

  timezone_style = fields.CheckBoxField('timezone_style',
                                    title="Display timezone",
                                    description=("Display timezone"),
                                    default=0)

  default = fields.DateTimeField('default',
                                   title="Default",
                                   description=("The default datetime."),
                                   default=None,
                                   display_style="text",
                                   display_order="ymd",
                                   input_style="text",
                                   required=0)

  default_now = fields.CheckBoxField('default_now',
                                      title="Default to now",
                                      description=(
      "Default date and time will be the date and time at showing of "
      "the form (if the default is left empty)."),
                                      default=0)

  date_separator = fields.StringField('date_separator',
                                      title='Date separator',
                                      description=(
      "Separator to appear between year, month, day."),
                                      default="/",
                                      required=0,
                                      display_width=2,
                                      display_maxwith=2,
                                      max_length=2)

  time_separator = fields.StringField('time_separator',
                                      title='Time separator',
                                      description=(
      "Separator to appear between hour and minutes."),
                                      default=":",
                                      required=0,
                                      display_width=2,
                                      display_maxwith=2,
                                      max_length=2)

  input_style = fields.ListField('input_style',
                                  title="Input style",
                                  description=(
      "The type of input used. 'text' will show the date part "
      "as text, while 'list' will use dropdown lists instead."),
                                  default="text",
                                  items=[("text", "text"),
                                        ("list", "list")],
                                  size=1)

  input_order = fields.ListField('input_order',
                                  title="Input order",
                                  description=(
      "The order in which date input should take place. Either "
      "year/month/day, day/month/year or month/day/year."),
                                  default="ymd",
                                  items=[("year/month/day", "ymd"),
                                        ("day/month/year", "dmy"),
                                        ("month/day/year", "mdy")],
                                  required=1,
                                  size=1)

  date_only = fields.CheckBoxField('date_only',
                                    title="Display date only",
                                    description=(
      "Display the date only, not the time."),
                                    default=0)

  ampm_time_style = fields.CheckBoxField('ampm_time_style',
                                           title="AM/PM time style",
                                           description=(
        "Display time in am/pm format."),
                                           default=0)

  property_names = Widget.property_names +\
                    ['default_now', 'date_separator', 'time_separator',
                     'input_style', 'input_order', 'date_only',
                     'ampm_time_style', 'timezone_style', 'hide_day',
                     'hidden_day_is_last_day']

  def getInputOrder(self, field):
    input_order = field.get_value('input_order')
    if field.get_value('hide_day'):
      if input_order == 'ymd':
        input_order = 'ym'
      elif input_order in ('dmy', 'mdy'):
        input_order = 'my'
    return input_order

  def render_dict(self, field, value, render_prefix=None):
    """
      This is yet another field rendering. It is designed to allow code to
      understand field's value data by providing its type and format when
      applicable.

      It returns a dict with 3 keys:
        type  : Text representation of value's type.
        format: Type-dependant-formated formating information.
                This only describes the field format settings, not the actual
                format of provided value.
        query : Passthrough of given value.
    """
    format_dict = self.format_to_sql_format_dict
    input_order = format_dict.get(self.getInputOrder(field),
                                  self.sql_format_default)
    if isinstance(value, unicode):
      value = value.encode(field.get_form_encoding())
    return {'query': value,
            'format': field.get_value('date_separator').join(input_order),
            'type': 'date'}

  def render(self, field, key, value, REQUEST, render_prefix=None):
    use_ampm = field.get_value('ampm_time_style')
    use_timezone = field.get_value('timezone_style')
    # FIXME: backwards compatibility hack:
    if not hasattr(field, 'sub_form'):
Nicolas Delaby's avatar
Nicolas Delaby committed
1261
      from StandardFields import create_datetime_text_sub_form
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
      field.sub_form = create_datetime_text_sub_form()
        
    # Is it still usefull to test the None value,
    # as DateTimeField should be considerer as the other field
    # and get an empty string as default value?
    # XXX hasattr(REQUEST, 'form') seems useless, 
    # because REQUEST always has a form property
    if (value in (None, '')) and (field.get_value('default_now')) and \
        ((REQUEST is None) or (not hasattr(REQUEST, 'form')) or \
        (not REQUEST.form.has_key('subfield_%s_%s' % (key, 'year')))):
      value = DateTime()
    year   = None
    month  = None
    day    = None
    hour   = None
    minute = None
    ampm   = None
    timezone = None
    if isinstance(value, DateTime):
      year = "%04d" % value.year()
      month = "%02d" % value.month()
      day = "%02d" % value.day()
      if use_ampm:
          hour = "%02d" % value.h_12()
      else:
          hour = "%02d" % value.hour()
      minute = "%02d" % value.minute()
      ampm = value.ampm()
      timezone = value.timezone()
    input_order = self.getInputOrder(field)
    if input_order == 'ymd':
      order = [('year', year),
                ('month', month),
                ('day', day)]
    elif input_order == 'dmy':
      order = [('day', day),
                ('month', month),
                ('year', year)]
    elif input_order == 'mdy':
      order = [('month', month),
                ('day', day),
                ('year', year)]
    elif input_order == 'my':
      order = [('month', month),
                ('year', year)]
    elif input_order == 'ym':
      order = [('year', year),
                ('month', month)]
    else:
      order = [('year', year),
                ('month', month),
                ('day', day)]
    result = []
    for sub_field_name, sub_field_value in order:
      result.append(field.render_sub_field(sub_field_name,
                                            sub_field_value, REQUEST, key=key))
    date_result = string.join(result, field.get_value('date_separator'))
    if not field.get_value('date_only'):
      time_result = (field.render_sub_field('hour', hour, REQUEST, key=key) +
                      field.get_value('time_separator') +
                      field.render_sub_field('minute', minute, REQUEST, key=key))

      if use_ampm:
        time_result += '&nbsp;' + field.render_sub_field('ampm',
                                                      ampm, REQUEST, key=key)
      if use_timezone:
        time_result += '&nbsp;' + field.render_sub_field('timezone',
                                                      timezone, REQUEST, key=key)
      return date_result + '&nbsp;&nbsp;&nbsp;' + time_result
    else:
      return date_result

  def format_value(self, field, value, mode='html'):
    # Is it still usefull to test the None value,
    # as DateTimeField should be considerer as the other field
    # and get an empty string as default value?
    if value in (None, ''):
      return ''

    use_ampm = field.get_value('ampm_time_style')
    use_timezone = field.get_value('timezone_style')

    year = "%04d" % value.year()
    month = "%02d" % value.month()
    day = "%02d" % value.day()
    if use_ampm:
      hour = "%02d" % value.h_12()
    else:
      hour = "%02d" % value.hour()
    minute = "%02d" % value.minute()
    ampm = value.ampm()
    timezone = value.timezone()

    order = self.getInputOrder(field)
    if order == 'ymd':
      output = [year, month, day]
    elif order == 'dmy':
      output = [day, month, year]
    elif order == 'mdy':
      output = [month, day, year]
    elif order == 'my':
      output = [month, year]
    elif order == 'ym':
      output = [year, month]
    else:
      output = [year, month, day]
    date_result = string.join(output, field.get_value('date_separator'))

    if mode in ('html', ):
      space = '&nbsp;'
    else:
      space = ' '

    if not field.get_value('date_only'):
      time_result = hour + field.get_value('time_separator') + minute
      if use_ampm:
          time_result += space + ampm
      if use_timezone:
          time_result += space + timezone
      return date_result + (space * 3) + time_result
    else:
      return date_result

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    return self.format_value(field, value, mode='html')

  def render_pdf(self, field, value, render_prefix=None):
    return self.format_value(field, value, mode='pdf')

1391
  def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
1392
      render_prefix, attr_dict, local_name):
1393 1394 1395 1396 1397 1398 1399
    """
      Return a field value rendered in odt format.
      - as_string return value as string or as xml object
      - attr_dict can be used for additional attributes (like style).
    """
    if attr_dict is None:
      attr_dict = {}
1400
    text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
1401
    # get the field value
1402 1403 1404
    if not value and field.get_value('default_now'):
      value = DateTime()
    text_node.text = self.format_value(field, value, mode='pdf').decode('utf-8')
1405 1406 1407 1408 1409
    text_node.attrib.update(attr_dict)
    if as_string:
      return etree.tostring(text_node)
    return text_node

1410
  def render_odg(self, field, value, as_string, ooo_builder, REQUEST,
1411
      render_prefix, attr_dict, local_name):
1412 1413 1414 1415 1416
    """
      Return a field value rendered in odt format.
      - as_string return value as string or as xml object
      - attr_dict can be used for additional attributes (like style).
    """
1417 1418
    return self.render_odt(field, value, as_string, ooo_builder, REQUEST,
                           render_prefix, attr_dict, local_name)
1419

1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
DateTimeWidgetInstance = DateTimeWidget()

class LabelWidget(Widget):
    """Widget that is a label only. It simply returns its default value.
    """
    property_names = ['title', 'description',
                      'default', 'css_class', 'hidden', 'extra']

    default = fields.TextAreaField(
        'default',
        title="Label text",
        description="Label text to render",
        default="",
        width=20, height=3,
        required=0)

1436
    def render(self, field, key, value, REQUEST=None, render_prefix=None):
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
        return render_element("div",
                              css_class=field.get_value('css_class'),
                              contents=field.get_value('default'))

    # XXX should render view return the same information as render?
    def render_view(self, field, value, REQUEST=None, render_prefix=None):
        return field.get_value('default')

LabelWidgetInstance = LabelWidget()

def render_tag(tag, **kw):
  """Render the tag. Well, not all of it, as we may want to / it.
  """
  attr_list = []

  # special case handling for css_class
  if kw.has_key('css_class'):
    if kw['css_class'] != "":
      attr_list.append('class="%s"' % kw['css_class'])
    del kw['css_class']

  # special case handling for extra 'raw' code
  if kw.has_key('extra'):
    extra = kw['extra'] # could be empty string but we don't care
    del kw['extra']
  else:
    extra = ""

  # handle other attributes
  for key, value in kw.items():
    if value == None:
        value = key
    attr_list.append('%s="%s"' % (key, html_quote(value)))

  attr_str = string.join(attr_list, " ")
  return "<%s %s %s" % (tag, attr_str, extra)

def render_element(tag, **kw):
  if kw.has_key('contents'):
    contents = kw['contents']
    del kw['contents']
    return "%s>%s</%s>" % (apply(render_tag, (tag, ), kw), contents, tag)
  else:
    return apply(render_tag, (tag, ), kw) + " />"


##############################################################################
#
# Copyright (c) 2002-2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean Paul Smets <jp@nexedi.com>
#                    Jerome Perrin <jerome@nexedi.com>
#                    Yoshinori Okuji <yo@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################


class IntegerWidget(TextWidget) :
  def render(self, field, key, value, REQUEST, render_prefix=None) :
    """Render an editable integer.
    """
    if isinstance(value, float):
      value = int(value)
    display_maxwidth = field.get_value('display_maxwidth') or 0
    if display_maxwidth > 0:
      return render_element("input",
                            type="text",
                            name=key,
                            css_class=field.get_value('css_class'),
                            value=value,
                            size=field.get_value('display_width'),
                            maxlength=display_maxwidth,
                            extra=field.get_value('extra'))
    else:
      return render_element("input",
                            type="text",
                            name=key,
                            css_class=field.get_value('css_class'),
                            value=value,
                            size=field.get_value('display_width'),
                            extra=field.get_value('extra'))

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """Render a non-editable interger."""
    if isinstance(value, float):
      value = int(value)
    return TextWidget.render_view(self, field, value, REQUEST=REQUEST)

IntegerWidgetInstance = IntegerWidget()
class FloatWidget(TextWidget):

  property_names = TextWidget.property_names +\
                    ['input_style','precision']

  input_style = fields.ListField('input_style',
                                  title="Input style",
                                  description=(
      "The type of float we should enter. "),
                                  default="-1234.5",
                                  items=[("-1234.5",  "-1234.5"),
1557 1558 1559 1560 1561
                                         ("-1 234.5", "-1 234.5"),
                                         ("-1 234,5", "-1 234,5"),
                                         ("-1.234,5", "-1.234,5"),
                                         ("-1,234.5", "-1,234.5"),
                                         ("-12.3%", "-12.3%"),],
1562 1563 1564 1565 1566 1567 1568
                                  required=1,
                                  size=1)

  precision = fields.IntegerField('precision',
                                      title='Precision',
                                      description=(
      "Number of digits after the decimal point"),
1569
                                      default='',
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
                                      required=0)

  def format_value(self, field, value):
    """Formats the value as requested"""
    if value not in (None,''):
      precision = field.get_value('precision')
      input_style = field.get_value('input_style')
      percent = 0
      original_value = value
      if input_style.find('%')>=0:
        percent=1
        try:
          value = float(value) * 100
        except ValueError:
          return value
      try :
        float_value = float(value)
        if precision not in (None, ''):
          float_value = round(float_value, precision)
        value = str(float_value)
      except ValueError:
        return value
      else:
        if 'e' in value:
          # %f will not use exponential format
          value = '%f' % float(original_value)
      value_list = value.split('.')
      integer = value_list[0]
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
      
      decimal_separator = ''
      decimal_point = '.'
      
      if input_style == "-1234.5":
        decimal_point = '.'
      elif input_style == '-1 234.5':
        decimal_separator = ' '
        decimal_point = '.'
      elif input_style == '-1 234,5':
        decimal_separator = ' '
        decimal_point = ','
      elif input_style == '-1.234,5':
        decimal_separator = '.'
        decimal_point = ','
      elif input_style == '-1,234.5':
        decimal_separator = ','
        decimal_point = '.'

      if input_style.find(decimal_separator) >= 0:
1618
        integer = value_list[0]
1619 1620 1621 1622
        sign = ''
        if integer.startswith('-'):
          sign = '-'
          integer = integer[1:]
1623
        i = len(integer) % 3
1624 1625
        value = integer[:i]
        while i != len(integer):
1626
          value += decimal_separator + integer[i:i+3]
1627
          i += 3
1628 1629
        if value[0] == decimal_separator:
          value = value[1:]
1630
        value = '%s%s' % (sign, value)
1631 1632 1633
      else:
        value = value_list[0]
      if precision != 0:
1634
        value += decimal_point
1635 1636
      if precision not in (None, ''):
        for i in range(0, precision):
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
          if i < len(value_list[1]):
            value += value_list[1][i]
          else:
            value += '0'
      else:
        value += value_list[1]
      if percent:
        value += '%'
      return value.strip()
    return ''

  def render(self, field, key, value, REQUEST, render_prefix=None):
    """Render Float input field
    """
    value = self.format_value(field, value)
    display_maxwidth = field.get_value('display_maxwidth') or 0
    extra_keys = {}
    if display_maxwidth > 0:
      extra_keys['maxlength'] = display_maxwidth
    return render_element( "input",
                            type="text",
                            name=key,
                            css_class=field.get_value('css_class'),
                            value=value,
                            size=field.get_value('display_width'),
                            extra=field.get_value('extra'),
                            **extra_keys)

  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """
      Render Float display field.
      This patch add:
        * replacement of spaces by unbreakable spaces if the content is float-like
        * support of extra CSS class when render as pure text
    """
    value = self.format_value(field, value)

    float_value = None
    try:
      float_value = float(value.replace(' ', ''))
    except:
      pass
    if float_value != None:
      value = value.replace(' ', '&nbsp;')

    extra = field.get_value('extra')
    if extra not in (None, ''):
      value = "<div %s>%s</div>" % (extra, value)

    css_class = field.get_value('css_class')
    if css_class not in ('', None):
      return "<span class='%s'>%s</span>" % (css_class, value)
    return value

  def render_pdf(self, field, value, render_prefix=None):
    """Render the field as PDF."""
    return self.format_value(field, value)

  def render_dict(self, field, value, render_prefix=None):
    """
      This is yet another field rendering. It is designed to allow code to
      understand field's value data by providing its type and format when
      applicable.

      It returns a dict with 3 keys:
        type  : Text representation of value's type.
        format: Type-dependant-formated formating information.
                This only describes the field format settings, not the actual
                format of provided value.
        query : Passthrough of given value.
    """
1708
    precision = field.get_value('precision')
1709 1710 1711 1712 1713 1714 1715 1716
    format = '0'
    if precision:
      format = '0.'
      # in 'format', the only important thing is the number of decimal places,
      # so we add some places until we reach the precision defined on the
      # field.
      for x in xrange(0, precision):
        format += '0'
1717 1718 1719
    if isinstance(value, unicode):
      value = value.encode(field.get_form_encoding())
    return {'query': value,
1720
            'format': format,
1721 1722
            'type': 'float'}

1723
  def render_odt_view(self, field, value, as_string, ooo_builder, REQUEST,
1724
      render_prefix, attr_dict, local_name):
1725 1726 1727
    if attr_dict is None:
      attr_dict = {}
    text_node = Element('{%s}%s' % (TEXT_URI, local_name), nsmap=NSMAP)
1728
    text_node.text = self.format_value(field, value).decode('utf-8')
1729 1730 1731 1732 1733
    text_node.attrib.update(attr_dict)
    if as_string:
      return etree.tostring(text_node)
    return text_node

1734
  def render_odg(self, field, value, as_string, ooo_builder, REQUEST,
1735
      render_prefix, attr_dict, local_name):
1736 1737 1738
    if attr_dict is None:
      attr_dict = {}
    value = field.render_pdf(value)
1739 1740
    return Widget.render_odg(self, field, value, as_string, ooo_builder,
                             REQUEST, render_prefix, attr_dict, local_name)
1741

1742 1743 1744 1745 1746 1747 1748 1749
FloatWidgetInstance = FloatWidget()

class LinkWidget(TextWidget):
  def render_view(self, field, value, REQUEST=None, render_prefix=None):
    """Render link.
    """
    link_type = field.get_value('link_type', REQUEST=REQUEST)
    if REQUEST is None:
1750 1751
      # stop relying on get_request bein patched in Globals
      REQUEST = field.REQUEST
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

    if link_type == 'internal':
      value = urljoin(REQUEST['BASE0'], value)
    elif link_type == 'relative':
      value = urljoin(REQUEST['URL1'], value)

    return '<a href="%s">%s</a>' % (value,
        field.get_value('title', cell=getattr(REQUEST,'cell',None)))

LinkWidgetInstance = LinkWidget()