ListBox.py 125 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3 4
# Copyright (c) 2002,2006 Nexedi SARL and Contributors. All Rights Reserved.
#                    Yoshinori Okuji <yo@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6
#
# WARNING: This program as such is intended to be used by professional
7
# programmers who take the whole responsibility of assessing all potential
Jean-Paul Smets's avatar
Jean-Paul Smets committed
8 9
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
10
# guarantees and support are strongly adviced to contract a Free Software
Jean-Paul Smets's avatar
Jean-Paul Smets committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

Yoshinori Okuji's avatar
Yoshinori Okuji committed
29
import sys
30
from OFS.Traversable import NotFound
31
from AccessControl import ClassSecurityInfo, Unauthorized
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33 34
from Products.Formulator.DummyField import fields
from Products.Formulator import Widget, Validator
from Products.Formulator.Field import ZMIField
35
from Products.Formulator.Errors import FormValidationError, ValidationError
36
from Selection import Selection, DomainSelection
37
from Tool.SelectionTool import createFolderMixInPageSelectionMethod
Yoshinori Okuji's avatar
Yoshinori Okuji committed
38
from Products.ERP5Type.Utils import getPath
39
from Products.ERP5Type.Document import newTempBase
40
from Products.CMFCore.utils import getToolByName
41
from Products.ZSQLCatalog.zsqlbrain import ZSQLBrain
42
from Products.ERP5Type.Message import Message
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43

44
from Acquisition import aq_base, aq_self, aq_inner
45
import Acquisition
Jérome Perrin's avatar
Jérome Perrin committed
46
from zLOG import LOG, WARNING
Yoshinori Okuji's avatar
Yoshinori Okuji committed
47
from ZODB.POSException import ConflictError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
from Products.ERP5Type.Globals import InitializeClass, get_request
50
from Products.PythonScripts.Utility import allow_class
51
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
52
from warnings import warn
53
import cgi
54

55
DEFAULT_LISTBOX_DISPLAY_STYLE = 'table'
56 57
DEFAULT_LISTBOX_PAGE_NAVIGATION_TEMPLATE = 'ListBox_viewSliderPageNavigationRenderer'
DEFAULT_LISTBOX_PAGE_TEMPLATE = 'ListBox_asHTML'
58

59
class MethodWrapper:
60
  def __init__(self, context, method_name):
61
    self.context = context
62
    self.method_name = self.__name__ = method_name
63

64 65 66 67 68 69
  def __call__(self, *args, **kw):
    raise NotImplementedError

class ListMethodWrapper(MethodWrapper):
  """This class wraps list methods so that they behave like portal_catalog.
  """
70 71
  def __call__(self, *args, **kw):
    brain_list = []
72
    for obj in getattr(self.context, self.method_name)(*args, **kw):
73 74 75 76 77 78
      brain = ZSQLBrain(None, None).__of__(obj)
      brain.uid = obj.getUid()
      brain.path = obj.getPath()
      brain_list.append(brain)
    return brain_list

79 80 81 82 83 84
class CatalogMethodWrapper(MethodWrapper):
  """This class wraps catalog list methods so that they discard a pre-defined
     set of parameters which are part of the Selection API but not in
     SQLCatalog API.
  """
  def __call__(self, *args, **kw):
85
    for parameter_id in ('selection', 'selection_name', 'select_columns',
86
      'reset', 'selection_index', 'list_selection_name', 'list_start',
87
      'list_lines', 'listbox_list_start', 'listbox_uid', 'listbox_nextPage',
88
      'listbox_previousPage', 'listbox_page_start', 'page_start',
89 90 91 92
      # Also strip common HTML field names
      # XXX: I'm not sure if those values really belong to here
      'md5_object_uid_list', 'cancel_url', 'listbox_list_selection_name',
      'form_id', 'select_language', 'select_favorite', 'select_module',
93
      'portal_status_message', 'all_languages',
94
      'select_jump', 'select_action', 'Base_doSelect'):
95
      kw.pop(parameter_id, None)
96 97 98 99 100 101
    # Strip all entries which have an empty string as value (ie, an empty
    # field).
    # XXX: I'm not sure if this filtering really belongs to here.
    # It is probably needed at a more generic level (Forms ? Selection ?), or
    # even a more specific one (limited to HTML ?)...
    for key, value in kw.items():
102
      if value == '':
103
        kw.pop(key)
104 105
    return getattr(self.context, self.method_name)(*args, **kw)

106 107
class ReportTree:
  """This class describes a report tree.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
108
  """
109
  def __init__(self, obj = None, is_pure_summary = False, depth = 0, is_open = False,
110
               selection_domain = None, exception_uid_list = None, base_category = None):
111 112 113 114
    self.obj = obj
    self.is_pure_summary = is_pure_summary
    self.depth = depth
    self.is_open = is_open
115
    self.selection_domain = selection_domain
116 117 118
    self.exception_uid_list = exception_uid_list
    if exception_uid_list is None:
      self.exception_uid_set = None
119
    else:
120
      self.exception_uid_set = set(exception_uid_list)
121
    self.base_category = base_category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122

123 124 125 126 127 128
    relative_url = obj.getRelativeUrl()
    if base_category is not None and not relative_url.startswith(base_category + '/'):
      self.domain_url = '%s/%s' % (base_category, relative_url)
    else:
      self.domain_url = relative_url

129 130
allow_class(ReportTree)

131 132 133 134
class ReportSection:
  """This class describes a report section.
  """
  def __init__(self, is_summary = False, object_list = (), object_list_len = 0,
135
               is_open = False, selection_domain = None, context = None, offset = 0,
136
               depth = 0, domain_title = None):
137 138 139 140
    self.is_summary = is_summary
    self.object_list = object_list
    self.object_list_len = object_list_len
    self.is_open = is_open
141
    self.selection_domain = selection_domain
142 143 144
    self.context = context
    self.offset = offset
    self.depth = depth
145
    self.domain_title = domain_title
Jean-Paul Smets's avatar
Jean-Paul Smets committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

class ListBoxWidget(Widget.Widget):
    """
        ListBox widget

        The ListBox widget allows to display a collection of objects in a form.
        The ListBox widget can be used for many applications:

        1- show the content of a folder by providing a list of meta_types
           and eventually a sort order

        2- show the content of a relation by providing the name of the relation,
           a list of meta_types and eventually a sort order

        3- show the result of a search request by selecting a query and
           providing parameters for that query (and eventually a sort order)

        In all 3 cases, a parameter to hold the current start item must be
        stored somewhere, typically in a selection object.

        Parameters in case 3 should stored in a selection object which allows a per user
        per PC storage.

    """
170 171 172 173 174
    # Define Properties for ListBoxWidget.
    property_names = list(Widget.Widget.property_names)

    # Default has no meaning in ListBox.
    property_names.remove('default')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
175 176 177 178 179

    lines = fields.IntegerField('lines',
                                title='Lines',
                                description=(
        "The number of lines of this list. Required."),
180
                                default=20,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
181
                                required=1)
182
    property_names.append('lines')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
183 184 185 186 187 188 189

    columns = fields.ListTextAreaField('columns',
                                 title="Columns",
                                 description=(
        "A list of attributes names to display. Required."),
                                 default=[],
                                 required=1)
190
    property_names.append('columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
191 192 193 194 195 196 197

    all_columns = fields.ListTextAreaField('all_columns',
                                 title="More Columns",
                                 description=(
        "An optional list of attributes names to display."),
                                 default=[],
                                 required=0)
198
    property_names.append('all_columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
199

200 201 202 203 204 205 206 207
    style_columns = fields.ListTextAreaField('style_columns',
                                 title="List Style Columns",
                                 description=(
        "An optional list of list style columns to display."),
                                 default=[],
                                 required=0)
    property_names.append('style_columns')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
208 209 210 211 212 213
    search_columns = fields.ListTextAreaField('search_columns',
                                 title="Searchable Columns",
                                 description=(
        "An optional list of columns to search."),
                                 default=[],
                                 required=0)
214
    property_names.append('search_columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
215

216 217 218 219 220 221
    sort_columns = fields.ListTextAreaField('sort_columns',
                                 title="Sortable Columns",
                                 description=(
        "An optional list of columns to sort."),
                                 default=[],
                                 required=0)
222
    property_names.append('sort_columns')
223

Jean-Paul Smets's avatar
Jean-Paul Smets committed
224 225 226 227 228
    sort = fields.ListTextAreaField('sort',
                                 title='Default Sort',
                                 description=('The default sort keys and order'),
                                 default=[],
                                 required=0)
229
    property_names.append('sort')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
230 231 232

    list_method = fields.MethodField('list_method',
                                 title='List Method',
Jérome Perrin's avatar
Jérome Perrin committed
233
                                 description=('The method to use to list '
Jean-Paul Smets's avatar
Jean-Paul Smets committed
234 235 236
                                              'objects'),
                                 default='',
                                 required=0)
237
    property_names.append('list_method')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
238

239 240
    count_method = fields.MethodField('count_method',
                                 title='Count Method',
Jérome Perrin's avatar
Jérome Perrin committed
241
                                 description=('The method to use to count '
242 243 244
                                              'objects'),
                                 default='',
                                 required=0)
245
    property_names.append('count_method')
246

Jean-Paul Smets's avatar
Jean-Paul Smets committed
247 248
    stat_method = fields.MethodField('stat_method',
                                 title='Stat Method',
Jérome Perrin's avatar
Jérome Perrin committed
249
                                 description=('The method to use to stat '
Jean-Paul Smets's avatar
Jean-Paul Smets committed
250 251 252
                                              'objects'),
                                 default='',
                                 required=0)
253
    property_names.append('stat_method')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
254

255 256
    row_css_method = fields.MethodField('row_css_method',
                                 title='Row CSS Method',
Jérome Perrin's avatar
Jérome Perrin committed
257 258
                                 description=('The method to set the css '
                                              'class name of a row'),
259 260 261 262
                                 default='',
                                 required=0)
    property_names.append('row_css_method')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
263 264
    selection_name = fields.StringField('selection_name',
                                 title='Selection Name',
Jérome Perrin's avatar
Jérome Perrin committed
265 266
                                 description=('The name of the selection to '
                                              'store selection parameters'),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
267
                                 default='',
268
                                 required=0)
269
    property_names.append('selection_name')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
270 271 272 273

    meta_types = fields.ListTextAreaField('meta_types',
                                 title="Meta Types",
                                 description=(
Jérome Perrin's avatar
Jérome Perrin committed
274
        "Meta Types of objects to list."),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
275 276
                                 default=[],
                                 required=0)
277
    property_names.append('meta_types')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
278 279 280 281

    portal_types = fields.ListTextAreaField('portal_types',
                                 title="Portal Types",
                                 description=(
Jérome Perrin's avatar
Jérome Perrin committed
282
        "Portal Types of objects to list."),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
283 284
                                 default=[],
                                 required=0)
285
    property_names.append('portal_types')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
286 287 288 289 290 291 292

    default_params = fields.ListTextAreaField('default_params',
                                 title="Default Parameters",
                                 description=(
        "Default Parameters for the List Method."),
                                 default=[],
                                 required=0)
293
    property_names.append('default_params')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
294 295 296 297

    search = fields.CheckBoxField('search',
                                 title='Search Row',
                                 description=('Search Row'),
298
                                 default=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
299
                                 required=0)
300
    property_names.append('search')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
301 302 303 304

    select = fields.CheckBoxField('select',
                                 title='Select Column',
                                 description=('Select Column'),
305
                                 default=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
306
                                 required=0)
307
    property_names.append('select')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
308

309 310 311 312
    anchor = fields.CheckBoxField('anchor',
                                  title='Anchor Column',
                                  description=(
      'An optional anchor column which can always clickable.'),
313
                                  default=0,
314 315 316
                                  required=0)
    property_names.append('anchor')

Jérome Perrin's avatar
Jérome Perrin committed
317 318 319 320 321 322 323
    hide_rows_on_no_search_criterion = fields.CheckBoxField(
                                 'hide_rows_on_no_search_criterion',
                                 title='Hide Rows (On No Search Criterion)',
                                 description=('Hide listbox rows if no search '
                                             'criterion is provided by user'),
                                                default=0,
                                                required=0)
324 325
    property_names.append('hide_rows_on_no_search_criterion')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
326 327 328 329 330 331
    editable_columns = fields.ListTextAreaField('editable_columns',
                                 title="Editable Columns",
                                 description=(
        "An optional list of columns which can be modified."),
                                 default=[],
                                 required=0)
332
    property_names.append('editable_columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
333

334 335 336 337 338 339
    stat_columns = fields.ListTextAreaField('stat_columns',
                                 title="Stat Columns",
                                 description=(
        "An optional list of columns which can be used for statistics."),
                                 default=[],
                                 required=0)
340
    property_names.append('stat_columns')
341 342 343 344 345 346 347

    url_columns = fields.ListTextAreaField('url_columns',
                                 title="URL Columns",
                                 description=(
        "An optional list of columns which can provide a custom URL."),
                                 default=[],
                                 required=0)
348
    property_names.append('url_columns')
349

350 351 352 353 354 355 356 357
    untranslatable_columns = fields.ListTextAreaField('untranslatable_columns',
                                 title="Untranslatable Columns",
                                 description=(
        "An optional list of columns titles which should not be translated."),
                                 default=[],
                                 required=0)
    property_names.append('untranslatable_columns')

358
    # XXX do we still need this?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
359 360 361
    global_attributes = fields.ListTextAreaField('global_attributes',
                                 title="Global Attributes",
                                 description=(
Jérome Perrin's avatar
Jérome Perrin committed
362 363
        "An optional list of attributes which are set by hidden fields and "
        "which are applied to each editable column."),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
364 365
                                 default=[],
                                 required=0)
366
    property_names.append('global_attributes')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
367 368 369 370

    domain_tree = fields.CheckBoxField('domain_tree',
                                 title='Domain Tree',
                                 description=('Selection Tree'),
371
                                 default=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
372
                                 required=0)
373
    property_names.append('domain_tree')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
374 375 376 377 378 379 380

    domain_root_list = fields.ListTextAreaField('domain_root_list',
                                 title="Domain Root",
                                 description=(
        "A list of domains which define the possible root."),
                                 default=[],
                                 required=0)
381
    property_names.append('domain_root_list')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
382 383 384 385

    report_tree = fields.CheckBoxField('report_tree',
                                 title='Report Tree',
                                 description=('Report Tree'),
386
                                 default=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
387
                                 required=0)
388
    property_names.append('report_tree')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
389 390 391 392 393 394 395

    report_root_list = fields.ListTextAreaField('report_root_list',
                                 title="Report Root",
                                 description=(
        "A list of domains which define the possible root."),
                                 default=[],
                                 required=0)
396
    property_names.append('report_root_list')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
397

398 399 400 401 402 403 404 405
    display_style_list = fields.ListTextAreaField('display_style_list',
                                title="Display style",
                                description=(
        "A list of styles which change the listbox rendering."),
                                default=[],
                                required=0)
    property_names.append('display_style_list')

406 407 408 409
    default_display_style = fields.StringField('default_display_style',
                                title="Default display style",
                                description=(
        "A default display style for listbox rendering."),
410
                                default=DEFAULT_LISTBOX_DISPLAY_STYLE,
411 412 413
                                required=0)
    property_names.append('default_display_style')

414 415 416
    global_search_column = fields.StringField('global_search_column',
                                title="Global search column",
                                description=("Global search column make query."),
417 418
                                default=None,
                                required=0)
419
    property_names.append('global_search_column')
420

421 422 423 424
    page_navigation_template = fields.StringField('page_navigation_template',
                                title="Page Navigation Template",
                                description=("Page Navigation Template used to render listbox page navigation."),
                                default=DEFAULT_LISTBOX_PAGE_NAVIGATION_TEMPLATE,
425
                                required=0)
426
    property_names.append('page_navigation_template')
427

Jean-Paul Smets's avatar
Jean-Paul Smets committed
428 429 430
    list_action = fields.StringField('list_action',
                                 title='List Action',
                                 description=('The id of the object action'
431
                                              ' to display the current list'),
432
                                 default='',
433
                                 required=0)
434
    property_names.append('list_action')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
435

436 437 438 439 440 441 442 443
    page_template = fields.StringField('page_template',
                                 title='Page Template',
                                 description=('The id of a Page Template'
                                              ' to render the ListBox'),
                                 default='',
                                 required=0)
    property_names.append('page_template')

444
    def render_view(self, field, value, REQUEST=None, render_format='html', key='listbox', render_prefix=None):
445
        """
446
          Render a ListBox in read-only.
447
        """
448
        if REQUEST is None: REQUEST=get_request()
449 450
        return self.render(field, key, value, REQUEST, render_format=render_format,
                           render_prefix=render_prefix)
451

452 453
    def render(self, field, key, value, REQUEST, render_format='html',
               render_prefix=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
454 455 456
        """
          This is where most things happen. This method renders a list
          of items
457

Jean-Paul Smets's avatar
Jean-Paul Smets committed
458 459 460
          render_format allows to produce either HTML (default)
          or produce a generic 'list' format which can be converted by page templates
          or dtml into various formats (ex. PDF, CSV, OpenOffice, etc.)
461

Jean-Paul Smets's avatar
Jean-Paul Smets committed
462
          the 'list' format includes additional metainformation
463

Jean-Paul Smets's avatar
Jean-Paul Smets committed
464
          - depth in a report tree (ex. 0, 1, 2, etc.)
465

Jean-Paul Smets's avatar
Jean-Paul Smets committed
466
          - nature of the line (ex. stat or nonstat)
467

Jean-Paul Smets's avatar
Jean-Paul Smets committed
468
          - identification of the tree (ex. relative_url)
469

Jean-Paul Smets's avatar
Jean-Paul Smets committed
470
          - uid if any (to allow future import)
471

Jean-Paul Smets's avatar
Jean-Paul Smets committed
472
          - etc.
473

Jean-Paul Smets's avatar
Jean-Paul Smets committed
474
          which is intended to simplify operation with a spreadsheet or a pagetemplate
Jean-Paul Smets's avatar
Jean-Paul Smets committed
475
        """
476 477
        if REQUEST is None:
          REQUEST = get_request()
478
        if render_format == 'list':
479 480
          renderer = ListBoxListRenderer(self, field, REQUEST,
                                         render_prefix=render_prefix)
481
        else:
482
          renderer = ListBoxHTMLRenderer(self, field, REQUEST, render_prefix=render_prefix)
483

484
        return renderer()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
485

486
ListBoxWidgetInstance = ListBoxWidget()
487

488 489 490
def lazyMethod(func):
  """Return a function which stores a computed value in an instance
  at the first call.
491
  """
492 493
  key = '_cache_' + str(id(func))
  def decorated(self, *args, **kw):
494
    try:
495
      return getattr(self, key)
496
    except AttributeError:
497 498
      result = func(self, *args, **kw)
      setattr(self, key, result)
499
      return result
500
  return decorated
501 502

class ListBoxRenderer:
503 504 505 506 507
  """This class deals with rendering of a ListBox field.

  In ListBox, rendering is not only viewing but also setting parameters in a selection
  and a request object.
  """
508

509
  def __init__(self, widget = None, field = None, REQUEST = None, render_prefix=None, **kw):
510 511 512 513 514
    """Store the parameters for later use.
    """
    self.widget = widget
    self.field = field
    self.request = REQUEST
515
    self.render_prefix = render_prefix
516
    self.displayed_column_id_list = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
517

518 519 520
  def getPhysicalPath(self):
    """
      Return the path of form we render.
521
      This function is required to be able to use ZopeProfiler product with
522 523 524 525
      listbox.
    """
    return self.field.getPhysicalPath()

526 527 528 529
  def getLineClass(self):
    """Return a class object for a line. This must be overridden.
    """
    raise NotImplementedError, "getLineClass must be overridden in a subclass"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
530

531
  # Here, define many getters which cache the results for better performance.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
532

533 534 535
  def getContext(self):
    """Return the context of rendering this ListBox.
    """
536 537 538 539
    value = self.request.get('here')
    if value is None:
      value = self.getForm().aq_parent
    return value
Jean-Paul Smets's avatar
Jean-Paul Smets committed
540

541
  getContext = lazyMethod(getContext)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
542

543 544 545
  def getForm(self):
    """Return the form which contains the ListBox.
    """
546
    return self.field.aq_parent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
547

548
  getForm = lazyMethod(getForm)
549

550 551 552 553
  def getEncoding(self):
    """Retutn the encoding of strings in the fields. Default to UTF-8.
    """
    return self.getPortalObject().getProperty('management_page_charset', 'utf-8')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
554

555
  getEncoding = lazyMethod(getEncoding)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
556

557 558 559 560 561
  def isReset(self):
    """Determine if the ListBox should be reset.
    """
    reset = self.request.get('reset', 0)
    return (reset not in (0, '0'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
562

563
  isReset = lazyMethod(isReset)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
564

565 566 567 568
  def getFieldErrorDict(self):
    """Return a dictionary of errors.
    """
    return self.request.get('field_errors', {})
Jean-Paul Smets's avatar
Jean-Paul Smets committed
569

570
  getFieldErrorDict = lazyMethod(getFieldErrorDict)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
571

572 573
  def getUrl(self):
    """
574 575 576 577 578 579 580
      Return a requested URL.
      Generate the URL from context and request because self.request['URL']
      might contain a function name, which would make all redirections call
      the function - which both we don't want and will probably crash.
    """
    return '%s/%s' % (self.getContext().absolute_url(),
                      self.request.other.get('current_form_id', 'view'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
581

582
  getUrl = lazyMethod(getUrl)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
583

584 585 586 587 588 589
  def getRequestedSelectionName(self):
    """Return a selection name which may be passed by a request.
    If not present, return "default". This selection can be different from the selection
    defined in the ListBox.
    """
    selection_name = self.request.get('selection_name', 'default')
590

591 592 593 594
    # This is a workaround, as selection_name becomes a list or tuple sometimes.
    # XXX really? why?
    if not isinstance(selection_name, str):
      selection_name = selection_name[0]
Yoshinori Okuji's avatar
Yoshinori Okuji committed
595

596
    return selection_name
597

598
  getRequestedSelectionName = lazyMethod(getRequestedSelectionName)
599

600 601 602 603
  def getSelectionIndex(self):
    """Return the index of a requested selection, or None if not specified.
    """
    return self.request.get('selection_index', None)
604

605
  getSelectionIndex = lazyMethod(getSelectionIndex)
606

607 608 609 610
  def getReportDepth(self):
    """Return the depth of reports, or None if not specified.
    """
    return self.request.get('report_depth', None)
611

612
  getReportDepth = lazyMethod(getReportDepth)
613

614 615 616 617
  def getPortalObject(self):
    """Return the portal object.
    """
    return self.getContext().getPortalObject()
618

619
  getPortalObject = lazyMethod(getPortalObject)
620

621 622 623 624
  def getPortalUrlString(self):
    """Return the URL of the portal as a string.
    """
    return self.getPortalObject().portal_url()
625

626
  getPortalUrlString = lazyMethod(getPortalUrlString)
627

628 629 630 631
  def getCategoryTool(self):
    """Return the Category Tool.
    """
    return self.getPortalObject().portal_categories
632

633
  getCategoryTool = lazyMethod(getCategoryTool)
634

635 636 637 638
  def getDomainTool(self):
    """Return the Domain Tool.
    """
    return self.getPortalObject().portal_domains
639

640
  getDomainTool = lazyMethod(getDomainTool)
641

642 643 644 645
  def getCatalogTool(self):
    """Return the Catalog Tool.
    """
    return self.getPortalObject().portal_catalog
646

647
  getCatalogTool = lazyMethod(getCatalogTool)
648

649 650 651 652
  def getSelectionTool(self):
    """Return the Selection Tool.
    """
    return self.getPortalObject().portal_selections
653

654
  getSelectionTool = lazyMethod(getSelectionTool)
655

656 657 658 659 660 661 662 663
  def getPrefixedString(self, string):
    prefix = self.render_prefix
    if prefix is None:
      result = string
    else:
      result = '%s_%s' % (prefix, string)
    return result

664 665
  def getId(self):
    """Return the id of the field. Usually, "listbox".
666
       The prefix will automatically be added
667
    """
668
    return self.getPrefixedString(self.field.id)
669

670
  getId = lazyMethod(getId)
671

672 673 674 675 676 677 678
  def getUnprefixedId(self):
    """Return the id of the field. Usually, "listbox".
    """
    return self.field.id

  getUnprefixedId = lazyMethod(getUnprefixedId)

679 680 681 682
  def getTitle(self):
    """Return the title. Make sure that it is in unicode.
    """
    return unicode(self.field.get_value('title'), self.getEncoding())
683

684
  getTitle = lazyMethod(getTitle)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
685

686 687 688 689 690
  def getMaxLineNumber(self):
    """Return the maximum number of lines shown in a page.
    This must be overridden in subclasses.
    """
    raise NotImplementedError, "getMaxLineNumber must be overridden in a subclass"
691

692 693 694 695
  def showSearchLine(self):
    """Return a boolean that represents whether a search line is displayed or not.
    """
    return self.field.get_value('search')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
696

697
  showSearchLine = lazyMethod(showSearchLine)
698

699 700 701 702
  def showSelectColumn(self):
    """Return a boolean that represents whether a select column is displayed or not.
    """
    return self.field.get_value('select')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
703

704
  showSelectColumn = lazyMethod(showSelectColumn)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
705

706 707 708 709 710 711 712
  def showAnchorColumn(self):
    """Return a boolean that represents whether a anchor column is displayed or not.
    """
    return self.field.get_value('anchor')

  showAnchorColumn = lazyMethod(showAnchorColumn)

713
  def isHideRowsOnNoSearchCriterion(self, REQUEST=None):
714 715 716
    """
      Return a boolean that represents whether search rows are shown or not.
    """
717 718
    # BBB REQUEST passed to this method is simply discarded. The parameter
    # exists only for API compatibility.
719
    REQUEST = self.request
720 721 722 723 724
    hide_rows_on_no_search_criterion = \
                            self.field.get_value('hide_rows_on_no_search_criterion')
    if not hide_rows_on_no_search_criterion:
      # we show all rows and do not care to hide anything
      return 0
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

    # Always display lines in report mode
    if self.isReportTreeMode():
      return 0

    # In domain mode, returns lines only if a domain is selected
    if self.isDomainTreeMode():
      if self.getDomainSelection():
        return 0

    # ignore_hide_rows parameter force to display the content
    ignore_hide_rows = REQUEST.get('ignore_hide_rows', 0)
    if ignore_hide_rows:
      return 0

740 741
    # we could hide rows only if missing in request or selection search criterions
    selection_params = self.getSelection().getParams()
742 743 744 745 746 747 748 749 750 751 752 753

    # Try to get workflow state parameter, in order to always allow worklist display
    # guess all column names from catalog schema
    possible_state_list = [column_name for column_name in
         self.getPortalObject().portal_catalog.getSQLCatalog().getColumnMap() if
         column_name.endswith('state') and '.' not in column_name]
    for state_var in possible_state_list:
      workflow_state_criterion = REQUEST.get(state_var,
                                        selection_params.get(state_var, None))
      if workflow_state_criterion not in (None, ""):
        return 0

754 755 756 757 758 759 760
    listbox_searchable_column_id_list = [x[0] for x in self.getSearchValueList() \
                                           if x[0] is not None]

    for listbox_searchable_column_id in listbox_searchable_column_id_list:
      search_criterion = REQUEST.get(listbox_searchable_column_id, \
                                     selection_params.get(listbox_searchable_column_id, None))
      if search_criterion not in (None, "",) and not isinstance(search_criterion, dict):
Fabien Morin's avatar
Fabien Morin committed
761
        # search criterion is usually input by user by UI, ignore created automated
762 763 764 765 766
        # by listbox_xxx form fields selection parameters as they do not represent
        # user input but rather a developer formating definition in form
        return 0
    return 1

767
  isHideRowsOnNoSearchCriterion = lazyMethod(isHideRowsOnNoSearchCriterion)
768

769 770
  def showStat(self):
    """Return a boolean that represents whether a stat line is displayed or not.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
771

772 773 774 775
    FIXME: This is not very correct, because stat columns may define their own
    stat method independently.
    """
    return (self.getStatMethod() is not None) and (len(self.getStatColumnList()) > 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
776

777
  showStat = lazyMethod(showStat)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
778

779 780 781 782
  def isDomainTreeSupported(self):
    """Return a boolean that represents whether a domain tree is supported or not.
    """
    return (self.field.get_value('domain_tree') and len(self.getDomainRootList()) > 0)
783

784
  isDomainTreeSupported = lazyMethod(isDomainTreeSupported)
785 786 787 788 789 790

  def isReportTreeSupported(self):
    """Return a boolean that represents whether a report tree is supported or not.
    """
    return (self.field.get_value('report_tree') and len(self.getReportRootList()) > 0)

791
  isReportTreeSupported = lazyMethod(isReportTreeSupported)
792 793 794 795 796 797

  def isDomainTreeMode(self):
    """Return whether the current mode is domain tree mode or not.
    """
    return self.isDomainTreeSupported() and self.getSelection().domain_tree_mode

798
  isDomainTreeMode = lazyMethod(isDomainTreeMode)
799 800 801 802 803 804

  def isReportTreeMode(self):
    """Return whether the current mode is report tree mode or not.
    """
    return self.isReportTreeSupported() and self.getSelection().report_tree_mode

805
  isReportTreeMode = lazyMethod(isReportTreeMode)
806 807 808 809 810 811

  def getDefaultParamList(self):
    """Return the list of default parameters.
    """
    return self.field.get_value('default_params')

812
  getDefaultParamList = lazyMethod(getDefaultParamList)
813 814 815 816 817 818 819 820 821 822 823

  def getListMethodName(self):
    """Return the name of the list method. If not defined, return None.
    """
    list_method = self.field.get_value('list_method')
    try:
      name = getattr(list_method, 'method_name')
    except AttributeError:
      name = list_method
    return name or None

824
  getListMethodName = lazyMethod(getListMethodName)
825 826 827 828 829 830 831 832 833 834 835

  def getCountMethodName(self):
    """Return the name of the count method. If not defined, return None.
    """
    count_method = self.field.get_value('count_method')
    try:
      name = getattr(count_method, 'method_name')
    except AttributeError:
      name = count_method
    return name or None

836
  getCountMethodName = lazyMethod(getCountMethodName)
837 838 839 840 841 842 843 844 845 846 847

  def getStatMethodName(self):
    """Return the name of the stat method. If not defined, return None.
    """
    stat_method = self.field.get_value('stat_method')
    try:
      name = getattr(stat_method, 'method_name')
    except AttributeError:
      name = stat_method
    return name or None

848
  getStatMethodName = lazyMethod(getStatMethodName)
849

850 851 852 853 854 855 856 857 858 859 860
  def getRowCSSMethodName(self):
    """Return the name of the row CSS method. If not defined, return None.
    """
    row_css_method = self.field.get_value('row_css_method')
    try:
      name = getattr(row_css_method, 'method_name')
    except AttributeError:
      name = row_css_method
    return name or None

  getRowCSSMethodName = lazyMethod(getRowCSSMethodName)
Fabien Morin's avatar
Fabien Morin committed
861

862 863 864
  def getSelectionName(self):
    """Return the selection name.
    """
865
    return self.getPrefixedString(self.field.get_value('selection_name'))
866

867
  getSelectionName = lazyMethod(getSelectionName)
868 869 870 871 872 873 874

  def getMetaTypeList(self):
    """Return the list of meta types for filtering. Return None when empty.
    """
    meta_types = [c[0] for c in self.field.get_value('meta_types')]
    return meta_types or None

875
  getMetaTypeList = lazyMethod(getMetaTypeList)
876 877 878 879 880 881 882

  def getPortalTypeList(self):
    """Return the list of portal types for filtering. Return None when empty.
    """
    portal_types = [c[0] for c in self.field.get_value('portal_types')]
    return portal_types or None

883
  getPortalTypeList = lazyMethod(getPortalTypeList)
884 885 886 887 888 889 890

  def getColumnList(self):
    """Return the columns. Make sure that the titles are in unicode.
    """
    columns = self.field.get_value('columns')
    return [(str(c[0]), unicode(c[1], self.getEncoding())) for c in columns]

891
  getColumnList = lazyMethod(getColumnList)
892 893 894

  def getAllColumnList(self):
    """Return the all columns. Make sure that the titles are in unicode.
895
       Make sure there is no duplicates.
896 897 898 899 900 901 902 903
    """
    all_column_list = list(self.getColumnList())
    all_column_id_set = set([c[0] for c in all_column_list])
    all_column_list.extend([(str(c[0]), unicode(c[1], self.getEncoding())) \
                              for c in self.field.get_value('all_columns') \
                              if c[0] not in all_column_id_set])
    return all_column_list

904
  getAllColumnList = lazyMethod(getAllColumnList)
905

906 907
  def getStyleColumnList(self):
    """Return the style columns columns.
908
    """
909
    return self.field.get_value('style_columns')
910

911
  getStyleColumnList = lazyMethod(getStyleColumnList)
912

913 914 915 916 917 918 919 920 921 922
  def getStatColumnList(self):
    """Return the stat columns. Fall back to all the columns if empty.
    """
    stat_columns = self.field.get_value('stat_columns')
    if stat_columns:
      stat_column_list = [(str(c[0]), unicode(c[1], self.getEncoding())) for c in stat_columns]
    else:
      stat_column_list = [(c[0], c[0]) for c in self.getAllColumnList()]
    return stat_column_list

923
  getStatColumnList = lazyMethod(getStatColumnList)
924 925 926 927 928 929 930

  def getUrlColumnList(self):
    """Return the url columns. Make sure that it is an empty list, when not defined.
    """
    url_columns = self.field.get_value('url_columns')
    return url_columns or []

931
  def getUntranslatableColumnList(self):
Fabien Morin's avatar
Fabien Morin committed
932
    """Return the untranslatable columns. Make sure that it is an empty list,
933 934 935 936 937
    when not defined.
    """
    untranslatable_columns = self.field.get_value('untranslatable_columns')
    return untranslatable_columns or []

938
  getUrlColumnList = lazyMethod(getUrlColumnList)
939 940 941 942 943 944

  def getDefaultSortColumnList(self):
    """Return the default sort columns.
    """
    return self.field.get_value('sort')

945
  getDefaultSortColumnList = lazyMethod(getDefaultSortColumnList)
946 947 948 949 950 951 952

  def getDomainRootList(self):
    """Return the domain root list. Make sure that the titles are in unicode.
    """
    domain_root_list = self.field.get_value('domain_root_list')
    return [(str(c[0]), unicode(c[1], self.getEncoding())) for c in domain_root_list]

953
  getDomainRootList = lazyMethod(getDomainRootList)
954 955 956 957 958 959 960

  def getReportRootList(self):
    """Return the report root list. Make sure that the titles are in unicode.
    """
    report_root_list = self.field.get_value('report_root_list')
    return [(str(c[0]), unicode(c[1], self.getEncoding())) for c in report_root_list]

961
  getReportRootList = lazyMethod(getReportRootList)
962

963 964 965 966 967 968 969 970 971
  def getDisplayStyleList(self):
    """Return the list of avaible display style. Make sure that the 
    titles are in unicode"""
    display_style_list = self.field.get_value('display_style_list')
    return [(str(c[0]), unicode(c[1], self.getEncoding())) for c in \
                                                      display_style_list]

  getDisplayStyleList = lazyMethod(getDisplayStyleList)

972
  def getDefaultDisplayStyle(self):
973 974
    """Return the default display list style."""
    return self.field.get_value('default_display_style')
975 976 977

  getDefaultDisplayStyle = lazyMethod(getDefaultDisplayStyle)

978
  def getGlobalSearchColumn(self):
979
    """Return the full text search key."""
980
    return self.field.get_value('global_search_column')
981

982
  getGlobalSearchColumn = lazyMethod(getGlobalSearchColumn)
983

984 985 986 987 988 989 990 991 992
  # backwards compatability
  def getGlobalSearchColumnScript(self):
    warn("getGlobalSearchColumnScript() is deprecated. Do not use it!", \
         DeprecationWarning,
         stacklevel=2)
    return 'Base_doSelect'
  getFullTextSearchKey=getGlobalSearchColumn
  getFullTextSearchKeyScript=getGlobalSearchColumnScript

993 994 995
  def getPageNavigationTemplate(self):
    """Return the list box page navigation template."""
    return self.field.get_value('page_navigation_template')
996

997 998 999
  getPageNavigationTemplate = lazyMethod(getPageNavigationTemplate)
  # backwards compatability
  getPageNavigationMode = getPageNavigationTemplate
1000

1001 1002 1003 1004 1005 1006 1007
  def getSearchColumnIdSet(self):
    """Return the set of the ids of the search columns. Fall back to the catalog schema, if not defined.
    """
    search_columns = self.field.get_value('search_columns')
    if search_columns:
      search_column_id_list = [c[0] for c in search_columns]
    else:
1008 1009 1010 1011 1012
      search_column_id_list = []
      isValidColumn = self.getCatalogTool().getSQLCatalog().isValidColumn
      for column_id, column_title in self.getAllColumnList():
        if isValidColumn(column_id):
          search_column_id_list.append(column_id)
1013 1014
    return set(search_column_id_list)

1015
  getSearchColumnIdSet = lazyMethod(getSearchColumnIdSet)
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

  def getSortColumnIdSet(self):
    """Return the set of the ids of the sort columns. Fall back to search column ids, if not defined.
    """
    sort_columns = self.field.get_value('sort_columns')
    if sort_columns:
      sort_column_id_set = set([c[0] for c in sort_columns])
    else:
      sort_column_id_set = self.getSearchColumnIdSet()
    return sort_column_id_set

1027
  getSortColumnIdSet = lazyMethod(getSortColumnIdSet)
1028 1029 1030 1031 1032 1033 1034

  def getEditableColumnIdSet(self):
    """Return the set of the ids of the editable columns.
    """
    editable_columns = self.field.get_value('editable_columns')
    return set([c[0] for c in editable_columns])

1035
  getEditableColumnIdSet = lazyMethod(getEditableColumnIdSet)
1036 1037 1038 1039

  def getListActionUrl(self):
    """Return the URL of the list action.
    """
1040 1041 1042 1043 1044 1045 1046
    list_action = self.field.get_value('list_action')
    if '/' in list_action:
      # This is a 'real' URL
      return list_action
    else:
      # This is only a method name. Let us build the URL
      list_action_part_list = [self.getContext().absolute_url(), '/', list_action]
1047 1048 1049 1050
    if '?' in list_action_part_list[-1]:
      list_action_part_list.append('&reset=1')
    else:
      list_action_part_list.append('?reset=1')
1051 1052
    if self.request.get('ignore_layout', None):
      list_action_part_list.append('&ignore_layout:int=1')
1053 1054
    return ''.join(list_action_part_list)

1055
  getListActionUrl = lazyMethod(getListActionUrl)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

  # Whether the selection object is initialized.
  is_selection_initialized = False

  def getSelection(self):
    """FIXME: Tweak a selection and return the selection object.
    This code depends on the implementation of Selection too much.
    In the future, the API of SelectionTool should be refactored and
    ListBox should not use Selection directly.
    """
    selection_tool = self.getSelectionTool()
    selection_name = self.getSelectionName()
    selection = selection_tool.getSelectionFor(selection_name, REQUEST = self.request)

    if self.is_selection_initialized:
      return selection

    # Create a selection, if not present, with the default sort order.
    if selection is None:
1075 1076 1077 1078
      selection = Selection(selection_name,
                            params=dict(self.getDefaultParamList()),
                            default_sort_on=self.getDefaultSortColumnList(),
                           ).__of__(selection_tool)
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    # Or make sure all sort arguments are valid.
    else:
      # Reset the selection, if specified.
      if self.isReset():
        selection_tool.setSelectionToAll(selection_name)
        selection_tool.setSelectionSortOrder(selection_name, sort_on = [])

      # Modify the default sort index every time, because it may change immediately.
      selection.edit(default_sort_on = self.getDefaultSortColumnList())

      # Filter out non-sortable items.
      sort_column_id_set = self.getSortColumnIdSet()
      sort_list = [c for c in selection.sort_on if c[0] in sort_column_id_set]
      if len(selection.sort_on) != len(sort_list):
        selection.sort_on = sort_list

    if getattr(selection, 'flat_list_mode', None) is None:
      # Initialize the render mode. Choose flat list mode by default.
      selection.edit(flat_list_mode = 1, domain_tree_mode = 0, report_tree_mode = 0)

    # Remember if the items have to be displayed for report tree mode.
    is_report_opened = self.request.get('is_report_opened', selection.isReportOpened())
    selection.edit(report_opened = is_report_opened)

    self.is_selection_initialized = True

    return selection

1107
  getSelection = lazyMethod(getSelection)
1108 1109 1110 1111 1112 1113

  def getCheckedUidList(self):
    """Return the list of checked uids.
    """
    return self.getSelection().getCheckedUids()

1114
  getCheckedUidList = lazyMethod(getCheckedUidList)
1115

1116 1117 1118 1119 1120
  def getCheckedUidSet(self):
    """Return the set of checked uids.
    """
    return set(self.getCheckedUidList())

1121
  getCheckedUidSet = lazyMethod(getCheckedUidSet)
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  
  def setDisplayedColumnIdList(self, displayed_column_id_list):
    """Set the column to be displayed.
       Impact the result of getSelectedColumnList.
       Parameter : 
       displayed_column_id_list : List of id. Exemple : ('id', 'title')
    """
    self.displayed_column_id_list = displayed_column_id_list

  def getDisplayedColumnIdList(self):
    """Return the list of displayed column id
    """
    return self.displayed_column_id_list
1135

1136 1137 1138 1139 1140 1141 1142 1143
  def getListboxDisplayStyle(self):
    """Return the current listbox display style.
    """
    request = self.request
    selection = self.getSelection()
    return request.get('list_style', \
                        selection.getParams().get('list_style', self.getDefaultDisplayStyle()))

1144 1145 1146
  def getSelectedColumnList(self):
    """Return the list of selected columns.
    """
1147
    column_list = []
1148 1149 1150
    default_listbox_display_style = self.getDefaultDisplayStyle()
    listbox_display_style = self.getListboxDisplayStyle()
    dynamic_column_list_override = (self.getDisplayedColumnIdList() != None)
1151
    list_style_column_change_required = listbox_display_style not in ('', DEFAULT_LISTBOX_DISPLAY_STYLE,)
1152 1153
    if dynamic_column_list_override:
      # dynamically setting columns is supported
1154 1155 1156 1157 1158 1159
      available_column = self.getAllColumnList()
      #Create a dict to make a easy search
      available_column_dict = dict()
      for id,title in available_column:
        available_column_dict[id] = (id,title)

1160
      # We check columns are present
1161 1162 1163 1164 1165
      for id in self.getDisplayedColumnIdList():
        if available_column_dict.has_key(id):
          column_list.append(available_column_dict[id])
        else:
          raise AttributeError, "Column %s is not avaible" % id
1166 1167 1168 1169
    elif list_style_column_change_required and not dynamic_column_list_override:
      # no dynamically setting of columns happens , still we have different than default
      # listbox list style so try to get columns from 'More columns'
      list_style_prefix = "%s_" %listbox_display_style
1170
      for column in  self.getStyleColumnList():
1171 1172
        if column[1].startswith(list_style_prefix):
          column_list.append((column[0],column[1].replace(list_style_prefix, '',)))
1173 1174
    else:
      column_list = self.getSelectionTool().getSelectionColumns(self.getSelectionName(),
1175 1176
                                                       columns = self.getColumnList(),
                                                       REQUEST = self.request)
1177
    return column_list
1178

1179
  getSelectedColumnList = lazyMethod(getSelectedColumnList)
1180 1181 1182 1183 1184 1185 1186 1187 1188

  def getColumnAliasList(self):
    """Return the list of column aliases for SQL, because SQL does not allow a symbol to contain dots.
    """
    alias_list = []
    for sql, title in self.getSelectedColumnList():
      alias_list.append(sql.replace('.', '_'))
    return alias_list

1189
  getColumnAliasList = lazyMethod(getColumnAliasList)
1190 1191 1192 1193

  def getParamDict(self):
    """Return a dictionary of parameters.
    """
1194
    params = dict(self.getSelection().getParams())
1195 1196 1197 1198 1199 1200 1201
    if self.getListMethodName():
      # Update parameters, only if list_method is defined.
      # (i.e. do not update parameters in listboxes intended to show a previously defined selection.
      params.update(self.request.form)
      for k, v in self.getDefaultParamList():
        params.setdefault(k, v)

1202 1203 1204 1205 1206
      search_prefix = 'search_%s_' % (self.getId(), )
      for k, v in params.items():
        if k.startswith(search_prefix):
          params[k[len(search_prefix):]] = v

1207 1208 1209 1210 1211
      search_value_list = [x for x in self.getSearchValueList(param_dict=params) if isinstance(x[1], basestring)]
      listbox_form = self.getForm()
      listbox_id = self.getId()
      for search_id, search_value, search_field in search_value_list:
        if search_field is None:
1212
          search_alias = '_'.join(search_id.split('.'))
1213
          # If the search field could not be found, try to get an "editable" field on current form.
1214 1215
          search_field = self.getEditableField(search_alias)
          if search_field is None:
1216
            continue
1217

1218
        render_dict = search_field.render_dict(search_value)
1219
        if render_dict is not None:
1220
          params[search_id] = render_dict
1221

1222 1223 1224 1225
      # Set parameters, depending on the list method.
      list_method_name = self.getListMethodName()
      meta_type_list = self.getMetaTypeList()
      portal_type_list = self.getPortalTypeList()
1226 1227 1228 1229 1230
      if portal_type_list is not None:
        params.setdefault('portal_type', portal_type_list)
      elif meta_type_list is not None:
        params.setdefault('meta_type', meta_type_list)

1231
      # Remove FileUpload parameters
1232 1233 1234 1235 1236 1237
      for k, v in params.items():
        if k == "listbox":
          # listbox can also contain useless parameters
          new_list = []
          for line in v:
            for k1, v1 in line.items():
1238
              if hasattr(v1, 'read'):
1239 1240 1241
                del line[k1]
            new_list.append(line)
          params[k] = new_list
1242
        if hasattr(v, 'read'):
1243
          del params[k]
1244

1245 1246 1247
      # remove some erp5_xhtml_style specific parameters
      params.pop('saved_form_data', None)

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    # Set the columns. The idea behind this is that, instead of selecting all columns,
    # ListBox can specify only required columns, in order to reduce the data transferred
    # from a SQL Server to Zope.
    sql_column_list = []
    for (sql, title), alias in zip(self.getSelectedColumnList(), self.getColumnAliasList()):
      if sql != alias:
        sql_column_list.append('%s AS %s' % (sql, alias))
      else:
        sql_column_list.append(alias)

    # XXX why is this necessary? For compatibility?
    for sql, title in self.getAllColumnList():
      if sql in ('catalog.path', 'path'):
        alias = sql.replace('.', '_')
        if sql != alias:
          sql_column_list.append('%s AS %s' % (sql, alias))
        else:
          sql_column_list.append(alias)
        break

    params['select_columns'] = ', '.join(sql_column_list)

    # XXX Remove selection_expression if present.
    # This is necessary for now, because the actual selection expression in
    # search catalog does not take the requested columns into account. If
    # select_expression is passed, this can raise an exception, because stat
    # method sets select_expression, and this might cause duplicated column
    # names.
    #
    # In the future, this must be addressed in a clean way. selection_expression
    # should be used for search catalog, and search catalog should not use
    # catalog.* but only selection_expression. But this is a bit difficult,
    # because there is no simple way to distinguish queried columns from callable
    # objects in the current ListBox configuration.
    if 'select_expression' in params:
      del params['select_expression']
1284
    params.setdefault('limit', 1000) 
1285

1286
    self.getSelection().edit(params=params)
1287 1288
    return params

1289
  getParamDict = lazyMethod(getParamDict)
1290

1291 1292 1293 1294 1295
  def getEditableField(self, alias):
    """Get an editable field for column, using column alias.
    Return None if a field for this column does not exist.
    """
    form = self.getForm()
1296
    editable_field_id = '%s_%s' % (self.getUnprefixedId(), alias)
1297 1298 1299 1300
    field = self.field
    while form is not None:
      #Search the editable field in the form
      if form.has_field(editable_field_id, include_disabled=1):
1301
        return form.get_field(editable_field_id, include_disabled=1)
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
      elif field.meta_type == 'ProxyField':
        # if we are rendering a proxy field, also look for editable 
        # fields from the template field's form.
        field = field.getTemplateField()
        if field is None:
          form = None
        else:
          form = aq_inner(field).aq_parent
      else:
        form = None
    
1313 1314
    return None

1315 1316 1317 1318 1319
  def getListMethod(self):
    """Return the list method object.
    """
    list_method_name = self.getListMethodName()

1320 1321
    if list_method_name in ('objectValues', 'contentValues'):
      list_method = ListMethodWrapper(self.getContext(), list_method_name)
1322 1323
    elif list_method_name == 'searchFolder':
      list_method = CatalogMethodWrapper(self.getContext(), list_method_name)
1324
    elif list_method_name is not None:
1325
      list_method = getattr(self.getContext(), list_method_name, None)
1326 1327 1328 1329 1330
    else:
      list_method = None

    return list_method

1331
  getListMethod = lazyMethod(getListMethod)
1332 1333 1334 1335 1336 1337 1338 1339 1340

  def getCountMethod(self):
    """Return the count method object.
    """
    count_method_name = self.getCountMethodName()

    if count_method_name == 'objectValues':
      # Get all objects anyway in this case.
      count_method = None
1341 1342 1343 1344
    elif count_method_name == 'portal_catalog':
      count_method = CatalogMethodWrapper(self.getCatalogTool(), 'countResults')
    elif count_method_name == 'countFolder':
      count_method = CatalogMethodWrapper(self.getContext(), count_method_name)
1345
    elif count_method_name is not None:
1346
      count_method = getattr(self.getContext(), count_method_name, None)
1347 1348 1349 1350 1351
    else:
      count_method = None

    return count_method

1352
  getCountMethod = lazyMethod(getCountMethod)
1353 1354 1355 1356 1357 1358 1359 1360 1361

  def getStatMethod(self):
    """Return the stat method object.
    """
    stat_method_name = self.getStatMethodName()

    if stat_method_name == 'objectValues':
      # Nothing to do in this case.
      stat_method = None
1362 1363 1364 1365
    elif stat_method_name == 'portal_catalog':
      stat_method = CatalogMethodWrapper(self.getCatalogTool(), 'countResults')
    elif stat_method_name == 'countFolder':
      stat_method = CatalogMethodWrapper(self.getContext(), stat_method_name)
1366
    elif stat_method_name is not None:
1367
      stat_method = getattr(self.getContext(), stat_method_name, None)
1368 1369 1370 1371 1372
    else:
      stat_method = None

    return stat_method

1373
  getStatMethod = lazyMethod(getStatMethod)
1374

1375 1376 1377 1378 1379 1380
  def getRowCSSMethod(self):
    """Return the row css method object.
    """
    row_css_method_name = self.getRowCSSMethodName()
    row_css_method = None
    if row_css_method_name is not None:
1381
      row_css_method = getattr(self.getContext(), row_css_method_name, None)
1382 1383 1384
    return row_css_method

  getRowCSSMethod = lazyMethod(getRowCSSMethod)
Fabien Morin's avatar
Fabien Morin committed
1385

1386 1387 1388
  def getDomainSelection(self):
    """Return a DomainSelection object wrapped with the context.
    """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1389
    portal_object = self.getPortalObject()
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    selection = self.getSelection()
    domain_list = selection.getDomainList()

    if len(domain_list) > 0:
      category_tool = self.getCategoryTool()
      domain_tool = self.getDomainTool()
      root_dict = {}

      for domain in domain_list:
        # XXX workaround for a past bug in Selection
        if not isinstance(domain, str):
          continue

        root = None
        base_domain = domain.split('/', 1)[0]
        if category_tool is not None:
          root = category_tool.restrictedTraverse(domain, None)
          if root is not None :
1408
            root_dict[base_domain] = ('portal_categories', domain)
1409
          elif domain_tool is not None:
1410 1411 1412 1413
            try:
              root = domain_tool.getDomainByPath(domain, None)
            except KeyError:
              root = None
1414
            if root is not None:
1415
              root_dict[base_domain] = ('portal_domains', domain)
1416
        if root is None:
1417 1418 1419
          root = portal_object.restrictedTraverse(domain, None)
          if root is not None:
            root_dict[None] = (None, domain)
1420 1421 1422

      return DomainSelection(domain_dict = root_dict).__of__(self.getContext())

1423
  getDomainSelection = lazyMethod(getDomainSelection)
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

  def getStatSelectExpression(self):
    """Return a string which expresses the information retrieved by SELECT for
    the statistics.
    """
    select_expression_list = []
    if self.showStat():
      stats = self.getSelectionTool().getSelectionStats(self.getSelectionName(), REQUEST = self.request)
      stat_column_list = self.getStatColumnList()

      for index, ((sql, title), alias) in enumerate(zip(self.getSelectedColumnList(), self.getColumnAliasList())):
        # XXX This might be slow.
        for column in stat_column_list:
          if column[0] == sql:
            break
        else:
          column = None
        if (column is not None) and (column[0] == column[1]):
          try:
            if stats[index] != ' ':
              select_expression_list.append('%s(%s) AS %s' % (stats[index], sql, alias))
            else:
              select_expression_list.append("'' AS %s" % alias)
          except IndexError:
            select_expression_list.append("'' AS %s" % alias)

    return ', '.join(select_expression_list)

1452
  getStatSelectExpression = lazyMethod(getStatSelectExpression)
1453

1454 1455 1456 1457 1458 1459
  def makeReportTreeList(self, root_dict = None, report_path = None, base_category = None, depth = 0,
                         unfolded_list = (), is_report_opened = True, sort_on = (('id', 'ASC'),)):
    """Return a list of report trees.
    """
    if isinstance(report_path, str):
      report_path = report_path.split('/')
1460
    if base_category is None and len(report_path):
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
      base_category = report_path[0]

    category_tool = self.getCategoryTool()
    domain_tool = self.getDomainTool()
    portal_object = self.getPortalObject()
    report_depth = self.getReportDepth()

    if root_dict is None:
      root_dict = {}

    # Find the root object.
    is_empty_level = 1
1473
    category = base_category
1474
    while is_empty_level:
1475
      if not root_dict.has_key(category):
1476 1477 1478
        root = None
        if category_tool is not None:
          try:
1479
            if category == 'parent':
1480
              # parent has a special treatment
1481 1482
              root = self.getContext()
              root_dict[category] = root_dict[None] = (root, (None, root.getRelativeUrl()))
1483
            else:
1484 1485 1486
              root = category_tool[category]
              root_dict[category] = root_dict[None] = (root, ('portal_categories', root.getRelativeUrl()))
            report_path = report_path[1:]
1487 1488 1489 1490
          except KeyError:
            pass
        if root is None and domain_tool is not None:
          try:
1491 1492
            root = domain_tool[category]
            root_dict[category] = root_dict[None] = (root, ('portal_domains', root.getRelativeUrl()))
1493 1494 1495 1496
            report_path = report_path[1:]
          except KeyError:
            pass
        if root is None:
1497 1498 1499
          root = portal_object.unrestrictedTraverse(report_path, None)
          if root is not None:
            root_dict[None] = (root, (None, root.getRelativeUrl()))
1500 1501
          report_path = ()
      else:
1502 1503
        root_dict[None] = root_dict[category]
        root = root_dict[None][0]
1504 1505 1506
        report_path = report_path[1:]
      is_empty_level = (root is None or root.objectCount() == 0) and (len(report_path) != 0)
      if is_empty_level:
1507
        category = report_path[0]
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524

    tree_list = []
    if root is None: return tree_list

    # Get the list of objects in the root. Use getChildDomainValueList, if defined,
    # to generate child domains dynamically.
    getChildDomainValueList = getattr(aq_base(root), 'getChildDomainValueList', None)
    contentValues = getattr(aq_base(root), 'contentValues', None)
    if getChildDomainValueList is not None and base_category != 'parent':
      obj_list = root.getChildDomainValueList(root, depth = depth)
    elif contentValues is not None:
      obj_list = root.contentValues(sort_on = sort_on)
    else:
      obj_list = ()

    for obj in obj_list:
      new_root_dict = root_dict.copy()
1525 1526 1527 1528
      new_root_dict[None] = new_root_dict[base_category] = (obj, (new_root_dict[base_category][1][0], obj.getRelativeUrl()))
      domain_dict = {}
      for k, v in new_root_dict.iteritems():
        domain_dict[k] = v[1]
1529
      selection_domain = DomainSelection(domain_dict = domain_dict)
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

      if base_category == 'parent':
        exception_uid_list = []
      else:
        exception_uid_list = None

      #LOG('ListBox', 0, 'depth = %r, report_depth = %r, unfolded_list = %r, obj.getRelativeUrl() = %r' % (depth, report_depth, unfolded_list, obj.getRelativeUrl()))
      if (report_depth is not None and depth <= (report_depth - 1)) or obj.getRelativeUrl() in unfolded_list:
        # If the base category is parent, do not display sub-objects
        # which can be used as a part of the report tree. Otherwise,
        # sub-objects are displayed twice unnecessarily.
        if base_category == 'parent':
          for sub_obj in obj.contentValues(sort_on = sort_on):
            if getattr(aq_base(sub_obj), 'objectValues', None) is not None:
1544
              exception_uid_list.append(sub_obj.getUid())
1545 1546 1547

        # Summary (open)
        tree_list.append(ReportTree(obj = obj, is_pure_summary = True, depth = depth,
1548
                                    base_category = base_category,
1549
                                    is_open = True, selection_domain = selection_domain,
1550 1551 1552 1553
                                    exception_uid_list = exception_uid_list))
        if is_report_opened:
          # List (contents, closed, must be strict selection)
          tree_list.append(ReportTree(obj = obj, is_pure_summary = False, depth = depth,
1554
                                      base_category = base_category,
1555
                                      is_open = False, selection_domain = selection_domain,
1556
                                      exception_uid_list = exception_uid_list))
1557 1558 1559 1560 1561
        # manage multiple base category
        if len(report_path) >= 1 and base_category != report_path[0]:
          new_base_category = None
        else:
          new_base_category = base_category
1562 1563
        tree_list.extend(self.makeReportTreeList(root_dict = new_root_dict,
                                                 report_path = report_path,
1564
                                                 base_category = new_base_category,
1565 1566 1567 1568 1569 1570 1571
                                                 depth = depth + 1,
                                                 unfolded_list = unfolded_list,
                                                 is_report_opened = is_report_opened,
                                                 sort_on = sort_on))
      else:
        # Summary (closed)
        tree_list.append(ReportTree(obj = obj, is_pure_summary = True, depth = depth,
1572
                                    base_category = base_category,
1573
                                    is_open = False, selection_domain = selection_domain,
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
                                    exception_uid_list = exception_uid_list))

    return tree_list

  def getLineStart(self):
    """Return where the first line should start from. Note that this is simply a requested value,
    so the real value can be different from this. For example, if the value exceeds the total number
    of lines, the start number is forced to fit into somewhere. This must be overridden in subclasses.
    """
    raise NotImplementedError, "getLineStart must be overridden in a subclass"

1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
  def getSelectedDomainPath(self):
    """Return a selected domain path.
    """
    domain_path = self.getSelection().getDomainPath()
    if domain_path == ('portal_categories',):
      try:
        # Default to the first domain.
        domain_path = self.getDomainRootList()[0][0]
      except IndexError:
        domain_path = None
    return domain_path

1597
  getSelectedDomainPath = lazyMethod(getSelectedDomainPath)
1598

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
  def getSelectedReportPath(self):
    """Return a selected report path.
    """
    category_tool = self.getCategoryTool()
    domain_tool = self.getDomainTool()
    report_root_list = self.getReportRootList()
    selection = self.getSelection()

    default_selection_report_path = report_root_list[0][0].split('/', 1)[0]
    if (category_tool is None or category_tool._getOb(default_selection_report_path, None) is None) \
        and (domain_tool is None or domain_tool._getOb(default_selection_report_path, None) is None):
      default_selection_report_path = report_root_list[0][0]

    return selection.getReportPath(default = default_selection_report_path)

1614
  getSelectedReportPath = lazyMethod(getSelectedReportPath)
1615

1616 1617 1618 1619 1620 1621
  def getLabelValueList(self):
    """Return a list of values, where each value is a tuple consisting of an property id, a title and a string which
    describes the current sorting order, one of ascending, descending and None. If a value is not sortable, the id is
    set to None, otherwise to a string.
    """
    sort_list = self.getSelectionTool().getSelectionSortOrder(self.getSelectionName())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1622 1623 1624
    sort_dict = {}
    for sort_item in sort_list:
      sort_dict[sort_item[0]] = sort_item[1] # sort_item can be couple or a triplet
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
    sort_column_id_set = self.getSortColumnIdSet()

    value_list = []
    for c in self.getSelectedColumnList():
      if c[0] in sort_column_id_set:
        value_list.append((c[0], c[1], sort_dict.get(c[0])))
      else:
        value_list.append((None, c[1], None))

    return value_list

1636
  def getSearchValueList(self, param_dict=None):
1637 1638 1639 1640 1641
    """Return a list of values, where each value is a tuple consisting of an alias, a current value and a search field.
    If a column is not searchable, the alias is set to None, otherwise to a string. If a search field is not present,
    it is set to None.
    """
    search_column_id_set = self.getSearchColumnIdSet()
1642 1643
    if param_dict is None:
      param_dict = self.getParamDict()
1644

1645
    value_list = []
1646
    for (sql, title), alias in zip(self.getSelectedColumnList(), self.getColumnAliasList()):
1647 1648
      if sql in search_column_id_set:
        # Get the current value and encode it in unicode.
1649
        param = param_dict.get(alias, param_dict.get(sql, u''))
1650 1651
        if isinstance(param, dict):
          param = param.get('query', u'')
1652 1653 1654 1655
        if isinstance(param, str):
          param = unicode(param, self.getEncoding())

        # Obtain a search field, if any.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1656 1657 1658
        form = self.getForm()
        if form.has_field(alias):
          search_field = form.get_field(alias)
1659 1660 1661
        else:
          search_field = None

1662
        value_list.append((sql, param, search_field))
1663 1664 1665 1666
      else:
        value_list.append((None, None, None))

    return value_list
Fabien Morin's avatar
Fabien Morin committed
1667

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
  def getStatValueList(self):
    """Return a list of values, where each value is a tuple consisting of an original value and a processed value.
    A processed value is always an unicode object, and it may differ from the original value, for instance,
    a processed value may describe an error, when an original value is None.
    """
    # First, get the statitics by the global stat method.
    param_dict = self.getParamDict()
    new_param_dict = param_dict.copy()
    new_param_dict['select_expression'] = self.getStatSelectExpression()
    selection = self.getSelection()
    selection.edit(params = new_param_dict)
1679 1680 1681 1682 1683 1684 1685 1686 1687

    _result = {'value':None, 'called':False}
    def getStatMethodResult():
      """Stat method must be called only when necessary"""
      if _result['called']:
        return _result['value']
      _result['value'] = selection(method = self.getStatMethod(), context = self.getContext(), REQUEST = self.request)
      _result['called'] = True
      return _result['value']
1688 1689

    # For each column, check the presense of a specific stat method. If not present,
1690
    # use getStatMethodResult defined above.
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
    value_list = []
    stat_column_dict = dict(self.getStatColumnList())
    for (sql, title), alias in zip(self.getSelectedColumnList(), self.getColumnAliasList()):
      original_value = None
      processed_value = None

      # Get a specific stat method, if any.
      stat_method_id = stat_column_dict.get(sql)
      if stat_method_id is not None and stat_method_id != sql:
        stat_method = getattr(self.getContext(), stat_method_id)
      else:
        stat_method = None

1704 1705 1706 1707
      if stat_method_id is None:
        original_value = None
        processed_value = u''
      elif stat_method is None:
1708
        try:
1709
          original_value = getattr(getStatMethodResult()[0], alias)
1710 1711 1712 1713 1714 1715 1716
          processed_value = original_value
        except (IndexError, AttributeError, KeyError, ValueError):
          original_value = None
          processed_value = u''
      else:
        if callable(stat_method):
          try:
1717 1718
            original_value = stat_method(selection = selection,
                                         selection_name = selection.getName())
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
            processed_value = original_value
          except (ConflictError, RuntimeError):
            raise
          except:
            LOG('ListBox', WARNING, 'could not call %r with %r' % (stat_method, self.getContext()),
                error = sys.exc_info())
            original_value = None
            processed_value = u''
        else:
          original_value = stat_method
          processed_value = original_value
1730

1731 1732 1733
      editable_field = self.getEditableField(alias)
      if editable_field is not None:
        processed_value = editable_field.render_view(value=original_value)
1734 1735

      if not isinstance(processed_value, unicode):
1736
        processed_value = unicode(str(processed_value), self.getEncoding(), 'replace')
1737 1738 1739 1740 1741

      value_list.append((original_value, processed_value))

    return value_list

1742 1743 1744 1745 1746 1747 1748 1749
  def getRowCSSClassName(self, **kw):
    """Return the css class name of a table row. If the method is not callable, returns None.
    """
    row_css_method = self.getRowCSSMethod()
    if callable(row_css_method):
      return row_css_method(**kw)
    return None

1750 1751 1752 1753 1754 1755 1756 1757
  def getReportSectionList(self):
    """Return a list of report sections.
    """
    param_dict = self.getParamDict()
    category_tool = self.getCategoryTool()
    domain_tool = self.getDomainTool()
    report_depth = self.getReportDepth()
    selection = self.getSelection()
1758
    selection_tool = self.getSelectionTool()
1759
    report_list = selection.getReportList()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1760
    stat_select_expression = self.getStatSelectExpression()
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    stat_method = self.getStatMethod()
    count_method = self.getCountMethod()
    list_method = self.getListMethod()
    context = self.getContext()
    selection_name = self.getSelectionName()
    start = self.getLineStart()
    max_lines = self.getMaxLineNumber()
    report_section_list = []

    if self.isReportTreeMode():
      # In report tree mode, there are three types of lines:
      #
      #   - summary line with statistics
      #   - summary line with the first object in a domain
      #   - object line
      #
      # These lines are compiled into report sections for convenience.

      selection_report_path = self.getSelectedReportPath()

      #LOG('ListBox', 0, 'report_depth = %r' % (report_depth,))
      if report_depth is not None:
        selection_report_current = ()
      else:
        selection_report_current = report_list

      report_tree_list = self.makeReportTreeList(report_path = selection_report_path,
                                                 unfolded_list = selection_report_current,
                                                 is_report_opened = selection.isReportOpened(),
                                                 sort_on = selection.sort_on)

1792 1793
      # Update report list if report_depth was specified. This information is used
      # to store what domains are unfolded by clicking on a depth.
1794 1795 1796 1797 1798 1799
      if report_depth is not None:
        report_list = [t.obj.getRelativeUrl() for t in report_tree_list if t.is_open]
        selection.edit(report_list = report_list)

      for report_tree in report_tree_list:
        # Prepare query by defining selection report object.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1800
        report_tree_obj = report_tree.obj
1801 1802 1803 1804

        # FIXME: this code needs optimization. The query should be delayed
        # as late as possible, because this code queries all data, even if
        # it is not displayed.
1805
        selection.edit(report = report_tree.selection_domain)
1806

1807 1808 1809 1810 1811 1812 1813 1814
        # FIXME: The following is only meant to be a temporary workaround.
        # Eventually, Selection should be rewritten to provide a more complete
        # API than just one __call__ method, and to support method_name
        # redefinition by the domain.

        # If the domain has a context_url, list_method or stat_method
        # parameters, we should use them instead of the ListBox ones when
        # looking for objects in the domain.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1815
        domain_context = report_tree_obj.getProperty('context_url', None)
1816 1817 1818 1819
        if domain_context is not None:
          domain_context = context.restrictedTraverse(domain_context)
        else:
          domain_context = context
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1820
        domain_list_method = report_tree_obj.getProperty('list_method',
1821
            list_method)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1822
        domain_stat_method = report_tree_obj.getProperty('stat_method',
1823 1824
            stat_method)

1825 1826 1827 1828 1829 1830 1831
        if report_tree.is_pure_summary and self.showStat():
          # Push a new select_expression.
          new_param_dict = param_dict.copy()
          new_param_dict['select_expression'] = stat_select_expression
          selection.edit(params = new_param_dict)

          # Query the stat.
1832
          stat_brain = selection(method=domain_stat_method, context=domain_context, REQUEST=self.request)
1833

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1834
          domain_title = report_tree_obj.getTitle()# XXX Yusei Keep original domain title before overriding
1835

1836 1837 1838 1839 1840 1841 1842
          stat_result = {}
          for index, (k, v) in enumerate(self.getSelectedColumnList()):
            try:
              stat_result[k] = str(stat_brain[0][index + 1])
            except IndexError:
              stat_result[k] = ''

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1843
          stat_context = report_tree_obj.asContext(**stat_result)
1844
          # XXX yo thinks that this code below is useless, so disabled.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1845
          #absolute_url_txt = report_tree_obj.absolute_url()
1846
          #stat_context.absolute_url = lambda: absolute_url_txt
1847
          stat_context.domain_url = report_tree.domain_url
1848 1849
          report_section_list.append(ReportSection(is_summary = True, object_list = [stat_context],
                                                   object_list_len = 1, is_open = report_tree.is_open,
1850
                                                   selection_domain = report_tree.selection_domain,
1851 1852
                                                   context = stat_context, depth = report_tree.depth,
                                                   domain_title = domain_title))
1853 1854 1855 1856 1857
        else:
          selection.edit(params = param_dict)

          if list_method is not None:
            # FIXME: this should use a count method, if present, and obtain objects, only if necessary.
1858
            object_list = selection(method=domain_list_method, context=domain_context, REQUEST=self.request)
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
          else:
            # If list_method is None, use already selected values.
            object_list = self.getSelectionTool().getSelectionValueList(selection_name,
                                                                        context = context,
                                                                        REQUEST = self.request)

          if report_tree.exception_uid_set is not None:
            # Filter folders if this is a parent tree.
            new_object_list = []
            for o in object_list:
              if o.getUid() not in report_tree.exception_uid_set:
                new_object_list.append(o)
            object_list = new_object_list

          object_list_len = len(object_list)
          #LOG('ListBox', 0, 'report_tree.__dict__ = %r, object_list = %r, object_list_len = %r' % (report_tree.__dict__, object_list, object_list_len))
          if not report_tree.is_pure_summary:
1876
            if self.showStat():
1877 1878 1879
              report_section_list.append(ReportSection(is_summary = False, object_list = object_list,
                                                       object_list_len = object_list_len,
                                                       is_open = report_tree.is_open,
1880
                                                       selection_domain = report_tree.selection_domain,
1881
                                                       depth = report_tree.depth))
1882
          else:
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1883
            stat_context = report_tree_obj.asContext()
1884 1885
            #absolute_url_txt = s[0].absolute_url()
            #stat_context.absolute_url = lambda : absolute_url_txt
1886
            stat_context.domain_url = report_tree.domain_url
1887 1888 1889 1890 1891 1892 1893
            if object_list_len and report_tree.is_open:
              # Display the first object at the same level as a category selector,
              # if this selector is open.
              report_section_list.append(ReportSection(is_summary = False,
                                                       object_list = [object_list[0]],
                                                       object_list_len = 1,
                                                       is_open = True,
1894
                                                       selection_domain = report_tree.selection_domain,
1895 1896
                                                       context = stat_context,
                                                       depth = report_tree.depth))
1897 1898 1899 1900
              report_section_list.append(ReportSection(is_summary = False,
                                                       object_list = object_list,
                                                       object_list_len = object_list_len - 1,
                                                       is_open = True,
1901
                                                       selection_domain = report_tree.selection_domain,
1902 1903
                                                       offset = 1,
                                                       depth = report_tree.depth))
1904 1905 1906 1907
            else:
              if report_tree.exception_uid_list is not None:
                # Display current parent domain.
                report_section_list.append(ReportSection(is_summary = False,
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1908
                                                         object_list = [report_tree_obj],
1909 1910
                                                         object_list_len = 1,
                                                         is_open = report_tree.is_open,
1911
                                                         selection_domain = report_tree.selection_domain,
1912 1913
                                                         context = stat_context,
                                                         depth = report_tree.depth))
1914 1915 1916 1917 1918 1919
              else:
                # No data to display
                report_section_list.append(ReportSection(is_summary = False,
                                                         object_list = [None],
                                                         object_list_len = 1,
                                                         is_open = report_tree.is_open,
1920
                                                         selection_domain = report_tree.selection_domain,
1921 1922
                                                         context = stat_context,
                                                         depth = report_tree.depth))
1923 1924 1925 1926 1927 1928 1929

      # Reset the report parameter.
      selection.edit(report = None)
    else:
      # Flat list mode or domain tree mode.
      selection.edit(params = param_dict, report = None)

1930
      domain_found = 0
1931
      if self.isDomainTreeMode():
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
        domain_selection = self.getDomainSelection()
        selection.edit(domain=domain_selection)
        if domain_selection is not None:
          for k, d in domain_selection.asDomainDict().iteritems():
            if k is not None:
              domain = domain_selection._getDomainObject(
                  context.getPortalObject(), d)
              # FIXME: The following is only meant to be a temporary
              # workaround. Eventually, Selection should be rewritten to
              # provide a more complete API than just one __call__ method, and
              # to support method_name redefinition by the domain.

              # If the domain has a context_url, list_method or count_method
              # parameters, we should use them instead of the ListBox ones
              # when looking for objects in the domain.
              domain_context = domain.getProperty('context_url', None)
              if domain_context is not None:
                domain_context = context.restrictedTraverse(domain_context)
              else:
                domain_context = context
              domain_list_method = domain.getProperty('list_method',
                  list_method)
              domain_count_method = domain.getProperty('count_method',
                  count_method)
1956
              domain_found = 1
1957
              break
1958
      if not domain_found:
1959 1960 1961
        domain_context = context
        domain_list_method = list_method
        domain_count_method = count_method
1962 1963 1964 1965

      if list_method is not None:
        if count_method is not None and not selection.invert_mode and max_lines > 0:
          # If the count method is available, get only required objects.
1966
          count = selection(method=domain_count_method, context=domain_context, REQUEST=self.request)
1967 1968 1969 1970
          object_list_len = int(count[0][0])

          # Tweak the line start.
          if start >= object_list_len:
1971
            start = max(object_list_len - 1, 0)
1972 1973 1974 1975 1976 1977
          start -= (start % max_lines)

          # Obtain only required objects.
          new_param_dict = param_dict.copy()
          new_param_dict['limit'] = (start, max_lines)
          selection.edit(params = new_param_dict)
1978
          object_list = selection(method=domain_list_method, context=domain_context, REQUEST=self.request)
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
          selection.edit(params = param_dict) # XXX Necessary?

          # Add padding for convenience.
          report_section_list.append(ReportSection(is_summary = False,
                                                   object_list_len = start))
          report_section_list.append(ReportSection(is_summary = False,
                                                   object_list = object_list,
                                                   object_list_len = len(object_list)))
          report_section_list.append(ReportSection(is_summary = False,
                                                   object_list_len = object_list_len - len(object_list) - start))
        else:
1990
          object_list = selection(method=domain_list_method, context=domain_context, REQUEST=self.request)
1991 1992 1993 1994 1995 1996
          object_list_len = len(object_list)
          report_section_list.append(ReportSection(is_summary = False,
                                                   object_list = object_list,
                                                   object_list_len = object_list_len))
      else:
        # If list_method is None, use already selected values.
1997
        object_list = selection_tool.getSelectionValueList(selection_name,
1998
                                                                   context = context, REQUEST = self.request)
1999
        object_list_len= len(object_list)
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        report_section_list.append(ReportSection(is_summary = False,
                                                 object_list = object_list,
                                                 object_list_len = object_list_len))

    return report_section_list

  def query(self):
    """Get report sections and construct a list of lines. Note that this method has a side
    effect in the selection, and the renderer object itself.
    """
    start = self.getLineStart()
    max_lines = self.getMaxLineNumber()
2012 2013 2014 2015
    if self.isHideRowsOnNoSearchCriterion():
      report_section_list = []
    else:
      report_section_list = self.getReportSectionList()
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
    param_dict = self.getParamDict()

    # Set the total number of objects.
    self.total_size = sum([s.object_list_len for s in report_section_list])

    # Calculuate the start and the end offsets, and set the page numbers.
    if max_lines == 0:
      end = self.total_size
      self.total_pages = 1
      self.current_page = 0
    else:
      self.total_pages = int(max(self.total_size - 1, 0) / max_lines) + 1
2028 2029 2030
      if start >= self.total_size:
        start = max(self.total_size - 1, 0)
      start -= (start % max_lines)
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
      self.current_page = int(start / max_lines)
      end = min(start + max_lines, self.total_size)
      param_dict['list_start'] = start
      param_dict['list_lines'] = max_lines
      selection = self.getSelection()
      selection.edit(params = param_dict)

    # Make a list of lines.
    line_class = self.getLineClass()
    line_list = []
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062

    try:
      section_index = 0
      current_section_base_index = 0
      current_section = report_section_list[0]
      current_section_size = current_section.object_list_len
      for i in range(start, end):
        # Make sure we go to the right section.
        while current_section_base_index + current_section_size <= i:
          current_section_base_index += current_section_size
          section_index += 1
          current_section = report_section_list[section_index]
          current_section_size = current_section.object_list_len

        offset = i - current_section_base_index + current_section.offset
        if current_section.is_summary:
          index = None
        elif self.isReportTreeMode():
          index = offset
        else:
          index = i
        #LOG('ListBox', 0, 'current_section.__dict__ = %r' % (current_section.__dict__,))
2063 2064 2065 2066 2067 2068
        row_css_class_name = self.getRowCSSClassName(
          brain=current_section.object_list[offset],
          field=self.field,
          list_index=index,
          total_size=self.total_size,
          **param_dict)
2069 2070 2071 2072 2073 2074
        line = line_class(renderer = self,
                          obj = current_section.object_list[offset],
                          index = index,
                          is_summary = current_section.is_summary,
                          context = current_section.context,
                          is_open = current_section.is_open,
2075
                          selection_domain = current_section.selection_domain,
2076
                          depth = current_section.depth,
2077 2078
                          domain_title = current_section.domain_title,
                          row_css_class_name = row_css_class_name)
2079 2080 2081 2082
        line_list.append(line)
    except IndexError:
      # If the report section list is empty, nothing to do.
      pass
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096

    return line_list

  def render(self, **kw):
    """Render the data. This must be overridden.
    """
    raise NotImplementedError, "render must be overridden in a subclass"

  def __call__(self, **kw):
    """Render the ListBox. The real rendering must be done the method "render" which should
    be defined in subclasses.
    """
    return self.render(**kw)

2097
class ListBoxRendererLine:
2098 2099 2100
  """This class describes a line in a ListBox to assist ListBoxRenderer.
  """
  def __init__(self, renderer = None, obj = None, index = 0, is_summary = False, context = None,
2101 2102
               is_open = False, selection_domain = None, depth = 0, domain_title=None, render_prefix=None,
               row_css_class_name=None):
2103 2104 2105 2106 2107 2108 2109 2110
    """In reality, the object is a brain or a brain-like object.
    """
    self.renderer = renderer
    self.obj = obj
    self.index = index
    self.is_summary = is_summary
    self.context = context
    self.is_open = is_open
2111
    self.selection_domain = selection_domain
2112
    self.depth = depth
2113
    self.domain_title = domain_title
2114
    self.render_prefix = render_prefix
2115
    self.row_css_class_name = row_css_class_name
Fabien Morin's avatar
Fabien Morin committed
2116

2117 2118 2119 2120 2121 2122 2123 2124 2125
  def getBrain(self):
    """Return the brain. This can be identical to a real object.
    """
    return self.obj

  def getObject(self):
    """Return a real object.
    """
    try:
2126
      return self.obj.getObject()
2127
    except AttributeError:
2128
      return self.obj
2129

2130
  getObject = lazyMethod(getObject)
2131 2132 2133 2134 2135 2136

  def getUid(self):
    """Return the uid of the object.
    """
    return getattr(aq_base(self.obj), 'uid', None)

2137
  getUid = lazyMethod(getUid)
2138

Jean-Paul Smets's avatar
Jean-Paul Smets committed
2139 2140 2141 2142 2143
  def getUrl(self):
    """Return the absolute URL path of the object
    """
    return self.getBrain().getUrl()

2144
  getUrl = lazyMethod(getUrl)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2145

2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
  def isSummary(self):
    """Return whether this line is a summary or not.
    """
    return self.is_summary

  def getContext(self):
    """Return the context of a line. This is used only for a summary line.
    """
    return self.context

  def isOpen(self):
    """Return whether this line is open or not. This is used only for a summary line.
    """
    return self.is_open

  def getDomainUrl(self):
    """Return the URL of a domain. Used only for a summary line.
    """
    return getattr(self.getContext(), 'domain_url', '')

2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
  def getDomainTitle(self):
    """Return original title of domain"""
    if self.domain_title is not None:
      return self.domain_title
    else:
      context = self.getContext()
      if context is not None:
        return context.getTitleOrId() or ''
    return ''

2176 2177 2178 2179 2180 2181 2182 2183
  def getDepth(self):
    """Return the depth of a domain. Used only for a summary line.
    """
    return self.depth

  def getDomainSelection(self):
    """Return the domain selection. Used only for a summary line.
    """
2184
    return self.selection_domain
2185

2186 2187 2188 2189
  def getRowCSSClassName(self):
    """Return the css class name of a row.
    """
    return self.row_css_class_name
Fabien Morin's avatar
Fabien Morin committed
2190

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
  def getValueList(self):
    """Return the list of values corresponding to selected columns.

    The format of a return value is [(original_value, processed_value), ...],
    where the original value means a raw result, while the processed value stands for
    a value more comprehensive for human, such as an error message.

    Every processed value is guaranteed to be encoded in unicode.
    """
    # If this is a report line without statistics, just return an empty result.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2201
    renderer = self.renderer
2202 2203
    obj = self.getObject()
    if obj is None:
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2204
      return [(None, '')] * len(renderer.getSelectedColumnList())
2205 2206

    # Otherwise, evaluate each column.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2207
    stat_column_dict = dict(renderer.getStatColumnList())
2208 2209
    _marker = []
    value_list = []
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2210 2211
    selection = renderer.getSelection()
    param_dict = renderer.getParamDict()
2212 2213 2214 2215

    # Embed the selection index.
    selection.edit(index = self.index)

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2216
    for (sql, title), alias in zip(renderer.getSelectedColumnList(), renderer.getColumnAliasList()):
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
      editable_field = None
      original_value = None
      processed_value = None

      if self.isSummary():
        # Use a stat method for a summary.
        stat_method_id = stat_column_dict.get(sql)
        if stat_method_id == sql:
          stat_method_id = None

        context = self.getContext()
        if getattr(aq_base(context), alias, _marker) is not _marker and stat_method_id is None:
          # If a stat method is not specified, use the result in the context itself.
          original_value = getattr(context, alias)
          processed_value = original_value
2232
        elif stat_method_id is not None:
2233 2234 2235 2236 2237 2238 2239
          stat_method = getattr(context, stat_method_id)
          if callable(stat_method):
            try:
              new_param_dict = param_dict.copy()
              new_param_dict['closed_summary'] = not self.isOpen()
              selection.edit(params = new_param_dict, report = self.getDomainSelection())
              try:
2240 2241
                original_value = stat_method(selection = selection,
                                             selection_name = selection.getName())
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
                processed_value = original_value
              except (ConflictError, RuntimeError):
                raise
              except:
                LOG('ListBox', WARNING, 'could not call %r with %r' % (stat_method, new_param_dict),
                    error = sys.exc_info())
                processed_value = 'Could not evaluate %s' % (stat_method_id,)
            finally:
              selection.edit(params = param_dict, report = None)
          else:
            original_value = stat_method
            processed_value = original_value
      else:
        # This is an usual line.
2256
        brain = self.getBrain()
2257 2258

        # Use a widget, if any.
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2259
        editable_field = renderer.getEditableField(alias)
2260
        tales = False
2261
        if editable_field is not None:
2262 2263 2264 2265 2266 2267 2268
          # XXX we need to take care of whether the editable field is
          # a proxy field or not, because a proxy field may inherit a
          # tales expression from a template field, and the API is not
          # unified.
          get_tales = getattr(editable_field, 'get_recursive_tales',
                              editable_field.get_tales)
          tales = get_tales('default')
2269
          if tales:
2270 2271
            original_value = editable_field.__of__(obj).get_value('default',
                                                        cell=brain)
2272
            processed_value = original_value
2273

2274 2275
        # If a tales expression is not defined, get a skin, an accessor or a property.
        if not tales:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
2276
          if getattr(aq_self(brain), alias, None) is not None:
2277 2278
            original_value = getattr(brain, alias)
            processed_value = original_value
2279
          else:
2280 2281
            try:
              # Get the trailing part.
2282
              try:
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
                property_id = sql[sql.rindex('.') + 1:]
              except ValueError:
                property_id = sql

              try:
                original_value = obj.getProperty(property_id, _marker)
                if original_value is _marker:
                  raise AttributeError, property_id
                processed_value = original_value
              except AttributeError:
                original_value = getattr(obj, property_id, None)
                processed_value = original_value
            except (AttributeError, KeyError, Unauthorized):
2296
              original_value = None
2297
              processed_value = 'Could not evaluate %s' % property_id
2298 2299 2300 2301 2302

      # If the value is callable, evaluate it.
      if callable(original_value):
        try:
          try:
2303 2304 2305
            original_value = original_value(brain = self.getBrain(),
                                            selection = selection,
                                            selection_name = selection.getName())
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
            processed_value = original_value
          except TypeError:
            original_value = original_value()
            processed_value = original_value
        except (ConflictError, RuntimeError):
          raise
        except:
          processed_value = 'Could not evaluate %s' % (original_value,)
          LOG('ListBox', WARNING, 'could not evaluate %r' % (original_value,),
              error = sys.exc_info())
          original_value = None

      # Process the value.
      if processed_value is None:
        processed_value = u''
2321
      elif not isinstance(processed_value, unicode):
2322
        processed_value = unicode(str(processed_value), renderer.getEncoding(), 'replace')
2323 2324 2325

      value_list.append((original_value, processed_value))

2326
    #LOG('ListBox.getValueList', 0, value_list)
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
    return value_list

class ListBoxHTMLRendererLine(ListBoxRendererLine):
  """This class is specialized to the HTML renderer.
  """
  def render(self):
    """Render the values obtained by getValueList. The result is a list of tuples,
    where each tuple consists of a piece of HTML, the original value and a boolean value which represents
    an error status. If the status is true, an error is detected.
    """
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2337 2338 2339 2340 2341 2342
    renderer = self.renderer
    request = renderer.request
    editable_column_id_set = renderer.getEditableColumnIdSet()
    field_id = renderer.getId()
    form = renderer.getForm()
    error_dict = renderer.getFieldErrorDict()
2343
    brain = self.getBrain()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2344 2345 2346 2347
    encoding = renderer.getEncoding()
    url_column_dict = dict(renderer.getUrlColumnList())
    selection = renderer.getSelection()
    selection_name = renderer.getSelectionName()
2348 2349
    ignore_layout = int(request.get('ignore_layout',
                        0 if request.get('is_web_mode') else 1))
2350
    editable_mode = int(request.get('editable_mode', 0))
2351
    ui_domain = 'erp5_ui'
2352 2353 2354 2355
    # We need a way to pass the current line object (ie. brain) to the
    # field which is being displayed. Since the render_view API did not
    # permit this, we use the 'cell' value to pass the line object.
    request.set('cell', brain)
2356 2357
    html_list = []

2358 2359 2360
    # Generate page selection methods based on the Listbox id
    createFolderMixInPageSelectionMethod(field_id)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
    # Check is there is a validation error at the level of the listbox
    # as a whole. This will be required later to decide wherer to
    # display values from (ie. from the REQUEST or from the object)
    has_error = 0
    for key in error_dict.keys():
      for editable_id in editable_column_id_set:
        candidate_field_key = "%s_%s" % (field_id, editable_id)
        if key.startswith(candidate_field_key):
          has_error = 1
          break
      if has_error:
        break

2374
    for (original_value, processed_value), (sql, title), alias \
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2375
      in zip(self.getValueList(), renderer.getSelectedColumnList(), renderer.getColumnAliasList()):
2376 2377 2378 2379 2380 2381 2382 2383
      # By default, no error.
      error = False

      # Embed the selection index.
      selection.edit(index = self.index)

      # If a field is editable, generate an input form.
      # XXX why don't we generate an input form when a widget is not defined?
2384
      editable_field = renderer.getEditableField(alias)
2385

2386
      # Prepare link value - we now use it for both static and field rendering
2387
      no_link = self.isSummary()
2388 2389 2390 2391 2392 2393 2394
      url_method = None
      url = None

      # Find an URL method.
      if url_column_dict.has_key(sql):
        url_method_id = url_column_dict.get(sql)
        if url_method_id != sql:
2395
          if url_method_id not in (None, ''):
2396 2397 2398 2399 2400
            url_method = getattr(brain, url_method_id, None)
            if url_method is None:
              LOG('ListBox', WARNING, 'could not find the url method %s' % (url_method_id,))
              no_link = True
          else:
2401
            # If the URL Method is empty, generate no link.
2402 2403 2404 2405
            no_link = True

      if url_method is not None:
        try:
2406 2407
          url = url_method(brain = brain, selection = selection,
                           selection_name = selection.getName())
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
        except (ConflictError, RuntimeError):
          raise
        except:
          LOG('ListBox', WARNING, 'could not evaluate the url method %r with %r' % (url_method, brain),
              error = sys.exc_info())
      elif not no_link:
        # XXX For compatibility?
        # Check if this object provides a specific URL method.
        if getattr(brain, 'getListItemUrl', None) is not None:
          try:
            url = brain.getListItemUrl(alias, self.index, selection_name)
          except (ConflictError, RuntimeError):
            raise
          except:
            LOG('ListBox', WARNING, 'could not evaluate the url method getListItemUrl with %r' % (brain,),
                error = sys.exc_info())
        else:
          try:
2426 2427 2428 2429 2430
            # brain.absolute_url() is slow because it invokes
            # _aq_dynamic() every time to get brain.REQUEST,
            # so we call request.physicalPathToURL() directly
            # instead of brain.absolute_url().
            url = request.physicalPathToURL(brain.getPath())
2431 2432 2433
            params = []
            if ignore_layout:
              params.append('ignore_layout:int=1')
2434 2435
            if editable_mode:
              params.append('editable_mode:int=1')
2436
            if selection_name:
2437 2438 2439 2440 2441
              params.extend(('selection_name=%s' % selection_name,
                             'selection_index=%s' % self.index,
                             'reset:int=1'))
            if params:
              url = '%s?%s' % (url, '&amp;'.join(params))
2442 2443 2444
          except AttributeError:
            pass

2445
      if editable_field is not None:
2446
        # XXX what if the object does not have uid?
2447
        key = '%s_%s' % (editable_field.getId(), self.getUid())
2448
        if sql in editable_column_id_set:
2449
          listbox_defines_column_as_editable = True
2450 2451
          if has_error: # If there is any error on listbox, we should use what the user has typed
            display_value = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2452
          else:
2453 2454 2455 2456 2457
            validated_value_dict = request.get(field_id, None)
            if validated_value_dict is None:
              # If this is neither an error nor a validated listbox
              # we should use the original value
              display_value = original_value
2458
            else:
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
              # If the listbox has been validated (ie. as it is the
              # case whenever a relation field displays a popup menu)
              # we have to use the value entered by the user
              display_value = None #
          if error_dict.has_key(key): # If error on current field, we should display message
            error_text = error_dict[key].error_text
            error_text = cgi.escape(error_text)
            if isinstance(error_text, str):
              error_mapping = getattr(error_dict[key], 'error_mapping', None)
              if error_mapping is not None:
                error_text = u'%s' % Message(domain=ui_domain,
                                             message=error_text,
                                             mapping=error_mapping)
              else:
                error_text = u'%s' % Message(domain=ui_domain,
                                             message=error_text)
            error_message = u'<br />' + error_text
          else:
            error_message = u''
2478
        else:
2479
          listbox_defines_column_as_editable = False
2480
          error_message = u''
2481
          display_value = original_value
2482

2483
        enabled = editable_field.get_value('enabled', REQUEST=request)
2484
        editable = editable_field.get_value('editable', REQUEST=request)
2485
        if enabled:
2486 2487
          # Field is editable only if listbox lists it in editable columns AND
          # if listbox_field is editable
2488 2489 2490 2491
          cell_html = editable_field.render(
            value=display_value,
            REQUEST=request,
            key=key,
2492 2493
            editable=(not self.isSummary()) \
              and listbox_defines_column_as_editable and editable,
2494
          )
2495 2496
          if isinstance(cell_html, str):
            cell_html = unicode(cell_html, encoding)
2497
        else:
2498
          cell_html = u''
2499

2500 2501 2502
        if url is None:
          html = cell_html + error_message
        else:
2503
          if editable:
2504 2505 2506 2507
            html = u'%s' % cell_html
          else:
            html = u'<a href="%s">%s</a>' % (url, cell_html)
          if error_message not in ('', None):
2508
            html += u' <span class="error">%s</span>' % error_message
2509 2510
      else:
        # If not editable, show a static text with a link, if enabled.
Julien Muchembled's avatar
Julien Muchembled committed
2511 2512
        html = cgi.escape(processed_value)
        if url is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2513 2514
          # JPS-XXX - I think we should not display a URL for objects
          # which do not have the View permission
Julien Muchembled's avatar
typo  
Julien Muchembled committed
2515
          if isinstance(url, str):
2516
            url = unicode(url, encoding)
Julien Muchembled's avatar
Julien Muchembled committed
2517
          html = u'<a href="%s">%s</a>' % (url, html)
2518

2519
      html_list.append((html, original_value, error, editable_field, url))
2520 2521
    return html_list

2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
allow_class(ListBoxHTMLRendererLine)

class ListBoxRendererContext(Acquisition.Explicit):
  """This class helps making a context for a Page Template,
  because Page Template requires an acquisition context.
  """
  def __init__(self, renderer):
    self.renderer = renderer
    # XXX this is a workaround for GlobalTranslationService.
    self.Localizer = renderer.getContext().Localizer
2532 2533
    # XXX this is a workaround for unicodeconflictresolver.
    self.REQUEST = renderer.request
2534 2535 2536

  def __getattr__(self, name):
    return getattr(self.renderer, name)
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548

class ListBoxHTMLRenderer(ListBoxRenderer):
  """This class implements HTML rendering for ListBox.
  """
  def getLineClass(self):
    """Return the line class.
    """
    return ListBoxHTMLRendererLine

  def getLineStart(self):
    """Return a requested start number.
    """
2549
    return int(self.getParamDict().get('list_start', 0))
2550

2551
  getLineStart = lazyMethod(getLineStart)
2552 2553 2554 2555 2556 2557

  def getMaxLineNumber(self):
    """Return the maximum number of lines shown in a page.
    """
    return self.field.get_value('lines')

2558
  getMaxLineNumber = lazyMethod(getMaxLineNumber)
2559

2560 2561 2562 2563
  def getMD5Checksum(self):
    """Generate a MD5 checksum against checked uids. This is used to confirm
    that selected values do not change between a display of a dialog and an execution.

2564 2565 2566
    FIXME: SelectionTool.getSelectionChecksum's uid_list parameter is
    deprecated, but Folder_deleteObjectList does not use the feature that
    checked uids are used when no list method is specified.
2567
    """
2568 2569 2570 2571
    return self.getSelectionTool().getSelectionChecksum(
      self.getSelectionName(),
      uid_list=self.request.get('uids'),
    )
2572

2573 2574 2575 2576 2577 2578
  def getPhysicalRoot(self):
    """Return the physical root (an Application object). This method is required for
    Page Template to make a context.
    """
    return self.getContext().getPhysicalRoot()

2579
  asHTML = PageTemplateFile('www/%s' %DEFAULT_LISTBOX_PAGE_TEMPLATE, globals())
2580 2581 2582 2583 2584 2585 2586 2587

  def getPageTemplate(self):
    """Return a Page Template to render.
    """
    context = ListBoxRendererContext(self)

    # If a specific template is specified, use it.
    method_id = self.field.get_value('page_template')
2588 2589
    if method_id not in (None, ''):
      try:
2590
        return getattr(context, method_id)
2591
      except AttributeError:
2592
        return getattr(context.getPortalObject(), method_id).__of__(context)
2593
      return aq_base(getattr(self.getContext(), method_id)).__of__(context)
2594 2595
    # Try to get a page template from acquisition context then portal object
    # and fallback on default page template.
2596
    page_template = getattr(self.getContext(), DEFAULT_LISTBOX_PAGE_TEMPLATE, None)
2597 2598
    if page_template is None:
        portal_object = context.getPortalObject()
2599
        page_template = getattr(portal_object, DEFAULT_LISTBOX_PAGE_TEMPLATE, context.asHTML)
2600
    return page_template.__of__(context)
2601

2602 2603 2604
  def render(self, **kw):
    """Render the data in HTML.
    """
2605 2606 2607
    request = self.request
    field_id = self.getId()
    
2608 2609 2610
    # Make it sure to store the current selection, only if a list method is defined.
    list_method = self.getListMethod()
    if list_method is not None:
2611
      selection = self.getSelection()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
2612
      method_path = '%s/%s' % (getPath(self.getContext()), self.getListMethodName())
2613 2614 2615 2616
      list_url = '%s?selection_name=%s' % (self.getUrl(), self.getRequestedSelectionName())
      selection_index = self.getSelectionIndex()
      if selection_index is not None:
        list_url += '&selection_index=%s' % selection_index
2617
      selection.edit(method_path = method_path, list_url = list_url)
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
      
      # listbox search columnd are passed in format: <listbox_field_id>_<search_column>
      # this is done to allow multiple listboxes in one page with same search column names
      update_selection = False
      form_dict = request.form
      listbox_kw = selection.getParams()
      listbox_arguments_list = [x for x in form_dict.keys() if x.startswith(field_id)]
      for original_listbox_argument in listbox_arguments_list:
        listbox_argument = original_listbox_argument.replace('%s_' %field_id, '', 1)
        listbox_argument_value = form_dict.get(original_listbox_argument, None)
        if listbox_argument in list(self.getSearchColumnIdSet()) and \
           listbox_argument_value not in (None,):
          update_selection = True
          listbox_kw[listbox_argument] = listbox_argument_value
      if update_selection:
        selection.edit(listbox_kw)
      self.getSelectionTool().setSelectionFor(self.getSelectionName(), selection, REQUEST = request)
2635

2636 2637
    # do pass current form and respective field through request
    form = self.getForm()
Ivan Tyagov's avatar
Ivan Tyagov committed
2638 2639
    request.set('%s_form_id' %field_id, form.getId())
    request.set('%s_field_id' %field_id, field_id)
2640 2641 2642 2643 2644
    pt = self.getPageTemplate()
    return pt()

allow_class(ListBoxHTMLRenderer)

2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
class ListBoxListRenderer(ListBoxRenderer):
  """This class implements list rendering for ListBox.
  """
  def getLineClass(self):
    """Return the line class. For now, ListBoxListRenderer uses the generic class.
    """
    return ListBoxRendererLine

  def getLineStart(self):
    """Return always 0.
    """
    return 0

  def getMaxLineNumber(self):
    """Return always 0 (infinite).
    """
    return 0

  def render(self, **kw):
    """Render the data in a list of ListBoxLine objects.
    """
    listboxline_list = []

    # Make a title line.
    title_listboxline = ListBoxLine()
    title_listboxline.markTitleLine()
    for c in self.getSelectedColumnList():
      title_listboxline.addColumn(c[0], c[1].encode(self.getEncoding()))
    listboxline_list.append(title_listboxline)

    # Obtain the list of lines.
    checked_uid_set = set(self.getCheckedUidList())
    for line in self.query():
      listboxline = ListBoxLine()
      listboxline.markDataLine()
2680
      listboxline.setSectionDepth(line.getDepth())
2681
      listboxline.setRowCSSClassName(line.getRowCSSClassName())
2682 2683
      if line.isSummary():
        listboxline.markSummaryLine()
2684 2685 2686 2687 2688 2689
        # XXX It was line.getDepth()+1 before, but
        # it probably make no sense so I (seb) removed this
        listboxline.setSectionDepth(line.getDepth())
        # Do not get the context again, it was already computed
        # in getReportSectionList
        listboxline.setSectionName(line.domain_title)
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
        listboxline.setSectionFolded(not line.isOpen())

      if line.getBrain() is not None:
        uid = line.getUid()
        listboxline.setObjectUid(uid)
        listboxline.checkLine(uid in checked_uid_set)

      for (original_value, processed_value), (sql, title) in zip(line.getValueList(), self.getSelectedColumnList()):
        if isinstance(original_value, unicode):
          value = original_value.encode(self.getEncoding())
        else:
          value = original_value

        if isinstance(value, str):
          value = value.replace('&nbsp;', ' ')

        listboxline.addColumn(sql, value)

      listboxline_list.append(listboxline)

    # Make a stat line, if enabled.
    if self.showStat():
      stat_listboxline = ListBoxLine()
      stat_listboxline.markStatLine()

      for (original_value, processed_value), (sql, title) in zip(self.getStatValueList(), self.getSelectedColumnList()):
        if isinstance(original_value, unicode):
          value = original_value.encode(self.getEncoding())
        else:
          value = original_value

        if isinstance(value, str):
          value = value.replace('&nbsp;', ' ')

2724
        stat_listboxline.addColumn(sql, value)
2725 2726 2727 2728 2729 2730 2731

      listboxline_list.append(stat_listboxline)

    return listboxline_list

class ListBoxValidator(Validator.Validator):
    property_names = Validator.Validator.property_names
2732 2733
    message_names = Validator.Validator.message_names + ['required_not_found']
    required_not_found = 'Input is required but no input given.'
2734 2735 2736 2737 2738 2739 2740 2741

    def validate(self, field, key, REQUEST):
        form = field.aq_parent
        # We need to know where we get the getter from
        # This is coppied from ERP5 Form
        here = getattr(form, 'aq_parent', REQUEST)
        columns = field.get_value('columns')
        editable_columns = field.get_value('editable_columns')
2742 2743
        column_ids = [x[0] for x in columns]
        editable_column_ids = [x[0] for x in editable_columns]
2744
        editable_field_dict = {}
2745 2746 2747 2748 2749
        for sql in editable_column_ids:
          alias = sql.replace('.', '_')
          editable_field_dict[alias] = ListBoxRenderer(
                                          field=field).getEditableField(alias)
          
2750 2751
        selection_name = field.get_value('selection_name')
        #LOG('ListBoxValidator', 0, 'field = %s, selection_name = %s' % (repr(field), repr(selection_name)))
2752 2753
        portal = here.getPortalObject()
        params = portal.portal_selections.getSelectionParamsFor(
2754
                                                           selection_name,
2755
                                                           REQUEST=REQUEST)
2756
        portal_url = portal.portal_url
2757 2758 2759

        result = {}
        error_result = {}
2760 2761 2762 2763 2764 2765 2766 2767 2768
        listbox_empty = REQUEST.get('%s_empty' % field.id, False)
        if listbox_empty:
          listbox_uids = []
        else:
          try:
            listbox_uids = REQUEST['%s_uid' % field.id]
          except KeyError:
            raise KeyError('Field %s is not present in request object.'
                           % field.id)
2769 2770 2771
        select = field.get_value('select')
        if select:
          selected_uid_set = set(REQUEST.get('uids', ()))
2772 2773
        #LOG('ListBox.validate: REQUEST',0,REQUEST)
        errors = []
2774
        object_list = None
2775 2776 2777 2778 2779
        # We have two things to do in the case of temp objects,
        # the first thing is to create a list with new temp objects
        # then try to validate some data, and then create again
        # the list with a listbox as parameter. Like this we
        # can use tales expression
2780 2781
        listbox = {}
        for uid in listbox_uids:
2782
          if uid[:4] == 'new_':
2783
            if object_list is None:
2784 2785
              list_method = field.get_value('list_method')
              list_method = getattr(here, list_method.method_name)
2786 2787
              #LOG('ListBoxValidator', 0, 'call %s' % repr(list_method))
              object_list = list_method(REQUEST=REQUEST, **params)
2788
            row_key = uid[4:]
2789 2790 2791 2792
            for o in object_list:
              if o.getUid() == uid:
                break
            else:
2793
              # First case: dialog input to create new objects
2794
              o = newTempBase(portal, row_key) # Arghhh - XXX acquisition problem - use portal root
2795
              o.uid = uid
2796
            listbox[row_key] = row_result = {}
2797 2798
            # We first try to set a listbox corresponding to all things
            # we can validate, so that we can use the same list
2799 2800
            # as the one used for displaying the listbox
            for sql in editable_column_ids:
2801
              editable_field = editable_field_dict.get(sql.replace('.', '_'))
2802 2803
              if editable_field is not None:
                error_result_key = '%s_%s' % (editable_field.id, o.uid)
2804
                key = 'field_' + error_result_key
2805
                REQUEST.set('cell', o)
2806
                try:
2807
                  value = editable_field._validate_helper(key, REQUEST) # We need cell
2808
                  # Here we set the property
2809
                  row_result[sql] = value
2810
                except ValidationError, err:
2811
                  pass
2812 2813
                except KeyError:
                  pass
2814 2815
        # Here we generate again the object_list with listbox the listbox we
        # have just created
2816
        if listbox:
2817 2818
          list_method = field.get_value('list_method')
          list_method = getattr(here, list_method.method_name)
2819
          REQUEST.set(field.id, listbox)
2820
          object_list = list_method(REQUEST=REQUEST, **params)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2821
        for uid in listbox_uids:
2822 2823
          row_result = {}
          if uid[:4] == 'new_':
2824
            # First case: dialog input to create new objects
2825
            row_key = uid[4:]
2826 2827 2828 2829
            for o in object_list:
              if o.getUid() == uid:
                break
            else:
2830
              o = newTempBase(portal, row_key) # Arghhh - XXX acquisition problem - use portal root
2831
              o.uid = uid
2832
            for sql in editable_column_ids:
2833
              editable_field = editable_field_dict.get(sql.replace('.', '_'))
2834
              if editable_field is not None:
2835
                REQUEST.set('cell', o)
2836 2837 2838
                editable = editable_field.get_value('editable', REQUEST=REQUEST)
                enabled = editable_field.get_value('enabled', REQUEST=REQUEST)
                if editable and enabled and field.need_validate(REQUEST):
2839
                  error_result_key = '%s_%s' % (editable_field.id, o.uid)
2840
                  key = 'field_' + error_result_key
2841
                  try:
2842 2843
                    row_result[sql] = editable_field._validate_helper(
                      key, REQUEST) # We need cell
2844
                  except ValidationError, err:
2845 2846 2847
                    #LOG("ListBox ValidationError",0,str(err))
                    err.field_id = error_result_key
                    errors.append(err)
2848 2849 2850 2851
                  except KeyError:
                    err = ValidationError('required_not_found', field)
                    err.field_id = field.id
                    errors.append(err)
2852 2853
          else:
            # Second case: modification of existing objects
2854 2855
            #try:
            if 1: #try:
2856 2857
              # We must try this
              # because sometimes, we can be provided bad uids
2858 2859
              try :
                o = here.portal_catalog.getObject(uid)
2860
              except (KeyError, NotFound, ValueError), err:
2861 2862
                # It is possible that this object is not catalogged yet. So
                # the object must be obtained from ZODB.
2863
                if object_list is None:
2864 2865
                  list_method = field.get_value('list_method')
                  list_method = getattr(here, list_method.method_name)
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
                  object_list = list_method(REQUEST=REQUEST, **params)
                for o in object_list:
                  try:
                    if o.getUid() == int(uid):
                      break
                  except ValueError:
                    if str(o.getUid()) == uid:
                      break
                else:
                  raise err
2876 2877 2878
              row_key = o.getUrl()
              for sql in editable_column_ids:
                editable_field = editable_field_dict.get(sql.replace('.', '_'))
2879
                if editable_field is not None:
2880
                  REQUEST.set('cell', o) # We need cell
2881 2882
                  if editable_field.get_value('editable', REQUEST=REQUEST) and \
                     editable_field.need_validate(REQUEST):
2883
                    error_result_key = '%s_%s' % (editable_field.id, o.uid)
2884
                    key = 'field_' + error_result_key
2885
                    try:
2886 2887
                      row_result[sql] = error_result[error_result_key] = \
                        editable_field._validate_helper(key, REQUEST)
2888
                    except ValidationError, err:
2889 2890
                      err.field_id = error_result_key
                      errors.append(err)
2891 2892 2893 2894
                    except KeyError:
                      err = ValidationError('required_not_found', field)
                      err.field_id = field.id
                      errors.append(err)
2895 2896
            #except:
            else:
2897
              LOG("ListBox WARNING",0,"Object uid %s could not be validated" % uid)
2898
          result[row_key] = row_result
2899 2900
          if select:
            row_result['listbox_selected'] = uid in selected_uid_set
2901
        if len(errors) > 0:
Nicolas Delaby's avatar
Nicolas Delaby committed
2902 2903
            #LOG("ListBox FormValidationError",0,str(error_result))
            #LOG("ListBox FormValidationError",0,str(errors))
2904
            raise FormValidationError(errors, error_result)
2905
        return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2906 2907 2908 2909

ListBoxValidatorInstance = ListBoxValidator()

class ListBox(ZMIField):
2910
  meta_type = "ListBox"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2911

2912 2913
  widget = ListBoxWidgetInstance
  validator = ListBoxValidatorInstance
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2914

2915
  security = ClassSecurityInfo()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
2916

2917 2918 2919 2920
  security.declareProtected('Access contents information', 'get_value')
  def get_value(self, id, **kw):
    if (id == 'default'):
      if (kw.get('render_format') in ('list', )):
2921 2922 2923 2924 2925 2926
        request = kw.get('REQUEST', None)
        if request is None:
          request = get_request()
        # here the field can be a a proxyfield target, in this case just find
        # back the original proxy field so that renderer's calls to .get_value
        # are called on the proxyfield.
2927 2928 2929
        field = request.get(
          'field__proxyfield_%s_%s_%s' % (self.id, self._p_oid, id),
          self)
2930 2931
        return self.widget.render(field, self.generate_field_key(), None,
                                  request,
2932 2933
                                  render_format=kw.get('render_format'),
                                  render_prefix=kw.get('render_prefix'))
2934
      else:
2935 2936 2937
        return None
    else:
      return ZMIField.get_value(self, id, **kw)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
2938

2939 2940 2941
  security.declareProtected('Access contents information', 'getListMethodName')
  def getListMethodName(self):
    """Return the name of the list method. If not defined, return None.
2942 2943

       XXX - Is this method really necessary - I am not sure - JPS
2944 2945
       Why not use Formulator API instead ? -> the answer is that it is a
         MethodField, and it's method_name attribute is not available from
2946 2947
         restricted environment. It is only used in
         ERP5Site_checkNamingConventions
2948 2949 2950

      XXX also this method is not compatible with ProxyFields.
      It will go away soon.
2951 2952 2953 2954 2955 2956 2957
    """
    list_method = self.get_value('list_method')
    try:
      name = getattr(list_method, 'method_name')
    except AttributeError:
      name = list_method
    return name or None
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968

class ListBoxLine:
  meta_type = "ListBoxLine"
  security = ClassSecurityInfo()
  #security.declareObjectPublic()

  def __init__(self):
    """
      Initialize the line and set the default values
      Selected columns must be defined in parameter of listbox.render...
    """
2969

2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
    self.is_title_line = 0
    self.is_data_line = 1
    self.is_stat_line = 0
    self.is_summary_line = 0

    self.is_section_folded = 1

    self.config_dict = {
      'is_checked' : 0,
      'uid' : None,
      'section_name' : None,
      'section_depth' : 0,
      'content_mode' : 'DataLine'
    }
    self.config_display_list = []

    self.column_dict = {}
    self.column_id_list = []
2988
    self.row_css_class_name = ''
Fabien Morin's avatar
Fabien Morin committed
2989

2990 2991
  security.declarePublic('__getitem__')
  def __getitem__(self, column_id):
2992
    return self.getColumnProperty(column_id)
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008

  #security.declarePublic('View')
  def setConfigProperty(self, config_id, config_value):
    self.config_dict[config_id] = config_value

  #security.declarePublic('View')
  def getConfigProperty(self, config_id):
    return self.config_dict[config_id]

  #security.declarePublic('View')
  def setListboxLineContentMode(self, content_mode):
    """
      Toogle the content type of the line
      content_mode can be 'TitleLine' 'StatLine' 'DataLine'
      Default value is 'DataLine'
    """
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
    content_mode_dict = {
      'TitleLine':(1,0,0,0),
      'DataLine':(0,1,0,0),
      'StatLine':(0,0,1,0),
      'SummaryLine':(0,0,0,1)
    }
    self.is_title_line,\
    self.is_data_line,\
    self.is_stat_line,\
    self.is_summary_line = content_mode_dict[content_mode]

3020
    self.setConfigProperty('content_mode', content_mode)
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041

  #security.declarePublic('View')
  def markTitleLine(self):
    """
      Set content of the line to 'TitleLine'
    """
    self.setListboxLineContentMode('TitleLine')

  security.declarePublic('isTitleLine')
  def isTitleLine(self):
    """
      Returns 1 is this line contains no data but only title of columns
    """
    return self.is_title_line

  #security.declarePublic('View')
  def markStatLine(self):
    """
      Set content of the line to 'StatLine'
    """
    self.setListboxLineContentMode('StatLine')
3042

3043 3044
  security.declarePublic('isStatLine')
  def isStatLine(self):
3045 3046 3047 3048
    """
      Returns 1 is this line contains no data but only stats
    """
    return self.is_stat_line
3049

3050 3051 3052 3053 3054 3055
  #security.declarePublic('View')
  def markDataLine(self):
    """
      Set content of the line to 'DataLine'
    """
    self.setListboxLineContentMode('DataLine')
3056

3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
  security.declarePublic('isDataLine')
  def isDataLine(self):
    """
      Returns 1 is this line contains data
    """
    return self.is_data_line

  #security.declarePublic('View')
  def markSummaryLine(self):
    """
      Set content of the line to 'SummaryLine'
    """
    self.setListboxLineContentMode('SummaryLine')

  security.declarePublic('isSummaryLine')
  def isSummaryLine(self):
    """
      Returns 1 is this line is a summary line
    """
    return self.is_summary_line

  #security.declarePublic('View')
  def checkLine(self, is_checked):
    """
      Set line to checked if is_checked=1
      Default value is 0
    """
3084
    self.setConfigProperty('is_checked', is_checked)
3085 3086 3087 3088 3089 3090 3091

  security.declarePublic('isLineChecked')
  def isLineChecked(self):
    """
      Returns 1 is this line is checked
    """
    return self.getConfigProperty('is_checked')
3092

3093 3094 3095 3096 3097 3098
  #security.declarePublic('View')
  def setObjectUid(self, object_uid):
    """
      Define the uid of the object
      Default value is None
    """
3099
    self.setConfigProperty('uid', object_uid)
3100 3101 3102 3103 3104 3105 3106

  security.declarePublic('getObjectUid')
  def getObjectUid(self):
    """
      Get the uid of the object related to the line
    """
    return self.getConfigProperty('uid')
3107

3108 3109 3110 3111 3112 3113
  #security.declarePublic('View')
  def setSectionName(self, section_name):
    """
      Set the section name of this line
      Default value is None
    """
3114
    self.setConfigProperty('section_name', section_name)
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129

  security.declarePublic('getSectionName')
  def getSectionName(self):
    """
      Returns the section name of this line
      Default value is None
    """
    return self.getConfigProperty('section_name')

  #security.declarePublic('View')
  def setSectionDepth(self, depth):
    """
      Set the section depth of this line
      default value is 0 and means no depth
    """
3130
    self.setConfigProperty('section_depth', depth)
3131

3132 3133 3134 3135 3136 3137 3138
  security.declarePublic('getSectionDepth')
  def getSectionDepth(self):
    """
      Returns the section depth of this line
      0 means no depth
    """
    return self.getConfigProperty('section_depth')
3139

3140 3141 3142 3143 3144 3145
  #security.declarePublic('View')
  def setSectionFolded(self, is_section_folded):
    """
      Set the section mode of this line to 'Folded' if is_section_folded=1
    """
    self.is_section_folded = is_section_folded
3146

3147 3148 3149 3150 3151
  security.declarePublic('isSectionFolded')
  def isSectionFolded(self):
    """
      Returns 1 if section is in 'Folded' Mode
    """
3152 3153
    return self.is_section_folded

3154 3155 3156
  #security.declarePublic('View')
  def addColumn(self, column_id, column_value):
    """
3157
      Add a new column
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
    """
    self.column_dict[column_id] = column_value
    self.column_id_list.append(column_id)

  security.declarePublic('getColumnProperty')
  def getColumnProperty(self, column_id):
    """
      Returns the property of a column
    """
    return self.column_dict[column_id]

  security.declarePublic('getColumnPropertyList')
  def getColumnPropertyList(self, column_id_list = None):
    """
3172
      Returns a list of the property
3173 3174
      column_id_list selects the column_id returned
    """
3175

3176 3177
    if column_id_list == None:
      column_id_list = self.column_id_list
3178

3179 3180 3181 3182
    if self.isTitleLine():
      config_column = [None] * len(self.config_display_list)
    else:
      config_column = [self.config_dict[column_id] for column_id in self.config_display_list]
3183

3184 3185
    return config_column + [self.column_dict[column_id] for column_id in column_id_list]

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
  security.declarePublic('getColumnPropertyTypeName')
  def getColumnPropertyTypeName(self, column_id):
    """
      Returns the type of a property of a column in
      the form of a string

      NOTE: experimental method - may change in the future
    """
    return type(self.column_dict[column_id]).__name__

3196 3197 3198 3199 3200 3201
  security.declarePublic('getColumnItemList')
  def getColumnItemList(self, column_id_list = None ):
    """
      Returns a list of property tuple
      column_id_list selects the column_id returned
    """
3202

3203 3204
    if column_id_list == None:
      column_id_list = self.column_id_list
3205

3206 3207 3208 3209 3210 3211 3212
    """
    if self.isTitleLine():
      config_column = [None] * len(self.config_display_list)
    else:
      config_column = [(config_id, self.config_dict[column_id]) for config_id in self.config_display_list]
    """
    config_column = [(config_id, self.config_dict[config_id]) for config_id in self.config_display_list]
3213

3214
    return config_column + [(column_id , self.column_dict[column_id]) for column_id in column_id_list]
3215

3216 3217 3218 3219 3220 3221 3222 3223
  security.declarePublic('setListboxLineDisplayListMode')
  def setListboxLineDisplayListMode(self, display_list):
    """
      Set the config columns displayable
      display_list can content the key of self.config_dict
      Default value of display_list is []
    """
    self.config_display_list = display_list
3224

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
  security.declarePublic('setRowCSSClassName')
  def setRowCSSClassName(self, row_css_class_name):
    """Set the CSS class name of a row
    """
    self.row_css_class_name = row_css_class_name

  security.declarePublic('getRowCSSClassName')
  def getRowCSSClassName(self):
    """Return the CSS class name of a row
    """
    return self.row_css_class_name
Fabien Morin's avatar
Fabien Morin committed
3236

3237 3238 3239
InitializeClass(ListBoxLine)
allow_class(ListBoxLine)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
3240
# Psyco
3241
from Products.ERP5Type.PsycoWrapper import psyco
3242
#psyco.bind(ListBoxWidget.render)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
3243 3244
psyco.bind(ListBoxValidator.validate)

3245 3246 3247
# Register get_value
from Products.ERP5Form.ProxyField import registerOriginalGetValueClassAndArgument
registerOriginalGetValueClassAndArgument(ListBox, 'default')