#324: Hopefully this fixes the issue with malformed UTF-8 sequences causing SuperTux...
[supertux.git] / src / video / font.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //                     Ingo Ruhnke <grumbel@gmx.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 #include <config.h>
22
23 #include <cstdlib>
24 #include <cstring>
25 #include <stdexcept>
26
27 #include <SDL_image.h>
28 #include "physfs/physfs_sdl.hpp"
29
30 #include "lisp/parser.hpp"
31 #include "lisp/lisp.hpp"
32 #include "screen.hpp"
33 #include "font.hpp"
34 #include "renderer.hpp"
35 #include "drawing_context.hpp"
36 #include "log.hpp"
37
38 namespace {
39 bool     has_multibyte_mark(unsigned char c);
40 uint32_t decode_utf8(const std::string& text, size_t& p);
41
42 struct UTF8Iterator
43 {
44   const std::string&     text;
45   std::string::size_type pos;
46   uint32_t chr;
47
48   UTF8Iterator(const std::string& text_)
49     : text(text_),
50       pos(0)
51   {
52     try {
53       chr = decode_utf8(text, pos);
54     } catch (std::exception) {
55       log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
56       chr = 0;
57     }
58   }
59
60   bool done() const
61   {
62     return pos > text.size();
63   }
64
65   UTF8Iterator& operator++() {
66     try {
67       chr = decode_utf8(text, pos);
68     } catch (std::exception) {
69       log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
70       chr = 0;
71       ++pos;
72     }
73
74     return *this;
75   }
76
77   uint32_t operator*() const {
78     return chr;
79   }
80 };
81
82 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
83 {
84   Uint8* pixels = (Uint8*)surface->pixels;
85
86   for(int y = start_y; y < end_y; ++y)
87     {
88       const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
89       if (p > threshold)
90         {
91           return false;
92         }
93     }
94   return true;
95 }
96 } // namespace
97
98 Font::Font(GlyphWidth glyph_width_,
99            const std::string& filename,
100            const std::string& shadowfile,
101            int char_width, int char_height_,
102            int shadowsize_)
103   : glyph_width(glyph_width_),
104     glyph_surface(0), shadow_glyph_surface(0),
105     char_height(char_height_),
106     shadowsize(shadowsize_)
107 {
108   glyph_surface = new Surface(filename);
109   shadow_glyph_surface  = new Surface(shadowfile);
110
111   first_char = 32;
112   char_count = ((int) glyph_surface->get_height() / char_height) * 16;
113
114   if (glyph_width == FIXED)
115     {
116       for(uint32_t i = 0; i < char_count; ++i)
117         {
118           float x = (i % 16) * char_width;
119           float y = (i / 16) * char_height;
120
121           Glyph glyph;
122           glyph.advance = char_width;
123           glyph.offset  = Vector(0, 0);
124           glyph.rect    = Rect(x, y, x + char_width, y + char_height);
125
126           glyphs.push_back(glyph);
127           shadow_glyphs.push_back(glyph);
128         }
129     }
130   else // glyph_width == VARIABLE
131     {
132       // Load the surface into RAM and scan the pixel data for characters
133       SDL_Surface* surface = IMG_Load_RW(get_physfs_SDLRWops(filename), 1);
134       if(surface == NULL) {
135         std::ostringstream msg;
136         msg << "Couldn't load image '" << filename << "' :" << SDL_GetError();
137         throw std::runtime_error(msg.str());
138       }
139
140       SDL_LockSurface(surface);
141
142       for(uint32_t i = 0; i < char_count; ++i)
143         {
144           int x = (i % 16) * char_width;
145           int y = (i / 16) * char_height;
146
147           int left = x;
148           while (left < x + char_width &&
149                  vline_empty(surface, left, y, y + char_height, 64))
150             left += 1;
151
152           int right = x + char_width - 1;
153           while (right > left &&
154                  vline_empty(surface, right, y, y + char_height, 64))
155             right -= 1;
156
157           Glyph glyph;
158           glyph.offset = Vector(0, 0);
159
160           if (left <= right)
161             glyph.rect = Rect(left,  y, right+1, y + char_height);
162           else // glyph is completely transparent
163             glyph.rect = Rect(x,  y, x + char_width, y + char_height);
164
165           glyph.advance = glyph.rect.get_width() + 1; // FIXME: might be useful to make spacing configurable
166
167           glyphs.push_back(glyph);
168           shadow_glyphs.push_back(glyph);
169         }
170
171       SDL_UnlockSurface(surface);
172
173       SDL_FreeSurface(surface);
174     }
175 }
176
177 Font::~Font()
178 {
179   delete glyph_surface;
180   delete shadow_glyph_surface;
181 }
182
183 float
184 Font::get_text_width(const std::string& text) const
185 {
186   float curr_width = 0;
187   float last_width = 0;
188
189   for(UTF8Iterator it(text); !it.done(); ++it)
190     {
191       if (*it == '\n')
192         {
193           last_width = std::max(last_width, curr_width);
194           curr_width = 0;
195         }
196       else
197         {
198           int idx = chr2glyph(*it);
199           curr_width += glyphs[idx].advance;
200         }
201     }
202
203   return std::max(curr_width, last_width);
204 }
205
206 float
207 Font::get_text_height(const std::string& text) const
208 {
209   std::string::size_type text_height = char_height;
210
211   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
212     { // since UTF8 multibyte characters are decoded with values
213       // outside the ASCII range there is no risk of overlapping and
214       // thus we don't need to decode the utf-8 string
215       if (*it == '\n')
216         text_height += char_height + 2;
217     }
218
219   return text_height;
220 }
221
222 float
223 Font::get_height() const
224 {
225   return char_height;
226 }
227
228 std::string
229 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
230 {
231   // if text is already smaller, return full text
232   if ((int)s.length() <= line_length) {
233     if (overflow) *overflow = "";
234     return s;
235   }
236
237   // if we can find a whitespace character to break at, return text up to this character
238   int i = line_length;
239   while ((i > 0) && (s[i] != ' ')) i--;
240   if (i > 0) {
241     if (overflow) *overflow = s.substr(i+1);
242     return s.substr(0, i);
243   }
244
245   // FIXME: wrap at line_length, taking care of multibyte characters
246   if (overflow) *overflow = "";
247   return s;
248 }
249
250 std::string
251 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
252 {
253   std::string s = s_;
254
255   // if text is already smaller, return full text
256   if (get_text_width(s) <= width) {
257     if (overflow) *overflow = "";
258     return s;
259   }
260
261   // if we can find a whitespace character to break at, return text up to this character
262   for (int i = s.length()-1; i >= 0; i--) {
263     std::string s2 = s.substr(0,i);
264     if (s[i] != ' ') continue;
265     if (get_text_width(s2) <= width) {
266       if (overflow) *overflow = s.substr(i+1);
267       return s.substr(0, i);
268     }
269   }
270   
271   // FIXME: hard-wrap at width, taking care of multibyte characters
272   if (overflow) *overflow = "";
273   return s;
274 }
275
276 void
277 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
278            FontAlignment alignment, DrawingEffect drawing_effect,
279            float alpha) const
280 {
281   float x = pos_.x;
282   float y = pos_.y;
283
284   std::string::size_type last = 0;
285   for(std::string::size_type i = 0;; ++i)
286     {
287       if (text[i] == '\n' || i == text.size())
288         {
289           std::string temp = text.substr(last, i - last);
290
291           // calculate X positions based on the alignment type
292           Vector pos = Vector(x, y);
293
294           if(alignment == ALIGN_CENTER)
295             pos.x -= get_text_width(temp) / 2;
296           else if(alignment == ALIGN_RIGHT)
297             pos.x -= get_text_width(temp);
298
299           // Cast font position to integer to get a clean drawing result and
300           // no blurring as we would get with subpixel positions
301           pos.x = static_cast<int>(pos.x);
302
303           draw_text(renderer, temp, pos, drawing_effect, alpha);
304
305           if (i == text.size())
306             break;
307
308           y += char_height + 2;
309           last = i + 1;
310         }
311     }
312 }
313
314 void
315 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
316                 DrawingEffect drawing_effect, float alpha) const
317 {
318   if(shadowsize > 0)
319     {
320       // FIXME: shadow_glyph_surface and glyph_surface do currently
321       // share the same glyph array, this is incorrect and should be
322       // fixed, it is however hardly noticeable
323       draw_chars(renderer, shadow_glyph_surface, text,
324                  pos + Vector(shadowsize, shadowsize), drawing_effect, alpha);
325     }
326
327   draw_chars(renderer, glyph_surface, text, pos, drawing_effect, alpha);
328 }
329
330 int
331 Font::chr2glyph(uint32_t chr) const
332 {
333   int glyph_index = chr - first_char;
334
335   // we don't have the control chars 0x80-0xa0 in the font
336   if (chr >= 0x80) { // non-ascii character
337     glyph_index -= 32;
338     if(chr <= 0xa0) {
339       log_debug << "Unsupported utf-8 character '" << chr << "' found" << std::endl;
340       glyph_index = 0;
341     }
342   }
343
344   if(glyph_index < 0 || glyph_index >= (int) char_count) {
345     log_debug << "Unsupported utf-8 character found" << std::endl;
346     glyph_index = 0;
347   }
348
349   return glyph_index;
350 }
351
352 void
353 Font::draw_chars(Renderer *renderer, Surface* pchars, const std::string& text,
354                  const Vector& pos, DrawingEffect drawing_effect,
355                  float alpha) const
356 {
357   Vector p = pos;
358
359   for(UTF8Iterator it(text); !it.done(); ++it)
360     {
361       int font_index = chr2glyph(*it);
362
363       if(*it == '\n')
364         {
365           p.x = pos.x;
366           p.y += char_height + 2;
367         }
368       else if(*it == ' ')
369         {
370           p.x += glyphs[font_index].advance;
371         }
372       else
373         {
374           const Glyph& glyph = glyphs[font_index];
375           DrawingRequest request;
376
377           request.pos = p + glyph.offset;
378           request.drawing_effect = drawing_effect;
379           request.alpha = alpha;
380
381           SurfacePartRequest surfacepartrequest;
382           surfacepartrequest.size = glyph.rect.p2 - glyph.rect.p1;
383           surfacepartrequest.source = glyph.rect.p1;
384           surfacepartrequest.surface = pchars;
385
386           request.request_data = &surfacepartrequest;
387           renderer->draw_surface_part(request);
388
389           p.x += glyphs[font_index].advance;
390         }
391     }
392 }
393
394
395 namespace {
396
397 /**
398  * returns true if this byte matches a bitmask of 10xx.xxxx, i.e. it is the 2nd, 3rd or 4th byte of a multibyte utf8 string
399  */
400 bool has_multibyte_mark(unsigned char c) {
401   return ((c & 0300) == 0200);
402 }
403
404 /**
405  * gets unicode character at byte position @a p of UTF-8 encoded @a
406  * text, then advances @a p to the next character.
407  *
408  * @throws std::runtime_error if decoding fails.
409  * See unicode standard section 3.10 table 3-5 and 3-6 for details.
410  */
411 uint32_t decode_utf8(const std::string& text, size_t& p)
412 {
413   uint32_t c1 = (unsigned char) text[p+0];
414
415   if (has_multibyte_mark(c1)) std::runtime_error("Malformed utf-8 sequence");
416
417   if ((c1 & 0200) == 0000) {
418     // 0xxx.xxxx: 1 byte sequence
419     p+=1;
420     return c1;
421   }
422   else if ((c1 & 0340) == 0300) {
423     // 110x.xxxx: 2 byte sequence
424     if(p+1 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
425     uint32_t c2 = (unsigned char) text[p+1];
426     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
427     p+=2;
428     return (c1 & 0037) << 6 | (c2 & 0077);
429   }
430   else if ((c1 & 0360) == 0340) {
431     // 1110.xxxx: 3 byte sequence
432     if(p+2 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
433     uint32_t c2 = (unsigned char) text[p+1];
434     uint32_t c3 = (unsigned char) text[p+2];
435     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
436     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
437     p+=3;
438     return (c1 & 0017) << 12 | (c2 & 0077) << 6 | (c3 & 0077);
439   }
440   else if ((c1 & 0370) == 0360) {
441     // 1111.0xxx: 4 byte sequence
442     if(p+3 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
443     uint32_t c2 = (unsigned char) text[p+1];
444     uint32_t c3 = (unsigned char) text[p+2];
445     uint32_t c4 = (unsigned char) text[p+4];
446     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
447     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
448     if (!has_multibyte_mark(c4)) throw std::runtime_error("Malformed utf-8 sequence");
449     p+=4;
450     return (c1 & 0007) << 18 | (c2 & 0077) << 12 | (c3 & 0077) << 6 | (c4 & 0077);
451   }
452   throw std::runtime_error("Malformed utf-8 sequence");
453 }
454
455 } // namespace