FormPrintout.py 39.1 KB
Newer Older
Nicolas Delaby's avatar
Nicolas Delaby committed
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
##############################################################################
#
# Copyright (c) 2009 Nexedi KK and Contributors. All Rights Reserved.
#                    Tatuya Kamada <tatuya@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
26 27
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
# USA.
28 29
##############################################################################
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
30
from Products.CMFCore.utils import _checkPermission
31
from Products.ERP5Type import PropertySheet, Permissions
32 33
from Products.ERP5Form.ListBox import ListBox
from Products.ERP5Form.FormBox import FormBox
34
from Products.ERP5Form.ReportBox import ReportBox
35
from Products.ERP5Form.ImageField import ImageField
36
from Products.ERP5OOo.OOoUtils import OOoBuilder
37
from Products.CMFCore.exceptions import AccessControl_Unauthorized
Tatuya Kamada's avatar
Tatuya Kamada committed
38
from Acquisition import Implicit, aq_base
39
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, Persistent
40 41
from AccessControl import ClassSecurityInfo
from AccessControl.Role import RoleManager
42
from OFS.SimpleItem import Item
Tatuya Kamada's avatar
Tatuya Kamada committed
43
from urllib import quote, quote_plus
44 45
from copy import deepcopy
from lxml import etree
Nicolas Delaby's avatar
Nicolas Delaby committed
46
from lxml.etree import _Element, _ElementStringResult
47 48
from zLOG import LOG, DEBUG, INFO, WARNING
from mimetypes import guess_extension
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
49
from DateTime import DateTime
Tatuya Kamada's avatar
Tatuya Kamada committed
50
from decimal import Decimal
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
51
from xml.sax.saxutils import escape
Tatuya Kamada's avatar
Tatuya Kamada committed
52
import re
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

try:
  from webdav.Lockable import ResourceLockedError
  SUPPORTS_WEBDAV_LOCKS = 1
except ImportError:
  SUPPORTS_WEBDAV_LOCKS = 0

# Constructors
manage_addFormPrintout = DTMLFile("dtml/FormPrintout_add", globals())

def addFormPrintout(self, id, title="", form_name='', template='', REQUEST=None):
  """Add form printout to folder.

  Keyword arguments:
  id     -- the id of the new form printout to add
  title  -- the title of the form printout to add
  form_name -- the name of a form which contains data to printout
  template -- the name of a template which describes printout layout
  """
  # add actual object
  id = self._setObject(id, FormPrintout(id, title, form_name, template))
  # respond to the add_and_edit button if necessary
  add_and_edit(self, id, REQUEST)
  return ''

def add_and_edit(self, id, REQUEST):
  """Helper method to point to the object's management screen if
  'Add and Edit' button is pressed.

  Keyword arguments:
83
  id -- the id of the object we just added
84 85 86 87 88 89 90 91 92 93
  """
  if REQUEST is None:
    return
  try:
    u = self.DestinationURL()
  except AttributeError:
    u = REQUEST['URL1']
  if REQUEST['submit'] == " Add and Edit ":
    u = "%s/%s" % (u, quote(id))
  REQUEST.RESPONSE.redirect(u+'/manage_main')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
94

95 96 97
class FormPrintout(Implicit, Persistent, RoleManager, Item):
  """Form Printout

98 99 100
  FormPrintout is one of a reporting system in ERP5. 
  It enables to create a Printout, using an Open Document Format(ODF) 
  document as its design, an ERP5Form as its contents. 
101 102

  WARNING: The Form Printout currently supports only ODT format document.
Tatuya Kamada's avatar
Tatuya Kamada committed
103 104

  The functions status:
105
  
Tatuya Kamada's avatar
Tatuya Kamada committed
106 107
  Fields -> Paragraphs:      supported
  ListBox -> Table:          supported
108 109
  Report Section
      -> Frames or Sections: supported
Tatuya Kamada's avatar
Tatuya Kamada committed
110 111 112 113
  FormBox -> Frame:          experimentally supported
  ImageField -> Photo:       supported
  styles.xml:                supported
  meta.xml:                  not supported yet
114 115 116
  """
  
  meta_type = "ERP5 Form Printout"
117
  icon = "www/form_printout_icon.png"
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

  # Declarative Security
  security = ClassSecurityInfo()

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem)

  # Constructors
  constructors =   (manage_addFormPrintout, addFormPrintout)

  # Tabs in ZMI
  manage_options = ((
    {'label':'Edit', 'action':'manage_editFormPrintout'},
    {'label':'View', 'action': '' }, ) + Item.manage_options)
Nicolas Delaby's avatar
Nicolas Delaby committed
133

134 135
  security.declareProtected('View management screens', 'manage_editFormPrintout')
  manage_editFormPrintout = PageTemplateFile('www/FormPrintout_manageEdit', globals(),
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
136
                                             __name__='manage_editFormPrintout')
137
  manage_editFormPrintout._owner = None
138 139 140 141

  # alias definition to do 'add_and_edit'
  security.declareProtected('View management screens', 'manage_main')
  manage_main = manage_editFormPrintout
Nicolas Delaby's avatar
Nicolas Delaby committed
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  # default attributes
  template = None
  form_name = None

  def __init__(self, id, title='', form_name='', template=''):
    """Initialize id, title, form_name, template.

    Keyword arguments:
    id -- the id of a form printout
    title -- the title of a form printout
    form_name -- the name of a form which as a document content
    template -- the name of a template which as a document layout
    """
    self.id = id
    self.title = title
    self.form_name = form_name
    self.template = template

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
161
  security.declareProtected('View', 'index_html')
162 163
  def index_html(self, icon=0, preview=0, width=None, height=None, REQUEST=None):
    """Render and view a printout document."""
Nicolas Delaby's avatar
Nicolas Delaby committed
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    obj = getattr(self, 'aq_parent', None)
    if obj is not None:
      container = obj.aq_inner.aq_parent
      if not _checkPermission(Permissions.View, obj):
        raise AccessControl_Unauthorized('This document is not authorized for view.')
      else:
        container = None
    form = getattr(obj, self.form_name)
    if self.template is None or self.template == '':
      raise ValueError, 'Can not create a ODF Document without a printout template'
    printout_template = getattr(obj, self.template)

    report_method = None
    if hasattr(form, 'report_method'):
      report_method = getattr(obj, form.report_method)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
180 181 182 183 184
    extra_context = dict(container=container,
                         printout_template=printout_template,
                         report_method=report_method,
                         form=form,
                         here=obj)
Tatuya Kamada's avatar
Tatuya Kamada committed
185
    # set property to do aquisition
186
    content_type = printout_template.content_type
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
187
    self.strategy = self._createStrategy(content_type)
188
    printout = self.strategy.render(extra_context=extra_context)
189 190 191 192
    return self._oooConvertByFormat(printout,
                                    content_type=content_type, 
                                    extra_context=extra_context,
                                    REQUEST=REQUEST)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
193

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
194 195
  security.declareProtected('View', '__call__')
  __call__ = index_html
Nicolas Delaby's avatar
Nicolas Delaby committed
196

197 198 199 200 201 202 203 204 205 206 207 208 209 210
  security.declareProtected('Manage properties', 'doSettings')
  def doSettings(self, REQUEST, title='', form_name='', template=''):
    """Change title, form_name, template."""
    if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
      raise ResourceLockedError, "File is locked via WebDAV"
    self.form_name = form_name
    self.template = template
    self.title = title
    message = "Saved changes."
    if getattr(self, '_v_warnings', None):
      message = ("<strong>Warning:</strong> <i>%s</i>"
                % '<br>'.join(self._v_warnings))
    return self.manage_editFormPrintout(manage_tabs_message=message)

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
211
  def _createStrategy(slef, content_type=''):
212 213
    if guess_extension(content_type) == '.odt':
      return ODTStrategy()
214 215 216
    if guess_extension(content_type) == '.odg':
      return ODGStrategy()
    raise ValueError, 'Template type: %s is not supported' % content_type
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  def _oooConvertByFormat(self, printout, content_type=None, extra_context={}, REQUEST=None):
    """
    Convert the ODF document into the given format.

    Keyword arguments:
    printout -- ODF document
    content_type -- the content type of the printout
    extra_context -- extra_context including a format
    REQUEST -- Request object
    """
    options = extra_context.get('options', {})
    format = None
    if REQUEST is not None:
      format = options.get('format', REQUEST.get('format', None))
    if format is None:
      if REQUEST is not None:
        REQUEST.RESPONSE.setHeader('Content-Type','%s; charset=utf-8' % content_type)
        REQUEST.RESPONSE.setHeader('Content-disposition',
                                   'inline;filename="%s%s"' % (self.title_or_id(), guess_extension(content_type)))
      return printout
    from Products.ERP5Type.Document import newTempOOoDocument
    tmp_ooo = newTempOOoDocument(self, self.title_or_id())
    tmp_ooo.edit(base_data=printout,
                 fname=self.title_or_id(),
                 source_reference=self.title_or_id(),
                 base_content_type=content_type)
    tmp_ooo.oo_data = printout
    mime, data = tmp_ooo.convert(format)
    if REQUEST is not None:
      REQUEST.RESPONSE.setHeader('Content-type', mime)
      REQUEST.RESPONSE.setHeader('Content-disposition',
          'attachment;filename="%s.%s"' % (self.title_or_id(), format))
    return data

252 253 254 255
InitializeClass(FormPrintout)

class ODFStrategy(Implicit):
  """ODFStrategy creates a ODF Document. """
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
256

Tatuya Kamada's avatar
Tatuya Kamada committed
257
  odf_existent_name_list = []
Nicolas Delaby's avatar
Nicolas Delaby committed
258

259
  def render(self, extra_context={}):
260
    """Render a odf document, form as a content, template as a template.
261 262

    Keyword arguments:
263
    extra_context -- a dictionary, expected:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
264 265 266 267
      'here' : where it call
      'printout_template' : the template object, tipically a OOoTemplate
      'container' : the object which has a form printout object
      'form' : the form as a content
268 269 270 271 272 273 274 275 276
    """
    here = extra_context['here']
    if here is None:
      raise ValueError, 'Can not create a ODF Document without a parent acquisition context'
    form = extra_context['form']
    if not extra_context.has_key('printout_template') or extra_context['printout_template'] is None:
      raise ValueError, 'Can not create a ODF Document without a printout template'

    odf_template = extra_context['printout_template']
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
277

278
    # First, render the Template if it has a pt_render method
279 280 281 282
    ooo_document = None
    if hasattr(odf_template, 'pt_render'):
      ooo_document = odf_template.pt_render(here, extra_context=extra_context)
    else:
283
      # File object can be a template
284 285 286 287
      ooo_document = odf_template 

    # Create a new builder instance
    ooo_builder = OOoBuilder(ooo_document)
Tatuya Kamada's avatar
Tatuya Kamada committed
288
    self.odf_existent_name_list = ooo_builder.getNameList()
Nicolas Delaby's avatar
Nicolas Delaby committed
289

290
    # content.xml
291
    self._replaceContentXml(ooo_builder, extra_context)
292
    # styles.xml
293
    self._replaceStylesXml(ooo_builder, extra_context)
294
    # meta.xml is not supported yet
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
295 296
    # ooo_builder = self._replaceMetaXml(ooo_builder=ooo_builder, extra_context=extra_context)

297 298 299 300 301 302
    # Update the META informations
    ooo_builder.updateManifest()

    ooo = ooo_builder.render(name=odf_template.title or odf_template.id)
    return ooo

303
  def _replaceContentXml(self, ooo_builder, extra_context):
304 305 306
    """
    Replace the content.xml in an ODF document using an ERP5Form data.
    """
307
    content_xml = ooo_builder.extract('content.xml')
308 309 310 311
    # mapping ERP5Form to ODF
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)

312
    content_element_tree = etree.XML(content_xml)
313 314
    self._replaceXmlByForm(content_element_tree, form, here, extra_context,
                           ooo_builder)
315
    # mapping ERP5Report report method to ODF
316
    report_method=extra_context.get('report_method')
317 318 319
    base_name = getattr(report_method, '__name__', None)
    self._replaceXmlByReportSection(content_element_tree, extra_context,
                                    report_method, base_name, ooo_builder)
Nicolas Delaby's avatar
Nicolas Delaby committed
320

321
    content_xml = etree.tostring(content_element_tree, encoding='utf-8')
322
    # Replace content.xml in master openoffice template
323
    ooo_builder.replace('content.xml', content_xml)
324 325

  # this method not supported yet
326
  def _replaceStylesXml(self, ooo_builder, extra_context):
327
    """
328
    Replace the styles.xml file in an ODF document.
329
    """
330
    styles_xml = ooo_builder.extract('styles.xml')
331 332
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)
333
    styles_element_tree = etree.XML(styles_xml)
334 335
    self._replaceXmlByForm(styles_element_tree, form, here, extra_context,
                           ooo_builder)
Tatuya Kamada's avatar
Tatuya Kamada committed
336
    styles_xml = etree.tostring(styles_element_tree, encoding='utf-8')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
337

338
    ooo_builder.replace('styles.xml', styles_xml)
339 340

  # this method not implemented yet
341
  def _replaceMetaXml(self, ooo_builder, extra_context):
342
    """
343
    Replace meta.xml file in an ODF document.
344 345 346
    """
    return ooo_builder

347 348
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
349 350 351 352 353 354 355 356 357 358
    """
    Replace an element_tree object using an ERP5 form.

    Keyword arguments:
    element_tree -- the element_tree of a XML file in an ODF document.
    form -- an ERP5 form
    here -- called context
    extra_context -- extra_context
    ooo_builder -- the OOoBuilder object which have an ODF document.
    iteration_index -- the index which is used when iterating the group of items using ReportSection.
Nicolas Delaby's avatar
Nicolas Delaby committed
359

360
    Need to be overloaded in OD?Strategy Class
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
361
    """
362
    raise NotImplementedError
Nicolas Delaby's avatar
Nicolas Delaby committed
363

364 365
  def _replaceXmlByReportSection(self, element_tree, extra_context, report_method,
                                 base_name, ooo_builder):
366 367 368 369 370 371 372 373 374
    """
    Replace xml using ERP5Report ReportSection.
    Keyword arguments:
    element_tree -- the element tree object which have an xml document in an ODF document.
    extra_context -- the extra context
    report_method -- the report method object which is used in an ReportBox 
    base_name -- the name of a ReportBox field which is used to specify the target 
    ooo_builder -- the OOo Builder object which has ODF document.
    """
375
    if report_method is None:
376
      return
377 378
    report_section_list = report_method()
    portal_object = self.getPortalObject()
Tatuya Kamada's avatar
Tatuya Kamada committed
379

380
    target_tuple = self._pickUpTargetSection(base_name=base_name,
381 382 383
                                             report_section_list=report_section_list,
                                             element_tree=element_tree)
    if target_tuple is None:
384
      return
385 386 387 388
    target_xpath, original_target = target_tuple
    office_body = original_target.getparent()
    target_index = office_body.index(original_target)
    temporary_element_tree = deepcopy(original_target)
389
    for (index, report_item) in enumerate(report_section_list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
390
      report_item.pushReport(portal_object, render_prefix=None)
391 392 393
      here = report_item.getObject(portal_object)
      form_id = report_item.getFormId()
      form = getattr(here, form_id)
Nicolas Delaby's avatar
Nicolas Delaby committed
394

395 396
      target_element_tree = deepcopy(temporary_element_tree)
      # remove original target in the ODF template 
397
      if index == 0:
398
        office_body.remove(original_target)
Tatuya Kamada's avatar
Tatuya Kamada committed
399
      else:
400
        self._setUniqueElementName(base_name=base_name,
401
                                   iteration_index=index,
402 403 404
                                   xpath=target_xpath,
                                   element_tree=target_element_tree)

405 406
      self._replaceXmlByForm(target_element_tree, form, here, extra_context,
                             ooo_builder, iteration_index=index)
407 408
      office_body.insert(target_index, target_element_tree)
      target_index += 1
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
409
      report_item.popReport(portal_object, render_prefix=None)
410

411
  def _pickUpTargetSection(self, base_name='', report_section_list=[], element_tree=None):
412
    """pick up a ODF target object to iterate ReportSection
413
    base_name -- the target name to replace in an ODF document
414 415 416
    report_section_list -- ERP5Form ReportSection List which was created by a report method
    element_tree -- XML ElementTree object
    """
417
    frame_xpath = '//draw:frame[@draw:name="%s"]' % base_name
418 419
    frame_list = element_tree.xpath(frame_xpath, namespaces=element_tree.nsmap)
    # <text:section text:style-name="Sect2" text:name="Section2">
420
    section_xpath = '//text:section[@text:name="%s"]' % base_name
421
    section_list = element_tree.xpath(section_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
422 423
    if not frame_list and not section_list:
      return
424 425 426 427

    office_body = None
    original_target = None
    target_xpath = ''
Nicolas Delaby's avatar
Nicolas Delaby committed
428
    if frame_list:
429 430 431
      frame = frame_list[0]
      original_target = frame.getparent()
      target_xpath = frame_xpath
Nicolas Delaby's avatar
Nicolas Delaby committed
432
    elif section_list:
433 434 435 436
      original_target = section_list[0]
      target_xpath = section_xpath
    office_body = original_target.getparent()
    # remove if no report section
Nicolas Delaby's avatar
Nicolas Delaby committed
437
    if not report_section_list:
438
      office_body.remove(original_target)
Nicolas Delaby's avatar
Nicolas Delaby committed
439
      return
Nicolas Delaby's avatar
Nicolas Delaby committed
440

441
    return (target_xpath, original_target)
Nicolas Delaby's avatar
Nicolas Delaby committed
442

443 444 445 446 447 448 449 450 451
  def _setUniqueElementName(self, base_name='', iteration_index=0, xpath='', element_tree=None):
    """create a unique element name and set it to the element tree

    Keyword arguments:
    base_name -- the base name of the element
    iteration_index -- iteration index
    xpath -- xpath expression which was used to search the element
    element_tree -- element tree
    """
452
    if iteration_index == 0:
Tatuya Kamada's avatar
Tatuya Kamada committed
453
      return
454
    def getNameAttribute(target_element):
455 456 457 458 459 460 461
      attrib = target_element.attrib
      for key in attrib.keys():
        if key.endswith("}name"):
          return key
      return None
    odf_element_name =  "%s_%s" % (base_name, iteration_index)
    result_list = element_tree.xpath(xpath, namespaces=element_tree.nsmap)
462
    if not result_list:
463 464 465
      return
    target_element = result_list[0]
    name_attribute = getNameAttribute(target_element)
Nicolas Delaby's avatar
Nicolas Delaby committed
466
    if name_attribute:
467
      target_element.set(name_attribute, odf_element_name)
Nicolas Delaby's avatar
Nicolas Delaby committed
468

469 470
  def _replaceXmlByFormbox(self, element_tree, field, form, extra_context,
                           ooo_builder, iteration_index=0):
471 472
    """
    Replace an ODF frame using an ERP5Form form box field.
473

474 475 476
    Note: This method is incompleted yet. This function is intended to
    make an frame hide/show. But it has not such a feature currently. 
    """
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
477 478
    field_id = field.id
    enabled = field.get_value('enabled')
479
    draw_xpath = '//draw:frame[@draw:name="%s"]/draw:text-box/*' % field_id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
480
    text_list = element_tree.xpath(draw_xpath, namespaces=element_tree.nsmap)
481 482
    if not text_list:
      return
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
483 484 485 486 487
    target_element = text_list[0]
    frame_paragraph = target_element.getparent()
    office_body = frame_paragraph.getparent()
    if not enabled:
      office_body.remove(frame_paragraph)
488
      return
489
    # set when using report section
490 491 492 493 494
    self._setUniqueElementName(field_id, iteration_index, draw_xpath, element_tree)
    self._replaceXmlByForm(frame_paragraph, form, extra_context['here'], extra_context,
                           ooo_builder, iteration_index=iteration_index)

  def _replaceXmlByImageField(self, element_tree, image_field, ooo_builder, iteration_index=0):
495 496 497
    """
    Replace an ODF draw:frame using an ERP5Form image field.
    """
498 499
    alt = image_field.get_value('description') or image_field.get_value('title')
    image_xpath = '//draw:frame[@draw:name="%s"]/*' % image_field.id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
500
    image_list = element_tree.xpath(image_xpath, namespaces=element_tree.nsmap)
501 502
    if not image_list:
      return
Tatuya Kamada's avatar
Tatuya Kamada committed
503
    path = image_field.get_value('default')
504 505
    image_node = image_list[0]
    image_frame = image_node.getparent()
Tatuya Kamada's avatar
Tatuya Kamada committed
506 507
    if path is not None:
      path = path.encode()
Tatuya Kamada's avatar
Tatuya Kamada committed
508
    picture = self.getPortalObject().restrictedTraverse(path)
Tatuya Kamada's avatar
Tatuya Kamada committed
509
    picture_data = getattr(aq_base(picture), 'data', None)
510 511 512
    if picture_data is None:
      image_frame = image_node.getparent()
      image_frame.remove(image_node)
513
      return
Tatuya Kamada's avatar
Tatuya Kamada committed
514 515 516 517 518 519 520
    picture_type = picture.getContentType()
    picture_path = self._createOdfUniqueFileName(path=path, picture_type=picture_type)
    ooo_builder.addFileEntry(picture_path, media_type=picture_type, content=picture_data)
    picture_size = self._getPictureSize(picture, image_node)
    image_node.set('{%s}href' % element_tree.nsmap['xlink'], picture_path)
    image_frame.set('{%s}width' % element_tree.nsmap['svg'], picture_size[0])
    image_frame.set('{%s}height' % element_tree.nsmap['svg'], picture_size[1])
521
    # set when using report section
522
    self._setUniqueElementName(image_field.id, iteration_index, image_xpath, element_tree)
523

Tatuya Kamada's avatar
Tatuya Kamada committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  def _createOdfUniqueFileName(self, path='', picture_type=''):
    extension = guess_extension(picture_type)
    picture_path = 'Pictures/%s%s' % (quote_plus(path), extension)     
    if picture_path not in self.odf_existent_name_list:
      return picture_path
    number = 0
    while True:
      picture_path = 'Pictures/%s_%s%s' % (path, number, extension)
      if picture_path not in self.odf_existent_name_list:
        return picture_path
      number += 1

  def _getPictureSize(self, picture=None, image_node=None):
    if picture is None or image_node is None:
      return ('0cm', '0cm')
    draw_frame_node = image_node.getparent()
    svg_width = draw_frame_node.attrib.get('{%s}width' % draw_frame_node.nsmap['svg'])
    svg_height = draw_frame_node.attrib.get('{%s}height' % draw_frame_node.nsmap['svg'])
    if svg_width is None or svg_height is None:
      return ('0cm', '0cm')
    # if not match causes exception
    width_tuple = re.match("(\d[\d\.]*)(.*)", svg_width).groups()
    height_tuple = re.match("(\d[\d\.]*)(.*)", svg_height).groups()
    unit = width_tuple[1]
    w = Decimal(width_tuple[0])
    h = Decimal(height_tuple[0])
    aspect_ratio = 1
    try: # try image properties
      aspect_ratio = Decimal(picture.width) / Decimal(picture.height)
    except (TypeError, ZeroDivisionError):
      try: # try ERP5.Document.Image API
        height = Decimal(picture.getHeight())
        if height:
          aspect_ratio = Decimal(picture.getWidth()) / height
      except AttributeError: # fallback to Photo API
        height = float(picture.height())
        if height:
          aspect_ratio = Decimal(picture.width()) / height
Tatuya Kamada's avatar
Tatuya Kamada committed
562 563 564 565 566 567
    resize_w = h * aspect_ratio
    resize_h = w / aspect_ratio
    if resize_w < w:
      w = resize_w
    elif resize_h < h:
      h = resize_h
Tatuya Kamada's avatar
Tatuya Kamada committed
568
    return (str(w) + unit, str(h) + unit)
Nicolas Delaby's avatar
Nicolas Delaby committed
569 570


571
  def _appendTableByListbox(self, element_tree, listbox, REQUEST, iteration_index=0):
572 573 574
    """
    Append a ODF table using an ERP5 Form listbox.
    """
575 576 577
    table_id = listbox.id
    table_xpath = '//table:table[@table:name="%s"]' % table_id
    # this list should be one item list
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
578
    target_table_list = element_tree.xpath(table_xpath, namespaces=element_tree.nsmap)
579
    if not target_table_list:
580
      return element_tree
581 582 583

    target_table = target_table_list[0]
    newtable = deepcopy(target_table)
584

585 586
    table_header_rows_xpath = '%s/table:table-header-rows' % table_xpath
    table_row_xpath = '%s/table:table-row' % table_xpath
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
587
    table_header_rows_list = newtable.xpath(table_header_rows_xpath,  namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
588
    table_row_list = newtable.xpath(table_row_xpath, namespaces=element_tree.nsmap)
589 590 591

    # copy row styles from ODF Document
    has_header_rows = len(table_header_rows_list) > 0
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
592 593
    (row_top, row_middle, row_bottom) = self._copyRowStyle(table_row_list,
                                                           has_header_rows=has_header_rows)
594 595
    # create style-name and table-row dictionary if a reference name is set
    style_name_row_dictionary = self._createStyleNameRowDictionary(table_row_list)
596 597 598
    # clear original table 
    parent_paragraph = target_table.getparent()
    # clear rows 
Nicolas Delaby's avatar
Nicolas Delaby committed
599
    [newtable.remove(table_row) for table_row in table_row_list]
600 601 602 603

    listboxline_list = listbox.get_value('default',
                                         render_format='list',
                                         REQUEST=REQUEST, 
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
604
                                         render_prefix=None)
605 606
    # if ODF table has header rows, does not update the header rows
    # if does not have header rows, insert the listbox title line
607
    is_top = True
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
608
    last_index = len(listboxline_list) - 1
609 610
    for (index, listboxline) in enumerate(listboxline_list):
      listbox_column_list = listboxline.getColumnItemList()
611
      row_style_name = listboxline.getRowCSSClassName()
612 613
      if listboxline.isTitleLine() and not has_header_rows:
        row = deepcopy(row_top)
Nicolas Delaby's avatar
Nicolas Delaby committed
614
        self._updateColumnValue(row, listbox_column_list)
615
        newtable.append(row)
616
        is_top = False
617
      elif listboxline.isDataLine() and is_top:
Nicolas Delaby's avatar
Nicolas Delaby committed
618 619
        row = deepcopy(style_name_row_dictionary.get(row_style_name, row_top))
        self._updateColumnValue(row, listbox_column_list)
620 621
        newtable.append(row)
        is_top = False
Tatuya Kamada's avatar
Tatuya Kamada committed
622
      elif listboxline.isStatLine() or (index is last_index and listboxline.isDataLine()):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
623
        row = deepcopy(row_bottom)
Nicolas Delaby's avatar
Nicolas Delaby committed
624
        self._updateColumnStatValue(row, listbox_column_list, row_middle)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
625
        newtable.append(row)
626
      elif index > 0 and listboxline.isDataLine():
Nicolas Delaby's avatar
Nicolas Delaby committed
627 628
        row = deepcopy(style_name_row_dictionary.get(row_style_name, row_middle))
        self._updateColumnValue(row, listbox_column_list)
629 630
        newtable.append(row)

631
    self._setUniqueElementName(table_id, iteration_index, table_xpath, newtable)
Nicolas Delaby's avatar
Nicolas Delaby committed
632
    parent_paragraph.replace(target_table, newtable)
Nicolas Delaby's avatar
Nicolas Delaby committed
633

634
  def _copyRowStyle(self, table_row_list=None, has_header_rows=False):
635 636 637
    """
    Copy ODF table row styles.
    """
638 639
    if table_row_list is None:
      table_row_list = []
640 641 642 643 644
    def removeOfficeAttribute(row):
      if row is None or has_header_rows: return
      odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
      for odf_cell in odf_cell_list:
        self._removeColumnValue(odf_cell)
Nicolas Delaby's avatar
Nicolas Delaby committed
645

646 647 648
    row_top = None
    row_middle = None
    row_bottom = None
Nicolas Delaby's avatar
Nicolas Delaby committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    len_table_row_list = len(table_row_list)
    if len_table_row_list == 1:
      row_top = deepcopy(table_row_list[0])
      row_middle = deepcopy(table_row_list[0])
      row_bottom = deepcopy(table_row_list[0])
    elif len_table_row_list == 2 and has_header_rows:
      row_top = deepcopy(table_row_list[0])
      row_middle = deepcopy(table_row_list[0])
      row_bottom = deepcopy(table_row_list[-1])
    elif len_table_row_list == 2 and not has_header_rows:
      row_top = deepcopy(table_row_list[0])
      row_middle = deepcopy(table_row_list[1])
      row_bottom = deepcopy(table_row_list[-1])
    elif len_table_row_list >= 2:
      row_top = deepcopy(table_row_list[0])
      row_middle = deepcopy(table_row_list[1])
      row_bottom = deepcopy(table_row_list[-1])
666 667 668

    # remove office attribute if create a new header row 
    removeOfficeAttribute(row_top)
669
    return (row_top, row_middle, row_bottom)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
670

671

Nicolas Delaby's avatar
Nicolas Delaby committed
672
  def _createStyleNameRowDictionary(self, table_row_list):
673 674 675
    """create stylename and table row dictionary if a style name reference is set"""
    style_name_row_dictionary = {}
    for table_row in table_row_list:
Nicolas Delaby's avatar
Nicolas Delaby committed
676
      reference_element = table_row.find('.//*[@%s]' % self._name_attribute_name)
677
      if reference_element is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
678
        name = reference_element.attrib[self._name_attribute_name]
679 680
        style_name_row_dictionary[name] = deepcopy(table_row)
    return style_name_row_dictionary
Nicolas Delaby's avatar
Nicolas Delaby committed
681

Nicolas Delaby's avatar
Nicolas Delaby committed
682
  def _updateColumnValue(self, row, listbox_column_list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
683
    odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
684 685 686 687 688 689
    odf_cell_list_size = len(odf_cell_list)
    listbox_column_size = len(listbox_column_list)
    for (column_index, column) in enumerate(odf_cell_list):
      if column_index >= listbox_column_size:
        break
      value = listbox_column_list[column_index][1]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
690
      self._setColumnValue(column, value)
691

Nicolas Delaby's avatar
Nicolas Delaby committed
692
  def _updateColumnStatValue(self, row, listbox_column_list, row_middle):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
693
    """stat line is capable of column span setting"""
694
    if row_middle is None:
Nicolas Delaby's avatar
Nicolas Delaby committed
695
      return
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
696 697
    odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
    odf_column_span_list = self._getOdfColumnSpanList(row_middle)
698 699 700 701 702 703
    listbox_column_size = len(listbox_column_list)
    listbox_column_index = 0
    for (column_index, column) in enumerate(odf_cell_list):
      if listbox_column_index >= listbox_column_size:
        break
      value = listbox_column_list[listbox_column_index][1]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
704 705 706 707 708
      self._setColumnValue(column, value)
      column_span = self._getColumnSpanSize(column)
      listbox_column_index = self._nextListboxColumnIndex(column_span,
                                                          listbox_column_index,
                                                          odf_column_span_list)
709

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
710 711
  def _setColumnValue(self, column, value):
    self._clearColumnValue(column)
712
    if value is None:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
713
      self._removeColumnValue(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
714
    column_value, table_content = self._translateValueIntoColumnContent(value, column)
Nicolas Delaby's avatar
Nicolas Delaby committed
715
    [column.remove(child) for child in column]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
716 717 718 719 720 721 722 723 724
    if table_content is not None:
      column.append(table_content)
    value_attribute = self._getColumnValueAttribute(column)
    if value_attribute is not None and column_value is not None:
       column.set(value_attribute, column_value)

  def _translateValueIntoColumnContent(self, value, column):
    """translate a value as a table content"""
    table_content = None
Nicolas Delaby's avatar
Nicolas Delaby committed
725 726
    if len(column):
      table_content = deepcopy(column[0])
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
727 728 729 730 731
    # create a tempolaly etree object to generate a content paragraph
    fragment = self._valueAsOdfXmlElement(value=value, element_tree=column)
    column_value = None
    if table_content is not None:
      table_content.text = fragment.text
Nicolas Delaby's avatar
Nicolas Delaby committed
732
      for element in fragment:
Nicolas Delaby's avatar
Nicolas Delaby committed
733 734
        table_content.append(element)
      column_value = " ".join(table_content.itertext())
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
735 736 737 738
    return (column_value, table_content)

  def _valueAsOdfXmlElement(self, value=None, element_tree=None):
    """values as ODF XML element
Nicolas Delaby's avatar
Nicolas Delaby committed
739

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    replacing:
      \t -> tabs
      \n -> line-breaks
      DateTime -> Y-m-d
    """
    if value is None:
      value = ''
    translated_value = str(value)
    if isinstance(value, DateTime):
      translated_value = value.strftime('%Y-%m-%d')
    translated_value = escape(translated_value)
    text_namespace = element_tree.nsmap['text']
    tab_element_str = '<text:tab xmlns:text="%s"/>' % text_namespace
    line_break_element_str ='<text:line-break xmlns:text="%s"/>' % text_namespace
    translated_value = translated_value.replace('\t', tab_element_str)
    translated_value = translated_value.replace('\r', '')
    translated_value = translated_value.replace('\n', line_break_element_str)
    translated_value = unicode(str(translated_value),'utf-8')
    # create a paragraph
    template = '<text:p xmlns:text="%s">%s</text:p>'
    fragment_element_tree = etree.XML(template % (text_namespace, translated_value))
    return fragment_element_tree
Nicolas Delaby's avatar
Nicolas Delaby committed
762

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
763
  def _removeColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
764 765 766 767 768
    # to eliminate a default value, remove "office:*" attributes.
    # if remaining these attribetes, the column shows its default value,
    # such as '0.0', '$0'
    attrib = column.attrib
    for key in attrib.keys():
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
769
      if key.startswith("{%s}" % column.nsmap['office']):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
770
        del attrib[key]
Nicolas Delaby's avatar
Nicolas Delaby committed
771 772
    column.text = None
    [column.remove(child) for child in column]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
773

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
774
  def _clearColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
775 776
    attrib = column.attrib
    for key in attrib.keys():
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
777
      value_attribute = self._getColumnValueAttribute(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
778 779
      if value_attribute is not None:
        column.set(value_attribute, '')
Nicolas Delaby's avatar
Nicolas Delaby committed
780 781
    column.text = None
    for child in column:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
782
      # clear data except style
Nicolas Delaby's avatar
Nicolas Delaby committed
783
      style_value = child.attrib.get(self._style_attribute_name)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
784
      child.clear()
Nicolas Delaby's avatar
Nicolas Delaby committed
785
      if style_value:
Nicolas Delaby's avatar
Nicolas Delaby committed
786
        child.set(self._style_attribute_name, style_value)
Nicolas Delaby's avatar
Nicolas Delaby committed
787

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
788
  def _getColumnValueAttribute(self, column):
789 790 791 792 793
    attrib = column.attrib
    for key in attrib.keys():
      if key.endswith("value"):
        return key
    return None
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
794 795 796

  def _getColumnSpanSize(self, column=None):
    span_attribute = "{%s}number-columns-spanned" % column.nsmap['table']
Nicolas Delaby's avatar
Nicolas Delaby committed
797
    return int(column.attrib.get(span_attribute, 1))
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
798 799

  def _nextListboxColumnIndex(self, span=0, current_index=0, column_span_list=[]):
800 801 802 803 804 805 806
    hops = 0
    index = current_index
    while hops < span:
      column_span = column_span_list[index]
      hops += column_span
      index += 1
    return index
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
807 808

  def _getOdfColumnSpanList(self, row_middle=None):
809 810
    if row_middle is None:
      return []
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
811
    odf_cell_list = row_middle.findall("{%s}table-cell" % row_middle.nsmap['table'])
812 813
    column_span_list = []
    for column in odf_cell_list:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
814
      column_span = self._getColumnSpanSize(column)
815 816 817
      column_span_list.append(column_span)
    return column_span_list

Tatuya Kamada's avatar
Tatuya Kamada committed
818 819
  def _toUnicodeString(self, field_value = None):
    value = ''
Tatuya Kamada's avatar
Tatuya Kamada committed
820 821 822
    if isinstance(field_value, unicode):
      value = field_value
    elif field_value is not None:
Tatuya Kamada's avatar
Tatuya Kamada committed
823 824 825
      value = unicode(str(field_value), 'utf-8')
    return value

826 827
class ODTStrategy(ODFStrategy):
  """ODTStrategy create a ODT Document from a form and a ODT template"""
Nicolas Delaby's avatar
Nicolas Delaby committed
828 829

  _style_attribute_name = '{urn:oasis:names:tc:opendocument:xmlns:text:1.0}style-name'
Nicolas Delaby's avatar
Nicolas Delaby committed
830
  _name_attribute_name = '{urn:oasis:names:tc:opendocument:xmlns:text:1.0}name'
Nicolas Delaby's avatar
Nicolas Delaby committed
831

832 833
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
834 835 836 837 838 839 840 841 842 843 844 845
    """
    Replace an element_tree object using an ERP5 form.

    Keyword arguments:
    element_tree -- the element_tree of a XML file in an ODF document.
    form -- an ERP5 form
    here -- called context
    extra_context -- extra_context
    ooo_builder -- the OOoBuilder object which have an ODF document.
    iteration_index -- the index which is used when iterating the group of items using ReportSection.
    """
    field_list = form.get_fields(include_disabled=1) 
846
    REQUEST = here.REQUEST
847 848
    for (count, field) in enumerate(field_list):
      if isinstance(field, ListBox):
849 850
        self._appendTableByListbox(element_tree, field, REQUEST,
                                   iteration_index=iteration_index)
851 852 853 854
      elif isinstance(field, FormBox):
        if not hasattr(here, field.get_value('formbox_target_id')):
          continue
        sub_form = getattr(here, field.get_value('formbox_target_id'))
855 856
        content = self._replaceXmlByFormbox(element_tree, field, sub_form,
                                            extra_context, ooo_builder,
857 858 859
                                            iteration_index=iteration_index)
      elif isinstance(field, ReportBox):
         report_method = getattr(field, field.get_value('report_method'), None)
860 861
         self._replaceXmlByReportSection(element_tree, extra_context,
                                         report_method, field.id, ooo_builder)
862
      elif isinstance(field, ImageField):
863 864
        self._replaceXmlByImageField(element_tree, field,
                                     ooo_builder, iteration_index=iteration_index)
865
      else:
866
        self._replaceNodeViaReference(element_tree, field)
867

868
  def _replaceNodeViaReference(self, element_tree, field):
869
    """replace nodes (e.g. paragraphs) via ODF reference"""
870 871
    self._replaceNodeViaRangeReference(element_tree, field)
    self._replaceNodeViaPointReference(element_tree, field)
872
    self._replaceNodeViaFormName(element_tree, field)
873

874
  def _replaceNodeViaPointReference(self, element_tree, field, iteration_index=0):
875 876 877 878 879 880 881 882
    """Replace text node via an ODF point reference.

    point reference example:
     <text:reference-mark text:name="invoice-date"/>
    """
    field_id = field.id
    reference_xpath = '//text:reference-mark[@text:name="%s"]' % field_id
    reference_list = element_tree.xpath(reference_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
883 884 885 886 887 888 889 890
    for target_node in reference_list:
      node_to_replace = target_node.xpath('ancestor::text:p[1]', namespaces=element_tree.nsmap)[0]
      attr_dict = {}
      style_value = node_to_replace.attrib.get(self._style_attribute_name)
      if style_value:
        attr_dict.update({self._style_attribute_name: style_value})
      new_node = field.render_odt(attr_dict=attr_dict)
      node_to_replace.getparent().replace(node_to_replace, new_node)
891 892 893 894 895 896
    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=reference_xpath,
                               element_tree=element_tree)

897
  def _replaceNodeViaRangeReference(self, element_tree, field, iteration_index=0):
898 899 900 901 902
    """Replace text node via an ODF ranged reference.

    range reference example:
    <text:reference-mark-start text:name="week"/>Monday<text:reference-mark-end text:name="week"/>
    or
Nicolas Delaby's avatar
Nicolas Delaby committed
903 904
    <text:reference-mark-start text:name="my_title"/>
      <text:span text:style-name="T1">title</text:span>
905 906 907
    <text:reference-mark-end text:name="my_title"/>

    """
Nicolas Delaby's avatar
Nicolas Delaby committed
908
    field_id = field.id
909 910
    range_reference_xpath = '//text:reference-mark-start[@text:name="%s"]' % (field_id,)
    node_to_remove_list_xpath = '//text:reference-mark-start[@text:name="%s"]/'\
Nicolas Delaby's avatar
Nicolas Delaby committed
911 912
                            'following-sibling::*[node()/'\
                            'following::text:reference-mark-end[@text:name="%s"]]' % (field_id, field_id)
913
    node_to_remove_list = element_tree.xpath(node_to_remove_list_xpath, namespaces=element_tree.nsmap)
914
    reference_list = element_tree.xpath(range_reference_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
915
    if not reference_list:
916
      return element_tree
917
    referenced_node = reference_list[0]
918
    referenced_node.tail = None
919
    parent_node = referenced_node.getparent()
920
    text_reference_position = parent_node.index(referenced_node)
Nicolas Delaby's avatar
Nicolas Delaby committed
921 922 923 924

    #Delete all contents between <text:reference-mark-start/> and <text:reference-mark-end/>
    #Try to fetch style-name
    attr_dict = {}
925
    [(attr_dict.update(target_node.attrib), parent_node.remove(target_node)) for target_node in node_to_remove_list]
Nicolas Delaby's avatar
Nicolas Delaby committed
926 927
    new_node = field.render_odt(local_name='span', attr_dict=attr_dict)
    parent_node.insert(text_reference_position+1, new_node)
928 929 930 931 932
    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=range_reference_xpath,
                               element_tree=element_tree)
933

934 935 936 937 938 939 940 941 942 943 944 945 946
  def _replaceNodeViaFormName(self, element_tree, field, iteration_index=0):
    """
    Used to replace field in ODT document like checkboxes
    """
    field_id = field.id
    reference_xpath = '//*[@form:name = "%s"]' % field_id
    reference_list = element_tree.xpath(reference_xpath, namespaces=element_tree.nsmap)
    for target_node in reference_list:
      attr_dict = {}
      attr_dict.update(target_node.attrib)
      new_node = field.render_odt(attr_dict=attr_dict)
      target_node.getparent().replace(target_node, new_node)

947 948 949
class ODGStrategy(ODFStrategy):
  """ODGStrategy create a ODG Document from a form and a ODG template"""

Fabien Morin's avatar
Fabien Morin committed
950 951
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
952 953 954 955 956

    field_list = form.get_fields(include_disabled=1)
    for (count, field) in enumerate(field_list):
      text_xpath = '//draw:frame[@draw:name="%s"]/*' % field.id
      node_list = element_tree.xpath(text_xpath, namespaces=element_tree.nsmap)
Fabien Morin's avatar
Fabien Morin committed
957 958
      for target_node in node_list:
        attr_dict = {}
959 960 961
        # store child style using their local-name as key
        for descendant in target_node.iterdescendants():
          attr_dict.setdefault(descendant.tag, {}).update(descendant.attrib)
962
        new_node = field.render_odg(attr_dict=attr_dict)
963
        parent_node = target_node.getparent().replace(target_node, new_node)