de77a60d7320c993644ae6a958220a9d6097c9f3
[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/arrow_left.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, image_map):
153         if self.box_width != 0:
154             return self._wrapped_lines(image_map)
155         else:
156             return self.text.splitlines()
157
158     def _prepare_glyph(self, image_map, glyph, current_words, lines):
159         size = self.font.size(' '.join(current_words[:-1] + ['']))
160         x = size[0] * EIGHT_BIT_SCALE + self.padding
161         y = size[1] * lines * EIGHT_BIT_SCALE + self.padding
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             image_map[(x, y)] = image
169             x += image.get_width()
170
171     def _check_markup(self, word):
172         suffix = ''
173         if word[-1] in '.,':
174             suffix = word[-1]
175             word = word[:-1]
176
177         if not word:
178             return None
179         if word[0] == '{' and word[-1] == '}':
180             subwords = word[1:-1].split(',')
181             if all(subword in MARKUP_MAP for subword in subwords):
182                 return Glyph(word + suffix, subwords, suffix)
183
184         return None
185
186     def _wrapped_lines(self, image_map):
187         def words_fit(words):
188             words_line = ' '.join(words)
189             width = self.font.size(words_line)[0] * EIGHT_BIT_SCALE
190             if width < self.box_width:
191                 return True
192             elif len(words) == 1:
193                 Exception("Word %r too long for box." % (words[0],))
194             return False
195
196         line_count = 0
197         for line in self.text.splitlines():
198             line = line.strip()
199             if not line:
200                 line_count += 1
201                 yield line
202                 continue
203             current_words = []
204             remaining_words = line.split()
205             while remaining_words:
206                 word = remaining_words.pop(0)
207                 glyph = self._check_markup(word)
208                 if glyph is not None:
209                     word = glyph.text
210                 current_words.append(word)
211                 if words_fit(current_words):
212                     if glyph is not None:
213                         self._prepare_glyph(
214                             image_map, glyph, current_words, line_count)
215                 else:
216                     line_count += 1
217                     yield ' '.join(current_words[:-1])
218                     current_words = []
219                     if glyph is not None:
220                         word = glyph.markup_text
221                     remaining_words.insert(0, word)
222             if current_words and words_fit(current_words):
223                 line_count += 1
224                 yield ' '.join(current_words)
225
226     def prepare(self):
227         self.font = resources.get_font(self.fontname, self.fontsize)
228         image_map = {}
229         rendered_lines = []
230         width, height = self.padding * 2, self.padding * 2
231         for line in self.lines(image_map):
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
238         if self.full_width:
239             width = max(width, self.box_width)
240
241         self.surface = pygame.surface.Surface((width, height),
242                                               pygame.locals.SRCALPHA)
243         self.surface.fill(self.bg_colour)
244         self.update_size()
245
246         x, y = self.padding, self.padding
247         for line_surface in rendered_lines:
248             if self.centre:
249                 x = (width - line_surface.get_rect().width) / 2
250                 x += self.padding
251             self.surface.blit(line_surface, (x, y))
252             y += line_surface.get_rect().height
253         for pos, img in image_map.items():
254             self.surface.blit(img, pos)
255
256         self.render_border(self.surface)