Malformed UTF-8 sequences are no longer fatal
[supertux.git] / src / video / font.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <config.h>
21
22 #include <cstdlib>
23 #include <cstring>
24 #include <stdexcept>
25
26 #include "lisp/parser.hpp"
27 #include "lisp/lisp.hpp"
28 #include "screen.hpp"
29 #include "font.hpp"
30 #include "drawing_context.hpp"
31 #include "log.hpp"
32
33 Font::Font(const std::string& file, const std::string& shadowfile,
34            int w, int h, int shadowsize)
35     : chars(0), shadow_chars(0), w(w), h(h), shadowsize(shadowsize)
36 {
37   chars = new Surface(file);
38   shadow_chars = new Surface(shadowfile);
39  
40   first_char = 32;
41   char_count = ((int) chars->get_height() / h) * 16;
42 }
43
44 Font::~Font()
45 {
46   delete chars;
47   delete shadow_chars;
48 }
49
50 float
51 Font::get_text_width(const std::string& text) const
52 {
53   /** Let's calculate the size of the biggest paragraph */
54   std::string::size_type l, hl, ol;
55   hl = 0; l = 0;
56   while(true)
57     {
58     ol = l;
59     l = text.find("\n", l+1);
60     if(l == std::string::npos)
61       break;
62     if(hl < l-ol)
63       hl = l-ol;
64     }
65   if(hl == 0)
66     hl = text.size();
67
68   for (unsigned int i = 0; i < text.size(); i++)
69     if ((unsigned char) text[i] > 0xC2 && (unsigned char) text[i] < 0xC6)
70       hl--;  // control characters are a WASTE.
71
72   return hl * w;
73 }
74
75 float
76 Font::get_text_height(const std::string& text) const
77 {
78   /** Let's calculate height of the text */
79   std::string::size_type l, hh;
80   hh = h; l = 0;
81   while(true)
82     {
83     l = text.find("\n", l+1);
84     if(l == std::string::npos)
85       break;
86     hh += h + 2;
87     }
88
89   return hh;
90 }
91
92 float
93 Font::get_height() const
94 {
95   return h;
96 }
97
98 std::string
99 Font::wrap_to_width(const std::string& s, int max_width, std::string* overflow) const
100 {
101   return wrap_to_chars(s, max_width / w, overflow);
102 }
103
104 std::string
105 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
106 {
107   // if text is already smaller, return full text
108   if ((int)s.length() <= line_length) {
109     if (overflow) *overflow = "";
110     return s;
111   }
112
113   // if we can find a whitespace character to break at, return text up to this character
114   int i = line_length;
115   while ((i > 0) && (s[i] != ' ')) i--;
116   if (i > 0) {
117     if (overflow) *overflow = s.substr(i+1);
118     return s.substr(0, i);
119   }
120
121   // FIXME: wrap at line_length, taking care of multibyte characters
122   if (overflow) *overflow = "";
123   return s;
124 }
125
126 void
127 Font::draw(const std::string& text, const Vector& pos_, FontAlignment alignment,
128            DrawingEffect drawing_effect, float alpha) const
129 {
130   /* Cut lines changes into seperate strings, needed to support center/right text
131      alignments with break lines.
132      Feel free to replace this hack with a more elegant solution
133   */
134   char temp[1024];
135   std::string::size_type l, i, y;
136   bool done = false;
137   i = y = 0;
138
139   while(!done) {
140     l = text.find("\n", i);
141     if(l == std::string::npos) {
142       l = text.size();
143       done = true;
144     }
145
146     if(l > sizeof(temp)-1)
147       l = sizeof(temp)-1;
148     
149     temp[text.copy(temp, l - i, i)] = '\0';
150     
151     // calculate X positions based on the alignment type
152     Vector pos = Vector(pos_);
153     if(alignment == CENTER_ALLIGN)
154       pos.x -= get_text_width(temp) / 2;
155     else if(alignment == RIGHT_ALLIGN)
156       pos.x -= get_text_width(temp);
157
158     draw_text(temp, pos + Vector(0,y), drawing_effect, alpha);
159
160     i = l+1;
161     y += h + 2;
162   }
163 }
164
165 void
166 Font::draw_text(const std::string& text, const Vector& pos, 
167                 DrawingEffect drawing_effect, float alpha) const
168 {
169   if(shadowsize > 0)
170     draw_chars(shadow_chars, text, pos + Vector(shadowsize, shadowsize),
171                drawing_effect, alpha);
172
173   draw_chars(chars, text, pos, drawing_effect, alpha);
174 }
175
176 /** decoding of a byte stream to a single unicode character.
177  * This should be correct for well formed utf-8 sequences but doesn't check for
178  * all forms of illegal sequences.
179  * (see unicode standard section 3.10 table 3-5 and 3-6 for details)
180  */
181 uint32_t decode_utf8(const std::string& text, size_t& p)
182 {
183   // 1 byte sequence
184   uint32_t c = (unsigned char) text[p++];
185   if(c <= 0x7F) {
186     return c;
187   }
188   
189   // 2 byte sequence
190   if(p >= text.size())
191     throw std::runtime_error("Malformed utf-8 sequence");
192   uint32_t c2 = (unsigned char) text[p++];
193   if(c <= 0xDF) {
194     if(c < 0xC2)
195       throw std::runtime_error("Malformed utf-8 sequence");
196     return (c & 0x1F) << 6 | (c2 & 0x3F);
197   }
198   
199   // 3 byte sequence
200   if(p >= text.size())
201     throw std::runtime_error("Malformed utf-8 sequence");
202   uint32_t c3 = (unsigned char) text[p++];
203   if(c <= 0xEF) {
204     return (c & 0x0F) << 12 | (c2 & 0x3F) << 6 | (c3 & 0x3F);
205   }
206   
207   // 4 byte sequence
208   if(p >= text.size())
209     throw std::runtime_error("Malformed utf-8 sequence");
210   uint32_t c4 = (unsigned char) text[p++];
211   if(c <= 0xF4) {
212     return (c & 0x07) << 18 | (c2 & 0x3F) << 12 | (c3 & 0x3F) << 6 
213       | (c4 & 0x3F);
214   }
215
216   throw std::runtime_error("Malformed utf-8 sequence");
217 }
218
219 void
220 Font::draw_chars(Surface* pchars, const std::string& text, const Vector& pos,
221                  DrawingEffect drawing_effect, float alpha) const
222 {
223   Vector p = pos;
224   size_t i = 0;
225   while(i < text.size()) {
226     uint32_t c;
227     try {
228      c = decode_utf8(text, i);
229     } 
230     catch (std::runtime_error) {
231      log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + i)) << " found " << std::endl;
232      c = 0;
233      i++;
234     }
235     ssize_t font_index;
236
237     // a non-printable character?
238     if(c == '\n') {                                      
239       p.x = pos.x;
240       p.y += h + 2;
241       continue;
242     }
243     if(c == ' ') {
244       p.x += w;
245       continue;
246     }
247
248     font_index = c - first_char;
249     // we don't have the control chars 0x80-0xa0 in the font
250     if(c >= 0x80) {
251       font_index -= 32;
252       if(c <= 0xa0) {
253         log_debug << "Unsupported utf-8 character '" << c << "' found" << std::endl;
254         font_index = 0;
255       }
256     }
257         
258     if(font_index < 0 || font_index >= (ssize_t) char_count) {
259       log_debug << "Unsupported utf-8 character found" << std::endl;
260       font_index = 0;
261     }                   
262
263     int source_x = (font_index % 16) * w;
264     int source_y = (font_index / 16) * h;
265     pchars->draw_part(source_x, source_y, p.x, p.y, w, h, alpha,
266                       drawing_effect);
267     p.x += w;
268   }
269 }