Better menus, no default game.
[naja.git] / naja / widgets / text.py
1 import pygame
2
3 from naja.constants import FONT, FONT_SIZE, EIGHT_BIT_SCALE, PALETTE
4 from naja.resources import resources
5 from naja.resources.mutators import EIGHT_BIT, blender
6 from naja.utils import convert_colour
7 from naja.widgets.base import Widget
8
9
10 MARKUP_MAP = {
11     'NORTH': ('glyphs/arrow_up.png', None),
12     'SOUTH': ('glyphs/arrow_down.png', None),
13     'EAST': ('glyphs/arrow_right.png', None),
14     'WEST': ('glyphs/arrow_left.png', None),
15     'HEALTH': ('glyphs/health.png', PALETTE.DARK_RED),
16     'WINTOKEN': ('glyphs/win.png', PALETTE.DARK_OLIVE),
17     'KEY': ('glyphs/key.png', None),
18     'MSB': ('glyphs/msb.png', None),
19     'RED': ('glyphs/key.png', PALETTE.ORANGE),
20     'GREEN': ('glyphs/key.png', PALETTE.GREEN),
21     'BLUE': ('glyphs/key.png', PALETTE.BLUE),
22     'CLOCKWISE': ('glyphs/clockwise.png', None),
23     'ANTICLOCKWISE': ('glyphs/anticlockwise.png', None),
24
25     'HEALTH_NOCOLOUR': ('glyphs/health.png', None),
26     'WINTOKEN_NOCOLOUR': ('glyphs/win.png', None),
27 }
28
29
30 class Glyph(object):
31     def __init__(self, markup_text, glyph_keys, suffix=''):
32         self.markup_text = markup_text
33         self.glyph_keys = glyph_keys
34         self.text = ' ' * len(self.glyph_keys) + suffix
35
36
37 class TextWidget(Widget):
38
39     def __init__(self, pos, text, size=None, fontname=None, fontsize=None,
40                  colour=None, unselectable_colour=None):
41         super(TextWidget, self).__init__(pos, size)
42
43         self.text = text
44         self.fontname = fontname or FONT
45         self.fontsize = (fontsize or FONT_SIZE) // EIGHT_BIT_SCALE
46         self.colour = convert_colour(colour or PALETTE.BLACK)
47         if unselectable_colour is not None:
48             unselectable_colour = convert_colour(unselectable_colour)
49         self.unselectable_colour = unselectable_colour
50
51     def render_line(self, text):
52         colour = self.colour
53         if not self.is_selectable() and self.unselectable_colour is not None:
54             colour = self.unselectable_colour
55         text_surf = self.font.render(text, True, colour)
56         text_rect = text_surf.get_rect()
57         return pygame.transform.scale(
58             text_surf, (text_rect.width * EIGHT_BIT_SCALE,
59                         text_rect.height * EIGHT_BIT_SCALE))
60
61     def prepare(self):
62         self.font = resources.get_font(self.fontname, self.fontsize)
63         self.surface = self.render_line(self.text)
64         self.size = self.surface.get_rect().size
65
66     def draw(self, surface):
67         surface.blit(self.surface, self.pos)
68
69
70 class TextBoxWidget(TextWidget):
71     def __init__(self, *args, **kwargs):
72         self.padding = kwargs.pop('padding', 4)
73         self.border = kwargs.pop('border', 2)
74         self.bg_colour = convert_colour(kwargs.pop('bg_colour',
75                                                    PALETTE.LIGHT_VIOLET))
76         self.border_colour = convert_colour(kwargs.pop('border_colour',
77                                                        PALETTE.BLACK))
78         self.box_width = kwargs.pop('box_width', 0)
79
80         super(TextBoxWidget, self).__init__(*args, **kwargs)
81
82     def lines(self, image_map):
83         if self.box_width != 0:
84             return self._wrapped_lines(image_map)
85         else:
86             return self.text.splitlines()
87
88     def _prepare_glyph(self, image_map, glyph, current_words, lines):
89         size = self.font.size(' '.join(current_words[:-1] + ['']))
90         x = size[0] * EIGHT_BIT_SCALE + self.padding
91         y = size[1] * lines * EIGHT_BIT_SCALE + self.padding
92         for glyph_key in glyph.glyph_keys:
93             image_name, colour = MARKUP_MAP[glyph_key]
94             if colour is None:
95                 colour = self.colour
96             image = resources.get_image(
97                 image_name, transforms=(EIGHT_BIT, blender(colour)))
98             image_map[(x, y)] = image
99             x += image.get_width()
100
101     def _check_markup(self, word):
102         suffix = ''
103         if word[-1] in '.,':
104             suffix = word[-1]
105             word = word[:-1]
106
107         if word[0] == '{' and word[-1] == '}':
108             subwords = word[1:-1].split(',')
109             if all(subword in MARKUP_MAP for subword in subwords):
110                 return Glyph(word + suffix, subwords, suffix)
111
112         return None
113
114     def _wrapped_lines(self, image_map):
115         def words_fit(words):
116             words_line = ' '.join(words)
117             width = self.font.size(words_line)[0]
118             if width < self.box_width:
119                 return True
120             elif len(words) == 1:
121                 Exception("Word %r too long for box." % (words[0],))
122             return False
123
124         line_count = 0
125         for line in self.text.splitlines():
126             current_words = []
127             remaining_words = line.split()
128             while remaining_words:
129                 word = remaining_words.pop(0)
130                 glyph = self._check_markup(word)
131                 if glyph is not None:
132                     word = glyph.text
133                 current_words.append(word)
134                 if words_fit(current_words):
135                     if glyph is not None:
136                         self._prepare_glyph(
137                             image_map, glyph, current_words, line_count)
138                 else:
139                     line_count += 1
140                     yield ' '.join(current_words[:-1])
141                     current_words = []
142                     if glyph is not None:
143                         word = glyph.markup_text
144                     remaining_words.insert(0, word)
145             if current_words and words_fit(current_words):
146                 yield ' '.join(current_words)
147
148     def prepare(self):
149         self.font = resources.get_font(self.fontname, self.fontsize)
150         image_map = {}
151         rendered_lines = []
152         width, height = self.padding * 2, self.padding * 2
153         for line in self.lines(image_map):
154             line_surface = self.render_line(line)
155             line_rect = line_surface.get_rect()
156             rendered_lines.append(line_surface)
157             width = max(width, line_rect.width + self.padding * 2)
158             height += line_rect.height
159
160         self.surface = pygame.surface.Surface((width, height),
161                                               pygame.locals.SRCALPHA)
162         self.surface.fill(self.bg_colour)
163         self.size = self.surface.get_rect().size
164
165         x, y = self.padding, self.padding
166         for line_surface in rendered_lines:
167             self.surface.blit(line_surface, (x, y))
168             y += line_surface.get_rect().height
169         for pos, img in image_map.items():
170             self.surface.blit(img, pos)
171
172     def draw(self, surface):
173         surface.blit(self.surface, self.rect)