merge wyszukiwania.
[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('/newsearch/hint/') # {'minChars': 2, 'selectFirst': True, 'cacheLength': 50, 'matchContains': "word"})
35     tags = forms.CharField(widget=forms.HiddenInput, required=False)
36
37     book = forms.IntegerField(widget=forms.HiddenInput, min_value=0, required=False)
38
39     def __init__(self, *args, **kwargs):
40         tags = kwargs.pop('tags', [])
41         book = kwargs.pop('book', None)
42         super(SearchForm, self).__init__(*args, **kwargs)
43         self.fields['q'].widget.attrs['title'] = _('title, author, theme/topic, epoch, kind, genre, phrase')
44             #self.fields['q'].widget.attrs['style'] = ''
45         self.fields['tags'].initial = '/'.join(tag.url_chunk for tag in Tag.get_tag_list(tags))
46         if book is not None:
47             self.fields['book'].initial = book.id
48
49
50 class UserSetsForm(forms.Form):
51     def __init__(self, book, user, *args, **kwargs):
52         super(UserSetsForm, self).__init__(*args, **kwargs)
53         self.fields['set_ids'] = forms.ChoiceField(
54             choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user)],
55         )
56
57
58 class ObjectSetsForm(forms.Form):
59     def __init__(self, obj, user, *args, **kwargs):
60         super(ObjectSetsForm, self).__init__(*args, **kwargs)
61         self.fields['set_ids'] = forms.MultipleChoiceField(
62             label=_('Shelves'),
63             required=False,
64             choices=[(tag.id, "%s (%s)" % (tag.name, tag.book_count)) for tag in Tag.objects.filter(category='set', user=user)],
65             initial=[tag.id for tag in obj.tags.filter(category='set', user=user)],
66             widget=forms.CheckboxSelectMultiple
67         )
68
69
70 class NewSetForm(forms.Form):
71     name = forms.CharField(max_length=50, required=True)
72
73     def __init__(self, *args, **kwargs):
74         super(NewSetForm, self).__init__(*args, **kwargs)
75         self.fields['name'].widget.attrs['title'] = _('Name of the new shelf')
76
77     def save(self, user, commit=True):
78         name = self.cleaned_data['name']
79         new_set = Tag(name=name, slug=utils.get_random_hash(name), sort_key=name.lower(),
80             category='set', user=user)
81
82         new_set.save()
83         return new_set
84
85
86 FORMATS = [(f, f.upper()) for f in Book.ebook_formats]
87
88
89 class DownloadFormatsForm(forms.Form):
90     formats = forms.MultipleChoiceField(required=False, choices=FORMATS,
91             widget=forms.CheckboxSelectMultiple)
92
93     def __init__(self, *args, **kwargs):
94          super(DownloadFormatsForm, self).__init__(*args, **kwargs)
95
96
97 PDF_PAGE_SIZES = (
98     ('a4paper', _('A4')),
99     ('a5paper', _('A5')),
100 )
101
102
103 PDF_LEADINGS = (
104     ('', _('Normal leading')),
105     ('onehalfleading', _('One and a half leading')),
106     ('doubleleading', _('Double leading')),
107     )
108
109 PDF_FONT_SIZES = (
110     ('11pt', _('Default')),
111     ('13pt', _('Big'))
112     )
113
114
115 class CustomPDFForm(forms.Form):
116     nofootnotes = forms.BooleanField(required=False, label=_("Don't show footnotes"))
117     nothemes = forms.BooleanField(required=False, label=_("Don't disply themes"))
118     nowlfont = forms.BooleanField(required=False, label=_("Don't use our custom font"))
119     ##    pagesize = forms.ChoiceField(PDF_PAGE_SIZES, required=True, label=_("Paper size"))
120     leading = forms.ChoiceField(PDF_LEADINGS, required=False, label=_("Leading"))
121     fontsize = forms.ChoiceField(PDF_FONT_SIZES, required=True, label=_("Font size"))
122
123     @property
124     def customizations(self):
125         c = []
126         if self.cleaned_data['nofootnotes']:
127             c.append('nofootnotes')
128             
129         if self.cleaned_data['nothemes']:
130             c.append('nothemes')
131             
132         if self.cleaned_data['nowlfont']:
133             c.append('nowlfont')
134         
135             ##  c.append(self.cleaned_data['pagesize'])
136         c.append(self.cleaned_data['fontsize'])
137
138         if self.cleaned_data['leading']:
139             c.append(self.cleaned_data['leading'])
140
141         c.sort()
142
143         return c
144