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