Commit 6fc28174 authored by Nicolas Delaby's avatar Nicolas Delaby

reindent code with 2 spaces

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@29015 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent 6c18e27f
...@@ -133,7 +133,6 @@ class Image(File, OFSImage): ...@@ -133,7 +133,6 @@ class Image(File, OFSImage):
self.width = width self.width = width
self._setContentType(content_type) self._setContentType(content_type)
def _upradeImage(self): def _upradeImage(self):
""" """
This method upgrades internal data structures is required This method upgrades internal data structures is required
...@@ -194,117 +193,117 @@ class Image(File, OFSImage): ...@@ -194,117 +193,117 @@ class Image(File, OFSImage):
def tag(self, display=None, height=None, width=None, cookie=0, def tag(self, display=None, height=None, width=None, cookie=0,
alt=None, css_class=None, format='', quality=75, alt=None, css_class=None, format='', quality=75,
resolution=None, frame=None, **kw): resolution=None, frame=None, **kw):
"""Return HTML img tag.""" """Return HTML img tag."""
self._upradeImage() self._upradeImage()
# Get cookie if display is not specified.
if display is None:
display = self.REQUEST.cookies.get('display', None)
# display may be set from a cookie.
image_size = self.getSizeFromImageDisplay(display)
if (display is not None or resolution is not None or quality!=75 or format != ''\
or frame is not None) and image_size:
try:
mime, image = self.getConversion(display=display, format=format,
quality=quality, resolution=resolution,
frame=frame, image_size=image_size)
except KeyError:
# Generate photo on-the-fly
mime, image = self._makeDisplayPhoto(display, format=format, quality=quality,
resolution=resolution, frame=frame,
image_size=image_size)
self.setConversion(image, mime, display=display, format=format,
quality=quality, resolution=resolution,
frame=frame, image_size=image_size)
width, height = (image.width, image.height)
# Set cookie for chosen size
if cookie:
self.REQUEST.RESPONSE.setCookie('display', display, path="/")
else:
# TODO: Add support for on-the-fly resize?
height = self.getHeight()
width = self.getWidth()
if display: # Get cookie if display is not specified.
result = '<img src="%s?display=%s"' % (self.absolute_url(), display) if display is None:
else: display = self.REQUEST.cookies.get('display', None)
result = '<img src="%s"' % (self.absolute_url())
if alt is None: # display may be set from a cookie.
alt = getattr(self, 'title', '') image_size = self.getSizeFromImageDisplay(display)
if alt == '': if (display is not None or resolution is not None or quality!=75 or format != ''\
alt = self.getId() or frame is not None) and image_size:
result = '%s alt="%s"' % (result, html_quote(alt)) try:
mime, image = self.getConversion(display=display, format=format,
quality=quality, resolution=resolution,
frame=frame, image_size=image_size)
except KeyError:
# Generate photo on-the-fly
mime, image = self._makeDisplayPhoto(display, format=format, quality=quality,
resolution=resolution, frame=frame,
image_size=image_size)
self.setConversion(image, mime, display=display, format=format,
quality=quality, resolution=resolution,
frame=frame, image_size=image_size)
width, height = (image.width, image.height)
# Set cookie for chosen size
if cookie:
self.REQUEST.RESPONSE.setCookie('display', display, path="/")
else:
# TODO: Add support for on-the-fly resize?
height = self.getHeight()
width = self.getWidth()
if display:
result = '<img src="%s?display=%s"' % (self.absolute_url(), display)
else:
result = '<img src="%s"' % (self.absolute_url())
if height: if alt is None:
result = '%s height="%s"' % (result, height) alt = getattr(self, 'title', '')
if alt == '':
alt = self.getId()
result = '%s alt="%s"' % (result, html_quote(alt))
if width: if height:
result = '%s width="%s"' % (result, width) result = '%s height="%s"' % (result, height)
if not 'border' in map(string.lower, kw.keys()): if width:
result = '%s border="0"' % (result) result = '%s width="%s"' % (result, width)
if css_class is not None: if not 'border' in map(string.lower, kw.keys()):
result = '%s class="%s"' % (result, css_class) result = '%s border="0"' % (result)
for key in kw.keys(): if css_class is not None:
value = kw.get(key) result = '%s class="%s"' % (result, css_class)
result = '%s %s="%s"' % (result, key, value)
result = '%s />' % (result) for key in kw.keys():
value = kw.get(key)
result = '%s %s="%s"' % (result, key, value)
return result result = '%s />' % (result)
return result
def __str__(self): def __str__(self):
return self.tag() return self.tag()
security.declareProtected('Access contents information', 'displayIds') security.declareProtected('Access contents information', 'displayIds')
def displayIds(self, exclude=('thumbnail',)): def displayIds(self, exclude=('thumbnail',)):
"""Return list of display Ids.""" """Return list of display Ids."""
id_list = list(default_displays_id_list) id_list = list(default_displays_id_list)
# Exclude specified displays # Exclude specified displays
if exclude: if exclude:
for id in exclude: for id in exclude:
if id in id_list: if id in id_list:
id_list.remove(id) id_list.remove(id)
# Sort by desired photo surface area # Sort by desired photo surface area
def getSurfaceArea(img): def getSurfaceArea(img):
x, y = self.getSizeFromImageDisplay(img) x, y = self.getSizeFromImageDisplay(img)
return x * y return x * y
id_list.sort(key=getSurfaceArea) id_list.sort(key=getSurfaceArea)
return id_list return id_list
security.declareProtected('Access contents information', 'displayLinks') security.declareProtected('Access contents information', 'displayLinks')
def displayLinks(self, exclude=('thumbnail',)): def displayLinks(self, exclude=('thumbnail',)):
"""Return list of HTML <a> tags for displays.""" """Return list of HTML <a> tags for displays."""
links = [] links = []
for display in self.displayIds(exclude): for display in self.displayIds(exclude):
links.append('<a href="%s?display=%s">%s</a>' % (self.REQUEST['URL'], display, display)) links.append('<a href="%s?display=%s">%s</a>' % (self.REQUEST['URL'], display, display))
return links return links
security.declareProtected('Access contents information', 'displayMap') security.declareProtected('Access contents information', 'displayMap')
def displayMap(self, exclude=None, format='', quality=75, resolution=None): def displayMap(self, exclude=None, format='', quality=75, resolution=None):
"""Return list of displays with size info.""" """Return list of displays with size info."""
displays = [] displays = []
for id in self.displayIds(exclude): for id in self.displayIds(exclude):
if self._isGenerated(id, format=format, quality=quality, resolution=resolution): if self._isGenerated(id, format=format, quality=quality, resolution=resolution):
photo_width = self._photos[(id,format)].width photo_width = self._photos[(id,format)].width
photo_height = self._photos[(id,format)].height photo_height = self._photos[(id,format)].height
bytes = self._photos[(id,format)]._size() bytes = self._photos[(id,format)]._size()
age = self._photos[(id,format)]._age() age = self._photos[(id,format)]._age()
else: else:
(photo_width, photo_height, bytes, age) = (None, None, None, None) (photo_width, photo_height, bytes, age) = (None, None, None, None)
displays.append({'id': id, displays.append({'id': id,
'width': self.getSizeFromImageDisplay(id)[0], 'width': self.getSizeFromImageDisplay(id)[0],
'height': self.getSizeFromImageDisplay(id)[1], 'height': self.getSizeFromImageDisplay(id)[1],
'photo_width': photo_width, 'photo_width': photo_width,
'photo_height': photo_height, 'photo_height': photo_height,
'bytes': bytes, 'bytes': bytes,
'age': age 'age': age
}) })
return displays return displays
security.declarePrivate('_convertToText') security.declarePrivate('_convertToText')
...@@ -324,10 +323,10 @@ class Image(File, OFSImage): ...@@ -324,10 +323,10 @@ class Image(File, OFSImage):
filename=self.getTitleOrId(), filename=self.getTitleOrId(),
mimetype=src_mimetype) mimetype=src_mimetype)
if result is None: if result is None:
# portal_transforms fails to convert. # portal_transforms fails to convert.
LOG('TextDocument.convert', WARNING, LOG('TextDocument.convert', WARNING,
'portal_transforms failed to convert to %s: %r' % (mime_type, self)) 'portal_transforms failed to convert to %s: %r' % (mime_type, self))
result = '' result = ''
return mime_type, result return mime_type, result
else: else:
# text_content is not set, return empty string instead of None # text_content is not set, return empty string instead of None
...@@ -379,30 +378,30 @@ class Image(File, OFSImage): ...@@ -379,30 +378,30 @@ class Image(File, OFSImage):
security.declareProtected('View', 'index_html') security.declareProtected('View', 'index_html')
def index_html(self, REQUEST, RESPONSE, display=None, format='', quality=75, def index_html(self, REQUEST, RESPONSE, display=None, format='', quality=75,
resolution=None, frame=None): resolution=None, frame=None):
"""Return the image data.""" """Return the image data."""
self._upradeImage() self._upradeImage()
_setCacheHeaders(_ViewEmulator().__of__(self), dict(display=display, _setCacheHeaders(_ViewEmulator().__of__(self), dict(display=display,
format=format, quality=quality, resolution=resolution, frame=frame)) format=format, quality=quality, resolution=resolution, frame=frame))
# display may be set from a cookie (?) # display may be set from a cookie (?)
image_size = self.getSizeFromImageDisplay(display) image_size = self.getSizeFromImageDisplay(display)
if (display is not None or resolution is not None or quality != 75 or format != ''\ if (display is not None or resolution is not None or quality != 75 or format != ''\
or frame is not None) and image_size: or frame is not None) and image_size:
try: try:
mime, image = self.getConversion(display=display, format=format, mime, image = self.getConversion(display=display, format=format,
quality=quality, resolution=resolution, quality=quality, resolution=resolution,
frame=frame, image_size=image_size) frame=frame, image_size=image_size)
except KeyError: except KeyError:
# Generate photo on-the-fly # Generate photo on-the-fly
mime, image = self._makeDisplayPhoto(display, format=format, quality=quality, mime, image = self._makeDisplayPhoto(display, format=format, quality=quality,
resolution=resolution, frame=frame, resolution=resolution, frame=frame,
image_size=image_size) image_size=image_size)
RESPONSE.setHeader('Content-Type', mime) RESPONSE.setHeader('Content-Type', mime)
return image.index_html(REQUEST, RESPONSE) return image.index_html(REQUEST, RESPONSE)
# Return original image # Return original image
return OFSImage.index_html(self, REQUEST, RESPONSE) return OFSImage.index_html(self, REQUEST, RESPONSE)
# #
...@@ -411,114 +410,114 @@ class Image(File, OFSImage): ...@@ -411,114 +410,114 @@ class Image(File, OFSImage):
def _resize(self, display, width, height, quality=75, format='', def _resize(self, display, width, height, quality=75, format='',
resolution=None, frame=None): resolution=None, frame=None):
"""Resize and resample photo.""" """Resize and resample photo."""
newimg = StringIO() newimg = StringIO()
parameter_list = ['convert'] parameter_list = ['convert']
parameter_list.extend(['-colorspace', 'RGB']) parameter_list.extend(['-colorspace', 'RGB'])
if resolution: if resolution:
parameter_list.extend(['-density', '%sx%s' % (resolution, resolution)]) parameter_list.extend(['-density', '%sx%s' % (resolution, resolution)])
parameter_list.extend(['-quality', str(quality)]) parameter_list.extend(['-quality', str(quality)])
parameter_list.extend(['-geometry', '%sx%s' % (width, height)]) parameter_list.extend(['-geometry', '%sx%s' % (width, height)])
if frame: if frame:
parameter_list.append('-[%s]' % frame) parameter_list.append('-[%s]' % frame)
else: else:
parameter_list.append('-') parameter_list.append('-')
if format: if format:
parameter_list.append('%s:-' % format) parameter_list.append('%s:-' % format)
else:
parameter_list.append('-')
process = subprocess.Popen(parameter_list,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
imgin, imgout, err = process.stdin, process.stdout, process.stderr
def writeData(stream, data):
if isinstance(data, str):
stream.write(str(self.getData()))
else: else:
parameter_list.append('-') # Use PData structure to prevent
# consuming too much memory
process = subprocess.Popen(parameter_list, while data is not None:
stdin=subprocess.PIPE, stream.write(data.data)
stdout=subprocess.PIPE, data = data.next
stderr=subprocess.PIPE,
close_fds=True) writeData(imgin, self.getData())
imgin, imgout, err = process.stdin, process.stdout, process.stderr imgin.close()
newimg.write(imgout.read())
def writeData(stream, data): imgout.close()
if isinstance(data, str): if not newimg.tell():
stream.write(str(self.getData())) raise ConversionError('Image conversion failed (%s).' % err.read())
else: newimg.seek(0)
# Use PData structure to prevent return newimg
# consuming too much memory
while data is not None:
stream.write(data.data)
data = data.next
writeData(imgin, self.getData())
imgin.close()
newimg.write(imgout.read())
imgout.close()
if not newimg.tell():
raise ConversionError('Image conversion failed (%s).' % err.read())
newimg.seek(0)
return newimg
def _getDisplayData(self, display, format='', quality=75, resolution=None, frame=None, def _getDisplayData(self, display, format='', quality=75, resolution=None, frame=None,
image_size=None): image_size=None):
"""Return raw photo data for given display.""" """Return raw photo data for given display."""
if display is None: if display is None:
(width, height) = (self.getWidth(), self.getHeight()) (width, height) = (self.getWidth(), self.getHeight())
elif image_size is None: elif image_size is None:
(width, height) = self.getSizeFromImageDisplay(display) (width, height) = self.getSizeFromImageDisplay(display)
else: else:
(width, height) = image_size (width, height) = image_size
if width == 0 and height == 0: if width == 0 and height == 0:
width = self.getWidth() width = self.getWidth()
height = self.getHeight() height = self.getHeight()
(width, height) = self._getAspectRatioSize(width, height) (width, height) = self._getAspectRatioSize(width, height)
if (width, height) == (0, 0):return self.getData() if (width, height) == (0, 0):return self.getData()
return self._resize(display, width, height, quality, format=format, return self._resize(display, width, height, quality, format=format,
resolution=resolution, frame=frame) resolution=resolution, frame=frame)
def _getDisplayPhoto(self, display, format='', quality=75, resolution=None, frame=None, def _getDisplayPhoto(self, display, format='', quality=75, resolution=None, frame=None,
image_size=None): image_size=None):
"""Return photo object for given display.""" """Return photo object for given display."""
try: try:
base, ext = string.split(self.id, '.') base, ext = string.split(self.id, '.')
id = base + '_' + display + '.' + ext id = base + '_' + display + '.' + ext
except ValueError: except ValueError:
id = self.id +'_'+ display id = self.id +'_'+ display
image = OFSImage(id, self.getTitle(), self._getDisplayData(display, format=format, image = OFSImage(id, self.getTitle(), self._getDisplayData(display, format=format,
quality=quality, resolution=resolution, frame=frame, quality=quality, resolution=resolution, frame=frame,
image_size=image_size)) image_size=image_size))
return image return image
def _makeDisplayPhoto(self, display, format='', quality=75, resolution=None, frame=None, def _makeDisplayPhoto(self, display, format='', quality=75, resolution=None, frame=None,
image_size=None): image_size=None):
"""Create given display.""" """Create given display."""
image = self._getDisplayPhoto(display, format=format, quality=quality, image = self._getDisplayPhoto(display, format=format, quality=quality,
resolution=resolution, frame=frame, resolution=resolution, frame=frame,
image_size=image_size) image_size=image_size)
self.setConversion(image, mime=image.content_type, self.setConversion(image, mime=image.content_type,
display=display, format=format, display=display, format=format,
quality=quality, resolution=resolution, quality=quality, resolution=resolution,
frame=frame, image_size=image_size) frame=frame, image_size=image_size)
return (image.content_type, aq_base(image)) return (image.content_type, aq_base(image))
def _getAspectRatioSize(self, width, height): def _getAspectRatioSize(self, width, height):
"""Return proportional dimensions within desired size.""" """Return proportional dimensions within desired size."""
img_width, img_height = (self.getWidth(), self.getHeight()) img_width, img_height = (self.getWidth(), self.getHeight())
if img_width == 0: if img_width == 0:
return (0, 0) return (0, 0)
#XXX This is a temporary dirty fix!!! #XXX This is a temporary dirty fix!!!
width = int(width) width = int(width)
height = int(height) height = int(height)
img_width = int(img_width) img_width = int(img_width)
img_height = int(img_height) img_height = int(img_height)
if height > img_height * width / img_width: if height > img_height * width / img_width:
height = img_height * width / img_width height = img_height * width / img_width
else: else:
width = img_width * height / img_height width = img_width * height / img_height
return (width, height) return (width, height)
def _validImage(self): def _validImage(self):
"""At least see if it *might* be valid.""" """At least see if it *might* be valid."""
return self.getWidth() and self.getHeight() and self.getData() and self.getContentType() return self.getWidth() and self.getHeight() and self.getData() and self.getContentType()
security.declareProtected('View', 'getSizeFromImageDisplay') security.declareProtected('View', 'getSizeFromImageDisplay')
def getSizeFromImageDisplay(self, image_display): def getSizeFromImageDisplay(self, image_display):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment