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