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