added forced line break support to auto-wrapped text output
[rocksndiamonds.git] / src / libgame / text.c
1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // text.c
10 // ============================================================================
11
12 #include <stdio.h>
13 #include <stdarg.h>
14
15 #include "text.h"
16 #include "misc.h"
17
18
19 // ============================================================================
20 // font functions
21 // ============================================================================
22
23 void InitFontInfo(struct FontBitmapInfo *font_bitmap_info, int num_fonts,
24                   int (*select_font_function)(int),
25                   int (*get_font_from_token_function)(char *))
26 {
27   gfx.num_fonts = num_fonts;
28   gfx.font_bitmap_info = font_bitmap_info;
29   gfx.select_font_function = select_font_function;
30   gfx.get_font_from_token_function = get_font_from_token_function;
31 }
32
33 void FreeFontInfo(struct FontBitmapInfo *font_bitmap_info)
34 {
35   if (font_bitmap_info == NULL)
36     return;
37
38   free(font_bitmap_info);
39 }
40
41 struct FontBitmapInfo *getFontBitmapInfo(int font_nr)
42 {
43   int font_bitmap_id = gfx.select_font_function(font_nr);
44
45   return &gfx.font_bitmap_info[font_bitmap_id];
46 }
47
48 int getFontWidth(int font_nr)
49 {
50   int font_bitmap_id = gfx.select_font_function(font_nr);
51
52   return gfx.font_bitmap_info[font_bitmap_id].width;
53 }
54
55 int getFontHeight(int font_nr)
56 {
57   int font_bitmap_id = gfx.select_font_function(font_nr);
58
59   return gfx.font_bitmap_info[font_bitmap_id].height;
60 }
61
62 int getFontDrawOffsetX(int font_nr)
63 {
64   int font_bitmap_id = gfx.select_font_function(font_nr);
65
66   return gfx.font_bitmap_info[font_bitmap_id].draw_xoffset;
67 }
68
69 int getFontDrawOffsetY(int font_nr)
70 {
71   int font_bitmap_id = gfx.select_font_function(font_nr);
72
73   return gfx.font_bitmap_info[font_bitmap_id].draw_yoffset;
74 }
75
76 int getTextWidth(char *text, int font_nr)
77 {
78   return (text != NULL ? strlen(text) * getFontWidth(font_nr) : 0);
79 }
80
81 static int getFontCharPosition(int font_nr, char c)
82 {
83   int font_bitmap_id = gfx.select_font_function(font_nr);
84   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
85   boolean default_font = (font->num_chars == DEFAULT_NUM_CHARS_PER_FONT);
86   int font_pos = (unsigned char)c - 32;
87
88   // map some special characters to their ascii values in default font
89   if (default_font)
90     font_pos = MAP_FONT_ASCII(c) - 32;
91
92   // this allows dynamic special characters together with special font
93   if (font_pos < 0 || font_pos >= font->num_chars)
94     font_pos = 0;
95
96   return font_pos;
97 }
98
99 void getFontCharSource(int font_nr, char c, Bitmap **bitmap, int *x, int *y)
100 {
101   int font_bitmap_id = gfx.select_font_function(font_nr);
102   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
103   int font_pos = getFontCharPosition(font_nr, c);
104   int offset_x = (font->offset_x != 0 ? font->offset_x : font->width);
105   int offset_y = (font->offset_y != 0 ? font->offset_y : font->height);
106
107   *bitmap = font->bitmap;
108   *x = font->src_x + (font_pos % font->num_chars_per_line) * offset_x;
109   *y = font->src_y + (font_pos / font->num_chars_per_line) * offset_y;
110 }
111
112
113 // ============================================================================
114 // text string helper functions
115 // ============================================================================
116
117 int maxWordLengthInRequestString(char *text)
118 {
119   char *text_ptr;
120   int word_len = 0, max_word_len = 0;
121
122   for (text_ptr = text; *text_ptr; text_ptr++)
123   {
124     word_len = (*text_ptr != ' ' &&
125                 *text_ptr != '?' &&
126                 *text_ptr != '!' ? word_len + 1 : 0);
127
128     max_word_len = MAX(word_len, max_word_len);
129   }
130
131   return max_word_len;
132 }
133
134
135 // ============================================================================
136 // simple text drawing functions
137 // ============================================================================
138
139 static void DrawInitTextExt(char *text, int ypos, int font_nr, boolean update)
140 {
141   LimitScreenUpdates(TRUE);
142
143   UPDATE_BUSY_STATE();
144
145   if (window != NULL &&
146       gfx.draw_init_text &&
147       gfx.num_fonts > 0 &&
148       gfx.font_bitmap_info[font_nr].bitmap != NULL)
149   {
150     int x = (video.width - getTextWidth(text, font_nr)) / 2;
151     int y = ypos;
152     int width = video.width;
153     int height = getFontHeight(font_nr);
154
155     ClearRectangleOnBackground(drawto, 0, y, width, height);
156     DrawTextExt(drawto, x, y, text, font_nr, BLIT_MASKED);
157
158     if (update)
159       BlitBitmap(drawto, window, 0, 0, video.width, video.height, 0, 0);
160   }
161 }
162
163 void DrawInitText(char *text, int ypos, int font_nr)
164 {
165   DrawInitTextExt(text, ypos, font_nr, FALSE);
166 }
167
168 void DrawInitTextHead(char *text)
169 {
170   DrawInitTextExt(text, 120, FC_GREEN, FALSE);
171 }
172
173 void DrawInitTextItem(char *text)
174 {
175   DrawInitTextExt(text, 150, FC_YELLOW, TRUE);
176 }
177
178 void DrawTextF(int x, int y, int font_nr, char *format, ...)
179 {
180   char buffer[MAX_OUTPUT_LINESIZE + 1];
181   va_list ap;
182
183   va_start(ap, format);
184   vsprintf(buffer, format, ap);
185   va_end(ap);
186
187   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
188     Fail("string too long in DrawTextF() -- aborting");
189
190   DrawText(gfx.sx + x, gfx.sy + y, buffer, font_nr);
191 }
192
193 void DrawTextFCentered(int y, int font_nr, char *format, ...)
194 {
195   char buffer[MAX_OUTPUT_LINESIZE + 1];
196   va_list ap;
197
198   va_start(ap, format);
199   vsprintf(buffer, format, ap);
200   va_end(ap);
201
202   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
203     Fail("string too long in DrawTextFCentered() -- aborting");
204
205   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(buffer, font_nr)) / 2,
206            gfx.sy + y, buffer, font_nr);
207 }
208
209 void DrawTextS(int x, int y, int font_nr, char *text)
210 {
211   DrawText(gfx.sx + x, gfx.sy + y, text, font_nr);
212 }
213
214 void DrawTextSCentered(int y, int font_nr, char *text)
215 {
216   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(text, font_nr)) / 2,
217            gfx.sy + y, text, font_nr);
218 }
219
220 void DrawTextSAligned(int x, int y, char *text, int font_nr, int align)
221 {
222   DrawText(gfx.sx + ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
223            gfx.sy + y, text, font_nr);
224 }
225
226 void DrawText(int x, int y, char *text, int font_nr)
227 {
228   int mask_mode = BLIT_OPAQUE;
229
230   if (DrawingOnBackground(x, y))
231     mask_mode = BLIT_ON_BACKGROUND;
232
233   DrawTextExt(drawto, x, y, text, font_nr, mask_mode);
234
235   if (IN_GFX_FIELD_FULL(x, y))
236     redraw_mask |= REDRAW_FIELD;
237   else if (IN_GFX_DOOR_1(x, y))
238     redraw_mask |= REDRAW_DOOR_1;
239   else if (IN_GFX_DOOR_2(x, y))
240     redraw_mask |= REDRAW_DOOR_2;
241   else if (IN_GFX_DOOR_3(x, y))
242     redraw_mask |= REDRAW_DOOR_3;
243   else
244     redraw_mask |= REDRAW_ALL;
245 }
246
247 void DrawTextExt(DrawBuffer *dst_bitmap, int dst_x, int dst_y, char *text,
248                  int font_nr, int mask_mode)
249 {
250   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
251   int font_width = getFontWidth(font_nr);
252   int font_height = getFontHeight(font_nr);
253   Bitmap *src_bitmap;
254   int src_x, src_y;
255   char *text_ptr = text;
256
257   if (font->bitmap == NULL)
258     return;
259
260   // skip text to be printed outside the window (left/right will be clipped)
261   if (dst_y < 0 || dst_y + font_height > video.height)
262     return;
263
264   // add offset for drawing font characters
265   dst_x += font->draw_xoffset;
266   dst_y += font->draw_yoffset;
267
268   while (*text_ptr)
269   {
270     char c = *text_ptr++;
271
272     if (c == '\n')
273       c = ' ';          // print space instead of newline
274
275     getFontCharSource(font_nr, c, &src_bitmap, &src_x, &src_y);
276
277     // clip text at the left side of the window
278     if (dst_x < 0)
279     {
280       dst_x += font_width;
281
282       continue;
283     }
284
285     // clip text at the right side of the window
286     if (dst_x + font_width > video.width)
287       break;
288
289     if (mask_mode == BLIT_INVERSE)      // special mode for text gadgets
290     {
291       // first step: draw solid colored rectangle (use "cursor" character)
292       if (strlen(text) == 1)    // only one char inverted => draw cursor
293       {
294         Bitmap *cursor_bitmap;
295         int cursor_x, cursor_y;
296
297         getFontCharSource(font_nr, FONT_ASCII_CURSOR, &cursor_bitmap,
298                           &cursor_x, &cursor_y);
299
300         BlitBitmap(cursor_bitmap, dst_bitmap, cursor_x, cursor_y,
301                    font_width, font_height, dst_x, dst_y);
302       }
303
304       // second step: draw masked inverted character
305       SDLCopyInverseMasked(src_bitmap, dst_bitmap, src_x, src_y,
306                            font_width, font_height, dst_x, dst_y);
307     }
308     else if (mask_mode == BLIT_MASKED || mask_mode == BLIT_ON_BACKGROUND)
309     {
310       if (mask_mode == BLIT_ON_BACKGROUND)
311       {
312         // clear font character background
313         ClearRectangleOnBackground(dst_bitmap, dst_x, dst_y,
314                                    font_width, font_height);
315       }
316
317       BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y,
318                        font_width, font_height, dst_x, dst_y);
319     }
320     else        // normal, non-masked font blitting
321     {
322       BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y,
323                  font_width, font_height, dst_x, dst_y);
324     }
325
326     dst_x += font_width;
327   }
328 }
329
330
331 // ============================================================================
332 // text buffer drawing functions
333 // ============================================================================
334
335 #define MAX_LINES_FROM_FILE             1024
336
337 char *GetTextBufferFromFile(char *filename, int max_lines)
338 {
339   File *file;
340   char *buffer;
341   int num_lines = 0;
342
343   if (filename == NULL)
344     return NULL;
345
346   if (!(file = openFile(filename, MODE_READ)))
347     return NULL;
348
349   buffer = checked_calloc(1);   // start with valid, but empty text buffer
350
351   while (!checkEndOfFile(file) && num_lines < max_lines)
352   {
353     char line[MAX_LINE_LEN];
354     char *line_ptr;
355     int line_len;
356
357     // read next line of input file
358     if (!getStringFromFile(file, line, MAX_LINE_LEN))
359       break;
360
361     line_len = strlen(line);
362
363     // cut trailing line break (this can be newline and/or carriage return)
364     for (line_ptr = &line[line_len]; line_ptr >= line; line_ptr--)
365       if ((*line_ptr == '\n' || *line_ptr == '\r') && *(line_ptr + 1) == '\0')
366         *line_ptr = '\0';
367
368     // re-add newline (so the result is terminated by newline, but not CR/LF)
369     if (strlen(line) != line_len)
370       strcat(line, "\n");
371
372     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
373
374     strcat(buffer, line);
375
376     num_lines++;
377   }
378
379   closeFile(file);
380
381   if (getTextEncoding(buffer) == TEXT_ENCODING_UTF_8)
382   {
383     char *body_latin1 = getLatin1FromUTF8(buffer);
384
385     checked_free(buffer);
386
387     buffer = body_latin1;
388   }
389
390   return buffer;
391 }
392
393 static boolean RenderLineToBuffer(char **src_buffer_ptr, char *dst_buffer,
394                                   int *dst_buffer_len, int line_length,
395                                   boolean last_line_was_empty)
396 {
397   char *text_ptr = *src_buffer_ptr;
398   char *buffer = dst_buffer;
399   int buffer_len = *dst_buffer_len;
400   boolean buffer_filled = FALSE;
401
402   while (*text_ptr)
403   {
404     char *word_ptr;
405     int word_len;
406
407     if (strEqual(text_ptr, "  "))       // special case: force line break
408       buffer_filled = TRUE;
409
410     // skip leading whitespaces
411     while (*text_ptr == ' ' || *text_ptr == '\t')
412       text_ptr++;
413
414     word_ptr = text_ptr;
415     word_len = 0;
416
417     // look for end of next word
418     while (*word_ptr != ' ' && *word_ptr != '\t' && *word_ptr != '\0')
419     {
420       word_ptr++;
421       word_len++;
422     }
423
424     if (word_len == 0)
425     {
426       continue;
427     }
428     else if (*text_ptr == '\n')         // special case: force empty line
429     {
430       if (buffer_len == 0)
431         text_ptr++;
432
433       // prevent printing of multiple empty lines
434       if (buffer_len > 0 || !last_line_was_empty)
435         buffer_filled = TRUE;
436     }
437     else if (word_len < line_length - buffer_len)
438     {
439       // word fits into text buffer -- add word
440
441       if (buffer_len > 0)
442         buffer[buffer_len++] = ' ';
443
444       strncpy(&buffer[buffer_len], text_ptr, word_len);
445       buffer_len += word_len;
446       buffer[buffer_len] = '\0';
447       text_ptr += word_len;
448     }
449     else if (buffer_len > 0)
450     {
451       // not enough space left for word in text buffer -- print buffer
452
453       buffer_filled = TRUE;
454     }
455     else
456     {
457       // word does not fit at all into empty text buffer -- cut word
458
459       strncpy(buffer, text_ptr, line_length);
460       buffer[line_length] = '\0';
461       text_ptr += line_length;
462       buffer_filled = TRUE;
463     }
464
465     if (buffer_filled)
466       break;
467   }
468
469   *src_buffer_ptr = text_ptr;
470   *dst_buffer_len = buffer_len;
471
472   return buffer_filled;
473 }
474
475 static boolean getCheckedTokenValueFromString(char *string, char **token,
476                                               char **value)
477 {
478   char *ptr;
479
480   if (!getTokenValueFromString(string, token, value))
481     return FALSE;
482
483   if (**token != '.')                   // token should begin with dot
484     return FALSE;
485
486   for (ptr = *token; *ptr; ptr++)       // token should contain no whitespace
487     if (*ptr == ' ' || *ptr == '\t')
488       return FALSE;
489
490   for (ptr = *value; *ptr; ptr++)       // value should contain no whitespace
491     if (*ptr == ' ' || *ptr == '\t')
492       return FALSE;
493
494   return TRUE;
495 }
496
497 static void DrawTextBuffer_Flush(int x, int y, char *buffer, int font_nr,
498                                  int line_length, int cut_length,
499                                  int mask_mode, boolean centered,
500                                  int current_ypos)
501 {
502   int buffer_len = strlen(buffer);
503   int font_width = getFontWidth(font_nr);
504   int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
505   int offset_xsize =
506     (centered ? font_width * (line_length - buffer_len) / 2 : 0);
507   int final_cut_length = MAX(0, cut_length - offset_chars);
508   int xx = x + offset_xsize;
509   int yy = y + current_ypos;
510
511   buffer[final_cut_length] = '\0';
512
513   if (mask_mode != -1)
514     DrawTextExt(drawto, xx, yy, buffer, font_nr, mask_mode);
515   else
516     DrawText(xx, yy, buffer, font_nr);
517 }
518
519 static int DrawTextBufferExt(int x, int y, char *text_buffer, int font_nr,
520                              int line_length, int cut_length, int max_lines,
521                              int line_spacing, int mask_mode, boolean autowrap,
522                              boolean centered, boolean parse_comments,
523                              boolean is_text_area)
524 {
525   char buffer[line_length + 1];
526   int buffer_len;
527   int font_height = getFontHeight(font_nr);
528   int line_height = font_height + line_spacing;
529   int current_line = 0;
530   int current_ypos = 0;
531   int max_ysize = max_lines * line_height;
532
533   if (text_buffer == NULL || *text_buffer == '\0')
534     return 0;
535
536   if (current_line >= max_lines)
537     return 0;
538
539   if (cut_length == -1)
540     cut_length = line_length;
541
542   buffer[0] = '\0';
543   buffer_len = 0;
544
545   while (*text_buffer && current_ypos < max_ysize)
546   {
547     char line[MAX_LINE_LEN + 1];
548     char *line_ptr;
549     boolean last_line_was_empty = TRUE;
550     int num_line_chars = MAX_LINE_LEN;
551     int i;
552
553     // copy next line from text buffer to line buffer (nearly fgets() style)
554     for (i = 0; i < num_line_chars && *text_buffer; i++)
555     {
556       if ((line[i] = *text_buffer++) == '\n')
557       {
558         // in text areas, 'line_length' sized lines cause additional empty line
559         if (i == line_length && is_text_area)
560           text_buffer--;
561
562         break;
563       }
564     }
565     line[i] = '\0';
566
567     // prevent 'num_line_chars' sized lines to cause additional empty line
568     if (i == num_line_chars && *text_buffer == '\n')
569       text_buffer++;
570
571     // skip comments (lines directly beginning with '#')
572     if (line[0] == '#' && parse_comments)
573     {
574       char *token, *value;
575
576       // try to read generic token/value pair definition after comment sign
577       if (getCheckedTokenValueFromString(line + 1, &token, &value))
578       {
579         // if found, flush the current buffer, if non-empty
580         if (buffer_len > 0 && current_ypos < max_ysize)
581         {
582           DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
583                                mask_mode, centered, current_ypos);
584           current_ypos += line_height;
585           current_line++;
586
587           buffer[0] = '\0';
588           buffer_len = 0;
589         }
590
591         if (strEqual(token, ".font"))
592           font_nr = gfx.get_font_from_token_function(value);
593         else if (strEqual(token, ".autowrap"))
594           autowrap = get_boolean_from_string(value);
595         else if (strEqual(token, ".centered"))
596           centered = get_boolean_from_string(value);
597         else if (strEqual(token, ".parse_comments"))
598           parse_comments = get_boolean_from_string(value);
599
600         // if font has changed, depending values need to be updated as well
601         font_height = getFontHeight(font_nr);
602         line_height = font_height + line_spacing;
603       }
604
605       continue;
606     }
607
608     // cut trailing newline and carriage return from input line
609     for (line_ptr = line; *line_ptr; line_ptr++)
610     {
611       if (*line_ptr == '\n' || *line_ptr == '\r')
612       {
613         *line_ptr = '\0';
614         break;
615       }
616     }
617
618     if (strlen(line) == 0)              // special case: force empty line
619       strcpy(line, "\n");
620
621     line_ptr = line;
622
623     while (*line_ptr && current_ypos < max_ysize)
624     {
625       boolean buffer_filled;
626
627       if (autowrap)
628       {
629         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
630                                            line_length, last_line_was_empty);
631       }
632       else
633       {
634         if (strlen(line_ptr) <= line_length)
635         {
636           buffer_len = strlen(line_ptr);
637           strcpy(buffer, line_ptr);
638         }
639         else
640         {
641           buffer_len = line_length;
642           strncpy(buffer, line_ptr, line_length);
643         }
644
645         buffer[buffer_len] = '\0';
646         line_ptr += buffer_len;
647
648         buffer_filled = TRUE;
649       }
650
651       if (buffer_filled)
652       {
653         DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
654                              mask_mode, centered, current_ypos);
655         current_ypos += line_height;
656         current_line++;
657
658         last_line_was_empty = (buffer_len == 0);
659
660         buffer[0] = '\0';
661         buffer_len = 0;
662       }
663     }
664   }
665
666   if (buffer_len > 0 && current_ypos < max_ysize)
667   {
668     DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
669                          mask_mode, centered, current_ypos);
670     current_ypos += line_height;
671     current_line++;
672   }
673
674   return current_line;
675 }
676
677 int DrawTextArea(int x, int y, char *text_buffer, int font_nr,
678                  int line_length, int cut_length, int max_lines,
679                  int line_spacing, int mask_mode, boolean autowrap,
680                  boolean centered, boolean parse_comments)
681 {
682   return DrawTextBufferExt(x, y, text_buffer, font_nr,
683                            line_length, cut_length, max_lines,
684                            line_spacing, mask_mode, autowrap,
685                            centered, parse_comments, TRUE);
686 }
687
688 int DrawTextBuffer(int x, int y, char *text_buffer, int font_nr,
689                    int line_length, int cut_length, int max_lines,
690                    int line_spacing, int mask_mode, boolean autowrap,
691                    boolean centered, boolean parse_comments)
692 {
693   return DrawTextBufferExt(x, y, text_buffer, font_nr,
694                            line_length, cut_length, max_lines,
695                            line_spacing, mask_mode, autowrap,
696                            centered, parse_comments, FALSE);
697 }
698
699 int DrawTextBufferS(int x, int y, char *text_buffer, int font_nr,
700                     int line_length, int cut_length, int max_lines,
701                     int line_spacing, int mask_mode, boolean autowrap,
702                     boolean centered, boolean parse_comments)
703 {
704   return DrawTextBuffer(gfx.sx + x, gfx.sy + y, text_buffer, font_nr,
705                         line_length, cut_length, max_lines,
706                         line_spacing, mask_mode, autowrap,
707                         centered, parse_comments);
708 }
709
710 int DrawTextBufferVA(int x, int y, char *format, va_list ap, int font_nr,
711                      int line_length, int cut_length, int max_lines,
712                      int line_spacing, int mask_mode, boolean autowrap,
713                      boolean centered, boolean parse_comments)
714 {
715   char text_buffer[MAX_OUTPUT_LINESIZE];
716   int text_length = vsnprintf(text_buffer, MAX_OUTPUT_LINESIZE, format, ap);
717
718   if (text_length >= MAX_OUTPUT_LINESIZE)
719     Warn("string too long in DrawTextBufferVA() -- truncated");
720
721   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
722                                          line_length, cut_length, max_lines,
723                                          line_spacing, mask_mode, autowrap,
724                                          centered, parse_comments);
725   return num_lines_printed;
726 }
727
728 int DrawTextFile(int x, int y, char *filename, int font_nr,
729                  int line_length, int cut_length, int max_lines,
730                  int line_spacing, int mask_mode, boolean autowrap,
731                  boolean centered, boolean parse_comments)
732 {
733   char *text_buffer = GetTextBufferFromFile(filename, MAX_LINES_FROM_FILE);
734   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
735                                          line_length, cut_length, max_lines,
736                                          line_spacing, mask_mode, autowrap,
737                                          centered, parse_comments);
738   checked_free(text_buffer);
739
740   return num_lines_printed;
741 }