655f1eccdc62be2c0d8a6bc8e7bcda7bef9fe91c
[wolnelektury.git] / apps / catalogue / forms.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 forms
6 from django.utils.translation import ugettext_lazy as _
7 from slughifi import slughifi
8
9 from catalogue.models import Tag, Book
10 from catalogue.fields import JQueryAutoCompleteSearchField
11 from catalogue import utils
12
13
14 class BookImportForm(forms.Form):
15     book_xml_file = forms.FileField(required=False)
16     book_xml = forms.CharField(required=False)
17
18     def clean(self):
19         from django.core.files.base import ContentFile
20
21         if not self.cleaned_data['book_xml_file']:
22             if self.cleaned_data['book_xml']:
23                 self.cleaned_data['book_xml_file'] = \
24                         ContentFile(self.cleaned_data['book_xml'].encode('utf-8'))
25             else:
26                 raise forms.ValidationError(_("Please supply an XML."))
27         return super(BookImportForm, self).clean()
28
29     def save(self, commit=True, **kwargs):
30         return Book.from_xml_file(self.cleaned_data['book_xml_file'], overwrite=True, **kwargs)
31
32
33 class SearchForm(forms.Form):
34     q = JQueryAutoCompleteSearchField()  # {'minChars': 2, 'selectFirst': True, 'cacheLength': 50, 'matchContains': "word"})
35
36     def __init__(self, source, *args, **kwargs):
37         kwargs['auto_id'] = False
38         super(SearchForm, self).__init__(*args, **kwargs)
39         self.fields['q'].widget.attrs['id'] = _('search')
40         self.fields['q'].widget.attrs['autocomplete'] = _('off')
41         self.fields['q'].widget.attrs['data-source'] = _(source)
42         if not 'q' in self.data:
43             self.fields['q'].widget.attrs['title'] = _('title, author, theme/topic, epoch, kind, genre, phrase')
44
45
46 class UserSetsForm(forms.Form):
47     def __init__(self, book, user, *args, **kwargs):
48         super(UserSetsForm, self).__init__(*args, **kwargs)
49         self.fields['set_ids'] = forms.ChoiceField(
50             choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user)],
51         )
52
53
54 class ObjectSetsForm(forms.Form):
55     def __init__(self, obj, user, *args, **kwargs):
56         super(ObjectSetsForm, self).__init__(*args, **kwargs)
57         self.fields['set_ids'] = forms.MultipleChoiceField(
58             label=_('Shelves'),
59             required=False,
60             choices=[(tag.id, "%s (%s)" % (tag.name, tag.book_count)) for tag in Tag.objects.filter(category='set', user=user)],
61             initial=[tag.id for tag in obj.tags.filter(category='set', user=user)],
62             widget=forms.CheckboxSelectMultiple
63         )
64
65
66 class NewSetForm(forms.Form):
67     name = forms.CharField(max_length=50, required=True)
68
69     def __init__(self, *args, **kwargs):
70         super(NewSetForm, self).__init__(*args, **kwargs)
71         self.fields['name'].widget.attrs['title'] = _('Name of the new shelf')
72
73     def save(self, user, commit=True):
74         name = self.cleaned_data['name']
75         new_set = Tag(name=name, slug=utils.get_random_hash(name), sort_key=name.lower(),
76             category='set', user=user)
77
78         new_set.save()
79         return new_set
80
81
82 FORMATS = [(f, f.upper()) for f in Book.ebook_formats]
83
84
85 class DownloadFormatsForm(forms.Form):
86     formats = forms.MultipleChoiceField(required=False, choices=FORMATS,
87             widget=forms.CheckboxSelectMultiple)
88
89     def __init__(self, *args, **kwargs):
90          super(DownloadFormatsForm, self).__init__(*args, **kwargs)
91
92
93 PDF_PAGE_SIZES = (
94     ('a4paper', _('A4')),
95     ('a5paper', _('A5')),
96 )
97
98
99 PDF_LEADINGS = (
100     ('', _('Normal leading')),
101     ('onehalfleading', _('One and a half leading')),
102     ('doubleleading', _('Double leading')),
103     )
104
105 PDF_FONT_SIZES = (
106     ('11pt', _('Default')),
107     ('13pt', _('Big'))
108     )
109
110
111 class CustomPDFForm(forms.Form):
112     nofootnotes = forms.BooleanField(required=False, label=_("Don't show footnotes"))
113     nothemes = forms.BooleanField(required=False, label=_("Don't disply themes"))
114     nowlfont = forms.BooleanField(required=False, label=_("Don't use our custom font"))
115     ##    pagesize = forms.ChoiceField(PDF_PAGE_SIZES, required=True, label=_("Paper size"))
116     leading = forms.ChoiceField(PDF_LEADINGS, required=False, label=_("Leading"))
117     fontsize = forms.ChoiceField(PDF_FONT_SIZES, required=True, label=_("Font size"))
118
119     @property
120     def customizations(self):
121         c = []
122         if self.cleaned_data['nofootnotes']:
123             c.append('nofootnotes')
124             
125         if self.cleaned_data['nothemes']:
126             c.append('nothemes')
127             
128         if self.cleaned_data['nowlfont']:
129             c.append('nowlfont')
130         
131             ##  c.append(self.cleaned_data['pagesize'])
132         c.append(self.cleaned_data['fontsize'])
133
134         if self.cleaned_data['leading']:
135             c.append(self.cleaned_data['leading'])
136
137         c.sort()
138
139         return c
140