source: publico/PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis/browser/boxes/manager.py @ 6498

Última Alteração nesse arquivo desde 6498 foi 6498, incluída por mazza, 9 anos atrás

refatoracao: eliminado BoxManager?, metodos integrados a Box

File size: 5.0 KB
Linha 
1from exceptions import ValueError
2
3import martian
4from AccessControl import getSecurityManager
5from Products.CMFCore.interfaces import IFolderish
6from Products.CMFCore.permissions import ModifyPortalContent
7from five import grok
8from five.grok.components import ZopeTwoPageTemplate
9from jinja2 import Environment, PackageLoader
10from persistent.dict import PersistentDict
11from plone.autoform.form import AutoExtensibleForm
12from z3c.form import form, datamanager
13from z3c.form.interfaces import IDataManager
14from zope.annotation import IAnnotations
15from zope.component import adapts, provideAdapter
16from zope.interface import implements
17from zope.schema.interfaces import IField
18
19from interfaces import box_schemas
20
21
22class PersistentDictionaryField(datamanager.DictionaryField):
23    adapts(PersistentDict, IField)
24    implements(IDataManager)
25provideAdapter(PersistentDictionaryField)
26
27template_factory = Environment(loader=PackageLoader(__name__))
28
29class Box(object):
30
31    ALL_BOXES_KEY = 'il.portalinterlegis.boxes'
32
33    BOX_TEMPLATE = '''
34      <div id="%s"%s>
35%s
36      </div>'''
37
38    def __init__(self, schema, number, permission=ModifyPortalContent, form_label=None):
39        self.schema = schema
40        self.number = number
41        self.permission = permission
42        #TODO: improve this text
43        self.form_label = form_label or u'Edite os valore desta caixa'
44
45    def __call__(self, context):
46        is_editable = getSecurityManager().checkPermission(self.permission, context)
47        return self.BOX_TEMPLATE % (self.key,
48                                    ' class ="editable-box"' if is_editable else '',
49                                    self.template.render(self.content(context)))
50
51    def content(self, context):
52        annotations = IAnnotations(context)
53        boxes = get_or_create_persistent_dict(annotations, self.ALL_BOXES_KEY)
54        return get_or_create_persistent_dict(boxes, self.key)
55
56    @property
57    def template(self):
58        return template_factory.get_template(
59            self.schema.__name__.lower() + '.html')
60
61    @property
62    def key(self):
63        return '%s_%s' % (self.schema.__name__, self.number)
64
65    @property
66    def form_name(self):
67        """Last part of form urls.
68        """
69        return 'box_%s' % self.key
70
71def build_box_form(box):
72
73    # the combination (form.EditForm, grok.View)
74    # is from https://mail.zope.org/pipermail/grok-dev/2008-July/005999.html
75    # (plone.directives.form.EditForm did not work well)
76    class BoxEditForm(AutoExtensibleForm, form.EditForm, grok.View):
77        grok.context(IFolderish)
78        grok.name(box.form_name)
79        grok.require('cmf.ModifyPortalContent')
80
81        label = box.form_label
82        schema = box.schema
83
84        def getContent(self):
85            return box.content(self.context)
86
87        def render(self):
88            # we cannot simply associtate this template in the class level
89            # because form.EditForm has a ".render()" method and grok.View
90            # assumes you cannot have both "template = ..." and ".render()".
91            # No problem, we make a method that simply renders the template
92            template = ZopeTwoPageTemplate(filename="boxform.pt")
93            return template.render(self)
94
95    globals()['BoxEditForm_%s' % box.key] = BoxEditForm
96    return BoxEditForm
97
98def build_many_box_forms(schema, max_number):
99    for number in range(1, max_number+1):
100        build_box_form(Box(schema, number))
101
102def get_or_create_persistent_dict(dictionary, key):
103    value = dictionary.get(key, None)
104    if not value:
105        dictionary[key] = value = PersistentDict()
106    return value
107
108# ROWS
109class DtRow(object):
110
111    ROW_TEMPLATE = '''
112  <div class="dt-row">%s
113  </div>'''
114
115    CELL_TEMPLATE = '''
116    <div class="dt-cell dt-position-%s dt-width-%s">%s
117    </div>'''
118
119    def __init__(self, *row_spec):
120        try:
121            for (width, template) in row_spec: pass
122        except ValueError, e:
123            e.args += row_spec
124            raise
125        self.row_spec = row_spec
126
127    def _cells(self, context):
128        """Iterates transforming each cell spec from (width, template) to
129           (position, width, rendered_html)
130        """
131        position = 0
132        for (width, template) in self.row_spec:
133            yield (position, width, template(context))
134            position += width
135
136    def render(self, context):
137        """Renders the html of one row.
138        `row_spec` is a sequence of cell specs: [(width, schema, number), ...]
139        """
140        return self.ROW_TEMPLATE % ''.join(
141            [self.CELL_TEMPLATE % cell for cell in self._cells(context)])
142
143
144class GridView(grok.View):
145    "Base class for all grid-like views"
146    martian.baseclass()
147
148    template = ZopeTwoPageTemplate(filename="gridview.pt")
149
150    def rows(self):
151        for row in self.grid:
152            yield row.render(self.context)
153
154################################################################
155# TODO: o unico lugar em que isto funcionou foi aqui. Entender porque e decidir lugar definitivo.
156
157# initialize all the box managers
158for s in box_schemas():
159    build_many_box_forms(s, 10)
160
Note: Veja TracBrowser para ajuda no uso do navegador do trac.
 

The contents and data of this website are published under license:
Creative Commons 4.0 Brasil - Atribuir Fonte - Compartilhar Igual.