rnd-20131217-1-src
[rocksndiamonds.git] / src / libgame / text.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2006 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * text.c                                                   *
12 ***********************************************************/
13
14 #include <stdio.h>
15 #include <stdarg.h>
16
17 #include "text.h"
18 #include "misc.h"
19
20
21 /* ========================================================================= */
22 /* font functions                                                            */
23 /* ========================================================================= */
24
25 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
26 static GC       font_clip_gc = None;
27
28 static void InitFontClipmasks()
29 {
30   XGCValues clip_gc_values;
31   unsigned int clip_gc_valuemask;
32   GC copy_clipmask_gc;
33   int i, j;
34
35   /* This stuff is needed because X11 (XSetClipOrigin(), to be precise) is
36      often very slow when preparing a masked XCopyArea() for big Pixmaps.
37      To prevent this, create small (tile-sized) mask Pixmaps which will then
38      be set much faster with XSetClipOrigin() and speed things up a lot. */
39
40   clip_gc_values.graphics_exposures = False;
41   clip_gc_valuemask = GCGraphicsExposures;
42   font_clip_gc = XCreateGC(display, window->drawable,
43                            clip_gc_valuemask, &clip_gc_values);
44
45   /* create graphic context structures needed for clipping */
46   clip_gc_values.graphics_exposures = False;
47   clip_gc_valuemask = GCGraphicsExposures;
48   copy_clipmask_gc = XCreateGC(display,
49                                gfx.font_bitmap_info[0].bitmap->clip_mask,
50                                clip_gc_valuemask, &clip_gc_values);
51
52   /* create only those clipping Pixmaps we really need */
53   for (i = 0; i < gfx.num_fonts; i++)
54   {
55     if (gfx.font_bitmap_info[i].bitmap == NULL)
56       continue;
57
58     gfx.font_bitmap_info[i].clip_mask =
59       checked_calloc(gfx.font_bitmap_info[i].num_chars * sizeof(Pixmap));
60
61     for (j = 0; j < gfx.font_bitmap_info[i].num_chars; j++)
62     {
63       Bitmap *src_bitmap = gfx.font_bitmap_info[i].bitmap;
64       Pixmap src_pixmap = src_bitmap->clip_mask;
65       int xpos = j % gfx.font_bitmap_info[i].num_chars_per_line;
66       int ypos = j / gfx.font_bitmap_info[i].num_chars_per_line;
67       int width  = gfx.font_bitmap_info[i].width;
68       int height = gfx.font_bitmap_info[i].height;
69       int src_x = gfx.font_bitmap_info[i].src_x + xpos * width;
70       int src_y = gfx.font_bitmap_info[i].src_y + ypos * height;
71
72       gfx.font_bitmap_info[i].clip_mask[j] =
73         XCreatePixmap(display, window->drawable, width, height, 1);
74
75       XCopyArea(display, src_pixmap, gfx.font_bitmap_info[i].clip_mask[j],
76                 copy_clipmask_gc, src_x, src_y, width, height, 0, 0);
77     }
78   }
79
80   XFreeGC(display, copy_clipmask_gc);
81 }
82
83 static void FreeFontClipmasks()
84 {
85   int i, j;
86
87   if (gfx.num_fonts == 0 || gfx.font_bitmap_info[0].bitmap == NULL)
88     return;
89
90   for (i = 0; i < gfx.num_fonts; i++)
91   {
92     if (gfx.font_bitmap_info[i].clip_mask)
93     {
94       for (j = 0; j < gfx.font_bitmap_info[i].num_chars; j++)
95         XFreePixmap(display, gfx.font_bitmap_info[i].clip_mask[j]);
96       free(gfx.font_bitmap_info[i].clip_mask);
97     }
98
99     gfx.font_bitmap_info[i].clip_mask = NULL;
100     gfx.font_bitmap_info[i].num_chars = 0;
101   }
102
103   if (font_clip_gc)
104     XFreeGC(display, font_clip_gc);
105   font_clip_gc = None;
106 }
107 #endif /* TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND */
108
109 void InitFontInfo(struct FontBitmapInfo *font_bitmap_info, int num_fonts,
110                   int (*select_font_function)(int),
111                   int (*get_font_from_token_function)(char *))
112 {
113   gfx.num_fonts = num_fonts;
114   gfx.font_bitmap_info = font_bitmap_info;
115   gfx.select_font_function = select_font_function;
116   gfx.get_font_from_token_function = get_font_from_token_function;
117
118 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
119   InitFontClipmasks();
120 #endif
121 }
122
123 void FreeFontInfo(struct FontBitmapInfo *font_bitmap_info)
124 {
125   if (font_bitmap_info == NULL)
126     return;
127
128 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
129   FreeFontClipmasks();
130 #endif
131
132   free(font_bitmap_info);
133 }
134
135 struct FontBitmapInfo *getFontBitmapInfo(int font_nr)
136 {
137   int font_bitmap_id = gfx.select_font_function(font_nr);
138
139   return &gfx.font_bitmap_info[font_bitmap_id];
140 }
141
142 int getFontWidth(int font_nr)
143 {
144   int font_bitmap_id = gfx.select_font_function(font_nr);
145
146   return gfx.font_bitmap_info[font_bitmap_id].width;
147 }
148
149 int getFontHeight(int font_nr)
150 {
151   int font_bitmap_id = gfx.select_font_function(font_nr);
152
153   return gfx.font_bitmap_info[font_bitmap_id].height;
154 }
155
156 int getTextWidth(char *text, int font_nr)
157 {
158   return (text != NULL ? strlen(text) * getFontWidth(font_nr) : 0);
159 }
160
161 static int getFontCharPosition(int font_nr, char c)
162 {
163   int font_bitmap_id = gfx.select_font_function(font_nr);
164   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
165   boolean default_font = (font->num_chars == DEFAULT_NUM_CHARS_PER_FONT);
166   int font_pos = (unsigned char)c - 32;
167
168   /* map some special characters to their ascii values in default font */
169   if (default_font)
170     font_pos = MAP_FONT_ASCII(c) - 32;
171
172   /* this allows dynamic special characters together with special font */
173   if (font_pos < 0 || font_pos >= font->num_chars)
174     font_pos = 0;
175
176   return font_pos;
177 }
178
179 void getFontCharSource(int font_nr, char c, Bitmap **bitmap, int *x, int *y)
180 {
181   int font_bitmap_id = gfx.select_font_function(font_nr);
182   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
183   int font_pos = getFontCharPosition(font_nr, c);
184
185   *bitmap = font->bitmap;
186   *x = font->src_x + (font_pos % font->num_chars_per_line) * font->width;
187   *y = font->src_y + (font_pos / font->num_chars_per_line) * font->height;
188 }
189
190
191 /* ========================================================================= */
192 /* text string helper functions                                              */
193 /* ========================================================================= */
194
195 int maxWordLengthInString(char *text)
196 {
197   char *text_ptr;
198   int max_word_len = 0;
199
200   for (text_ptr = text; *text_ptr; text_ptr++)
201     max_word_len = (*text_ptr != ' ' ? max_word_len + 1 : 0);
202
203   return max_word_len;
204 }
205
206
207 /* ========================================================================= */
208 /* simple text drawing functions                                             */
209 /* ========================================================================= */
210
211 void DrawInitTextExt(char *text, int ypos, int font_nr, boolean force)
212 {
213   static unsigned int progress_delay = 0;
214   unsigned int progress_delay_value = 100;      /* (in milliseconds) */
215
216   UPDATE_BUSY_STATE();
217
218   if (!force && !DelayReached(&progress_delay, progress_delay_value))
219     return;
220
221   if (window != NULL &&
222       gfx.draw_init_text &&
223       gfx.num_fonts > 0 &&
224       gfx.font_bitmap_info[font_nr].bitmap != NULL)
225   {
226     int x = (video.width - getTextWidth(text, font_nr)) / 2;
227     int y = ypos;
228     int width = video.width;
229     int height = getFontHeight(font_nr);
230
231     ClearRectangle(drawto, 0, y, width, height);
232     DrawTextExt(drawto, x, y, text, font_nr, BLIT_OPAQUE);
233
234     /* this makes things significantly faster than directly drawing to window */
235     BlitBitmap(drawto, window, 0, y, width, height, 0, y);
236   }
237 }
238
239 void DrawInitText(char *text, int ypos, int font_nr)
240 {
241   DrawInitTextExt(text, ypos, font_nr, TRUE);
242 }
243
244 void DrawInitTextIfNeeded(char *text, int ypos, int font_nr)
245 {
246   DrawInitTextExt(text, ypos, font_nr, FALSE);
247 }
248
249 void DrawTextF(int x, int y, int font_nr, char *format, ...)
250 {
251   char buffer[MAX_OUTPUT_LINESIZE + 1];
252   va_list ap;
253
254   va_start(ap, format);
255   vsprintf(buffer, format, ap);
256   va_end(ap);
257
258   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
259     Error(ERR_EXIT, "string too long in DrawTextF() -- aborting");
260
261   DrawText(gfx.sx + x, gfx.sy + y, buffer, font_nr);
262 }
263
264 void DrawTextFCentered(int y, int font_nr, char *format, ...)
265 {
266   char buffer[MAX_OUTPUT_LINESIZE + 1];
267   va_list ap;
268
269   va_start(ap, format);
270   vsprintf(buffer, format, ap);
271   va_end(ap);
272
273   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
274     Error(ERR_EXIT, "string too long in DrawTextFCentered() -- aborting");
275
276   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(buffer, font_nr)) / 2,
277            gfx.sy + y, buffer, font_nr);
278 }
279
280 void DrawTextS(int x, int y, int font_nr, char *text)
281 {
282   DrawText(gfx.sx + x, gfx.sy + y, text, font_nr);
283 }
284
285 void DrawTextSCentered(int y, int font_nr, char *text)
286 {
287   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(text, font_nr)) / 2,
288            gfx.sy + y, text, font_nr);
289 }
290
291 void DrawTextCentered(int y, int font_nr, char *text)
292 {
293   DrawText((gfx.sxsize - getTextWidth(text, font_nr)) / 2, y, text, font_nr);
294 }
295
296 void DrawTextSAligned(int x, int y, char *text, int font_nr, int align)
297 {
298   DrawText(gfx.sx + ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
299            gfx.sx + y, text, font_nr);
300 }
301
302 void DrawTextAligned(int x, int y, char *text, int font_nr, int align)
303 {
304   DrawText(ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
305            y, text, font_nr);
306 }
307
308 void DrawText(int x, int y, char *text, int font_nr)
309 {
310   int mask_mode = BLIT_OPAQUE;
311
312   if (DrawingOnBackground(x, y))
313     mask_mode = BLIT_ON_BACKGROUND;
314
315   DrawTextExt(drawto, x, y, text, font_nr, mask_mode);
316
317   if (x < gfx.dx)
318     redraw_mask |= REDRAW_FIELD;
319   else if (y < gfx.vy || gfx.vy == 0)
320     redraw_mask |= REDRAW_DOOR_1;
321 }
322
323 void DrawTextExt(DrawBuffer *dst_bitmap, int dst_x, int dst_y, char *text,
324                  int font_nr, int mask_mode)
325 {
326 #if 1
327   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
328 #else
329   int font_bitmap_id = gfx.select_font_function(font_nr);
330   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
331 #endif
332   int font_width = getFontWidth(font_nr);
333   int font_height = getFontHeight(font_nr);
334 #if 0
335   int border_1 = gfx.sx + gfx.sxsize;
336   int border_2 = gfx.dx + gfx.dxsize;
337   int dst_x_start = dst_x;
338 #endif
339   Bitmap *src_bitmap;
340   int src_x, src_y;
341   char *text_ptr = text;
342
343   if (font->bitmap == NULL)
344     return;
345
346   /* skip text to be printed outside the window (left/right will be clipped) */
347   if (dst_y < 0 || dst_y + font_height > video.height)
348     return;
349
350   /* add offset for drawing font characters */
351   dst_x += font->draw_xoffset;
352   dst_y += font->draw_yoffset;
353
354   while (*text_ptr)
355   {
356     char c = *text_ptr++;
357
358     if (c == '\n')
359       c = ' ';          /* print space instead of newline */
360
361     getFontCharSource(font_nr, c, &src_bitmap, &src_x, &src_y);
362
363     /* clip text at the left side of the window */
364     if (dst_x < 0)
365     {
366       dst_x += font_width;
367
368       continue;
369     }
370
371     /* clip text at the right side of the window */
372 #if 1
373     if (dst_x + font_width > video.width)
374       break;
375 #else
376     /* (this does not work well when trying to print text to whole screen) */
377     if ((dst_x_start < border_1 && dst_x + font_width > border_1) ||
378         (dst_x_start < border_2 && dst_x + font_width > border_2))
379       break;
380 #endif
381
382     if (mask_mode == BLIT_INVERSE)      /* special mode for text gadgets */
383     {
384       /* first step: draw solid colored rectangle (use "cursor" character) */
385       if (strlen(text) == 1)    /* only one char inverted => draw cursor */
386       {
387         Bitmap *cursor_bitmap;
388         int cursor_x, cursor_y;
389
390         getFontCharSource(font_nr, FONT_ASCII_CURSOR, &cursor_bitmap,
391                           &cursor_x, &cursor_y);
392
393         BlitBitmap(cursor_bitmap, dst_bitmap, cursor_x, cursor_y,
394                    font_width, font_height, dst_x, dst_y);
395       }
396
397 #if defined(TARGET_SDL)
398       /* second step: draw masked inverted character */
399       SDLCopyInverseMasked(src_bitmap, dst_bitmap, src_x, src_y,
400                            font_width, font_height, dst_x, dst_y);
401 #else
402       /* second step: draw masked black rectangle (use "space" character) */
403       SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
404                     dst_x - src_x, dst_y - src_y);
405       BlitBitmapMasked(src_bitmap, dst_bitmap, 0, 0,
406                        font_width, font_height, dst_x, dst_y);
407 #endif
408     }
409     else if (mask_mode == BLIT_MASKED || mask_mode == BLIT_ON_BACKGROUND)
410     {
411       if (mask_mode == BLIT_ON_BACKGROUND)
412       {
413         /* clear font character background */
414         ClearRectangleOnBackground(dst_bitmap, dst_x, dst_y,
415                                    font_width, font_height);
416       }
417
418 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
419       /* use special font tile clipmasks */
420       {
421         int font_pos = getFontCharPosition(font_nr, c);
422
423         SetClipMask(src_bitmap, font_clip_gc, font->clip_mask[font_pos]);
424         SetClipOrigin(src_bitmap, font_clip_gc, dst_x, dst_y);
425       }
426 #else
427       SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
428                     dst_x - src_x, dst_y - src_y);
429 #endif
430
431       BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y,
432                        font_width, font_height, dst_x, dst_y);
433     }
434     else        /* normal, non-masked font blitting */
435     {
436       BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y,
437                  font_width, font_height, dst_x, dst_y);
438     }
439
440     dst_x += font_width;
441   }
442 }
443
444
445 /* ========================================================================= */
446 /* text buffer drawing functions                                             */
447 /* ========================================================================= */
448
449 #define MAX_LINES_FROM_FILE             1024
450
451 #if 1
452
453 char *GetTextBufferFromFile(char *filename, int max_lines)
454 {
455   File *file;
456   char *buffer;
457   int num_lines = 0;
458
459   if (filename == NULL)
460     return NULL;
461
462   if (!(file = openFile(filename, MODE_READ)))
463     return NULL;
464
465   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
466
467   while (!checkEndOfFile(file) && num_lines < max_lines)
468   {
469     char line[MAX_LINE_LEN];
470
471     /* read next line of input file */
472     if (!getStringFromFile(file, line, MAX_LINE_LEN))
473       break;
474
475     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
476
477     strcat(buffer, line);
478
479     num_lines++;
480   }
481
482   closeFile(file);
483
484   return buffer;
485 }
486
487 #else
488
489 char *GetTextBufferFromFile(char *filename, int max_lines)
490 {
491   FILE *file;
492   char *buffer;
493   int num_lines = 0;
494
495   if (filename == NULL)
496     return NULL;
497
498   if (!(file = fopen(filename, MODE_READ)))
499     return NULL;
500
501   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
502
503   while (!feof(file) && num_lines < max_lines)
504   {
505     char line[MAX_LINE_LEN];
506
507     /* read next line of input file */
508     if (!fgets(line, MAX_LINE_LEN, file))
509       break;
510
511     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
512
513     strcat(buffer, line);
514
515     num_lines++;
516   }
517
518   fclose(file);
519
520   return buffer;
521 }
522
523 #endif
524
525 void DrawTextToTextArea_OLD(int x, int y, char *text, int font_nr, int line_length,
526                             int area_xsize, int area_ysize, int mask_mode)
527 {
528   int area_line = 0;
529   int font_height = getFontHeight(font_nr);
530
531   if (text == NULL)
532     return;
533
534   while (*text && area_line < area_ysize)
535   {
536     char buffer[MAX_OUTPUT_LINESIZE + 1];
537     int i;
538
539     for (i = 0; i < line_length && *text; i++)
540       if ((buffer[i] = *text++) == '\n')
541         break;
542     buffer[MIN(i, area_xsize)] = '\0';
543
544     DrawTextExt(drawto, x, y + area_line * font_height, buffer, font_nr,
545                 mask_mode);
546
547     area_line++;
548   }
549
550   redraw_mask |= REDRAW_FIELD;
551 }
552
553 static boolean RenderLineToBuffer(char **src_buffer_ptr, char *dst_buffer,
554                                   int *dst_buffer_len, int line_length,
555                                   boolean last_line_was_empty)
556 {
557   char *text_ptr = *src_buffer_ptr;
558   char *buffer = dst_buffer;
559   int buffer_len = *dst_buffer_len;
560   boolean buffer_filled = FALSE;
561
562   while (*text_ptr)
563   {
564     char *word_ptr;
565     int word_len;
566
567     /* skip leading whitespaces */
568     while (*text_ptr == ' ' || *text_ptr == '\t')
569       text_ptr++;
570
571     word_ptr = text_ptr;
572     word_len = 0;
573
574     /* look for end of next word */
575     while (*word_ptr != ' ' && *word_ptr != '\t' && *word_ptr != '\0')
576     {
577       word_ptr++;
578       word_len++;
579     }
580
581     if (word_len == 0)
582     {
583       continue;
584     }
585     else if (*text_ptr == '\n')         /* special case: force empty line */
586     {
587       if (buffer_len == 0)
588         text_ptr++;
589
590       /* prevent printing of multiple empty lines */
591       if (buffer_len > 0 || !last_line_was_empty)
592         buffer_filled = TRUE;
593     }
594     else if (word_len < line_length - buffer_len)
595     {
596       /* word fits into text buffer -- add word */
597
598       if (buffer_len > 0)
599         buffer[buffer_len++] = ' ';
600
601       strncpy(&buffer[buffer_len], text_ptr, word_len);
602       buffer_len += word_len;
603       buffer[buffer_len] = '\0';
604       text_ptr += word_len;
605     }
606     else if (buffer_len > 0)
607     {
608       /* not enough space left for word in text buffer -- print buffer */
609
610       buffer_filled = TRUE;
611     }
612     else
613     {
614       /* word does not fit at all into empty text buffer -- cut word */
615
616       strncpy(buffer, text_ptr, line_length);
617       buffer[line_length] = '\0';
618       text_ptr += line_length;
619       buffer_filled = TRUE;
620     }
621
622     if (buffer_filled)
623       break;
624   }
625
626   *src_buffer_ptr = text_ptr;
627   *dst_buffer_len = buffer_len;
628
629   return buffer_filled;
630 }
631
632 #if 0
633 void DrawTextWrapped_OLD(int x, int y, char *text, int font_nr, int line_length,
634                          int max_lines)
635 {
636   char *text_ptr = text;
637   int current_line = 0;
638   int font_height = getFontHeight(font_nr);
639
640   while (*text_ptr && current_line < max_lines)
641   {
642     char buffer[line_length + 1];
643     int buffer_len = 0;
644
645     buffer[0] = '\0';
646
647     RenderLineToBuffer(&text_ptr, buffer, &buffer_len, line_length, TRUE);
648
649     DrawText(x, y + current_line * font_height, buffer, font_nr);
650     current_line++;
651   }
652 }
653 #endif
654
655 #if 0
656 int DrawTextFromFile_OLD(int x, int y, char *filename, int font_nr,
657                          int line_length, int max_lines, boolean wrap_text)
658 {
659   int font_height = getFontHeight(font_nr);
660   char line[MAX_LINE_LEN];
661   char buffer[line_length + 1];
662   int buffer_len;
663   int current_line = 0;
664   FILE *file;
665
666   if (current_line >= max_lines)
667     return 0;
668
669   if (filename == NULL)
670     return 0;
671
672   if (!(file = fopen(filename, MODE_READ)))
673     return 0;
674
675   buffer[0] = '\0';
676   buffer_len = 0;
677
678   while (!feof(file) && current_line < max_lines)
679   {
680     char *line_ptr;
681     boolean last_line_was_empty = TRUE;
682
683     /* read next line of input file */
684     if (!fgets(line, MAX_LINE_LEN, file))
685       break;
686
687     /* skip comments (lines directly beginning with '#') */
688     if (line[0] == '#')
689       continue;
690
691     /* cut trailing newline from input line */
692     for (line_ptr = line; *line_ptr; line_ptr++)
693     {
694       if (*line_ptr == '\n' || *line_ptr == '\r')
695       {
696         *line_ptr = '\0';
697         break;
698       }
699     }
700
701     if (strlen(line) == 0)              /* special case: force empty line */
702       strcpy(line, "\n");
703
704     line_ptr = line;
705
706     while (*line_ptr && current_line < max_lines)
707     {
708 #if 1
709       boolean buffer_filled;
710
711       if (wrap_text)
712       {
713         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
714                                            line_length, last_line_was_empty);
715       }
716       else
717       {
718         if (strlen(line_ptr) <= line_length)
719         {
720           buffer_len = strlen(line_ptr);
721           strcpy(buffer, line_ptr);
722         }
723         else
724         {
725           buffer_len = line_length;
726           strncpy(buffer, line_ptr, line_length);
727         }
728
729         buffer[buffer_len] = '\0';
730         line_ptr += buffer_len;
731
732         buffer_filled = TRUE;
733       }
734 #else
735       boolean buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
736                                                  line_length, last_line_was_empty);
737 #endif
738
739       if (buffer_filled)
740       {
741         DrawText(x, y + current_line * font_height, buffer, font_nr);
742         current_line++;
743
744         last_line_was_empty = (buffer_len == 0);
745
746         buffer[0] = '\0';
747         buffer_len = 0;
748       }
749     }
750   }
751
752   fclose(file);
753
754   if (buffer_len > 0 && current_line < max_lines)
755   {
756     DrawText(x, y + current_line * font_height, buffer, font_nr);
757     current_line++;
758   }
759
760   return current_line;
761 }
762 #endif
763
764 static boolean getCheckedTokenValueFromString(char *string, char **token,
765                                               char **value)
766 {
767   char *ptr;
768
769   if (!getTokenValueFromString(string, token, value))
770     return FALSE;
771
772   if (**token != '.')                   /* token should begin with dot */
773     return FALSE;
774
775   for (ptr = *token; *ptr; ptr++)       /* token should contain no whitespace */
776     if (*ptr == ' ' || *ptr == '\t')
777       return FALSE;
778
779   for (ptr = *value; *ptr; ptr++)       /* value should contain no whitespace */
780     if (*ptr == ' ' || *ptr == '\t')
781       return FALSE;
782
783   return TRUE;
784 }
785
786 static void DrawTextBuffer_Flush(int x, int y, char *buffer, int font_nr,
787                                  int line_length, int cut_length,
788                                  int line_spacing, int mask_mode,
789                                  boolean centered, int current_line)
790 {
791   int buffer_len = strlen(buffer);
792   int font_width = getFontWidth(font_nr);
793   int font_height = getFontHeight(font_nr);
794   int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
795   int offset_xsize =
796     (centered ? font_width * (line_length - buffer_len) / 2 : 0);
797   int final_cut_length = MAX(0, cut_length - offset_chars);
798   int xx = x + offset_xsize;
799   int yy = y + current_line * (font_height + line_spacing);
800
801   buffer[final_cut_length] = '\0';
802
803   if (mask_mode != -1)
804     DrawTextExt(drawto, xx, yy, buffer, font_nr, mask_mode);
805   else
806     DrawText(xx, yy, buffer, font_nr);
807 }
808
809 int DrawTextBuffer(int x, int y, char *text_buffer, int font_nr,
810                    int line_length, int cut_length, int max_lines,
811                    int line_spacing, int mask_mode, boolean autowrap,
812                    boolean centered, boolean parse_comments)
813 {
814 #if 0
815   int font_width = getFontWidth(font_nr);
816   int font_height = getFontHeight(font_nr);
817 #endif
818   char buffer[line_length + 1];
819   int buffer_len;
820   int current_line = 0;
821
822   if (text_buffer == NULL || *text_buffer == '\0')
823     return 0;
824
825   if (current_line >= max_lines)
826     return 0;
827
828   if (cut_length == -1)
829     cut_length = line_length;
830
831   buffer[0] = '\0';
832   buffer_len = 0;
833
834   while (*text_buffer && current_line < max_lines)
835   {
836     char line[MAX_LINE_LEN + 1];
837     char *line_ptr;
838     boolean last_line_was_empty = TRUE;
839 #if 1
840     int num_line_chars = MAX_LINE_LEN;
841 #else
842     int num_line_chars = (autowrap ? MAX_LINE_LEN : line_length);
843 #endif
844     int i;
845
846     /* copy next line from text buffer to line buffer (nearly fgets() style) */
847     for (i = 0; i < num_line_chars && *text_buffer; i++)
848       if ((line[i] = *text_buffer++) == '\n')
849         break;
850     line[i] = '\0';
851
852     /* prevent 'num_line_chars' sized lines to cause additional empty line */
853     if (i == num_line_chars && *text_buffer == '\n')
854       text_buffer++;
855
856     /* skip comments (lines directly beginning with '#') */
857     if (line[0] == '#' && parse_comments)
858     {
859       char *token, *value;
860
861       /* try to read generic token/value pair definition after comment sign */
862       if (getCheckedTokenValueFromString(line + 1, &token, &value))
863       {
864         /* if found, flush the current buffer, if non-empty */
865         if (buffer_len > 0 && current_line < max_lines)
866         {
867           DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
868                                line_spacing, mask_mode, centered, current_line);
869
870           current_line++;
871
872           buffer[0] = '\0';
873           buffer_len = 0;
874         }
875
876         if (strEqual(token, ".font"))
877           font_nr = gfx.get_font_from_token_function(value);
878         else if (strEqual(token, ".autowrap"))
879           autowrap = get_boolean_from_string(value);
880         else if (strEqual(token, ".centered"))
881           centered = get_boolean_from_string(value);
882         else if (strEqual(token, ".parse_comments"))
883           parse_comments = get_boolean_from_string(value);
884       }
885
886       continue;
887     }
888
889     /* cut trailing newline and carriage return from input line */
890     for (line_ptr = line; *line_ptr; line_ptr++)
891     {
892       if (*line_ptr == '\n' || *line_ptr == '\r')
893       {
894         *line_ptr = '\0';
895         break;
896       }
897     }
898
899     if (strlen(line) == 0)              /* special case: force empty line */
900       strcpy(line, "\n");
901
902     line_ptr = line;
903
904     while (*line_ptr && current_line < max_lines)
905     {
906       boolean buffer_filled;
907
908       if (autowrap)
909       {
910         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
911                                            line_length, last_line_was_empty);
912       }
913       else
914       {
915         if (strlen(line_ptr) <= line_length)
916         {
917           buffer_len = strlen(line_ptr);
918           strcpy(buffer, line_ptr);
919         }
920         else
921         {
922           buffer_len = line_length;
923           strncpy(buffer, line_ptr, line_length);
924         }
925
926         buffer[buffer_len] = '\0';
927         line_ptr += buffer_len;
928
929         buffer_filled = TRUE;
930       }
931
932       if (buffer_filled)
933       {
934 #if 1
935         DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
936                              line_spacing, mask_mode, centered, current_line);
937 #else
938         int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
939         int offset_xsize =
940           (centered ?  font_width * (line_length - buffer_len) / 2 : 0);
941         int final_cut_length = MAX(0, cut_length - offset_chars);
942         int xx = x + offset_xsize;
943
944         buffer[final_cut_length] = '\0';
945
946         if (mask_mode != -1)
947           DrawTextExt(drawto, xx, y + current_line * font_height, buffer,
948                       font_nr, mask_mode);
949         else
950           DrawText(xx, y + current_line * font_height, buffer, font_nr);
951 #endif
952
953         current_line++;
954
955         last_line_was_empty = (buffer_len == 0);
956
957         buffer[0] = '\0';
958         buffer_len = 0;
959       }
960     }
961   }
962
963   if (buffer_len > 0 && current_line < max_lines)
964   {
965 #if 1
966     DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
967                          line_spacing, mask_mode, centered, current_line);
968 #else
969     int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
970         int offset_xsize =
971           (centered ?  font_width * (line_length - buffer_len) / 2 : 0);
972     int final_cut_length = MAX(0, cut_length - offset_chars);
973     int xx = x + offset_xsize;
974
975     buffer[final_cut_length] = '\0';
976
977     if (mask_mode != -1)
978       DrawTextExt(drawto, xx, y + current_line * font_height, buffer,
979                   font_nr, mask_mode);
980     else
981       DrawText(xx, y + current_line * font_height, buffer, font_nr);
982 #endif
983
984     current_line++;
985   }
986
987   return current_line;
988 }
989
990 int DrawTextBufferVA(int x, int y, char *format, va_list ap, int font_nr,
991                      int line_length, int cut_length, int max_lines,
992                      int line_spacing, int mask_mode, boolean autowrap,
993                      boolean centered, boolean parse_comments)
994 {
995   char text_buffer[MAX_OUTPUT_LINESIZE];
996   int text_length = vsnprintf(text_buffer, MAX_OUTPUT_LINESIZE, format, ap);
997
998   if (text_length >= MAX_OUTPUT_LINESIZE)
999     Error(ERR_WARN, "string too long in DrawTextBufferVA() -- truncated");
1000
1001   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
1002                                          line_length, cut_length, max_lines,
1003                                          line_spacing, mask_mode, autowrap,
1004                                          centered, parse_comments);
1005   return num_lines_printed;
1006 }
1007
1008 int DrawTextFile(int x, int y, char *filename, int font_nr,
1009                  int line_length, int cut_length, int max_lines,
1010                  int line_spacing, int mask_mode, boolean autowrap,
1011                  boolean centered, boolean parse_comments)
1012 {
1013   char *text_buffer = GetTextBufferFromFile(filename, MAX_LINES_FROM_FILE);
1014   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
1015                                          line_length, cut_length, max_lines,
1016                                          line_spacing, mask_mode, autowrap,
1017                                          centered, parse_comments);
1018   checked_free(text_buffer);
1019
1020   return num_lines_printed;
1021 }
1022
1023 #if 0
1024 void DrawTextWrapped(int x, int y, char *text, int font_nr, int line_length,
1025                      int max_lines)
1026 {
1027   DrawTextBuffer(x, y, text, font_nr, line_length, -1, max_lines, -1, TRUE,
1028                  FALSE, FALSE);
1029 }
1030
1031 void DrawTextToTextArea(int x, int y, char *text, int font_nr, int line_length,
1032                         int cut_length, int max_lines, int mask_mode)
1033 {
1034   DrawTextBuffer(x, y, text, font_nr, line_length, cut_length, max_lines,
1035                  mask_mode, FALSE, FALSE, FALSE);
1036 }
1037 #endif