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