fb0c31fd507e3ba3843c7b464c7f052c4b4e566d
[naja.git] / naja / widgets / text.py
1 import pygame
2
3 from naja.constants import FONT, FONT_SIZE, EIGHT_BIT_SCALE
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': (1, 'glyphs/arrow_up.png'),
12     'SOUTH': (1, 'glyphs/arrow_down.png'),
13     'EAST': (1, 'glyphs/arrow_right.png'),
14     'WEST': (1, 'glyphs/arrow_left.png'),
15 }
16
17
18 class TextWidget(Widget):
19
20     def __init__(self, pos, text, size=None, fontname=None, fontsize=None,
21                  colour=None):
22         super(TextWidget, self).__init__(pos, size)
23
24         self.text = text
25         self.fontname = fontname or FONT
26         self.fontsize = (fontsize or FONT_SIZE) // EIGHT_BIT_SCALE
27         self.colour = convert_colour(colour or (0, 0, 0))
28
29     def render_line(self, text):
30         text_surf = self.font.render(text, True, self.colour)
31         text_rect = text_surf.get_rect()
32         return pygame.transform.scale(
33             text_surf, (text_rect.width * EIGHT_BIT_SCALE,
34                         text_rect.height * EIGHT_BIT_SCALE))
35
36     def prepare(self):
37         self.font = resources.get_font(self.fontname, self.fontsize)
38         self.surface = self.render_line(self.text)
39         self.size = self.surface.get_rect().size
40
41     def draw(self, surface):
42         surface.blit(self.surface, self.pos)
43
44
45 class TextBoxWidget(TextWidget):
46     def __init__(self, *args, **kwargs):
47         self.padding = kwargs.pop('padding', 5)
48         self.border = kwargs.pop('border', 2)
49         self.bg_colour = convert_colour(kwargs.pop('bg_colour',
50                                                    (255, 255, 255, 192)))
51         self.border_colour = convert_colour(kwargs.pop('border_colour',
52                                                        (0, 0, 0)))
53         self.box_width = kwargs.pop('box_width', 0)
54
55         super(TextBoxWidget, self).__init__(*args, **kwargs)
56
57     def lines(self, image_map):
58         if self.box_width != 0:
59             return self._wrapped_lines(image_map)
60         else:
61             return self.text.splitlines()
62
63     def _wrapped_lines(self, image_map):
64         def words_fit(words):
65             words_line = ' '.join(words)
66             width = self.font.size(words_line)[0]
67             if width < self.box_width:
68                 return True
69             elif len(words) == 1:
70                 Exception("Word %r too long for box." % (words[0],))
71             return False
72
73         line_count = 0
74         for line in self.text.splitlines():
75             current_words = []
76             for word in line.split():
77                 suffix = ''
78                 if word[-1] in '.,':
79                     suffix = word[-1]
80                     word = word[:-1]
81                 markup_data = MARKUP_MAP.get(word, None)
82                 if markup_data is not None:
83                     word = ' ' * markup_data[0]
84                 word += suffix
85                 current_words.append(word)
86                 if words_fit(current_words):
87                     if markup_data is not None:
88                         size = self.font.size(
89                             ' '.join(current_words[:-1]) + ' ')
90                         pos = (size[0] * EIGHT_BIT_SCALE,
91                                size[1] * line_count * EIGHT_BIT_SCALE)
92                         pos = (pos[0] + self.padding, pos[1] + self.padding)
93                         image_map[pos] = resources.get_image(
94                             markup_data[1],
95                             transforms=(EIGHT_BIT, blender(self.colour)))
96                         continue
97                 else:
98                     line_count += 1
99                     yield ' '.join(current_words[:-1])
100                     current_words = current_words[-1:]
101             if current_words and words_fit(current_words):
102                 yield ' '.join(current_words)
103
104     def prepare(self):
105         self.font = resources.get_font(self.fontname, self.fontsize)
106         image_map = {}
107         rendered_lines = []
108         width, height = self.padding * 2, self.padding * 2
109         for line in self.lines(image_map):
110             line_surface = self.render_line(line)
111             line_rect = line_surface.get_rect()
112             rendered_lines.append(line_surface)
113             width = max(width, line_rect.width + self.padding * 2)
114             height += line_rect.height
115
116         self.surface = pygame.surface.Surface((width, height),
117                                               pygame.locals.SRCALPHA)
118         self.surface.fill(self.bg_colour)
119         self.size = self.surface.get_rect().size
120
121         x, y = self.padding, self.padding
122         for line_surface in rendered_lines:
123             self.surface.blit(line_surface, (x, y))
124             y += line_surface.get_rect().height
125         for pos, img in image_map.items():
126             self.surface.blit(img, pos)
127
128     def draw(self, surface):
129         surface.blit(self.surface, self.rect)