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