Fixes #3506: active picture links.
[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 django.core.urlresolvers import reverse
7 from catalogue.utils import split_tags
8 from ..engine import CustomCroppingEngine
9 import sorl.thumbnail.default
10 import logging
11
12 register = template.Library()
13
14 cropper = CustomCroppingEngine()
15
16 @register.inclusion_tag('picture/picture_wide.html', takes_context=True)
17 def picture_wide(context, picture):
18     context.update({
19         'picture': picture,
20         'main_link': reverse('picture_viewer', args=[picture.slug]),
21         'request': context.get('request'),
22         'tags': split_tags(picture.tags),
23         })
24     return context
25
26
27 @register.simple_tag()
28 def area_thumbnail_url(area, geometry):
29     def to_square(coords):
30         w = coords[1][0] - coords[0][0]
31         h = coords[1][1] - coords[0][1]
32         if w == h:
33             return coords
34         elif w > h:
35             return [[coords[0][0] + w/2 - h/2, coords[0][1]],
36                     [coords[1][0] - w/2 + h/2, coords[1][1]]]
37         else:
38             return [[coords[0][0], coords[0][1] + h/2 - w/2],
39                     [coords[1][0], coords[1][1] - h/2 + w/2, ]]
40
41     # so much for sorl extensibility.
42     # what to do about this?
43     _engine = sorl.thumbnail.default.engine
44     sorl.thumbnail.default.engine = cropper
45     coords = to_square(area.area)
46
47     try:
48         th = sorl.thumbnail.default.backend.get_thumbnail(
49             area.picture.image_file,
50             geometry,
51             crop="%dpx %dpx %dpx %dpx" % tuple(map(lambda d: max(0, d), tuple(coords[0] + coords[1]))))
52     except Exception, e:
53         logging.exception("Error creating a thumbnail for PictureArea")
54         return ''
55
56     sorl.thumbnail.default.engine = _engine
57
58     return th.url