Tweak markup, add chesspiece glyphs.
[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 }
23
24
25 class Glyph(object):
26     def __init__(self, markup_text, glyph_keys, suffix=''):
27         self.markup_text = markup_text
28         self.glyph_keys = glyph_keys
29         self.text = ' ' * len(self.glyph_keys) + suffix
30
31
32 class TextWidget(Widget):
33
34     def __init__(self, pos, text, size=None, fontname=None, fontsize=None,
35                  colour=None):
36         super(TextWidget, self).__init__(pos, size)
37
38         self.text = text
39         self.fontname = fontname or FONT
40         self.fontsize = (fontsize or FONT_SIZE) // EIGHT_BIT_SCALE
41         self.colour = convert_colour(colour or PALETTE.BLACK)
42
43     def render_line(self, text):
44         text_surf = self.font.render(text, True, self.colour)
45         text_rect = text_surf.get_rect()
46         return pygame.transform.scale(
47             text_surf, (text_rect.width * EIGHT_BIT_SCALE,
48                         text_rect.height * EIGHT_BIT_SCALE))
49
50     def prepare(self):
51         self.font = resources.get_font(self.fontname, self.fontsize)
52         self.surface = self.render_line(self.text)
53         self.size = self.surface.get_rect().size
54
55     def draw(self, surface):
56         surface.blit(self.surface, self.pos)
57
58
59 class TextBoxWidget(TextWidget):
60     def __init__(self, *args, **kwargs):
61         self.padding = kwargs.pop('padding', 4)
62         self.border = kwargs.pop('border', 2)
63         self.bg_colour = convert_colour(kwargs.pop('bg_colour',
64                                                    PALETTE.LIGHT_VIOLET))
65         self.border_colour = convert_colour(kwargs.pop('border_colour',
66                                                        PALETTE.BLACK))
67         self.box_width = kwargs.pop('box_width', 0)
68
69         super(TextBoxWidget, self).__init__(*args, **kwargs)
70
71     def lines(self, image_map):
72         if self.box_width != 0:
73             return self._wrapped_lines(image_map)
74         else:
75             return self.text.splitlines()
76
77     def _prepare_glyph(self, image_map, glyph, current_words, lines):
78         size = self.font.size(' '.join(current_words[:-1] + ['']))
79         x = size[0] * EIGHT_BIT_SCALE + self.padding
80         y = size[1] * lines * EIGHT_BIT_SCALE + self.padding
81         for glyph_key in glyph.glyph_keys:
82             image_name, colour = MARKUP_MAP[glyph_key]
83             if colour is None:
84                 colour = self.colour
85             image = resources.get_image(
86                 image_name, transforms=(EIGHT_BIT, blender(colour)))
87             image_map[(x, y)] = image
88             x += image.get_width()
89
90     def _check_markup(self, word):
91         suffix = ''
92         if word[-1] in '.,':
93             suffix = word[-1]
94             word = word[:-1]
95
96         if word[0] == '{' and word[-1] == '}':
97             subwords = word[1:-1].split(',')
98             if all(subword in MARKUP_MAP for subword in subwords):
99                 return Glyph(word + suffix, subwords, suffix)
100
101         return None
102
103     def _wrapped_lines(self, image_map):
104         def words_fit(words):
105             words_line = ' '.join(words)
106             width = self.font.size(words_line)[0]
107             if width < self.box_width:
108                 return True
109             elif len(words) == 1:
110                 Exception("Word %r too long for box." % (words[0],))
111             return False
112
113         line_count = 0
114         for line in self.text.splitlines():
115             current_words = []
116             remaining_words = line.split()
117             while remaining_words:
118                 word = remaining_words.pop(0)
119                 glyph = self._check_markup(word)
120                 if glyph is not None:
121                     word = glyph.text
122                 current_words.append(word)
123                 if words_fit(current_words):
124                     if glyph is not None:
125                         self._prepare_glyph(
126                             image_map, glyph, current_words, line_count)
127                 else:
128                     line_count += 1
129                     yield ' '.join(current_words[:-1])
130                     current_words = []
131                     if glyph is not None:
132                         word = glyph.markup_text
133                     remaining_words.insert(0, word)
134             if current_words and words_fit(current_words):
135                 yield ' '.join(current_words)
136
137     def prepare(self):
138         self.font = resources.get_font(self.fontname, self.fontsize)
139         image_map = {}
140         rendered_lines = []
141         width, height = self.padding * 2, self.padding * 2
142         for line in self.lines(image_map):
143             line_surface = self.render_line(line)
144             line_rect = line_surface.get_rect()
145             rendered_lines.append(line_surface)
146             width = max(width, line_rect.width + self.padding * 2)
147             height += line_rect.height
148
149         self.surface = pygame.surface.Surface((width, height),
150                                               pygame.locals.SRCALPHA)
151         self.surface.fill(self.bg_colour)
152         self.size = self.surface.get_rect().size
153
154         x, y = self.padding, self.padding
155         for line_surface in rendered_lines:
156             self.surface.blit(line_surface, (x, y))
157             y += line_surface.get_rect().height
158         for pos, img in image_map.items():
159             self.surface.blit(img, pos)
160
161     def draw(self, surface):
162         surface.blit(self.surface, self.rect)