ScribusUtils.py 92.5 KB
Newer Older
Kevin Deldycke's avatar
Kevin Deldycke committed
1 2 3 4
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#               Guy Oswald OBAMA <guy@nexedi.com>
5
#               thomas <thomas@nexedi.com>
6
#               Mame C.Sall <mame@nexedi.com>
Kevin Deldycke's avatar
Kevin Deldycke committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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.
#
##############################################################################

24 25 26
# This code is under refactoring. This code will change in near future
# with a lot of cleanups. This is stored only for a temporary purpose.
# Do not rely on the real implementation. It is assumed that the code is
27 28
# improved and modified significantly.
# UPDATE => the code is almost refactored and supports
29

Kevin Deldycke's avatar
Kevin Deldycke committed
30 31
from Products.PythonScripts.Utility import allow_class
from ZPublisher.HTTPRequest import FileUpload
32
from xml.dom.ext.reader import PyExpat
Kevin Deldycke's avatar
Kevin Deldycke committed
33 34 35 36 37
from xml.dom import Node, minidom
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass, get_request
from zipfile import ZipFile, ZIP_DEFLATED
from StringIO import StringIO
38
from zLOG import LOG, TRACE, WARNING, ERROR, INFO
Kevin Deldycke's avatar
Kevin Deldycke committed
39 40
import imghdr
import random
41
import getopt, sys, os, re
Kevin Deldycke's avatar
Kevin Deldycke committed
42 43
from urllib import quote

44
from Products.ERP5.ERP5Site import ERP5Site
45
from Products.Formulator.TALESField import TALESMethod
46
from Products.Formulator.MethodField import Method
47 48
from Products.ERP5Type.Utils import convertToUpperCase

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
# defining global variables
# ANFLAG tag
# these values can be found in the Scribus document format
# (www.scribus.org.uk)
def_noScroll = '8388608'
def_noSpellCheck = '4194304'
def_editable = '262144'
def_password = '8192'
def_multiLine = '4096'
def_noExport = '4'
def_required = '2'
def_readOnly = '1'
# SCRIPT CONFIGURATION
# define if the script uses personal properties or create a
# PropertySheet and a Document model to save data.
# used in 'setPropertySheetAndDocument', 'setObjectPortalType'
65
# and 'setPDFForm'
66
def_usePropertySheet = 0
Kevin Deldycke's avatar
Kevin Deldycke committed
67

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

class ManageModule:
  """
  Manage the module that will contain the form
  """
  security = ClassSecurityInfo()

  security.declarePublic('setObjectNames')
  def setObjectNames(self, object_portal_type_id, object_title):
    """
    initialize object names view_pdf, view_list, etc. to be able
    to create correctly all objects in the module.
    return a dict of names.
    """
    temp_portal_type = object_portal_type_id.replace(' ','')
    object_names = {}
84
    real_object_names={}
85 86 87 88
    # declaring object that generate pdf output
    object_names['view_pdf'] = temp_portal_type + '_view' +\
                    temp_portal_type + 'AsPdf'
    # declaring form to list the objects of a module
89
    # TODO: use module portal type, not "object title + Module"
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
    object_names['view_list'] = object_title.replace(' ','') +\
                    'Module_view' + temp_portal_type + 'List'
    # declaring main object form
    object_names['view_id'] = temp_portal_type + '_view'
    # declaring object that holds the CSS data
    object_names['css'] = temp_portal_type + '_css.css'
    # declaring object name containing the background pictures
    object_names['page'] = temp_portal_type + '_background_'
    # return object declaration
    return object_names


  security.declarePublic('setSkinFolder')
  def setSkinFolder(self,
                    portal,
                    portal_skins_folder):
    """
    create and manage skin folder according to the skin folder
    name specified by the user (as portal_skin_folder).
    returns skin_folder, recovered from portal.portal_skins
    """
    portal_skins_folder_name = portal_skins_folder
    portal_skins = portal.portal_skins
    if not portal_skins_folder_name in portal.portal_skins.objectIds():
      # create new folder if does not exist yet
      portal_skins.manage_addFolder(portal_skins_folder_name)
    skin_folder = portal.portal_skins[portal_skins_folder_name]
    for skin_name, selection in portal_skins.getSkinPaths():
      selection = selection.split (',')
      if portal_skins_folder_name not in selection:
        new_selection = [portal_skins_folder_name,]
121
        new_selection.extend(selection)
122
        portal_skins.manage_skinLayers(skinpath = tuple(new_selection),
123
                                       skinname = skin_name,
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
                                       add_skin = 1)
    return skin_folder


  security.declarePublic('setModuleForm')
  def setModuleForm(self,
                    object_title,
                    skin_folder,
                    #portal,
                    #portal_skins_folder,
                    form_view_list,
                    module_title,
                    module_id,
                    def_lineNumberInList
                    ):
    """
    Manage ERP5 Form to handle and view the Module. then process
    the list inside this form. This procedure does not need to
    parse the scribus file as the ModuleForm is always present
    and generated the same way
    returns nothing
    """
    # the form is already existing and has been created through
    # setERP5Form. getting form object to update properties
    form_view_list_object = skin_folder[form_view_list]
    form_list_id = form_view_list_object.id
    form_list = form_view_list_object.restrictedTraverse(form_list_id)
    # defining groups for objects listing
152
    form_view_list_object.add_group('bottom')
153
    # defining module title
154
    title_module = '' # XXX use module title provided by user
155 156 157 158 159 160
    for word in module_title.split():
      title_module += str(word.capitalize() + ' ')
    # add listbox field to list the created objects
    id = 'listbox'
    title = title_module
    field_type = 'ListBox'
161 162 163 164
    form_view_list_object.manage_addField(id, title, field_type)
    form_view_list_object.move_field_group(['listbox'],
             form_view_list_object.group_list[0], 'bottom')

165 166 167 168 169 170 171 172
    # manage ListBox settings
    values_settings = {}
    values_settings['pt'] = "form_list"
    values_settings['action'] = "Base_doSelect"
    # set the form settings
    for key, value in values_settings.items():
      setattr(form_view_list_object, key, value)
    # manage edit property of ListBox
173 174 175 176 177
    listbox = getattr(form_view_list_object, id)
    listbox.manage_edit_xmlrpc(
        dict(lines=def_lineNumberInList,
             columns=[('id', 'ID'),
                      ('title', 'Title'),
178 179
                      ('description', 'Description'),
                      ('translated_simulation_state', 'State')],
180 181 182 183 184 185 186
             list_action='list',
             search=1,
             select=1,
             list_method=Method('searchFolder'),
             count_method=Method('countFolder'),
             selection_name='%s_selection' % module_id))

187 188 189 190 191 192 193

  security.declarePublic('setObjectForm')
  def setObjectForm(self,
                    skin_folder,
                    object_names,
                    option_html,
                    global_properties,
194
                    object_portal_type
195 196 197 198 199 200 201 202 203 204 205
                    ):
    """
    create and manage erp5 form to handle object, and update its
    properties (groups, values, etc.)
    return list of groups in form (used afterwards when creating
    fields).
    """
    # getting form object
    form_view_id_object = skin_folder[object_names['view_id']]
    form_id = form_view_id_object.id
    form = form_view_id_object.restrictedTraverse(form_id)
206
    #get the scaling factor
207 208 209 210 211
    # managing form groups
    default_groups = []
    if option_html !=1:
      # using default ERP5 positioning convention
      # based on 'left'/'right'/etc.
212
      default_groups = ['left', 'right', 'center', 'bottom', 'hidden']
213 214 215 216 217
    else:
      # using special page positioning convention for
      # pdf-like rendering
      for page_iterator in range(global_properties['page']):
        page_number = 'page_%s' % str(page_iterator)
218
        default_groups.append(page_number)
219
        
220
    # default_groups list completed, need to update the form_groups
221
    # rename the first group because it can't be removed
222 223
    if len(form.group_list):
      form.rename_group(form.group_list[0], default_groups[0])
224 225

    # add other groups
226 227
    for group in default_groups:
      if group not in form.group_list:
228
        form.add_group(group)
229
    form_view_id_object.rename_group('Default', default_groups[0])
230 231 232 233 234 235

    # remove all other groups:
    for existing_group in list(form.get_groups(include_empty=1)):
      if existing_group not in default_groups:
        form.remove_group(existing_group)

236
    # adding all other items
237
    for group in default_groups:
238 239 240 241 242 243 244
      form_view_id_object.add_group(group)
    # updating form settings
    # building dict containing (property, value)
    values = {}
    values['title'] = str(object_portal_type)
    values['row_length'] = 4
    values['name'] = object_names['view_id']
245
    if option_html == 1:
246 247 248 249 250 251 252 253 254 255 256 257 258 259
      # this is the name of the new form, compatible either with html_style
      # and xhtml_style.
      values['pt'] = "form_render_PDFeForm"
    else:
      values['pt'] = "form_view"
    values['action'] = "Base_edit"
    values['update_action'] = ""
    values['method'] = 'POST'
    values['enctype'] = 'multipart/form-data'
    values['encoding'] = "UTF-8"
    values['stored_encoding'] = 'UTF-8'
    values['unicode_mode'] = 0
    # using the dict declared just above to set the attributes
    for key, value in values.items():
260
      setattr(form, key, value)
261
    return (default_groups)
262 263 264 265 266 267 268 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

  security.declarePublic('setFieldsInObjectForm')
  def setFieldsInObjectForm(self,
                            skin_folder,
                            object_names,
                            default_groups,
                            global_properties,
                            option_html
                            ):
    """
    create fields in form according to the page_objects
    recovered from the scribus document file. fields are
    then moved to their corresponding group, and are given
    their properties
    """
    form_view_id_object = skin_folder[object_names['view_id']]
    # iterating field a first time to get creation order
    # based on the 'nb' value
    field_nb_dict = {}
    # this dict will handle all the information about the field_names and
    # their creation order (field_nb).

    if option_html :
      # render is PDF-like, need to take care of the page holding the field
      for field_id in global_properties['object'].keys():
        field_nb = int(global_properties['object'][field_id]['nb'])
        #field_order =  global_properties['object'][field_id]['order']
        field_order = \
         int(global_properties['object'][field_id]['order'].split('page_')[1])
        # creating sub dict if does not exist yet
        if field_order not in field_nb_dict:
          field_nb_dict[field_order] = {}
        field_nb_dict[field_order][field_nb] = field_id
      # now field_nb_dict holds all the information about the
      # fields and their creation order: just need to create
      # them.

      for field_order_id in field_nb_dict.keys():
        # iterating pages
        for field_nb in range(len(field_nb_dict[field_order_id].keys())):
          field_id = field_nb_dict[field_order_id][field_nb + 1]
          # recovering field information
          field_values = global_properties['object'][field_id]
          field_type = field_values['erp_type']
          field_title = field_values['title']
          field_order = field_values['order']
308
          #field_tales = field_values['tales']
309 310
          # creating new field in form
          form_view_id_object.manage_addField(field_id,
311 312
                                              field_title,
                                              field_type)
313 314
          # move fields to destination group
          form_view_id_object.move_field_group(field_id,
315 316
                                               default_groups[0],
                                               field_order)
317
          # recover field
318
          access_field = getattr(form_view_id_object, field_id)
319
          if field_type == 'CheckBoxField':
320
            test_name = field_id[3:]
321 322 323 324 325 326 327
            tales = {field_id : {'default' : 'here'+ '/'+ test_name}}

            forms = [object_names['view_id']]
            form = form_view_id_object.restrictedTraverse(forms[0])
            for k, v in tales.items() :
              if hasattr(form, k) :
                form[k].manage_tales_xmlrpc(v)
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
          #if field_type == 'CheckBoxField':
          #  print "    dir(%s) > %s" % (field_id,dir(access_field))
          #  print "---manage_tales > %s \n\n" % dir(access_field.manage_tales)
          #  print "---manage_talesForm > %s \n\n" % \
          #         dir(access_field.manage_talesForm)
          #  print "---manage_talesForm__roles__ > %s\n\n " % \
          #         dir(access_field.manage_talesForm__roles__)
          #  print "---manage_tales__roles__ > %s" % \
          #         dir(access_field.manage_tales__roles__)
          #  print "--- 5 > %s" % dir(access_field.manage_tales_xmlrpc)
          #  print "--- 6 > %s" % \
          #         dir(access_field.manage_tales_xmlrpc__roles__)

    else:
      # rendering as basic ERP5 form : processing all
      # fields without taking care of their 'order'.
      for field_id in global_properties['object'].keys():
        field_nb = int(global_properties['object'][field_id]['nb'])
        if field_nb in field_nb_dict.keys():
          # field_nb is already used by another field. this can appen
          # when there are several pages in the document. In such case
          # the script find automatically the closest available value.
Fabien Morin's avatar
Fabien Morin committed
350
          LOG('ManageModule', ERROR, 
Fabien Morin's avatar
Fabien Morin committed
351 352
              'can not add %s to dict : %s already used by %s ' % \
              (field_id, field_nb, field_nb_dict[field_nb]))
353
          field_nb = field_nb + 1
354 355 356
          while field_nb in field_nb_dict.keys():
            # trying next value
            field_nb = field_nb + 1
Fabien Morin's avatar
Fabien Morin committed
357
        LOG('ManageModule', INFO, '  add %s to %s' % (field_id, field_nb))
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
        # value is available, no problem to link field_id to this field_nb
        field_nb_dict[field_nb] = field_id

      for field_nb in range(len(field_nb_dict.keys())):
        field_nb = field_nb +1
        field_id = field_nb_dict[field_nb]
        # recovering field information
        field_values = global_properties['object'][field_id]
        field_type = field_values['erp_type']
        field_title = field_values['title']
        field_order = field_values['order']
        # create field
        form_view_id_object.manage_addField(field_id,
                                            field_title,
                                            field_type)
        # move field to relative group
        form_view_id_object.move_field_group(field_id,
                                             default_groups[0],
                                             field_order)

    # field creation is complete
    form_id = form_view_id_object.id
    form = form_view_id_object.restrictedTraverse(form_id)
    # updating field properties
    # iterating fields
    for field_id in global_properties['object'].keys():
384
      field_attributes = getattr(form, field_id)
385 386 387 388 389 390 391 392
      #print "   %s => %s" % (field_id,field_attributes.values.keys())
      for attr_id, attr_val in \
         global_properties['object'][field_id]['attributes'].items():
        field_attributes.values[attr_id] = attr_val



  security.declarePublic('setModulePortalType')
393 394 395 396 397
  def setModulePortalType(self, 
                          portal_types,
                          object_portal_type_id,
                          module_portal_type,
                          object_names):
398 399 400 401 402
    """
    set portal_type for the module containing objects.
    returns nothing
    """
    portal_types.manage_addTypeInformation('ERP5 Type Information'
403 404
                , typeinfo_name = 'ERP5Type: ERP5 Folder'
                , id = module_portal_type)
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 435 436 437 438 439
    # getting portal_type access to be able to modify attributes
    module_portal_type_value = portal_types[module_portal_type]
    # set alowed content type
    module_portal_type_value.allowed_content_types = (object_portal_type_id,)
    module_portal_type_value.filter_content_types = 1
    # making a list of all the portal_type actions to be able to delete them
    action_list = module_portal_type_value.listActions()
    # cleaning all portal_types actions
    module_portal_type_value.deleteActions(
                selections = range(0, len(action_list)))
    # adding usefull actions (in our case the view action)
    module_portal_type_value.addAction( "view"
          , "View"
          , "string:${object_url}/%s"%object_names['view_list']
          , ""
          , "View"
          , "object_view"
          )



  security.declarePublic('setObjectPortalType')
  def setObjectPortalType(self,
                          portal_types,
                          object_portal_type_id,
                          object_portal_type,
                          object_names):
    name = ''
    if def_usePropertySheet:
      # generating 'typeinfo_name' property for the new portal type.
      # if class exists, then using it, otherwize using default ERP5
      # Document type.
      name = 'ERP5Type: ERP5 ' + object_portal_type # use with PropertySheet
    else:
      name = 'ERP5Type: ERP5 Document'  # use with local properties
440 441 442
    portal_types.manage_addTypeInformation( 'ERP5 Type Information',
                                            typeinfo_name = name,
                                            id = object_portal_type_id)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    object_portal_type_value = portal_types[object_portal_type_id]

    # cleaning all default actions
    action_list = object_portal_type_value.listActions()
    object_portal_type_value.deleteActions(
              selections = range(0, len(action_list)))
    # adding usefull actions (in our case the view action)
    object_portal_type_value.addAction( "view",
          "View",
          "string:${object_url}/%s" % object_names['view_id'],
          "",
          "View",
          "object_view"
          )
    object_portal_type_value.addAction( "print"
          , "Print"
459
          , "string:${object_url}/%s" % object_names['view_pdf']
460 461 462
          , ""
          , "View"
          , "object_print"
463
          , priority=2.0
464 465 466 467 468
          )


  security.declarePublic('registerModule')
  def registerModule(self,
469 470 471 472 473
                     portal,
                     module_id,
                     module_portal_type,
                     object_portal_type,
                     module_title):
474 475 476 477 478
    """
    register Module inside ERP5 instance
    """
    portal.newContent( id          = str(module_id),
                       portal_type = str(module_portal_type),
479
                       title       = module_title)
480

481
   
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
class ManageFiles:
  """
  Manages PDF file, by importing the PDF document and then getting
  the TALES expressions
  """
  security = ClassSecurityInfo()



  security.declarePublic('setERP5Form')
  def setERP5Form(self,
                  factory,
                  form_name,
                  form_title):
    """
    create an ERP5 Form by using the factory
    """
    factory.addERP5Form(form_name,
500
                        form_title)
501 502 503 504 505 506 507 508 509 510 511 512 513



  security.declarePublic('setCSSFile')
  def setCSSFile(self,
                 factory,
                 form_css_id,
                 form_css_content,
                 ):
    """
    create an ERP5 DTML Document in the folder related
    to factory and save the content of the CSS string
    """
514
    factory.addDTMLDocument(form_css_id, "css", form_css_content)
515 516 517 518 519 520 521 522


  security.declarePublic('importFile')
  def setPDFForm(self,
                 factory,
                 skin_folder,
                 object_names,
                 object_title,
523 524
                 pdf_file,
                 global_properties
525 526 527 528 529
                 ):
    """
    imports PDF file as a PDFForm in ERP5 and updates its TALES
    expressions
    """
530
    my_prefix = 'my_'
531
    pdf_file.seek(0)
532
    factory.addPDFForm(object_names['view_pdf'], object_title, pdf_file)
533 534 535 536 537
    # iterating objects in skin_folder
    for c in skin_folder.objectValues():
      if c.getId() == object_names['view_pdf']:
        # current object is PDF Form
        cell_name_list = c.getCellNames()
538 539
        for cell_name in global_properties['object'].keys():
          if cell_name[:len(my_prefix)] == my_prefix:
540
            cell_process_name_list = []
541 542 543 544 545 546 547 548 549 550
            suffix = cell_name[len(my_prefix):].split('_')[-1]
            # If properties field are filled in scribus, get Type form
            # global_properties. Else, guess Type by suffix id (eg: List, Date,...)
            list_field_type_list = ('ListField', 'MultiListField', 'LinesField',)
            date_field_type_list = ('DateTimeField',)
            suffix_mapping = {'List' : list_field_type_list,
                              'Date' : date_field_type_list}
            field_dict = global_properties['object'][cell_name]
            field_type = field_dict.get('erp_type', suffix_mapping.get(suffix, [''])[0])
            if def_usePropertySheet:
551 552
              # generating PropertySheet and Document, no need to use them to
              # get field data
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
              if field_type in list_field_type_list:
                TALES = "python: %s " % ', '.join(
               "here.get%s()" % convertToUpperCase(cell_name[len(my_prefix):]))
              elif field_type in date_field_type_list:
                attributes_dict = field_dict['attributes']
                # assign the property input_order
                input_order = attributes_dict['input_order']
                input_order = input_order.replace('y', 'Y')
                # make the Tales according to the cases
                date_pattern = '/'.join(['%%%s' % s for s in list(input_order)])
                if not(attributes_dict['date_only']):
                  date_pattern += ' %H:%M'
                TALES = "python: here.get%s() is not None and here.get%s().strftime('%s') or ''"\
                 % (convertToUpperCase(cell_name[len(my_prefix):]),
                    convertToUpperCase(cell_name[len(my_prefix):]),
                    date_pattern)
569
              else:
570 571
                TALES = "python: here.get%s()" %\
                                 convertToUpperCase(cell_name[len(my_prefix):])
572

573
            else:
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
              if field_type in list_field_type_list:
                TALES = "python: %s" % ', '.join(
                      "here.getProperty('%s')" % cell_name[len(my_prefix):])
              elif field_type in date_field_type_list:
                attributes_dict = field_dict['attributes']
                # assign the property input_order
                input_order = attributes_dict['input_order']
                input_order = input_order.replace('y', 'Y')
                # make the Tales according to the cases
                date_pattern = '/'.join(['%%%s' % s for s in list(input_order)])
                if not(attributes_dict['date_only']):
                  date_pattern += ' %H:%M'
                TALES = "python: here.getProperty('%s') is not None and here.getProperty('%s').strftime('%s') or ''"\
                      % (cell_name[len(my_prefix):],
                         cell_name[len(my_prefix):],
                         date_pattern)
590
              else:
591
                TALES = "python: here.getProperty('%s')" % cell_name[len(my_prefix):]
Fabien Morin's avatar
Fabien Morin committed
592
            LOG('ManageFiles', INFO, '   %s > %s ' % (cell_name, TALES))
593
            c.setCellTALES(cell_name, TALES)
594

595 596 597
  def getPDFFile(self, file_descriptor):
    """ Get file content """
    return file_descriptor.open()
598 599 600 601 602

  security.declarePublic('setBackgroundPictures')
  def setBackgroundPictures(self,
                            pdf_file,
                            object_names,
603
                            skin_folder,
604
                            desired_width,
605
                            desired_height,
606 607
                            resolution,
                            background_format
608 609 610 611 612
                            ):
    """
    extract background pictures from pdf file and convert them
    in the right format (JPEG) and save them in the corresponding
    folder (skin_folder).
613
    to work, this procedure needs convert (from ImageMagick)
614 615 616 617
    installed on the server otherwise nothing is created.
    Temp files wich are created are deleted once the job is done.
    At the end, return the properties (size_x, size_y) the background
    images have.
618 619
    """
    import commands
620
    from tempfile import NamedTemporaryFile
621
    # opening new file on HDD to save PDF content
622
    temp_pdf = NamedTemporaryFile()
623

624
    # get an unused file name on HDD to save created background image content
625
    temp_image = NamedTemporaryFile()
626 627
    temp_image_name = temp_image.name
    temp_image.close()
628

629 630 631 632
    # going to the begining of the input file
    pdf_file.seek(0)
    # saving content
    temp_pdf.write(pdf_file.read())
633
    temp_pdf.seek(0)
634
     
635 636 637 638 639
    def makeImageList():
      background_image_list = []
      # convert add a '-N' string a the end of the file name if there is more
      # than one page in the pdf file (where N is the number of the page,
      # begining at 0)
640
      if os.path.exists(temp_image_name):
641
        # thats mean there's only one page in the pdf file
642
        background_image_list.append(temp_image_name)
643 644 645
      else:
        # in the case of multi-pages pdf file, we must find all files
        image_number = 0
646 647
        while os.path.exists(temp_image_name + '-%s' % image_number):
          background_image_list.append(temp_image_name + '-%s' % image_number)
648 649 650
          image_number += 1
      return background_image_list

651
    try:
652
      result = commands.getstatusoutput('convert -verbose -density %s -resize %sx%s '\
653
          '%s %s' % (resolution, desired_width, desired_height, temp_pdf.name,
654
          background_format + ':' + temp_image_name))
655 656 657 658

      # check that the command has been done succeful
      if result[0] != 0:
        LOG('ScribusUtils.setBackgroundPictures :', ERROR, 'convert command'\
659
            'failed with the following error message : \n%s' % result[1])
660 661 662 663 664 665 666

        # delete all images created in this method before raise an error
        background_image_list = makeImageList()
        for background_image in background_image_list:
          if os.path.exists(background_image):
            os.remove(background_image)

667 668
        raise ValueError, 'Error: convert command failed with the following'\
                          'error message : \n%s' % result[1]
669
    finally:
670
      temp_pdf.close()
671
    
672
    background_image_list = makeImageList()
673 674 675
    if not len(background_image_list):
      LOG('ScribusUtils.setBackgroundPictures :', ERROR, 'no background '\
          'image found')
676 677
      raise ValueError, 'Error: ScribusUtils.setBackgroundPictures : '\
                        'no background'
678

679
    # get the real size of the first image
680 681 682 683 684 685 686 687 688 689 690 691 692
    # this could be usefull if the user only defined one dimention :
    # convert command has calculate the other using proportionnality
    rawstr = r'''
        PDF\s        # The line begin with PDF 
        (\d+)x(\d+)  # old file size
        =>           # Separator between old and new size
        (\d+)x(\d+)  # The matching pattern : width and height'''
    compile_obj = re.compile(rawstr, re.MULTILINE | re.VERBOSE)
    match_obj_list = re.findall(compile_obj, result[1])
    
    # old size is not use now, and depends of the density convert parameter
    #old_size_x = match_obj_list[0][0]
    #old_size_y = match_obj_list[0][1]
693

694 695
    real_size_x = match_obj_list[0][2]
    real_size_y = match_obj_list[0][3]
696 697

    # add images in erp5 :
698
    image_number = 0
699 700 701 702 703 704 705
    addImageMethod = skin_folder.manage_addProduct['OFSP'].manage_addImage
    for background_image in background_image_list:
      temp_background_file = open(background_image, 'r')
      form_page_id = object_names['page'] + str(image_number)
      addImageMethod(form_page_id, temp_background_file, "background image")
      image_number += 1

706
    # delete all images created in this method before raise an error
Fabien Morin's avatar
Fabien Morin committed
707
    background_image_list = makeImageList()
708
    for background_image in background_image_list:
709 710 711
      # remove the file from the system
      if os.path.exists(background_image):
        os.remove(background_image)
712 713 714 715

    size_x = int(real_size_x)
    size_y = int(real_size_y)
    LOG('ScribusUtils.setBackgroundPictures :', INFO, 
716
        'return size : x=%s, y=%s' % (size_x, size_y))
717
   
718
    return (size_x, size_y)
719

720 721
  security.declarePublic('getPageAttributes')
  def getPageAttributes (self,
722 723 724
                         global_properties,
                         pdf_file
                        ):
725 726 727
    '''return the size of the original pdf file (in pts)
    This is usefull to calculate proportionnality between original size and
    desired size. That permit to place correctly the fields on the page'''
728 729 730 731
    import commands
    from tempfile import NamedTemporaryFile
    # opening new file on HDD to save PDF content
    ScribusUtilsOriginalTempPDF= NamedTemporaryFile(mode= "w+b")
732
    ScribusUtilsOriginaltempsPDFName = ScribusUtilsOriginalTempPDF.name
733

734
    # going to the begining of the input file
735

736 737 738 739 740 741
    # saving content
    temp_pdf = open(ScribusUtilsOriginaltempsPDFName,'w')
    # going to the begining of the input file
    pdf_file.seek(0)
    # saving content
    temp_pdf.write(pdf_file.read())
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
    temp_pdf.close()    

    
    command_output = commands.getstatusoutput('pdfinfo %s' % \
        ScribusUtilsOriginaltempsPDFName)

    if command_output[0] != 0:
        LOG('ScribusUtils.getPageAttributes :', ERROR, 'pdfinfo command'\
            'failed with the following error message : \n%s' % command_output[1])
        raise ValueError, 'Error: convert command failed with the following'\
                          'error message : \n%s' % command_output[1]
    
    # get the pdf page size
    rawstr = r'''
        Page\ssize:        #begining of the instersting line
        \s*                #some spaces
        (\S+)\sx\s(\S+)    #the matching pattern : width and height in pts'''
    compile_obj = re.compile(rawstr, re.MULTILINE | re.VERBOSE)
    match_obj = re.search(compile_obj, command_output[1])
    width, height = match_obj.groups()
    width = int(round(float(width)))
    height = int(round(float(height)))

    LOG('width_groups, height_groups', 0, '%s, %s' % (width, height))
    return (width, height)

768

769 770
  security.declarePublic('setPropertySheetAndDocument')
  def setPropertySheetAndDocument(self,
771 772 773 774 775
                                  global_properties,
                                  object_portal_type,
                                  generator,
                                  skin_folder,
                                  object_names):
776 777 778 779 780 781 782
    """
    recover personal properties from dict global_properties
    and save them in a propertysheet
    then create the Document related to the object.
    PropertySheetRegistry and DocumentRegistry have to be
    reinitialized after this procedure has been called.
    """
783
    if def_usePropertySheet:
Fabien Morin's avatar
Fabien Morin committed
784
      LOG('ManageFiles', INFO, ' object_names = %s' % object_names['view_id'])
785 786 787 788 789 790 791 792 793 794 795
      #property_form = getattr(skin_folder,object_names['view_id'])
      # defining file name for Property Sheet
      name_file =''
      for word in object_portal_type.split():
        name_file += word.capitalize()
      # building list containing properties
      personal_properties_list = []
      for field_id in global_properties['object'].keys():
        if field_id.startswith('my_') and not (
           field_id.startswith('my_source') or
           field_id.startswith('my_destination') or
796
           field_id in ('my_start_date', 'my_stop_date')):
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
          field_type = global_properties['object'][field_id]['data_type']
          field_default = global_properties['object'][field_id]['default']
          personal_properties = { 'id' : field_id[3:],
                                  'description' : '',
                                  'type' : field_type,
                                  'mode' : 'w'}
          ## FOLLOWING QUOTED LINES CAN BE DELETED IF NOT USES
          ## just left in case : can be usefull to create a smart
          ## script that would be able to automatically create the
          ## local properties and associate them the good type (int,
          ## string, float, date, etc.)
          #print "   (field_id,field_default_value,field_type) = \
          #   (%s,%s,%s) " % (field_id[3:], field_default, field_type)
          #property_form.manage_addProperty(field_id[3:],
          #                                 field_default,
          #                                 field_type)
          personal_properties_list.append(personal_properties)
      # the following lines create the PropertySheet and the Document for the
      # new object. Must be uncoted when such files are needed, in such case
      # you must also specify Document type to comply with class declared in 
      # the Document. For that see 'setObjectPortalType' method 
      ## generate PropertySheet
819
      generator.generateLocalPropertySheet(name_file, personal_properties_list)
820
      ## generate Document
821
      generator.generateLocalDocument(name_file, object_portal_type)
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


class ManageCSS:
  """
  Manages all CSS information to generate the css file used in the
  PDF-like rendering
  """
  security = ClassSecurityInfo()

  security.declarePublic('setInit')
  def setInit(self):
    """
    initialize various containers (dicts) used to store attributes
    in a main dict.
    returns global dict containing all the sub-dicts
    """
    # declaring dicts used to generate CSS file
    # css_dict_head contains all the 'global' class, reffering to PAGE
    properties_css_dict_head = {}
    # css_dict_standard contains all the fields classes, when no error occurs
    properties_css_dict_standard = {}
    # css_dict_error contains the same thing, but in case error occurs.
    # there background is different so that users can see where the problem
    # is on the graphic view
    properties_css_dict_error = {}
    # css_dict_err_d contains coordinates and color to display text-error
    properties_css_dict_err_d = {}
    # declaring main container for all sub_dicts
    properties_css_dict = {}
    properties_css_dict['head'] = properties_css_dict_head
    properties_css_dict['standard'] = properties_css_dict_standard
    properties_css_dict['error'] = properties_css_dict_error
    properties_css_dict['err_d'] = properties_css_dict_err_d
    # return dict
    return properties_css_dict

  security.declarePublic('setPageProperties')
  def setPageProperties(self
860 861
          ,properties_css_dict
          ,page_iterator
862
          ,page_id
863 864 865 866
          ,new_width
          ,new_height
          ,old_width
          ,old_height):
867 868 869 870 871 872 873
    """
    recover all CSS data relative to the current page and save these
    information in the output dict
    """
    # Processing current page for CSS data
    # getting properties
    properties_css_page = {}
874
    properties_page = {}
875 876 877 878 879 880 881 882 883 884 885
    properties_css_page['position'] = 'relative'
    # creating image class for background
    properties_css_background = {}
    # making background id
    background_id =  page_id + '_background'
    #getting properties
    properties_css_background['position'] = 'absolute'
    #creating corresponding page group to form
    if page_iterator == 0:
      # margin-top = 0 (first page)
      properties_css_page['margin-top'] = "0px"
886 887 888
      #properties_css_background['margin-top'] = \
      #   str((y_pos -10))+ 'px'
      #properties_css_background['margin-left']= \
889
      #   str((x_pos- 5))+   'px' 
890
    else:
Fabien Morin's avatar
Fabien Morin committed
891
      properties_css_page['margin-top'] = "%spx" % (40)
892 893

    # set width and height on page block
894 895
    properties_css_page['width'] = str (new_width) + 'px'
    properties_css_page['height'] = str (new_height) + 'px'
896

897 898 899 900
    properties_page['actual_width'] = old_width
    properties_page['actual_height'] = old_height 
    properties_css_background['height'] = str(new_height) + 'px'
    properties_css_background['width'] = str (new_width) + 'px'
901 902 903 904
    # adding properties dict to global dicts
    properties_css_dict['head'][page_id] = properties_css_page
    properties_css_dict['head'][background_id] = properties_css_background
    # return updated dict
905
    return (properties_css_dict, properties_page)
906 907 908 909 910 911





  security.declarePublic('setFieldProperties')
912 913 914 915 916 917 918 919
  def setFieldProperties( self
                        , properties_css_dict
                        , field
                        , page_width
                        , page_height
                        , page_iterator
                        , page_gap
                        , keep_page
920 921
                        , properties_page
                        , space_between_pages):
922 923 924 925 926
    """
    recover all CSS data relative to the current page_object (field)
    and save these informations in the output dict
    """
    (field_name, properties_field) = field
Fabien Morin's avatar
Fabien Morin committed
927
    LOG('ManageCSS', INFO, 
Fabien Morin's avatar
Fabien Morin committed
928
        '   => %s : %s' % (field_name, properties_field['rendering']))
929

930 931 932 933 934 935
    # updating field properties if necessary
    if keep_page == 1:
      # document format is 1.3.* and define object position from the top-left
      # corner of the first page, whereas the field position is expected to
      # be found from the current's page top left corner.
      # that's why Y position must be updated
936

937 938
      scaling_factor1 = float(page_width)/properties_page['actual_width']
      scaling_factor2 = float(page_height)/properties_page['actual_height']
939

940 941
      properties_field['position_y'] = \
         str(float(properties_field['position_y']) - \
942
         (properties_page['actual_height'] + page_gap)* page_iterator)
943

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    # Processing object for CSS data
    # declaring dict containing all css data
    # _stand for general display
    field_dict = {}
    properties_css_object_stand = {}
    # _error when an error occurs
    properties_css_object_error = {}
    # _err_d to diplay the text error
    properties_css_object_err_d = {}
    #defining global properties
    properties_css_object_stand['position'] = 'absolute'
    properties_css_object_error['position'] = 'absolute'
    properties_css_object_err_d['position'] = 'absolute'
    properties_css_object_stand['padding'] = '0px'
    properties_css_object_error['padding'] = '0px'
    properties_css_object_err_d['padding'] = '0px'
    # getting field height
    properties_css_object_stand['height'] = \
962
        str(scaling_factor2 * float(properties_field['size_y'])) + 'px'
963
    properties_css_object_error['height'] = \
964
        str(scaling_factor2 * float(properties_field['size_y'])) + 'px'
965 966 967 968
    # defining font-size from height - 2 (this value seems to have a good
    # rendering on Mozilla and Konqueror)
    # do not match for TextArea (as it is a multiline object)
    if properties_field['type'] != 'TextAreaField':
969
      if float(properties_field['size_y']) > 8.0:
970 971 972 973 974
        properties_css_object_stand['font-size'] = \
          str((scaling_factor2 *float(properties_field['size_y']))-5.5 ) + 'px'
        properties_css_object_error['font-size'] = \
          str((scaling_factor2 *float(properties_field['size_y']))-5.5) + 'px'
      else:
975
        properties_css_object_stand['font-size'] = \
976 977
          str((scaling_factor2 *float(properties_field['size_y']))-3.5 ) + 'px'
        properties_css_object_error['font-size'] = \
978
          str((scaling_factor2 *float(properties_field['size_y']))-3.5) + 'px'
979
    else:
980
      properties_css_object_stand['font-size'] = \
981
        str(12) + 'px'
982
      properties_css_object_error['font-size'] = \
983
        str(12) + 'px'
984 985
    properties_css_object_err_d['margin-left'] = str(page_width +
        space_between_pages ) + 'px'
Fabien Morin's avatar
Fabien Morin committed
986
    properties_css_object_err_d['white-space'] = 'nowrap'
987
    properties_css_object_stand['margin-top'] = \
988
      str((scaling_factor2 *float(properties_field['position_y']))) + 'px'
989
    properties_css_object_error['margin-top'] = \
990
      str((scaling_factor2 *float(properties_field['position_y']))) + 'px'
991
    properties_css_object_err_d['margin-top'] = \
992
      str((scaling_factor2 *float(properties_field['position_y']))) + 'px'
993 994 995 996 997 998 999 1000 1001
    # adding special text_color for text error
    properties_css_object_err_d['color'] = 'rgb(255,0,0)'
    # then getting additional properties
    if properties_field['required'] ==1:
      # field is required: using special color
      # color is specified as light-blue when standard
      # color = 'green' when error
      properties_css_object_stand['background'] = 'rgb(192,192,255)'
      properties_css_object_error['background'] = 'rgb(128,128,255)'
1002 1003
    elif properties_field['type'] != 'TextAreaField':
      properties_css_object_stand['background'] = '#F5F5DC'
1004 1005
      properties_css_object_error['background'] = 'rgb(255,64,64)' #Previously,
                                          #B9D9D4 - should become a parameter
1006
    else:
1007 1008
      properties_css_object_stand['background'] = '#F5F5DC' # Previously,
                                          #B9D9D4 - should become a parameter
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
      properties_css_object_error['background'] = 'rgb(255,64,64)'

    # add completed properties (in our case only the class rendering the text
    # beside an error) to the return dict
    properties_css_dict['err_d'][field_name] = properties_css_object_err_d
    # the following variable take the number of field to render for this object
    field_nb = 1

    # now processing special rendering
    if properties_field['rendering']=='single':
      # single rendering (like StringField, TextArea, etc.).
      # Do not need any special treatment
      properties_css_object_stand['width'] = \
1022
        str(scaling_factor1 * float(properties_field['size_x'])) + 'px'
1023
      properties_css_object_error['width'] = \
1024
        str(scaling_factor1 * float(properties_field['size_x'])) + 'px'
1025
      properties_css_object_stand['margin-left'] = \
1026
        str((scaling_factor1 * float(properties_field['position_x']))) + 'px'
1027
      properties_css_object_error['margin-left'] = \
1028
        str((scaling_factor1 * float(properties_field['position_x']))) + 'px'
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
      # in case of checkboxfield, '_class_2' is used because field is rendered
      # as two fields, the first one hidden. (supports xhtml_style)
      # UPDATE : modified because need to keep compatibility with html_style
      #if properties_field['type'] == 'CheckBoxField':
      #  field_id = field_name + '_class_2'
      #else:
      field_id = field_name + '_class'
      # adding all these properties to the global dicts
      properties_css_dict['standard'][field_id] = properties_css_object_stand
      properties_css_dict['error'][field_id] = properties_css_object_error
    else:
      sub_field_dict = {}
      field_dict = {}
      if properties_field['type'] == 'RelationStringField':
        # rendering a relationStringField, based on two input areas
        # processing rendering of the two input fields. for that
        # each has to be evaluated and the values will be saved in
        # a dict

        # uptading number of fields to render
        field_nb = 2

        #field_1 = field_name + '_class_1'
        # processing main StringField
        field_dict[1] = {}
        field_dict[1]['width'] = \
1055
           str(scaling_factor1*(float(properties_field['size_x']) / 2)) + 'px'
1056
        field_dict[1]['margin-left'] = \
1057
           str(scaling_factor1*float(properties_field['position_x'])) + 'px'
1058 1059 1060

        # processing secondary input picture
        field_dict[2] = {}
1061 1062
        field_dict[2]['width'] = \
            str(scaling_factor1*(float(properties_field['size_x']) /2)) + 'px'
1063
        field_dict[2]['margin-left'] = \
1064 1065
              str(scaling_factor1*(float(properties_field['size_x']) /2  +\
              float(properties_field['position_x']))) + 'px'
1066 1067 1068
      elif properties_field['type'] == 'DateTimeField':
        # rendering DateTimeField, composed at least of three input
        # areas, and their order can be changed
Fabien Morin's avatar
Fabien Morin committed
1069
        LOG('ManageCSS', INFO, '  Type DateTimeField')
1070 1071 1072

        # getting the number of fields to render and their size unit
        if properties_field['date_only'] == '0':
Fabien Morin's avatar
Fabien Morin committed
1073
          LOG('ManageCSS', INFO, '   Option : Not Date Only')
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
          field_nb = 5
          # defining counting unit for fields
          # total = 6.1 units:
          # 2 > year
          # 1 > month
          # 1 > day
          # 0.1 > space between date and time
          # 1 > hour
          # 1 > minutes
          width_part = int(float(properties_field['size_x']) / 6.1)
        else: 
Fabien Morin's avatar
Fabien Morin committed
1085
          LOG('ManageCSS', INFO, '   Option : Date Only')
1086 1087
          field_nb = 3
          # same as before but without hours and minutes
1088
          width_part = int((float(properties_field['size_x']) / 4))
1089 1090


Fabien Morin's avatar
Fabien Morin committed
1091
        LOG('ManageCSS', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1092
            '  input_order=%s' % properties_field['input_order'])
1093 1094
        # defining global field rendering (for Date), ignoring for the moment
        # the whole part about the time
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

        # this following field refere to no existing field, it's use only 
        # when editable property is unchecked (there is only one field 
        # without _class_N but just _class, so, the 3 existing CSS selector 
        # can't be applied, that the reason for this new one)
        field_dict[0] = {}
        field_dict[0]['width'] = \
            str(scaling_factor1*float(width_part*(field_nb+1))) + 'px'
        field_dict[0]['margin-left'] = \
           str(scaling_factor1 *float(properties_field['position_x'])) + 'px'

1106
        if properties_field['input_order'] in \
1107
             ['day/month/year', 'dmy', 'dmY', 'month/day/year', 'mdy', 'mdY']:
1108

1109 1110 1111 1112
          # specified input order. must be dd/mm/yyyy or mm/dd/yyyy (year is
          # the last field).
          # processing first field
          field_dict[1] = {}
1113 1114
          field_dict[1]['width'] = str(scaling_factor1*float(width_part)) + \
              'px'
1115
          field_dict[1]['margin-left'] = \
1116
             str(scaling_factor1 *float(properties_field['position_x'])) + 'px'
1117 1118 1119

          # processing second field
          field_dict[2] = {}
1120 1121
          field_dict[2]['width'] = str(scaling_factor1*float(width_part)) + \
              'px'
1122
          field_dict[2]['margin-left'] = \
1123 1124
             str(scaling_factor1 *(float(properties_field['position_x']) + \
             width_part)) + 'px'
1125 1126 1127

          # processing last field
          field_dict[3] = {}
1128 1129
          field_dict[3]['width'] = str(scaling_factor1*float(width_part*2)) + \
              'px'
1130
          field_dict[3]['margin-left'] = \
1131 1132
             str(scaling_factor1 *(float(properties_field['position_x']) + \
             width_part*2)) + 'px'
1133 1134 1135 1136 1137 1138
        else:
          # all other cases, including default one (year/month/day)
          width_part = int(int(properties_field['size_x']) / 4)

          # processing year field
          field_dict[1] = {}
1139 1140
          field_dict[1]['width'] = str(scaling_factor1*float(width_part *2)) +\
              'px'
1141
          field_dict[1]['margin-left'] = \
1142
             str(scaling_factor1 *float(properties_field['position_x'])) + 'px'
1143 1144 1145

          # processing second field (two digits only)
          field_dict[2] = {}
1146 1147
          field_dict[2]['width'] = str(scaling_factor1*float(width_part)) + \
              'px'
1148
          field_dict[2]['margin-left'] = \
1149 1150
            str(scaling_factor1 *(float(properties_field['position_x']) + \
            width_part*2)) + 'px'
1151 1152 1153

          # processing day field
          field_dict[3] = {}
1154 1155
          field_dict[3]['width'] = str(scaling_factor1*float(width_part)) + \
              'px'
1156
          field_dict[3]['margin-left'] = \
1157 1158
            str(scaling_factor1 *(float(properties_field['position_x']) + \
            width_part*3)) + 'px'
1159 1160 1161 1162 1163


        # rendering time if necessary
        if properties_field['date_only'] == '0':
          # date is specified
Fabien Morin's avatar
Fabien Morin committed
1164
          LOG('ManageCSS', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1165
              '   position_x=%s' % properties_field['position_x'])
Fabien Morin's avatar
Fabien Morin committed
1166
          LOG('ManageCSS', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1167
              '   size_x=%s' % properties_field['size_x'])
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
          field_dict[4] = {}
          field_dict[4]['width'] = str(width_part) + 'px'
          field_dict[4]['margin-left'] = \
             str(int(properties_field['position_x']) +\
             int(properties_field['size_x']) - width_part*2) + 'px'

          field_dict[5] = {}
          field_dict[5]['width'] = str(width_part) + 'px'
          field_dict[5]['margin-left'] = \
             str(int(properties_field['position_x']) +\
             int(properties_field['size_x']) - width_part) + 'px'

      # number of fields to generate
Fabien Morin's avatar
Fabien Morin committed
1181
      LOG('ManageCSS', INFO, '\n   field_number = %s' % field_nb)
1182 1183 1184 1185 1186 1187 1188

      field_nb_range = field_nb + 1
      field_range = range(field_nb_range)
      for iterator in field_range:
        # iterator take the field_id according to the field_nb
        # ie (0..field_nb)
        #iterator = it + 1
Fabien Morin's avatar
Fabien Morin committed
1189
        LOG('ManageCSS', INFO, '   sub_field_id=%s' % iterator)
1190 1191 1192 1193
        if iterator == 0:
          class_name = field_name + '_class'
        else:
          class_name = field_name + '_class_' + str(iterator)
Fabien Morin's avatar
Fabien Morin committed
1194
        LOG('ManageCSS', INFO, '   class_name=%s' % class_name)
1195 1196 1197 1198 1199

        # managing standard class properties
        properties_css_dict['standard'][class_name] = {}
        for prop_id in properties_css_object_stand.keys():
          # saving global class properties into final dict
1200 1201
          properties_css_dict['standard'][class_name][prop_id] = \
              properties_css_object_stand[prop_id]
1202 1203
        for prop_id in field_dict[iterator].keys():
          # then adding special field properties (usually width and position_x)
1204 1205
          properties_css_dict['standard'][class_name][prop_id] = \
              field_dict[iterator][prop_id]
1206 1207 1208 1209

        # managing class error properties
        properties_css_dict['error'][class_name] = {}
        for prop_id in properties_css_object_error.keys():
1210 1211
          properties_css_dict['error'][class_name][prop_id] = \
              properties_css_object_error[prop_id]
1212
        for prop_id in field_dict[iterator].keys():
1213 1214
          properties_css_dict['error'][class_name][prop_id] = \
              field_dict[iterator][prop_id]
1215 1216

      # final printing for testing
Fabien Morin's avatar
Fabien Morin committed
1217
      LOG('ManageCSS', INFO, '\n\n   final printing')
1218
      for iterator in field_range:
1219 1220 1221 1222
        if iterator == 0:
          class_name = field_name + '_class'
        else:
          class_name = field_name + '_class_' + str(iterator)
Fabien Morin's avatar
Fabien Morin committed
1223
        LOG('ManageCSS', INFO, '    class=%s' % class_name)
1224
        for prop_id in properties_css_dict['standard'][class_name].keys():
Fabien Morin's avatar
Fabien Morin committed
1225
          LOG('ManageCSS', INFO, '      prop:%s=%s' % \
Fabien Morin's avatar
Fabien Morin committed
1226
              (prop_id,properties_css_dict['standard'][class_name][prop_id]))
1227 1228


1229 1230 1231
    return properties_css_dict

  security.declarePublic('setFinalProperties')
1232 1233
  def setFinalProperties( self
                        , properties_css_dict
1234 1235
                        , page_height
                        , space_between_pages):
1236 1237 1238 1239 1240 1241 1242 1243
    """
    adding 'page_end' class to add a div at the end of the last page
    in order to display the full last page under Konqueror
    Otherwize last page is cut and the user is not able to see the
    bottom of the document
    """
    properties_css_page = {}
    properties_css_page['position'] = 'relative'
1244
    properties_css_page['margin-top'] = "%spx" % str(space_between_pages)
1245 1246
    properties_css_dict['head']['page_end'] = properties_css_page
    return properties_css_dict
1247

1248
  security.declarePublic('generateOutputContent')
1249
  def generateOutputContent(self, properties_css_dict):
1250 1251 1252 1253
    """
    return a string containing the whole content of the CSS output
    from properties_css_dict
    """
Fabien Morin's avatar
Fabien Morin committed
1254
    LOG('ManageCSS', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1255
        ' createmodule > printing output from css_class_generator')
1256 1257 1258 1259
    form_css_content =  "/*-- special css form generated through ScribusUtils"\
        "module     --*/\n"
    form_css_content += "/*-- to have a graphic rendering with 'form_html' "\
        "page template --*/\n\n"
1260 1261 1262 1263 1264 1265 1266
    form_css_content += "/* head : classes declared for general purpose */\n"
    # iterating classes in document's head
    for class_name in properties_css_dict['head'].keys():
      # getting class properties_dict
      class_properties = properties_css_dict['head'][class_name]
      # joining exerything
      output_string = "." + str(class_name) + " {" \
1267 1268
                      + "; ".join(["%s:%s" % (id, val) for id, 
                        val in class_properties.items()]) \
1269 1270 1271 1272 1273 1274 1275 1276
                      + "}"
      # adding current line to css_content_object
      form_css_content += output_string + "\n"
    form_css_content += "\n/* standard field classes */ \n"
    # adding standard classes
    for class_name in properties_css_dict['standard'].keys():
      class_properties = properties_css_dict['standard'][class_name]
      output_string = "." + str(class_name) + " {" \
1277
                      + "; ".join(["%s:%s" % (id, val) for id, 
1278
                        val in class_properties.items()]) \
1279 1280 1281 1282 1283 1284 1285
                      + "}"
      form_css_content += output_string + "\n"
    form_css_content += "\n/* error field classes */\n"
    # adding error classes
    for class_name in properties_css_dict['error'].keys():
      class_properties = properties_css_dict['error'][class_name]
      output_string = "." + str(class_name) + "_error {" \
1286 1287
                      + "; ".join(["%s:%s" % (id, val) for id,
                      val in class_properties.items()]) \
1288 1289 1290 1291 1292 1293 1294
                      + "}"
      form_css_content += output_string + "\n"
    form_css_content += "\n/* text_error field classes */ \n"
    # adding field error classes
    for class_name in properties_css_dict['err_d'].keys():
      class_properties = properties_css_dict['err_d'][class_name]
      output_string = "." + str(class_name) + "_error_display {" \
1295 1296
                      + "; ".join(["%s:%s" % (id, val) for id,
                      val in class_properties.items()]) \
1297 1298 1299 1300
                      + "}"
      form_css_content += output_string + "\n"
    # return final String
    return form_css_content
1301

1302
  security.declarePublic('createOutputFile')
1303 1304 1305 1306
  def createOutputFile( self
                      , form_css_content
                      , form_css_id
                      , factory):
1307 1308 1309 1310
    """
    add a new file_object in zope, named form_css_id and containing
    the form_css_content
    """
1311
    factory.addDTMLDocument(form_css_id, "css", form_css_content)
1312 1313


Kevin Deldycke's avatar
Kevin Deldycke committed
1314 1315
class ScribusParser:
  """
1316
  Parses a Scribus file (pda) with PDF-elements inside
Kevin Deldycke's avatar
Kevin Deldycke committed
1317
  """
1318
  #declare security
Kevin Deldycke's avatar
Kevin Deldycke committed
1319
  security = ClassSecurityInfo()
1320

1321
  security.declarePublic('getObjectTooltipProperty')
1322 1323
  def getObjectTooltipProperty(self, check_key, default_value, object_name, 
      object_dict):
1324 1325
    """
    check if 'check_key' exists in 'object_dict' and has a value
1326 1327
    if true, then returns this value, else returns 'default_value' and 
    log 'object_name'
1328

1329 1330
    This function is used to get attributes'values in an object_dict and 
    to be sure a compatible value is returned (for that use default value)
1331 1332 1333
    """
    if object_dict.has_key(check_key):
      # 'check_key' exists
1334
      if len(object_dict[check_key]):
1335 1336 1337 1338 1339
        # check_key corresponding value is not null
        # returning this value
        return object_dict[check_key]
      else:
        # check_key is null, logging and asigning default value
Fabien Morin's avatar
Fabien Morin committed
1340 1341
        LOG("WARNING : " + str(object_name), WARNING, "invalid " \
            + str(check_key) + ": using " + str(default_value))
1342 1343 1344
        return default_value
    else:
      # check_key is null, logging and asigning default value
Fabien Morin's avatar
Fabien Morin committed
1345
      LOG("WARNING : " + str(object_name), WARNING, "no " + str(check_key) \
1346 1347 1348
      + ": using " + str(default_value))
      return default_value

1349 1350
  security.declarePublic('getXmlObjectPropertiesDict')
  def getXmlObjectsPropertiesDict(self, xml_string):
1351 1352 1353 1354 1355
    """
    takes a string containing a whole document and returns
    a full dict of 'PAGE', containing a dict of 'PAGEOBJECT',
    containing a dict of all the relative attributes
    """
1356

1357 1358 1359 1360
    # XXX this is a hack to correct a scribus problem
    # actualy scribus (version 1.3.3.12svn) use some invali xml caracters
    # like the '&#x5;' caracter wich is a carriage return caratere, used for
    # example in a text frame with many lines
1361 1362
    # this problem is well knowed by scribus community and seems to be
    # corrected in the 1.3.4 instable scribus version
1363 1364 1365
    xml_string = xml_string.replace('&#x5;', '\n')
    xml_string = xml_string.replace('&#x4;', '\t')

Kevin Deldycke's avatar
Kevin Deldycke committed
1366
    # Create DOM tree from the xml string
Fabien Morin's avatar
Fabien Morin committed
1367
    LOG('ScribusParser', INFO, ' > create DOM tree')
1368
    dom_tree = minidom.parseString(xml_string)
1369

1370
    # creating the root from the input file
Kevin Deldycke's avatar
Kevin Deldycke committed
1371
    dom_root = dom_tree.documentElement
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385


    # Here two cases are possible :
    # - if the Scribus Document format is 1.2.* or less, then
    #   the 'PAGE' contains all its 'PAGEOBJECT' elements so
    # - if the Scribus Document format is 1.3.*, then the 'PAGE'
    #   does not contain any other object, and each 'PAGEOBJECT'
    #   refers to its relative page_number using its 'OwnPage'
    #   property
    keep_page = 0
    if "Version" not in dom_root.attributes.keys():
      # no version propery is contained in the document
      # the content does not comply with the Scribus document
      # specification
Fabien Morin's avatar
Fabien Morin committed
1386
      LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1387
          " Bad Scribus document format : no 'Version' property ")
1388
      return (None, keep_page, 0)
1389
    else:  
1390

1391 1392 1393
      version = dom_root.attributes["Version"].value
      if version[:3] == "1.2" :
        # Scribus document format is 1.2
Fabien Morin's avatar
Fabien Morin committed
1394
        LOG('ScribusParser', INFO, ' found Scribus document format 1.2')
1395

1396
        #making a listing of all the PAGE objects
Fabien Morin's avatar
Fabien Morin committed
1397
        LOG('ScribusParser', INFO, ' > making listing of all PAGE objects')
1398
        page_list = dom_root.getElementsByTagName("PAGE")
1399

1400
        returned_page_dict = {}
1401

1402 1403
        #for each PAGE object, searching for PAGEOBJECT
        for page in page_list:
1404

1405 1406 1407 1408 1409
          # getting page number
          # parsing method from the previous ScribusUtils
          page_number = -1
          if 'NUM' in page.attributes.keys():
            page_number = str(page.attributes['NUM'].value)
1410

Fabien Morin's avatar
Fabien Morin committed
1411
          LOG('ScribusParser', INFO, '  > PAGE NUM=%s' % str(page_number))
1412

1413 1414
          # making a listing of all PAGEOBJECT in a specified PAGE
          page_object_list = page.getElementsByTagName("PAGEOBJECT")
1415

1416 1417
          # initialising global output dictionary containing pages of elements
          returned_page_object_list = []
1418

1419 1420
          # for each PAGEOBJECT, building dict with atributes
          for page_object in page_object_list:
1421

1422 1423 1424 1425 1426 1427 1428
            # initialising 
            returned_page_object = {}
            field_name = ''

            #iterating PAGEOBJECT attributes
            #old parsing method employed also here
            for node_id in page_object.attributes.keys():
1429 1430
              node_name = node_id.encode('utf8')
              node_value = page_object.attributes[node_id].value.encode('utf8')
1431

1432
              returned_page_object[node_name] = node_value
1433 1434 1435

              if node_name == 'ANNAME':
                if node_value != '':
1436
                  field_name = node_value.replace(' ', '_')
1437

1438 1439 1440 1441
            if field_name != '' :
              #if 'PAGEOBJECT' has a valid name, then adding it to the global
              #dictionary containing all the 'PAGEOBJECT' of the 'PAGE'
              returned_page_object_list.append(returned_page_object)
Fabien Morin's avatar
Fabien Morin committed
1442 1443
              LOG('ScribusParser', INFO, 
                  '    > PAGEOBJECT = ' + str(field_name))
1444

1445
          #after having scanned all 'PAGEOBJECT' from a 'PAGE', adding the
1446 1447
          #relative informations to the list of 'PAGE' before going to 
          # the next one
1448 1449 1450 1451
          #in case the page is not empty
          if len(returned_page_object_list) != 0: 
            returned_page_dict[page_number] = returned_page_object_list

Fabien Morin's avatar
Fabien Morin committed
1452
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1453
            '=> end ScribusParser.getXmlObjectPropertiesDict')
1454
        return (returned_page_dict, keep_page, 0)
1455 1456

        # end parsing document version 1.2.*
1457

1458
      else:
Fabien Morin's avatar
Fabien Morin committed
1459 1460
        LOG('ScribusParser', INFO, 
            ' found Scribus Doucment format 1.3 or higher')
1461 1462
        # assuming version is compliant with 1.3.* specifications

1463
        keep_page = 1
1464

1465 1466
        # first of all getting DOCUMENT element to recover Scratch coordinates
        document_list = dom_root.getElementsByTagName("DOCUMENT")
1467 1468 1469 1470
        scratch_left = \
            int(float(document_list[0].attributes["ScratchLeft"].value))
        scratch_top = \
            int(float(document_list[0].attributes["ScratchTop"].value))
1471
        page_gap = int(float(document_list[0].attributes["BORDERTOP"].value))
1472 1473
        scribus_page_width = \
            int(float(document_list[0].attributes["PAGEWIDTH"].value))
1474 1475
        scribus_page_height = \
           int(float(document_list[0].attributes["PAGEHEIGHT"].value)) 
Fabien Morin's avatar
Fabien Morin committed
1476
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1477 1478
            ' DOCUMENT > scratch_left = %s      scratch_top = %s' % \
            (scratch_left, scratch_top))
1479 1480 1481 1482 1483 1484 1485
        #page_list = dom_root.getElementsByTagName("PAGE")
        page_object_list = dom_root.getElementsByTagName("PAGEOBJECT")

        # iterating 'PAGE' to build the first layer of the output structure
        #for page in page_list:
        #  page_number = page

1486 1487
        # iterating 'PAGEOBJECT' to check compatibility (need a 'ANNAME' 
        # property) and recover the related 'PAGE'
1488 1489 1490 1491 1492 1493 1494
        returned_page_dict = {}
        for page_object in page_object_list:
          returned_page_object = {}
          field_name = ''
          field_OwnPage = ''
          # iterating field attributes
          for node_id in page_object.attributes.keys():
1495 1496
            node_name = node_id.encode('utf8')
            node_value = page_object.attributes[node_id].value.encode('utf8')
1497 1498 1499

            if node_name == 'ANNAME':
              if node_value != '':
1500
                field_name = node_value.replace(' ', '_')
Fabien Morin's avatar
Fabien Morin committed
1501
                LOG('ScribusParser', INFO, '> found field : %s' % field_name)
1502 1503 1504
            elif node_name == 'OwnPage':
              field_OwnPage = node_value
            elif node_name == 'XPOS':
Fabien Morin's avatar
Fabien Morin committed
1505 1506
              LOG('ScribusParser', INFO, 
                  '   > updating Xpos : %s - %s = %s' % \
1507
                  (scratch_left+int(float(node_value)), scratch_left, 
Fabien Morin's avatar
Fabien Morin committed
1508
                      node_value))
1509 1510
              node_value = str(int(float(node_value)) - scratch_left)
            elif node_name == 'YPOS':
Fabien Morin's avatar
Fabien Morin committed
1511 1512
              LOG('ScribusParser', INFO, 
                  '   > updating Ypos : %s - %s = %s' % \
Fabien Morin's avatar
Fabien Morin committed
1513 1514
                  (scratch_top+int(float(node_value)), scratch_top,
                    node_value))
1515 1516 1517 1518 1519
              node_value = str(int(float(node_value)) - scratch_top)

            returned_page_object[node_name] = node_value

          if field_name != '':
Fabien Morin's avatar
Fabien Morin committed
1520 1521
            LOG('ScribusParser', INFO, 
                ' > field has the name : %s' % field_name)
1522 1523 1524 1525
            # field seems to be ok, just need to check if the related page
            # already exists in the 'returned_page_dict'
            if not field_OwnPage in returned_page_dict.keys():
              # page does not exists, need to create it before adding the field
Fabien Morin's avatar
Fabien Morin committed
1526 1527
              LOG('ScribusParser', INFO, 
                  '  > adding new page')
1528 1529
              returned_page_dict[field_OwnPage] = []
            returned_page_dict[field_OwnPage].append(returned_page_object)
1530
        return (returned_page_dict, keep_page, page_gap)
1531

Kevin Deldycke's avatar
Kevin Deldycke committed
1532

1533
  security.declarePublic('getPropertiesConversionDict')
1534
  def getPropertiesConversionDict(self, text_page_dict, option_html):
1535
    """
1536 1537 1538 1539
    takes a dict generated from 'getXmlObjectsProperties' method
    and returns a dict of PAGE including a list with usefull
    'PAGEOBJECT' attributes updated with standard attributes
    and special informations contained in the
1540
    'ANTOOLTIP' attribute.
1541

1542 1543 1544 1545 1546 1547 1548 1549
    usefull attributes are
    - position & size
    - type & inputformat (for erp5 and html)
    - creation order (using 'nb' property)
    - erp5 relative position (left, right, etc.)
    - title information
    - other properties (read_only, multiline, etc.)
    - etc.
1550

1551 1552 1553 1554
    for each PAGE, all PAGEOBJECT are sorted according to their creation order
    'nb'
    """

Fabien Morin's avatar
Fabien Morin committed
1555
    LOG('ScribusParser', INFO, '\n  => ScribusParser.getPropertiesConversion')
1556
    returned_page_dict = {}
1557

1558 1559
    # declaring ScribusParser object to run other functions
    sp = ScribusParser()
1560

1561 1562 1563 1564 1565
    for page_number in text_page_dict.keys():
      # iterating through 'PAGE' object of the document
      # id = page_number
      # content = page_content
      page_content = text_page_dict[page_number]
1566

Fabien Morin's avatar
Fabien Morin committed
1567
      LOG('ScribusParser', INFO, ' => PAGE = %s" % str(page_number)')
1568

1569 1570 1571 1572 1573 1574
      # declaring special lists used to generate nb for all objects
      # this 'nb' property is usefull to define the object creation order
      # all objects are sorted (has nb / has no nb) and all objects without
      # nb attribte are added t othe end of the 'has nb' list
      nb_property_nbkey_list = []
      nb_property_nonbkey_list = []
1575

1576 1577
      # declaring output object
      returned_object_dict = {}
1578

1579 1580
      # if page_content.haskey('my_fax_field')
      # print "my_fax_field"
1581
      for object_data in page_content:
1582 1583 1584
        # iterating through 'PAGEOBJECT' of the page
        # id = object_name
        # content = object_content
1585

1586 1587 1588
        object_name = object_data['ANNAME']
        del object_data['ANNAME']
        object_content = object_data
1589 1590
        multiline_field= 0
        #multiline_field= object_content['ANFLAG']
Fabien Morin's avatar
Fabien Morin committed
1591
        LOG('ScribusParser', INFO, '  => PAGEOBJECT = " + str(object_name)')
1592 1593
        # recovering other attributes list (string format) from 'ANTOOLTIP'
        text_tooltipfield_properties = \
1594 1595
           sp.getObjectTooltipProperty('ANTOOLTIP', '', object_name, 
               object_content)
1596 1597
        #recovering the page attributes

1598 1599 1600
        #declaring output file
        tooltipfield_properties_dict = {}
        #splitting the different attributes
1601 1602
        tooltipfield_properties_list =  \
                    text_tooltipfield_properties.split('#')
1603

Fabien Morin's avatar
Fabien Morin committed
1604 1605
        LOG('ScribusParser', INFO, 
            '      ' + str(tooltipfield_properties_list))
1606

1607 1608 1609
        # test if first argument is nb according to previous
        # naming-conventions i.e composed of three digits without
        # id 'nb:' written
1610
        if  str(tooltipfield_properties_list[0]).isdigit():
1611 1612 1613
          # first value of tooltilfield is digit : assuming this is
          # a creation-order information compliant with the previous
          # naming convention
1614
          # modifying this field to make it compatible with new convention
Fabien Morin's avatar
Fabien Morin committed
1615
          LOG('ScribusParser', INFO, '        => first element = ' + \
Fabien Morin's avatar
Fabien Morin committed
1616
                str(tooltipfield_properties_list[0] + " is digit..."))
Fabien Morin's avatar
Fabien Morin committed
1617
          LOG("WARNING : " + str(object_name), WARNING, "out-of-date " \
1618 1619 1620 1621 1622
             + "for tooltipfield, please check naming_conventions")
          temp_nb = tooltipfield_properties_list[0]
          # deleting actual entry
          tooltipfield_properties_list.remove(temp_nb)
          # adding new entry to the list
1623
          tooltipfield_properties_list.append( "nb:" + str(temp_nb))
1624 1625 1626
          # end of translating work to get new standard compliant code
        for tooltipfield_property in tooltipfield_properties_list:
          #printing each property before spliting
Fabien Morin's avatar
Fabien Morin committed
1627
          LOG('ScribusParser', INFO, '         ' + str(tooltipfield_property))
1628 1629 1630 1631 1632 1633
          # splitting attribute_id / attribute_value
          tooltipfield_properties_split = tooltipfield_property.split(':')
          if len(tooltipfield_properties_split) == 2:
            tooltipfield_id = tooltipfield_properties_split[0]
            tooltipfield_value = tooltipfield_properties_split[1]
            # making dictionary from 'ANTOOLTIP' attributes
1634 1635
            tooltipfield_properties_dict[tooltipfield_id] = \
                        tooltipfield_value
1636
        # end of 'ANTOOLTIP' parsing
1637

1638 1639 1640 1641
        # getting usefull attributes from scribus 'PAGEOBJECT
        #and 'ANTOOLTIP'
        #
        object_properties = {} 
1642
        page_properties = {}
1643
        # getting object position and size
1644 1645
        object_properties['position_x'] = sp.getObjectTooltipProperty(\
                                          'XPOS',
1646 1647 1648
                                          '0',
                                          object_name,
                                          object_content)
1649 1650
        object_properties['position_y'] = sp.getObjectTooltipProperty(\
                                          'YPOS',
1651 1652 1653
                                          '0',
                                          object_name,
                                          object_content)
1654 1655 1656 1657 1658 1659 1660
        object_properties['size_x'] = sp.getObjectTooltipProperty(\
                                          'WIDTH',
                                          '100',
                                          object_name,
                                          object_content)
        object_properties['size_y'] = sp.getObjectTooltipProperty(\
                                          'HEIGHT',
1661
                                           '17',
1662 1663
                                          object_name,
                                          object_content)
1664

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
        # converting values to integer-compliant to prevent errors
        # when using them for that converting from 'str' -> 'float'
        # -> 'int' -> 'str'
        object_properties['position_x'] = \
              str(int(float(object_properties['position_x'])))
        object_properties['position_x'] = \
              str(int(float(object_properties['position_x'])))
        object_properties['position_y'] = \
              str(int(float(object_properties['position_y'])))
        object_properties['size_x'] = \
              str(int(float(object_properties['size_x'])))
        object_properties['size_y'] = \
              str(int(float(object_properties['size_y'])))
1678

1679 1680
        # getting object title
        # object title can only be user-specified in the 'tooltip' dict
1681 1682 1683 1684 1685
        object_properties['title'] = \
              sp.getObjectTooltipProperty('title',
                                          object_name,
                                          object_name,
                                          tooltipfield_properties_dict)
1686

1687
        # getting object order position for erp5 form
1688 1689 1690 1691 1692 1693
        temp_order = \
            sp.getObjectTooltipProperty('order',
                                        'none',
                                        object_name,
                                        tooltipfield_properties_dict)

1694 1695
        if temp_order not in  ['left','right']:
          # temp_order invalid
1696 1697
          # trying to get it from its position in original Scribus file
          if int(object_properties['position_x']) > 280.0 :
1698 1699 1700
            temp_order = 'right'
          else :
            temp_order = 'left'
1701
        object_properties['order'] = temp_order
1702 1703

        # getting special ANFLAG sub-properties
1704 1705 1706 1707
        temp_ANFLAG = long(sp.getObjectTooltipProperty('ANFLAG',
                                                       0,
                                                       object_name,
                                                       object_content))
1708 1709 1710 1711 1712 1713 1714 1715 1716
        # initialising results
        anflag_properties = {}
        anflag_properties['noScroll'] = 0
        anflag_properties['noSpellCheck'] = 0
        anflag_properties['editable'] = 0
        anflag_properties['password'] = 0
        anflag_properties['multiline'] = 0
        anflag_properties['noExport'] = 0
        anflag_properties['required'] = 0
1717
        anflag_properties['editable'] = 1
1718
        # analysing result
Fabien Morin's avatar
Fabien Morin committed
1719
        LOG('ScribusParser', INFO, '      => ANFLAG = ' + str(temp_ANFLAG))
1720 1721 1722
        # These tests uses some special variables
        # defined at the begining of the script
        if temp_ANFLAG - long(def_noScroll) >= 0:
1723
          # substracting value
1724
          temp_ANFLAG = temp_ANFLAG - long(def_noScroll)
1725 1726 1727
          # 'do not scroll' field
          # adding property
          anflag_properties['noscroll'] = 1
1728 1729
        if temp_ANFLAG - long(def_noSpellCheck) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_noSpellCheck)
1730 1731
          # 'do not spell check' field
          anflag_properties['noSpellCheck'] = 1
1732 1733
        if temp_ANFLAG - long(def_editable) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_editable)
1734 1735
          # 'editable' field
          anflag_properties['editable'] = 1
1736 1737
        if temp_ANFLAG - long(def_password) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_password)
1738 1739
          # 'password' field
          anflag_properties['password'] = 1
1740 1741
        if temp_ANFLAG - long(def_multiLine) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_multiLine)
1742 1743
          # 'multiline' field
          anflag_properties['multiline'] = 1
1744 1745
        if temp_ANFLAG - long(def_noExport) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_noExport)
1746 1747
          # 'do not export data' field
          anflag_properties['noExport'] = 1
1748 1749
        if temp_ANFLAG - long(def_required) >= 0:
          temp_ANFLAG = temp_ANFLAG - long(def_required)
1750 1751
          # 'required field
          anflag_properties['required'] = 1
1752
        if temp_ANFLAG == long(def_readOnly):
1753
          # 'read only" field
1754
          anflag_properties['editable'] = 0
Kevin Deldycke's avatar
Kevin Deldycke committed
1755

1756
        # getting maximum number of caracters the field can hold
1757 1758 1759 1760 1761
        # note : only used for textfields ('StringField', 'IntegerField',
        # 'FloatField', etc.)
        # first checking user specifications in tooltipfield
        object_properties['maximum_input'] = \
              sp.getObjectTooltipProperty('maximum_input',
1762 1763 1764
                                          0,
                                          object_name,
                                          tooltipfield_properties_dict)
1765 1766 1767 1768 1769 1770 1771
        # if returned value is empty, then trying 'ANMC' Scribus property
        if object_properties['maximum_input'] == 0:
          object_properties['maximum_input'] = \
                sp.getObjectTooltipProperty('ANMC',
                                            '0',
                                            object_name,
                                            object_content)
Fabien Morin's avatar
Fabien Morin committed
1772
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1773
            '      => MaxInput = %s' % object_properties['maximum_input'])
1774

1775 1776 1777
        # getting object type :
        # first checking for user-specified type in 'tooltip' properties
        if tooltipfield_properties_dict.has_key('type'):
1778 1779
          # 'type' id in tooltip : using it and ignoring other 'type'
          # information in scribus properties
1780
          object_properties['type'] = tooltipfield_properties_dict['type']
1781 1782 1783 1784 1785 1786
        elif tooltipfield_properties_dict.has_key('title_item'):
          # if page_object has a special attribute 'title_item' this means
          # the field is a CheckBoxField
          object_properties['type'] = 'CheckBoxField'
        # if no user-specified type has been found, trying to
        # find scribus-type  
1787 1788 1789 1790
        elif object_content.has_key('ANTYPE'):
          # from scribus type (selected in the scribus PDF-form properties)
          object_type = str(object_content['ANTYPE'])
          if object_type == '2':
1791 1792
            #type 2 = PDF-Button : InputButtonField
            object_properties['type'] = 'InputButtonField'
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
          elif object_type == '3':
            #type 3 = PDF-Text : Stringfield by default
            object_properties['type'] = 'StringField'
            if anflag_properties['multiline'] == 1:
              # Stringfield is multiline, converting to TextAreaField
              object_properties['type'] = 'TextAreaField'
            elif object_content.has_key('ANFORMAT'):
              object_format = str(object_content['ANFORMAT'])
              # checking kind of Stringfield
              if object_format == '1':
                #type is number
                object_properties['type'] = 'IntegerField'
              elif object_format == '2':
                #type is percentage
                object_properties['type'] = 'FloatField'
              elif object_format == '3':
                #type is date
                object_properties['type'] = 'DateTimeField'
              elif object_format == '4':
                #type is time
                object_properties['type'] = 'DateTimeField'
          elif object_type == '4':
            # type 4 = PDF-Checkbox
            object_properties['type'] = 'CheckBoxField'
          elif object_type == '5':
            # type 5 = PDF-Combobox
            object_properties['type'] = 'ComboBox'
          elif object_type == '6':
            # type 6 = PDF-ListBox
            object_properties['type'] = 'ListBox'
        else:
1824 1825 1826 1827
          # object type not found in user-properties neither in
          # document-properties. logging and initialising with
          # default type
          LOG("WARNING : " + str(object_name),
Fabien Morin's avatar
Fabien Morin committed
1828
              WARNING,
1829
              "no 'type' found, please check your document properties")
Fabien Morin's avatar
Fabien Morin committed
1830
          LOG('ScribusParser', WARNING, 
Fabien Morin's avatar
Fabien Morin committed
1831
              '      => no type specified :  default = StringField') 
1832
          object_properties['type'] = 'StringField'
Fabien Morin's avatar
Fabien Morin committed
1833
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1834
            '      type = ' + str(object_properties['type']))
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850


        # getting data_type relative to object type (used in
        # object property_sheet to save field value.
        object_properties['data_type'] = 'string'
        object_properties['default_data'] = ''
        if object_properties['type'] == 'IntegerField':
          object_properties['data_type'] = 'int'
          object_properties['default_data'] = 0
        if object_properties['type'] == 'CheckBoxField':
          object_properties['data_type'] = 'boolean'
          object_properties['default_data'] = 0
        if object_properties['type'] == 'DateTimeField':
          object_properties['data_type'] = 'date'
          object_properties['default_data'] = '1970/01/01'

1851
        # getting 'required' property
1852 1853 1854 1855 1856 1857 1858
        # checking for user data in tooltipfield. if nothing found then
        # taking hard-written value in anflag properties
        object_properties['required'] = \
            sp.getObjectTooltipProperty('required',
                                        anflag_properties['required'],
                                        object_name,
                                        tooltipfield_properties_dict)
1859

1860 1861 1862 1863 1864 1865
        object_properties['editable'] = \
            sp.getObjectTooltipProperty('editable',
                                        anflag_properties['editable'],
                                        object_name,
                                        tooltipfield_properties_dict)

1866
        # getting type properties for special types
1867 1868
        object_properties['rendering'] = 'single'
        # Stringfields handle properties
1869 1870 1871
        # checkbox objects belongs to a group of checkbox
        if str(object_properties['type']) == 'CheckBox' :
          # checking if THIS checkbox is in a group
1872 1873 1874 1875 1876
          object_properties['group'] = \
                sp.getObjectTooltipProperty('group',
                                            '0',
                                            object_name,
                                            tooltipfield_properties_dict)
Fabien Morin's avatar
Fabien Morin committed
1877
          LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1878
              '      group = ' + str(object_properties['group']))  
1879 1880 1881
        # object is listbox, and listbox have several possible values
        # WARNING listbox have not been tested in graphic rendering for
        # the moment. is there any use for listbox in PDF-like rendering ?
1882 1883
        if str(object_properties['type']) in ('ListBox', 'RadioField') :
          # checking if this listbox and the radioField has different possible values
1884 1885 1886 1887 1888 1889
          object_properties['items'] = \
                sp.getObjectTooltipProperty('items',
                                            '',
                                            object_name,
                                            tooltipfield_properties_dict)
        # object is datetimefield and need several informations
1890
        if str(object_properties['type']) == 'DateTimeField':
1891 1892 1893 1894 1895 1896 1897 1898
          # has been tested successfully
          object_properties['rendering'] = 'multiple'
          # checking if field has input_order property
          object_properties['input_order'] = \
                sp.getObjectTooltipProperty('input_order',
                                            'ymd',
                                            object_name,
                                            tooltipfield_properties_dict)
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
          # checking if field has date_only property
          object_properties['date_only'] = \
                sp.getObjectTooltipProperty('date_only',
                                            '1',
                                            object_name,
                                            tooltipfield_properties_dict)

          # checking if special date separator is specified
          # most of PDF forms already have '/' character to differenciate
          # date fields, in this case no separator is needed and the script
          # will automatically insert ' ' between element.
          # > this value is not used in ScribusUtils.py , but in PDFForm.py
          # when creating the fdf file to fill the PDF form.
1913 1914 1915 1916 1917
          if option_html == 1 and object_properties['editable'] == 1:
            object_properties['date_separator'] = ''
            object_properties['time_separator'] = ''
          else:
            object_properties['date_separator'] = \
1918
                sp.getObjectTooltipProperty('date_separator',
1919
                                            '/',
1920 1921
                                            object_name,
                                            tooltipfield_properties_dict)
1922
            object_properties['time_separator'] = \
1923
                sp.getObjectTooltipProperty('time_separator',
1924
                                            ':',
1925 1926
                                            object_name,
                                            tooltipfield_properties_dict)
1927

1928
        # object is relationstringfield and needs some information
1929
        if str(object_properties['type']) == 'RelationStringField':
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
          # has been tested successfully
          object_properties['rendering'] = 'multiple'
          object_properties['portal_type'] = \
                sp.getObjectTooltipProperty('portal_type',
                                            '0',
                                            object_name,
                                            tooltipfield_properties_dict)
          object_properties['base_category'] = \
                sp.getObjectTooltipProperty('base_category',
                                            '0',
                                            object_name,
                                            tooltipfield_properties_dict)
          object_properties['catalog_index'] = \
                sp.getObjectTooltipProperty('catalog_index',
                                            '0',
                                            object_name,
                                            tooltipfield_properties_dict)
          object_properties['default_module'] = \
                sp.getObjectTooltipProperty('default_module',
                                            '0',
                                            object_name,
                                            tooltipfield_properties_dict)
1952

1953 1954
        # getting creation order from 'tooltip' properties
        # used to create ERP5 objects in a special order
1955 1956
        if tooltipfield_properties_dict.has_key('nb') and \
           str(tooltipfield_properties_dict['nb']).isdigit():
1957 1958 1959
          # object has a nb properties containing its creation position
          # adding the object in the ordered list
          nb_value = int(tooltipfield_properties_dict['nb'])
Fabien Morin's avatar
Fabien Morin committed
1960 1961 1962
          LOG('ScribusParser', INFO, 
              "      =>'nb' property specified : using it")
          LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1963
              '         > len(list)=%s' % len(nb_property_nbkey_list))
1964 1965 1966
          # iterating through existing list to find right position
          # before inserting value
          if len(nb_property_nbkey_list) == 0:
Fabien Morin's avatar
Fabien Morin committed
1967
            LOG('ScribusParser', WARNING, 
Fabien Morin's avatar
Fabien Morin committed
1968
                "    => 'nb' list empty : adding without sorting")
1969
            # list is empty : adding value without sort
1970
            nb_property_nbkey_list.insert(0, (nb_value,object_name))
1971 1972
          elif nb_property_nbkey_list[len(nb_property_nbkey_list)-1][0] <= \
              nb_value:
Fabien Morin's avatar
Fabien Morin committed
1973
            LOG('ScribusParser', INFO, "    => 'nb' end : adding at the end")
1974
            # last element is smaller than new element : adding at the end
1975
            nb_property_nbkey_list.append((nb_value, object_name))
1976
          else:
Fabien Morin's avatar
Fabien Morin committed
1977
            LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1978
                '    => checking for place to add the element')
1979 1980 1981 1982
            # searching where to insert the element in the ordered list
            for temp_key in range(len(nb_property_nbkey_list)):
              temp_value = nb_property_nbkey_list[temp_key][0]
              temp_content = nb_property_nbkey_list[temp_key][1]
Fabien Morin's avatar
Fabien Morin committed
1983 1984
              LOG('ScribusParser', INFO, 
                  "      @" + str(temp_key) + " temp=" + \
Fabien Morin's avatar
Fabien Morin committed
1985
                  str(temp_value) + "/" + str(nb_value))
1986 1987 1988
              if nb_value < temp_value:
                #first position where actual 'nb' is smaller than temp 'nb'
                # inserting new couple (nb_value,object_name) here
Fabien Morin's avatar
Fabien Morin committed
1989
                LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
1990 1991
                    '      inserting here : ' + str(temp_value) + \
                    "/" + str(nb_value))
1992 1993
                nb_property_nbkey_list.insert(temp_key, (nb_value, 
                  object_name))
1994 1995
                # element has been insered , 
                # no need to continue the search => breaking
1996 1997 1998 1999
                break
        else:
          # object has no nb property. logging and adding it to the list of
          # nb-less objects. Script will automatically find a 'nb' value for this element
Fabien Morin's avatar
Fabien Morin committed
2000
          LOG("WARNING : " + str(object_name), WARNING, 
2001
              "no 'nb' defined : finding a free slot")
Fabien Morin's avatar
Fabien Morin committed
2002
          LOG('ScribusParser', WARNING, 
Fabien Morin's avatar
Fabien Morin committed
2003 2004
              "      => no 'nb' property specified : post-processing "\
              "will try to define one")
2005
          nb_property_nonbkey_list.append(object_name)
2006

2007 2008 2009
        # adding current object with its relative properties to the dict
        # before going to the next page_object
        returned_object_dict[object_name] = object_properties
2010

2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
      # final processing before returning full page with modified
      # page_object_properties : setting 'nb' property to all objects
      # without user-specified 'nb' property
      for object_name in nb_property_nonbkey_list:
        # listing all objects with no 'nb' declared
        # defining final position in output list : absolute pos + relative pos
        object_position = len(nb_property_nbkey_list) + 1 
        # and addind it to the end of the final nb-list
        # to give them a 'nb' property
        nb_property_nbkey_list.append((object_position,object_name))
Fabien Morin's avatar
Fabien Morin committed
2021
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
2022
            "    => 'nb' found for %s : %s" % (object_name, object_position))
2023

2024
      # now all page_object are referenced in the list, we just need to sort
2025 2026
      # the elements in the good order. for that a new list of objects 
      #is needed
2027 2028 2029 2030 2031 2032 2033 2034
      returned_object_list = []
      for nb_ind in range(len(nb_property_nbkey_list)):
        # iterating through final nb-list
        # getting list-object information
        (nb_key, nb_value) = nb_property_nbkey_list[nb_ind]
        # setting object's 'nb' property
        returned_object_dict[nb_value]['nb'] = nb_ind + 1
        # add the object at the end of the new list
2035
        returned_object_list.append((nb_value, returned_object_dict[nb_value]))
2036

2037 2038 2039
      # adding returned list of object to the page dict
      # before going to the next page
      returned_page_dict[page_number] = returned_object_list
2040

2041
    # returning final dict containing all the modified data
Fabien Morin's avatar
Fabien Morin committed
2042 2043
    LOG('ScribusParser', INFO, 
        '  => end ScribusParser.getPropertiesConversion')
2044
    return (returned_page_dict)
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058

  security.declarePublic('initFieldDict')
  def initFieldDict(self):
    """
    initialize the global_properties dict. this dict will be filled
    with Field attributes (from getFieldAttributes)
    """
    # initializing sub dicts and attributes
    global_object_dict = {}
    global_page_number = 0
    # defining main dict
    global_properties = {}
    global_properties['object'] = global_object_dict
    global_properties['page'] = global_page_number
Fabien Morin's avatar
Fabien Morin committed
2059
    global_properties['page_width'] = 595
2060
    global_properties['page_height']= 842
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    # return final main dict
    return global_properties




  security.declarePublic('getFieldAttributes')
  def getFieldAttributes(self,
                         field,
                         option_html,
                         page_id,
2072
                         global_properties):
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
    """
    get only useful field attributes from properties_field
    and save them in global_properties
    """
    (id,properties_field) = field
    # declaring dict to store data
    object_dict = {}
    # getting usefull properties for field generation
    object_dict['title'] = str(properties_field['title'])
    object_dict['erp_type'] = str(properties_field['type'])
    object_dict['data_type'] = str(properties_field['data_type'])
    object_dict['default'] = properties_field['default_data']
    object_dict['nb'] = str(properties_field['nb'])
    object_dict['attributes'] = {}
    if option_html ==1:
      # pdf-like rendering
      object_dict['order'] = page_id
    else:
      # erp rendering
      object_dict['order'] = properties_field['order']
    # recovering attributes
    # required attribute specify if the user has to fill this field
    object_dict['attributes']['required'] =\
               properties_field['required']
2097 2098 2099
    # editable attribute specify if the user can fill this field or not
    object_dict['attributes']['editable'] =\
               properties_field['editable']
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    # max number of caracters that can be entered in a field
    # only used with String fieds (including Integer and Float fields)
    if 'maximum_input' in properties_field.keys():
      if 'display_maxwidth' in object_dict['attributes'].keys():
        object_dict['attributes']['display_maxwidth'] = \
                 int(properties_field['maximum_input'])
        # can only be effective without css class, i.e only effective
        # in a ERP5-like rendering
      if 'display_width' in object_dict['attributes'].keys():
        object_dict['attributes']['display_width'] = \
                 int(properties_field['maximum_width'])

    # getting special properties for DateTimeField objects
    if object_dict['erp_type'] == 'DateTimeField':
      # recovering ERP equivalent for user's input_order
2115
      if properties_field['input_order'] in ['day/month/year', 'dmy', 'dmY']:
2116
        object_dict['attributes']['input_order'] = 'dmy'
2117
      elif properties_field['input_order'] in ['month/day/year','mdy', 'mdY']:
2118
        object_dict['attributes']['input_order'] = 'mdy'
2119
      elif properties_field['input_order'] in ['year/month/day','ymd', 'Ymd']:
2120 2121
        object_dict['attributes']['input_order'] = 'ymd'
      else:
Fabien Morin's avatar
Fabien Morin committed
2122
        LOG('ScribusParser', INFO, 
Fabien Morin's avatar
Fabien Morin committed
2123
            "   found incompatible 'input_order', assuming default ymd")
2124 2125
        object_dict['attributes']['input_order'] = 'ymd'
      # checking if date only or date + time
2126 2127
      object_dict['attributes']['date_only'] = \
          int(properties_field['date_only'])
2128 2129 2130 2131 2132

      object_dict['attributes']['date_separator'] = \
          properties_field['date_separator']
      object_dict['attributes']['time_separator'] = \
          properties_field['time_separator']
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
    # getting special attributes for RelationStringField
    elif object_dict['erp_type'] == 'RelationStringField':
      portal_type_item = properties_field['portal_type'].capitalize()
      object_dict['attributes']['portal_type'] =\
                 [(portal_type_item,portal_type_item)]
      object_dict['attributes']['base_category'] =\
                 properties_field['base_category']
      object_dict['attributes']['catalog_index'] =\
                 properties_field['catalog_index']
      object_dict['attributes']['default_module'] =\
                 properties_field['default_module']
2144
    # idem : special field concerning RadioField ( tested )
2145 2146 2147
    elif object_dict['erp_type'] == 'RadioField':
      # radio fields have not been tested for the moment
      items = []
2148
      for word_item in properties_field['items'].split('|'):
2149
        items.append((word_item, word_item.capitalize()))
2150
      object_dict['attributes']['items'] = items
2151 2152 2153 2154 2155 2156 2157 2158
    #elif object_dict['erp_type'] == 'CheckBoxField':
      # checkboxfield needs to have their field data updated
      # this is not done automatically so it is needed to do
      # it manually

    # save attributes to the global_properties dict
    global_properties['object'][id] = object_dict

Kevin Deldycke's avatar
Kevin Deldycke committed
2159 2160 2161 2162
  security.declareProtected('Import/Export objects', 'getContentFile')
  def getContentFile(self, file_descriptor):
    """ Get file content """
    return file_descriptor.read()
2163 2164 2165 2166
  security.declareProtected('Import/Export objects', 'getFileOpen')
  def getFileOpen(self, file_descriptor):
    """ Get file content """
    return file_descriptor.open('r')
Kevin Deldycke's avatar
Kevin Deldycke committed
2167 2168 2169
  
InitializeClass(ScribusParser)
allow_class(ScribusParser)  
2170 2171 2172 2173 2174 2175 2176 2177 2178

InitializeClass(ManageCSS)
allow_class(ManageCSS)

InitializeClass(ManageFiles)
allow_class(ManageFiles)

InitializeClass(ManageModule)
allow_class(ManageModule)