Vertically centre the bits box.
[naja.git] / naja / widgets / text.py
1 import pygame
2 import pygame.locals as pgl
3
4 from naja.constants import FONT, FONT_SIZE, EIGHT_BIT_SCALE, PALETTE, KEYS
5 from naja.resources import resources
6 from naja.resources.mutators import EIGHT_BIT, R180, blender
7 from naja.utils import convert_colour
8 from naja.widgets.base import Widget
9
10
11 MARKUP_MAP = {
12     'NORTH': ('glyphs/arrow_up.png', None),
13     'SOUTH': ('glyphs/arrow_down.png', None),
14     'EAST': ('glyphs/arrow_right.png', None),
15     'WEST': ('glyphs/arrow_left.png', None),
16     'RETURN': ('glyphs/return.png', None),
17     'HEALTH': ('glyphs/health.png', PALETTE.DARK_RED),
18     'WINTOKEN': ('glyphs/win.png', PALETTE.DARK_OLIVE),
19     'KEY': ('glyphs/key.png', None),
20     'MSB': ('glyphs/msb.png', None),
21     'RED': ('glyphs/key.png', PALETTE.ORANGE),
22     'GREEN': ('glyphs/key.png', PALETTE.GREEN),
23     'BLUE': ('glyphs/key.png', PALETTE.BLUE),
24     'CLOCKWISE': ('glyphs/clockwise.png', None),
25     'ANTICLOCKWISE': ('glyphs/anticlockwise.png', None),
26     'SHIFT_LEFT': ('glyphs/shift_left.png', None),
27     'SHIFT_RIGHT': ('glyphs/shift_right.png', None),
28     'COUNTDOWN': ('glyphs/countdown_4.png', PALETTE.DARK_VIOLET),
29
30     'HEALTH_NOCOLOUR': ('glyphs/health.png', None),
31     'WINTOKEN_NOCOLOUR': ('glyphs/win.png', None),
32 }
33
34
35 class Glyph(object):
36     def __init__(self, markup_text, glyph_keys, suffix=''):
37         self.markup_text = markup_text
38         self.glyph_keys = glyph_keys
39         self.text = ' ' * len(self.glyph_keys) + suffix
40
41
42 class TextWidget(Widget):
43
44     VIEW_PORT_DY = 50
45
46     def __init__(self, pos, text, fontname=None, fontsize=None,
47                  colour=None, unselectable_colour=None, view_port=None,
48                  centre=False, border=0, border_colour=PALETTE.GREY,
49                  padding=2):
50         super(TextWidget, self).__init__(pos)
51
52         self.text = text
53         self.fontname = fontname or FONT
54         self.fontsize = (fontsize or FONT_SIZE) // EIGHT_BIT_SCALE
55         self.colour = convert_colour(colour or PALETTE.BLACK)
56         if unselectable_colour is not None:
57             unselectable_colour = convert_colour(unselectable_colour)
58         self.unselectable_colour = unselectable_colour
59         self.view_port = (
60             pygame.Rect((0, 0), view_port) if view_port is not None else None)
61         self.centre = centre
62         self.centre_pos = pos
63         self.border = border
64         self.border_colour = convert_colour(border_colour)
65         self.padding = padding
66
67     def render_line(self, text):
68         colour = self.colour
69         if not self.is_selectable() and self.unselectable_colour is not None:
70             colour = self.unselectable_colour
71         text_surf = self.font.render(text, True, colour)
72         text_rect = text_surf.get_rect()
73         return pygame.transform.scale(
74             text_surf, (text_rect.width * EIGHT_BIT_SCALE,
75                         text_rect.height * EIGHT_BIT_SCALE))
76
77     def render_border(self, surface):
78         if not self.border or not self.border_colour:
79             return
80         rect = surface.get_rect()
81         rect = rect.inflate(- self.border / 2, - self.border / 2)
82         pygame.draw.rect(surface, self.border_colour, rect, self.border)
83
84     def update_size(self):
85         if self.view_port is not None:
86             self.size = self.view_port.size
87         else:
88             self.size = self.surface.get_rect().size
89         if self.centre:
90             self.pos = (self.centre_pos[0] - self.size[0] // 2,
91                         self.centre_pos[1])
92
93     def prepare(self):
94         self.font = resources.get_font(self.fontname, self.fontsize)
95         self.surface = self.render_line(self.text)
96         self.render_border(self.surface)
97         self.update_size()
98
99     def handle_event(self, ev):
100         if self.view_port is None:
101             return super(TextWidget, self).handle_event(ev)
102         if ev.type == pgl.KEYDOWN:
103             if ev.key in KEYS.DOWN:
104                 self.view_port.move_ip(0, self.VIEW_PORT_DY)
105                 if self.view_port.bottom > self.surface.get_rect().bottom:
106                     self.view_port.bottom = self.surface.get_rect().bottom
107                 return True
108             elif ev.key in KEYS.UP:
109                 self.view_port.move_ip(0, -self.VIEW_PORT_DY)
110                 if self.view_port.top < 0:
111                     self.view_port.top = 0
112                 return True
113         return super(TextWidget, self).handle_event(ev)
114
115     def draw(self, surface):
116         if self.view_port is None:
117             rect = self.rect
118             area = None
119         else:
120             rect = self.pos
121             area = self.view_port
122         surface.blit(self.surface, rect, area)
123         if self.view_port is not None:
124             self.draw_arrows(surface)
125
126     def draw_arrows(self, surface):
127         if self.view_port.top > 0:
128             up = resources.get_image('bits', 'arrow_on.png',
129                                      transforms=(EIGHT_BIT,))
130             icon_size = up.get_rect().height
131             pos = (self.pos[0] + self.view_port.width - icon_size, self.pos[1])
132             surface.blit(up, pos)
133         if self.view_port.bottom < self.surface.get_rect().bottom:
134             down = resources.get_image('bits', 'arrow_on.png',
135                                        transforms=(R180, EIGHT_BIT))
136             icon_size = down.get_rect().height
137             pos = (self.pos[0] + self.view_port.width - icon_size,
138                    self.pos[1] + self.view_port.height - icon_size)
139             surface.blit(down, pos)
140
141
142 class TextBoxWidget(TextWidget):
143     def __init__(self, *args, **kwargs):
144         self.bg_colour = convert_colour(kwargs.pop('bg_colour',
145                                                    PALETTE.LIGHT_VIOLET))
146         self.box_width = kwargs.pop('box_width', 0)
147         self.full_width = kwargs.pop('full_width', True)
148         kwargs.setdefault('padding', 4)
149
150         super(TextBoxWidget, self).__init__(*args, **kwargs)
151
152     def lines(self):
153         if self.box_width != 0:
154             return self._wrapped_lines()
155         else:
156             return ((line, []) for line in self.text.splitlines())
157
158     def _prepare_glyph(self, glyph, current_words):
159         glyphs = []
160         size = self.font.size(' '.join(current_words[:-1] + ['']))
161         x = size[0] * EIGHT_BIT_SCALE
162         for glyph_key in glyph.glyph_keys:
163             image_name, colour = MARKUP_MAP[glyph_key]
164             if colour is None:
165                 colour = self.colour
166             image = resources.get_image(
167                 image_name, transforms=(EIGHT_BIT, blender(colour)))
168             glyphs.append(((x, 0), image))
169             x += image.get_width()
170         return glyphs
171
172     def _check_markup(self, word):
173         suffix = ''
174         if word[-1] in '.,':
175             suffix = word[-1]
176             word = word[:-1]
177
178         if not word:
179             return None
180         if word[0] == '{' and word[-1] == '}':
181             subwords = word[1:-1].split(',')
182             if all(subword in MARKUP_MAP for subword in subwords):
183                 return Glyph(word + suffix, subwords, suffix)
184
185         return None
186
187     def _wrapped_lines(self):
188         def words_fit(words):
189             words_line = ' '.join(words)
190             width = self.font.size(words_line)[0] * EIGHT_BIT_SCALE
191             if width < self.box_width:
192                 return True
193             elif len(words) == 1:
194                 Exception("Word %r too long for box." % (words[0],))
195             return False
196
197         line_count = 0
198         for line in self.text.splitlines():
199             line = line.strip()
200             if not line:
201                 line_count += 1
202                 yield (line, [])
203                 continue
204             current_words, glyphs = [], []
205             remaining_words = line.split()
206             while remaining_words:
207                 word = remaining_words.pop(0)
208                 glyph = self._check_markup(word)
209                 if glyph is not None:
210                     word = glyph.text
211                 current_words.append(word)
212                 if words_fit(current_words):
213                     if glyph is not None:
214                         glyphs.extend(self._prepare_glyph(
215                             glyph, current_words))
216                 else:
217                     line_count += 1
218                     yield (' '.join(current_words[:-1]), glyphs)
219                     current_words, glyphs = [], []
220                     if glyph is not None:
221                         word = glyph.markup_text
222                     remaining_words.insert(0, word)
223             if current_words and words_fit(current_words):
224                 line_count += 1
225                 yield (' '.join(current_words), glyphs)
226
227     def prepare(self):
228         self.font = resources.get_font(self.fontname, self.fontsize)
229         rendered_lines = []
230         width, height = self.padding * 2, self.padding * 2
231         for line, glyphs in self.lines():
232             line_surface = self.render_line(line)
233             line_rect = line_surface.get_rect()
234             rendered_lines.append(line_surface)
235             width = max(width, line_rect.width + self.padding * 2)
236             height += line_rect.height
237             for pos, img in glyphs:
238                 line_surface.blit(img, pos)
239
240         if self.full_width:
241             width = max(width, self.box_width)
242
243         self.surface = pygame.surface.Surface((width, height),
244                                               pygame.locals.SRCALPHA)
245         self.surface.fill(self.bg_colour)
246         self.update_size()
247
248         x, y = self.padding, self.padding
249         for line_surface in rendered_lines:
250             if self.centre:
251                 x = (width - line_surface.get_rect().width) / 2
252                 x += self.padding
253             self.surface.blit(line_surface, (x, y))
254             y += line_surface.get_rect().height
255
256         self.render_border(self.surface)