zero negative crop values (resulting from mark overlapping frame border)
[wolnelektury.git] / apps / picture / templatetags / picture_tags.py
1 from django import template
2 from django.template import Node, Variable, Template, Context
3 from catalogue.utils import split_tags
4 from itertools import chain
5 from ..engine import CustomCroppingEngine
6 import sorl.thumbnail.default
7 import logging 
8
9 register = template.Library()
10
11 cropper = CustomCroppingEngine()
12
13 @register.inclusion_tag('picture/picture_short.html', takes_context=True)
14 def picture_short(context, picture):
15     context.update({
16         'picture': picture,
17         'main_link': picture.get_absolute_url(),
18         # 'related': picture.related_info(),
19         'request': context.get('request'),
20         'tags': split_tags(picture.tags),
21         })
22     return context
23                             
24 @register.inclusion_tag('picture/picture_wide.html', takes_context=True)
25 def picture_wide(context, picture):
26     context.update({
27         'picture': picture,
28         'main_link': picture.get_absolute_url(),
29         # 'related': picture.related_info(),
30         'request': context.get('request'),
31         'tags': split_tags(picture.tags),
32         })
33     return context
34
35
36 @register.simple_tag()
37 def area_thumbnail_url(area, geometry):
38     def to_square(coords):
39         w = coords[1][0] - coords[0][0]
40         h = coords[1][1] - coords[0][1]
41         if w == h:
42             return coords
43         elif w > h:
44             return [[coords[0][0] + w/2 - h/2, coords[0][1]],
45                     [coords[1][0] - w/2 + h/2, coords[1][1]]]
46         else:
47             return [[coords[0][0], coords[0][1] + h/2 - w/2],
48                     [coords[1][0], coords[1][1] - h/2 + w/2, ]]
49
50     # so much for sorl extensibility.                                                                                                                           # what to do about this?                                                                                                                                 
51     _engine = sorl.thumbnail.default.engine
52     sorl.thumbnail.default.engine = cropper
53     coords = to_square(area.area)
54
55     try:
56         th = sorl.thumbnail.default.backend.get_thumbnail(
57             area.picture.image_file,
58             geometry,
59             crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
60     except Exception, e:
61         logging.exception("Error creating a thumbnail for PictureArea")
62         return ''
63
64     sorl.thumbnail.default.engine = _engine
65
66     return th.url
67             
68
69                                             
70