more meta
[librarian.git] / src / librarian / covers / widgets / title.py
1 import PIL.ImageFont
2 from librarian import get_resource
3 from librarian.cover import Metric
4 from ..utils.textbox import TextBox, split_words
5 from .base import Widget
6
7
8 class TitleBox(Widget):
9     font_size = 159 # 45pt
10     leading = 176  # 50pt
11     tracking = 2.385
12
13     def __init__(self, cover, width, height, lines, force=False):
14         self.width = width
15         self.height = height
16         self.lines = lines
17         self.force = force
18         self.m = Metric(self, cover.m._scale)
19         super().__init__(cover)
20
21     def setup(self):
22         m = self.m
23         while True:
24             try:
25                 self.build_box()
26             except:
27                 if self.force:
28                     self.m = Metric(self, self.m._scale * .99)
29                     print('lower to', self.m.font_size)
30                 else:
31                     raise
32             else:
33                 break
34
35     def build_box(self):
36         title_font = PIL.ImageFont.truetype(
37             get_resource('fonts/SourceSans3VF-Roman.ttf'),
38             self.m.font_size,
39             layout_engine=PIL.ImageFont.LAYOUT_BASIC
40         )
41         title_font.set_variation_by_axes([800])
42
43         lines = self.lines or (int(self.height * (176/200) / self.m.leading) - 0)
44         
45         self.tb = TextBox(
46             self.width,
47             self.height,
48             split_words(self.cover.title),
49             title_font,
50             lines,
51             self.m.leading,
52             self.m.tracking,
53             .5, .5
54         )
55         self.margin_top = self.tb.margin_top
56             
57     def build(self, w, h):
58         return self.tb.as_pil_image(self.cover.color_scheme['text'])
59