[Zope] dtml-tree question
Hugo Ramos
Hugo Ramos" <hugo@zopers.org
Wed, 30 Aug 2000 00:55:24 +0100
This is a multi-part message in MIME format.
------=_NextPart_000_0059_01C0121C.FB3172C0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
----- Original Message -----
From: "Dieter Maurer" <dieter@handshake.de>
To: "Hugo Ramos" <hugo@zopers.org>
Cc: "ZOPE" <zope@zope.org>; "EUROZOPE" <eurozope@comlounge.net>
Sent: Tuesday, August 29, 2000 10:22 PM
Subject: Re: [Zope] dtml-tree question
> Hugo Ramos writes:
> > Is there a way to use my own self made '+' icon in a tree tag?
> > I'dd like to use my own icon only IF i want to... and not change the
python
> > source to use my own icon all the time!
> The code is partially there, but incomplete and commented out.
>
> If you do not mind other extensions as well, I could provide
> a TreeTag patch for several extensions, including the
> icon customization.
hello Dieter,
I've tryied to hack the treetag source already... but there's some kind of
bug in it:
line 566 (original source):
s.append([id,[]])
Why is this trying to append to 's' when 's' has become a tupple somewhere
before this line???... tupples don't accept append!!
This bug is really making me crazy... because it makes an error when
clicking the + icon in a dtml-tree that I must use...
Another thing:
I hacked the source of treetag.py to accept 2 more parameters in the
dtml-tree... icon_mi and icon_pl
The hacked source is in the attach.
Changes go from line 411-427. Of course i defined the 2 new parameters as
None in the file top.
Please somebody help me... I'm running out of ideias...
regards
=====
Hugo Ramos - hugo@zopers.org
ZopersORG - http://www.zopers.org
=====
Do not meddle in the affairs of programmers, for they are easy to annoy,
and have all the source code!!!
------=_NextPart_000_0059_01C0121C.FB3172C0
Content-Type: text/plain;
name="TreeTag.py"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="TreeTag.py"
#########################################################################=
#####
#=20
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#=20
# Copyright (c) Digital Creations. All rights reserved.
#=20
# This license has been certified as Open Source(tm).
#=20
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#=20
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#=20
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#=20
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#=20
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#=20
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#=20
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#=20
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#=20
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#=20
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#=20
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#=20
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#=20
#=20
# Disclaimer
#=20
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#=20
#=20
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#=20
#########################################################################=
#####
"""Rendering object hierarchies as Trees
"""
__rcs_id__=3D'$Id: TreeTag.py,v 1.43 2000/08/23 20:51:25 brian Exp $'
__version__=3D'$Revision: 1.43 $'[11:-2]
import types
from DocumentTemplate.DT_Util import *
from DocumentTemplate.DT_String import String
from string import join, split, rfind, find, translate
from urllib import quote, unquote
from zlib import compress, decompress
from binascii import b2a_base64, a2b_base64
tbl=3Djoin(map(chr, range(256)),'')
tplus=3Dtbl[:ord('+')]+'-'+tbl[ord('+')+1:]
tminus=3Dtbl[:ord('-')]+'+'+tbl[ord('-')+1:]
class Tree:
name=3D'tree'
blockContinuations=3D()
expand=3DNone
def __init__(self, blocks):
tname, args, section =3D blocks[0]
args=3Dparse_params(args, name=3DNone, expr=3DNone, nowrap=3D1,=20
expand=3DNone, leaves=3DNone,
header=3DNone, footer=3DNone,
branches=3DNone, branches_expr=3DNone,
sort=3DNone, reverse=3D1, =
skip_unauthorized=3D1,
id=3DNone, single=3D1, url=3DNone, =
icon_mi=3DNone, icon_pl=3DNone,
# opened_decoration=3DNone,
# closed_decoration=3DNone,
# childless_decoration=3DNone,
assume_children=3D1,
urlparam=3DNone)
has_key=3Dargs.has_key
if has_key('') or has_key('name') or has_key('expr'):
name,expr=3Dname_param(args,'tree',1)
if expr is not None: args['expr']=3Dexpr
elif has_key(''): args['name']=3Dname
else: name=3D'a tree tag'
if has_key('branches_expr'):
if has_key('branches'):
raise ParseError, _tm(
'branches and and branches_expr given', 'tree')
args['branches_expr']=3DVSEval.Eval(
args['branches_expr'], expr_globals).eval
elif not has_key('branches'): args['branches']=3D'tpValues'
if not has_key('id'): args['id']=3D'tpId'
if not has_key('url'): args['url']=3D'tpURL'
if not has_key('childless_decoration'):
args['childless_decoration']=3D''
=20
self.__name__ =3D name
self.section=3Dsection.blocks
self.args=3Dargs
=20
def render(self,md):
args=3Dself.args
have=3Dargs.has_key
if have('name'): v=3Dmd[args['name']]
elif have('expr'): v=3Dargs['expr'].eval(md)
else: v=3Dmd.this
return tpRender(v,md,self.section, self.args)
__call__=3Drender
String.commands['tree']=3DTree
pyid=3Did # Copy builtin
def tpRender(self, md, section, args,
simple_type=3D{type(''):0, type(1):0, =
type(1.0):0}.has_key):
"""Render data organized as a tree.
We keep track of open nodes using a cookie. The cookie stored the
tree state. State should be a tree represented like:
[] # all closed
['eagle'], # eagle is open
['eagle'], ['jeep', [1983, 1985]] # eagle, jeep, 1983 jeep and =
1985 jeep
where the items are object ids. The state will be converted to a
compressed and base64ed string that gets unencoded, uncompressed,=20
and evaluated on the other side.
Note that ids used in state need not be connected to urls, since
state manipulation is internal to rendering logic.
Note that to make eval safe, we do not allow the character '*' in
the state.
"""
data=3D[]
idattr=3Dargs['id']
if hasattr(self, idattr):
id=3Dgetattr(self, idattr)
if not simple_type(type(id)): id=3Did() =20
elif hasattr(self, '_p_oid'): id=3Doid(self)
else: id=3Dpyid(self)
try:
# see if we are being run as a sub-document
root=3Dmd['tree-root-url']
url=3Dmd['tree-item-url']
state=3Dmd['tree-state']
diff=3Dmd['tree-diff']
substate=3Dmd['-tree-substate-']
colspan=3Dmd['tree-colspan'] =20
level=3Dmd['tree-level']
except KeyError:
# OK, we are a top-level invocation
level=3D-1
if md.has_key('collapse_all'):
state=3D[id,[]],
elif md.has_key('expand_all'):
have_arg=3Dargs.has_key
if have_arg('branches'):
def get_items(node, branches=3Dargs['branches'], =
md=3Dmd):
validate=3Dmd.validate
if validate is None or not hasattr(node, =
'aq_acquire'):
items=3Dgetattr(node, branches)
else:
items=3Dnode.aq_acquire(branches, validate, md)
return items()
elif have_arg('branches_expr'):
def get_items(node, =
branches_expr=3Dargs['branches_expr'], md=3Dmd):
md._push(InstanceDict(node, md))
items=3Dbranches_expr(md)
md._pop()
return items
state=3D[id, tpValuesIds(self, get_items, args)],
else:
if md.has_key('tree-s'):
state=3Dmd['tree-s']
state=3Ddecode_seq(state)
try:
if state[0][0] !=3D id: state=3D[id,[]],
except IndexError: state=3D[id,[]],
else: state=3D[id,[]],
if md.has_key('tree-e'):
diff=3Ddecode_seq(md['tree-e'])
apply_diff(state, diff, 1)
if md.has_key('tree-c'):
diff=3Ddecode_seq(md['tree-c'])
apply_diff(state, diff, 0)
colspan=3DtpStateLevel(state)
substate=3Dstate
diff=3D[]
url=3D''
root=3Dmd['URL']
l=3Drfind(root,'/')
if l >=3D 0: root=3Droot[l+1:]
treeData=3D{'tree-root-url': root,
'tree-colspan': colspan,
'tree-state': state }
=20
md._push(InstanceDict(self, md))
md._push(treeData)
try: =
tpRenderTABLE(self,id,root,url,state,substate,diff,data,colspan,
section,md,treeData, level, args)
finally: md._pop(2)
if state is substate and not (args.has_key('single') and =
args['single']):
state=3Dstate or ([id],)
state=3Dencode_seq(state)
md['RESPONSE'].setCookie('tree-s',state)
return join(data,'')
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data,
colspan, section, md, treeData, level=3D0, =
args=3DNone,
simple_type=3D{type(''):0, type(1):0, =
type(1.0):0}.has_key,
):
"Render a tree as a table"
have_arg=3Dargs.has_key
exp=3D0
if level >=3D 0:
urlattr=3Dargs['url']
if urlattr and hasattr(self, urlattr):
tpUrl=3Dgetattr(self, urlattr)
if not simple_type(type(tpUrl)): tpUrl=3DtpUrl() =20
url =3D (url and ('%s/%s' % (url, tpUrl))) or tpUrl
root_url =3D root_url or tpUrl
treeData['tree-item-url']=3Durl
treeData['tree-level']=3Dlevel
treeData['tree-item-expanded']=3D0
idattr=3Dargs['id']
output=3Ddata.append
items=3DNone
if (have_arg('assume_children') and args['assume_children']
and substate is not state):
# We should not compute children unless we have to.
# See if we've been asked to expand our children.
for i in range(len(substate)):
sub=3Dsubstate[i]
if sub[0]=3D=3Did:
exp=3Di+1
break
if not exp: items=3D1
if items is None:
validate=3Dmd.validate
if have_arg('branches') and hasattr(self, args['branches']):
if validate is None or not hasattr(self, 'aq_acquire'):
items=3Dgetattr(self, args['branches'])
else:
items=3Dself.aq_acquire(args['branches'],validate,md)
items=3Ditems()
elif have_arg('branches_expr'):
items=3Dargs['branches_expr'](md)
if not items and have_arg('leaves'): items=3D1
if items and items !=3D 1:
if validate is not None:
unauth=3D[]
index=3D0
for i in items:
try: v=3Dvalidate(items,items,None,i,md)
except: v=3D0
if not v: unauth.append(index)
index=3Dindex+1
if unauth:
if have_arg('skip_unauthorized') and =
args['skip_unauthorized']:
items=3Dlist(items)
unauth.reverse()
for i in unauth: del items[i]
else:
raise ValidationError, unauth
if have_arg('sort'):
# Faster/less mem in-place sort
if type(items)=3D=3Dtype(()):
items=3Dlist(items)
sort=3Dargs['sort']
size=3Drange(len(items))
for i in size:
v=3Ditems[i]
k=3Dgetattr(v,sort)
try: k=3Dk()
except: pass
items[i]=3D(k,v)
items.sort()
for i in size:
items[i]=3Ditems[i][1]
if have_arg('reverse'):
items=3Dlist(items) # Copy the list
items.reverse()
diff.append(id)
_td_colspan=3D'<TD COLSPAN=3D"%s" NOWRAP></TD>'
_td_single =3D'<TD WIDTH=3D"16" NOWRAP></TD>'
sub=3DNone
if substate is state:
output('<TABLE CELLSPACING=3D"0">\n')
sub=3Dsubstate[0]
exp=3Ditems
else:
# Add prefix
output('<TR>\n')
# Add +/- icon
if items:
if level:
if level > 3: output(_td_colspan % (level-1))
elif level > 1: output(_td_single * (level-1))
output(_td_single)
output('\n')
output('<TD WIDTH=3D"16" VALIGN=3D"TOP" NOWRAP>')
for i in range(len(substate)):
sub=3Dsubstate[i]
if sub[0]=3D=3Did:
exp=3Di+1
break
####################################
# Mostly inline encode_seq for speed
s=3Dcompress(str(diff))
if len(s) > 57: s=3Dencode_str(s)
else:
s=3Db2a_base64(s)[:-1]
l=3Dfind(s,'=3D')
if l >=3D 0: s=3Ds[:l]
s=3Dtranslate(s, tplus)
####################################
script=3Dmd['SCRIPT_NAME']
# Propagate extra args through tree.
if args.has_key( 'urlparam' ):
param =3D args['urlparam']
param =3D "%s&" % param
else:
param =3D ""
if exp:
treeData['tree-item-expanded']=3D1
if args.has_key('icon_mi') and (args['icon_mi'] !=3D =
None):
output('<A NAME=3D"%s" =
HREF=3D"%s?%stree-c=3D%s#%s">'
'<IMG SRC=3D"%s%s" ALT=3D"-" =
BORDER=3D0></A>' %
(id, root_url, param, s, id, script, =
self.absolute_url() + '/' + args['icon_mi']))
else:
output('<A NAME=3D"%s" =
HREF=3D"%s?%stree-c=3D%s#%s">'
'<IMG SRC=3D"%s/p_/mi" ALT=3D"-" =
BORDER=3D0></A>' %
(id, root_url, param, s, id, script))
else:
if args.has_key('icon_pl') and (args['icon_pl'] !=3D =
None):
output('<A NAME=3D"%s" =
HREF=3D"%s?%stree-e=3D%s#%s">'
'<IMG SRC=3D"%s%s" ALT=3D"+" =
BORDER=3D0></A>' %
(id, root_url, param, s, id, script, =
self.absolute_url() + '/' + args['icon_pl']))
else:
output('<A NAME=3D"%s" =
HREF=3D"%s?%stree-e=3D%s#%s">'
'<IMG SRC=3D"%s/p_/pl" ALT=3D"+" =
BORDER=3D0></A>' %
(id, root_url, param, s, id, script))
output('</TD>\n')
else:
if level > 2: output(_td_colspan % level)
elif level > 0: output(_td_single * level)
output(_td_single)
output('\n')
=20
=20
# add item text
dataspan=3Dcolspan-level
output('<TD%s%s VALIGN=3D"TOP" ALIGN=3D"LEFT">' %
((dataspan > 1 and (' COLSPAN=3D"%s"' % dataspan) or ''),
(have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or =
''))
)
output(render_blocks(section, md))
output('</TD>\n</TR>\n')
if exp:
level=3Dlevel+1
dataspan=3Dcolspan-level
if level > 2: h=3D_td_colspan % level
elif level > 0: h=3D_td_single * level
else: h=3D''
if have_arg('header'):
doc=3Dargs['header']
if md.has_key(doc): doc=3Dmd.getitem(doc,0)
else: doc=3DNone
if doc is not None:
output(doc(
None, md,
standard_html_header=3D(
'<TR>%s<TD WIDTH=3D"16" NOWRAP></TD>'
'<TD%s VALIGN=3D"TOP">'
% (h,
(dataspan > 1 and (' COLSPAN=3D"%s"' % =
dataspan)
or ''))),
standard_html_footer=3D'</TD></TR>',
))
=20
if items=3D=3D1:
# leaves
if have_arg('leaves'):
doc=3Dargs['leaves']
if md.has_key(doc): doc=3Dmd.getitem(doc,0)
else: doc=3DNone
if doc is not None:
treeData['-tree-substate-']=3Dsub
treeData['tree-level']=3Dlevel
md._push(treeData)
try: output(doc(
None,md,
standard_html_header=3D(
'<TR>%s<TD WIDTH=3D"16" NOWRAP></TD>'
'<TD%s VALIGN=3D"TOP">'
% (h,
(dataspan > 1 and
(' COLSPAN=3D"%s"' % dataspan) or ''))),
standard_html_footer=3D'</TD></TR>',
))
finally: md._pop(1)
elif have_arg('expand'):
doc=3Dargs['expand']
if md.has_key(doc): doc=3Dmd.getitem(doc,0)
else: doc=3DNone
if doc is not None:
treeData['-tree-substate-']=3Dsub
treeData['tree-level']=3Dlevel
md._push(treeData)
try: output(doc(
None,md,
standard_html_header=3D(
'<TR>%s<TD WIDTH=3D"16" NOWRAP></TD>'
'<TD%s VALIGN=3D"TOP">'
% (h,
(dataspan > 1 and
(' COLSPAN=3D"%s"' % dataspan) or ''))),
standard_html_footer=3D'</TD></TR>',
))
finally: md._pop(1)
else:
__traceback_info__=3Dsub, args, state, substate
ids=3D{}
for item in items:
if hasattr(item, idattr):
id=3Dgetattr(item, idattr)
if not simple_type(type(id)): id=3Did()
elif hasattr(item, '_p_oid'): id=3Doid(item)
else: id=3Dpyid(item)
if len(sub)=3D=3D1: sub.append([])
substate=3Dsub[1]
ids[id]=3D1
md._push(InstanceDict(item,md))
try: data=3DtpRenderTABLE(
item,id,root_url,url,state,substate,diff,data,
colspan, section, md, treeData, level, args)
finally: md._pop()
if not sub[1]: del sub[1]
ids=3Dids.has_key
for i in range(len(substate)-1,-1):
if not ids(substate[i][0]): del substate[i]
if have_arg('footer'):
doc=3Dargs['footer']
if md.has_key(doc): doc=3Dmd.getitem(doc,0)
else: doc=3DNone
if doc is not None:
output(doc(
None, md,
standard_html_header=3D(
'<TR>%s<TD WIDTH=3D"16" NOWRAP></TD>'
'<TD%s VALIGN=3D"TOP">'
% (h,
(dataspan > 1 and (' COLSPAN=3D"%s"' % =
dataspan)
or ''))),
standard_html_footer=3D'</TD></TR>',
))
del diff[-1]
if not diff: output('</TABLE>\n')
return data
def apply_diff(state, diff, expand):
if not diff: return
s=3D[None, state]
diff.reverse()
__traceback_info__=3Ds, diff
while diff:
id=3Ddiff[-1]
del diff[-1]
if len(s)=3D=3D1: s.append([])
s=3Ds[1]
loc=3D-1
for i in range(len(s)):
if s[i][0]=3D=3Did:
loc=3Di
break
if loc >=3D 0:
if not diff and not expand:
del s[loc]
else:
s=3Ds[loc]
elif diff or expand:
s.append([id,[]])
s=3Ds[-1][1]
while diff:
id=3Ddiff[-1]
del diff[-1]
if diff or expand:
s.append([id,[]])
s=3Ds[-1][1]
def encode_seq(state):
"Convert a sequence to an encoded string"
state=3Dcompress(str(state))
l=3Dlen(state)
if l > 57:
states=3D[]
for i in range(0,l,57):
states.append(b2a_base64(state[i:i+57])[:-1])
state=3Djoin(states,'')
else: state=3Db2a_base64(state)[:-1]
l=3Dfind(state,'=3D')
if l >=3D 0: state=3Dstate[:l]
=20
state=3Dtranslate(state, tplus)
return state
def encode_str(state):
"Convert a sequence to an encoded string"
l=3Dlen(state)
if l > 57:
states=3D[]
for i in range(0,l,57):
states.append(b2a_base64(state[i:i+57])[:-1])
state=3Djoin(states,'')
else: state=3Db2a_base64(state)[:-1]
l=3Dfind(state,'=3D')
if l >=3D 0: state=3Dstate[:l]
=20
state=3Dtranslate(state, tplus)
return state
def decode_seq(state):
"Convert an encoded string to a sequence"
state=3Dtranslate(state, tminus)
l=3Dlen(state)
if l > 76:
states=3D[]
j=3D0
for i in range(l/76):
k=3Dj+76
states.append(a2b_base64(state[j:k]))
j=3Dk
if j < l:
state=3Dstate[j:]
l=3Dlen(state)
k=3Dl%4
if k: state=3Dstate+'=3D'*(4-k)
states.append(a2b_base64(state))
state=3Djoin(states,'')
else:
l=3Dlen(state)
k=3Dl%4
if k: state=3Dstate+'=3D'*(4-k)
state=3Da2b_base64(state)
state=3Ddecompress(state)
if find(state,'*') >=3D 0: raise 'Illegal State', state
try: return list(eval(state,{'__builtins__':{}}))
except: return []
=20
def tpStateLevel(state, level=3D0):
for sub in state:
if len(sub)=3D=3D2: level =3D max(level, 1+tpStateLevel(sub[1]))
else: level=3Dmax(level,1)
return level
def tpValuesIds(self, get_items, args,
simple_type=3D{type(''):0, type(1):0, =
type(1.0):0}.has_key,
):
# get_item(node) is a function that returns the subitems of node
# This should build the ids of subitems which are
# expandable (non-empty). Leaves should never be
# in the state - it will screw the colspan counting.
r=3D[]
idattr=3Dargs['id']
try:
try: items=3Dget_items(self)
except AttributeError: items=3D()
for item in items:
try:
if get_items(item):
if hasattr(item, idattr):
id=3Dgetattr(item, idattr)
if not simple_type(type(id)): id=3Did() =
=20
elif hasattr(item, '_p_oid'): id=3Doid(item)
else: id=3Dpyid(item)
e=3DtpValuesIds(item, get_items, args)
if e: id=3D[id,e]
else: id=3D[id]
r.append(id)
except: pass
except: pass
return r
def oid(self):
return b2a_base64(str(self._p_oid))[:-1]
=20
#icoSpace=3D'<IMG SRC=3D"Blank_icon" BORDER=3D"0">'
#icoPlus =3D'<IMG SRC=3D"Plus_icon" BORDER=3D"0">'
#icoMinus=3D'<IMG SRC=3D"Minus_icon" BORDER=3D"0">'
------=_NextPart_000_0059_01C0121C.FB3172C0--