rnd-20140213-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 word_len = 0, max_word_len = 0;
199
200   for (text_ptr = text; *text_ptr; text_ptr++)
201   {
202     word_len = (*text_ptr != ' ' ? word_len + 1 : 0);
203
204     max_word_len = MAX(word_len, max_word_len);
205   }
206
207   return max_word_len;
208 }
209
210
211 /* ========================================================================= */
212 /* simple text drawing functions                                             */
213 /* ========================================================================= */
214
215 void DrawInitTextExt(char *text, int ypos, int font_nr, boolean force)
216 {
217 #if 1
218 #if 0
219   static unsigned int progress_delay = 0;
220   unsigned int progress_delay_value = 100;      /* (in milliseconds) */
221 #endif
222
223   // LimitScreenUpdates(TRUE);  // (ignore "force" for now)
224   // LimitScreenUpdates(!force);
225   LimitScreenUpdates(TRUE);
226
227   UPDATE_BUSY_STATE();
228
229 #if 0
230   if (!force && !DelayReached(&progress_delay, progress_delay_value))
231     return;
232 #endif
233
234   if (window != NULL &&
235       gfx.draw_init_text &&
236       gfx.num_fonts > 0 &&
237       gfx.font_bitmap_info[font_nr].bitmap != NULL)
238   {
239     int x = (video.width - getTextWidth(text, font_nr)) / 2;
240     int y = ypos;
241     int width = video.width;
242     int height = getFontHeight(font_nr);
243
244     ClearRectangle(drawto, 0, y, width, height);
245     DrawTextExt(drawto, x, y, text, font_nr, BLIT_OPAQUE);
246
247     BlitBitmap(drawto, window, 0, 0, video.width, video.height, 0, 0);
248   }
249 #else
250   static unsigned int progress_delay = 0;
251   unsigned int progress_delay_value = 100;      /* (in milliseconds) */
252
253   // LimitScreenUpdates(TRUE);  // (ignore "force" for now)
254   LimitScreenUpdates(!force);
255
256   UPDATE_BUSY_STATE();
257
258   if (!force && !DelayReached(&progress_delay, progress_delay_value))
259     return;
260
261   if (window != NULL &&
262       gfx.draw_init_text &&
263       gfx.num_fonts > 0 &&
264       gfx.font_bitmap_info[font_nr].bitmap != NULL)
265   {
266     int x = (video.width - getTextWidth(text, font_nr)) / 2;
267     int y = ypos;
268     int width = video.width;
269     int height = getFontHeight(font_nr);
270
271     ClearRectangle(drawto, 0, y, width, height);
272     DrawTextExt(drawto, x, y, text, font_nr, BLIT_OPAQUE);
273
274     /* this makes things significantly faster than directly drawing to window */
275     BlitBitmap(drawto, window, 0, y, width, height, 0, y);
276   }
277 #endif
278 }
279
280 void DrawInitText(char *text, int ypos, int font_nr)
281 {
282   // DrawInitTextExt(text, ypos, font_nr, TRUE);
283   DrawInitTextExt(text, ypos, font_nr, FALSE);
284 }
285
286 void DrawInitTextAlways(char *text, int ypos, int font_nr)
287 {
288   DrawInitTextExt(text, ypos, font_nr, TRUE);
289 }
290
291 void DrawInitTextIfNeeded(char *text, int ypos, int font_nr)
292 {
293   DrawInitTextExt(text, ypos, font_nr, FALSE);
294 }
295
296 void DrawTextF(int x, int y, int font_nr, char *format, ...)
297 {
298   char buffer[MAX_OUTPUT_LINESIZE + 1];
299   va_list ap;
300
301   va_start(ap, format);
302   vsprintf(buffer, format, ap);
303   va_end(ap);
304
305   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
306     Error(ERR_EXIT, "string too long in DrawTextF() -- aborting");
307
308   DrawText(gfx.sx + x, gfx.sy + y, buffer, font_nr);
309 }
310
311 void DrawTextFCentered(int y, int font_nr, char *format, ...)
312 {
313   char buffer[MAX_OUTPUT_LINESIZE + 1];
314   va_list ap;
315
316   va_start(ap, format);
317   vsprintf(buffer, format, ap);
318   va_end(ap);
319
320   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
321     Error(ERR_EXIT, "string too long in DrawTextFCentered() -- aborting");
322
323   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(buffer, font_nr)) / 2,
324            gfx.sy + y, buffer, font_nr);
325 }
326
327 void DrawTextS(int x, int y, int font_nr, char *text)
328 {
329   DrawText(gfx.sx + x, gfx.sy + y, text, font_nr);
330 }
331
332 void DrawTextSCentered(int y, int font_nr, char *text)
333 {
334   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(text, font_nr)) / 2,
335            gfx.sy + y, text, font_nr);
336 }
337
338 void DrawTextCentered(int y, int font_nr, char *text)
339 {
340   DrawText((gfx.sxsize - getTextWidth(text, font_nr)) / 2, y, text, font_nr);
341 }
342
343 void DrawTextSAligned(int x, int y, char *text, int font_nr, int align)
344 {
345   DrawText(gfx.sx + ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
346            gfx.sx + y, text, font_nr);
347 }
348
349 void DrawTextAligned(int x, int y, char *text, int font_nr, int align)
350 {
351   DrawText(ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
352            y, text, font_nr);
353 }
354
355 void DrawText(int x, int y, char *text, int font_nr)
356 {
357   int mask_mode = BLIT_OPAQUE;
358
359   if (DrawingOnBackground(x, y))
360     mask_mode = BLIT_ON_BACKGROUND;
361
362   DrawTextExt(drawto, x, y, text, font_nr, mask_mode);
363
364 #if 1
365   if (IN_GFX_FIELD_FULL(x, y))
366     redraw_mask |= REDRAW_FIELD;
367   else if (IN_GFX_DOOR_1(x, y))
368     redraw_mask |= REDRAW_DOOR_1;
369   else if (IN_GFX_DOOR_2(x, y))
370     redraw_mask |= REDRAW_DOOR_2;
371   else if (IN_GFX_DOOR_3(x, y))
372     redraw_mask |= REDRAW_DOOR_3;
373   else
374     redraw_mask |= REDRAW_ALL;
375 #else
376   if (x < gfx.dx)
377     redraw_mask |= REDRAW_FIELD;
378   else if (y < gfx.vy || gfx.vy == 0)
379     redraw_mask |= REDRAW_DOOR_1;
380 #endif
381 }
382
383 void DrawTextExt(DrawBuffer *dst_bitmap, int dst_x, int dst_y, char *text,
384                  int font_nr, int mask_mode)
385 {
386 #if 1
387   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
388 #else
389   int font_bitmap_id = gfx.select_font_function(font_nr);
390   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
391 #endif
392   int font_width = getFontWidth(font_nr);
393   int font_height = getFontHeight(font_nr);
394 #if 0
395   int border_1 = gfx.sx + gfx.sxsize;
396   int border_2 = gfx.dx + gfx.dxsize;
397   int dst_x_start = dst_x;
398 #endif
399   Bitmap *src_bitmap;
400   int src_x, src_y;
401   char *text_ptr = text;
402
403   if (font->bitmap == NULL)
404     return;
405
406   /* skip text to be printed outside the window (left/right will be clipped) */
407   if (dst_y < 0 || dst_y + font_height > video.height)
408     return;
409
410   /* add offset for drawing font characters */
411   dst_x += font->draw_xoffset;
412   dst_y += font->draw_yoffset;
413
414   while (*text_ptr)
415   {
416     char c = *text_ptr++;
417
418     if (c == '\n')
419       c = ' ';          /* print space instead of newline */
420
421     getFontCharSource(font_nr, c, &src_bitmap, &src_x, &src_y);
422
423     /* clip text at the left side of the window */
424     if (dst_x < 0)
425     {
426       dst_x += font_width;
427
428       continue;
429     }
430
431     /* clip text at the right side of the window */
432 #if 1
433     if (dst_x + font_width > video.width)
434       break;
435 #else
436     /* (this does not work well when trying to print text to whole screen) */
437     if ((dst_x_start < border_1 && dst_x + font_width > border_1) ||
438         (dst_x_start < border_2 && dst_x + font_width > border_2))
439       break;
440 #endif
441
442     if (mask_mode == BLIT_INVERSE)      /* special mode for text gadgets */
443     {
444       /* first step: draw solid colored rectangle (use "cursor" character) */
445       if (strlen(text) == 1)    /* only one char inverted => draw cursor */
446       {
447         Bitmap *cursor_bitmap;
448         int cursor_x, cursor_y;
449
450         getFontCharSource(font_nr, FONT_ASCII_CURSOR, &cursor_bitmap,
451                           &cursor_x, &cursor_y);
452
453         BlitBitmap(cursor_bitmap, dst_bitmap, cursor_x, cursor_y,
454                    font_width, font_height, dst_x, dst_y);
455       }
456
457 #if defined(TARGET_SDL)
458       /* second step: draw masked inverted character */
459       SDLCopyInverseMasked(src_bitmap, dst_bitmap, src_x, src_y,
460                            font_width, font_height, dst_x, dst_y);
461 #else
462       /* second step: draw masked black rectangle (use "space" character) */
463       SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
464                     dst_x - src_x, dst_y - src_y);
465       BlitBitmapMasked(src_bitmap, dst_bitmap, 0, 0,
466                        font_width, font_height, dst_x, dst_y);
467 #endif
468     }
469     else if (mask_mode == BLIT_MASKED || mask_mode == BLIT_ON_BACKGROUND)
470     {
471       if (mask_mode == BLIT_ON_BACKGROUND)
472       {
473         /* clear font character background */
474         ClearRectangleOnBackground(dst_bitmap, dst_x, dst_y,
475                                    font_width, font_height);
476       }
477
478 #if defined(TARGET_X11_NATIVE_PERFORMANCE_WORKAROUND)
479       /* use special font tile clipmasks */
480       {
481         int font_pos = getFontCharPosition(font_nr, c);
482
483         SetClipMask(src_bitmap, font_clip_gc, font->clip_mask[font_pos]);
484         SetClipOrigin(src_bitmap, font_clip_gc, dst_x, dst_y);
485       }
486 #else
487       SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
488                     dst_x - src_x, dst_y - src_y);
489 #endif
490
491       BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y,
492                        font_width, font_height, dst_x, dst_y);
493     }
494     else        /* normal, non-masked font blitting */
495     {
496       BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y,
497                  font_width, font_height, dst_x, dst_y);
498     }
499
500     dst_x += font_width;
501   }
502 }
503
504
505 /* ========================================================================= */
506 /* text buffer drawing functions                                             */
507 /* ========================================================================= */
508
509 #define MAX_LINES_FROM_FILE             1024
510
511 #if 1
512
513 char *GetTextBufferFromFile(char *filename, int max_lines)
514 {
515   File *file;
516   char *buffer;
517   int num_lines = 0;
518
519   if (filename == NULL)
520     return NULL;
521
522   if (!(file = openFile(filename, MODE_READ)))
523     return NULL;
524
525   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
526
527   while (!checkEndOfFile(file) && num_lines < max_lines)
528   {
529     char line[MAX_LINE_LEN];
530
531     /* read next line of input file */
532     if (!getStringFromFile(file, line, MAX_LINE_LEN))
533       break;
534
535     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
536
537     strcat(buffer, line);
538
539     num_lines++;
540   }
541
542   closeFile(file);
543
544   return buffer;
545 }
546
547 #else
548
549 char *GetTextBufferFromFile(char *filename, int max_lines)
550 {
551   FILE *file;
552   char *buffer;
553   int num_lines = 0;
554
555   if (filename == NULL)
556     return NULL;
557
558   if (!(file = fopen(filename, MODE_READ)))
559     return NULL;
560
561   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
562
563   while (!feof(file) && num_lines < max_lines)
564   {
565     char line[MAX_LINE_LEN];
566
567     /* read next line of input file */
568     if (!fgets(line, MAX_LINE_LEN, file))
569       break;
570
571     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
572
573     strcat(buffer, line);
574
575     num_lines++;
576   }
577
578   fclose(file);
579
580   return buffer;
581 }
582
583 #endif
584
585 void DrawTextToTextArea_OLD(int x, int y, char *text, int font_nr, int line_length,
586                             int area_xsize, int area_ysize, int mask_mode)
587 {
588   int area_line = 0;
589   int font_height = getFontHeight(font_nr);
590
591   if (text == NULL)
592     return;
593
594   while (*text && area_line < area_ysize)
595   {
596     char buffer[MAX_OUTPUT_LINESIZE + 1];
597     int i;
598
599     for (i = 0; i < line_length && *text; i++)
600       if ((buffer[i] = *text++) == '\n')
601         break;
602     buffer[MIN(i, area_xsize)] = '\0';
603
604     DrawTextExt(drawto, x, y + area_line * font_height, buffer, font_nr,
605                 mask_mode);
606
607     area_line++;
608   }
609
610   redraw_mask |= REDRAW_FIELD;
611 }
612
613 static boolean RenderLineToBuffer(char **src_buffer_ptr, char *dst_buffer,
614                                   int *dst_buffer_len, int line_length,
615                                   boolean last_line_was_empty)
616 {
617   char *text_ptr = *src_buffer_ptr;
618   char *buffer = dst_buffer;
619   int buffer_len = *dst_buffer_len;
620   boolean buffer_filled = FALSE;
621
622   while (*text_ptr)
623   {
624     char *word_ptr;
625     int word_len;
626
627     /* skip leading whitespaces */
628     while (*text_ptr == ' ' || *text_ptr == '\t')
629       text_ptr++;
630
631     word_ptr = text_ptr;
632     word_len = 0;
633
634     /* look for end of next word */
635     while (*word_ptr != ' ' && *word_ptr != '\t' && *word_ptr != '\0')
636     {
637       word_ptr++;
638       word_len++;
639     }
640
641     if (word_len == 0)
642     {
643       continue;
644     }
645     else if (*text_ptr == '\n')         /* special case: force empty line */
646     {
647       if (buffer_len == 0)
648         text_ptr++;
649
650       /* prevent printing of multiple empty lines */
651       if (buffer_len > 0 || !last_line_was_empty)
652         buffer_filled = TRUE;
653     }
654     else if (word_len < line_length - buffer_len)
655     {
656       /* word fits into text buffer -- add word */
657
658       if (buffer_len > 0)
659         buffer[buffer_len++] = ' ';
660
661       strncpy(&buffer[buffer_len], text_ptr, word_len);
662       buffer_len += word_len;
663       buffer[buffer_len] = '\0';
664       text_ptr += word_len;
665     }
666     else if (buffer_len > 0)
667     {
668       /* not enough space left for word in text buffer -- print buffer */
669
670       buffer_filled = TRUE;
671     }
672     else
673     {
674       /* word does not fit at all into empty text buffer -- cut word */
675
676       strncpy(buffer, text_ptr, line_length);
677       buffer[line_length] = '\0';
678       text_ptr += line_length;
679       buffer_filled = TRUE;
680     }
681
682     if (buffer_filled)
683       break;
684   }
685
686   *src_buffer_ptr = text_ptr;
687   *dst_buffer_len = buffer_len;
688
689   return buffer_filled;
690 }
691
692 #if 0
693 void DrawTextWrapped_OLD(int x, int y, char *text, int font_nr, int line_length,
694                          int max_lines)
695 {
696   char *text_ptr = text;
697   int current_line = 0;
698   int font_height = getFontHeight(font_nr);
699
700   while (*text_ptr && current_line < max_lines)
701   {
702     char buffer[line_length + 1];
703     int buffer_len = 0;
704
705     buffer[0] = '\0';
706
707     RenderLineToBuffer(&text_ptr, buffer, &buffer_len, line_length, TRUE);
708
709     DrawText(x, y + current_line * font_height, buffer, font_nr);
710     current_line++;
711   }
712 }
713 #endif
714
715 #if 0
716 int DrawTextFromFile_OLD(int x, int y, char *filename, int font_nr,
717                          int line_length, int max_lines, boolean wrap_text)
718 {
719   int font_height = getFontHeight(font_nr);
720   char line[MAX_LINE_LEN];
721   char buffer[line_length + 1];
722   int buffer_len;
723   int current_line = 0;
724   FILE *file;
725
726   if (current_line >= max_lines)
727     return 0;
728
729   if (filename == NULL)
730     return 0;
731
732   if (!(file = fopen(filename, MODE_READ)))
733     return 0;
734
735   buffer[0] = '\0';
736   buffer_len = 0;
737
738   while (!feof(file) && current_line < max_lines)
739   {
740     char *line_ptr;
741     boolean last_line_was_empty = TRUE;
742
743     /* read next line of input file */
744     if (!fgets(line, MAX_LINE_LEN, file))
745       break;
746
747     /* skip comments (lines directly beginning with '#') */
748     if (line[0] == '#')
749       continue;
750
751     /* cut trailing newline from input line */
752     for (line_ptr = line; *line_ptr; line_ptr++)
753     {
754       if (*line_ptr == '\n' || *line_ptr == '\r')
755       {
756         *line_ptr = '\0';
757         break;
758       }
759     }
760
761     if (strlen(line) == 0)              /* special case: force empty line */
762       strcpy(line, "\n");
763
764     line_ptr = line;
765
766     while (*line_ptr && current_line < max_lines)
767     {
768 #if 1
769       boolean buffer_filled;
770
771       if (wrap_text)
772       {
773         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
774                                            line_length, last_line_was_empty);
775       }
776       else
777       {
778         if (strlen(line_ptr) <= line_length)
779         {
780           buffer_len = strlen(line_ptr);
781           strcpy(buffer, line_ptr);
782         }
783         else
784         {
785           buffer_len = line_length;
786           strncpy(buffer, line_ptr, line_length);
787         }
788
789         buffer[buffer_len] = '\0';
790         line_ptr += buffer_len;
791
792         buffer_filled = TRUE;
793       }
794 #else
795       boolean buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
796                                                  line_length, last_line_was_empty);
797 #endif
798
799       if (buffer_filled)
800       {
801         DrawText(x, y + current_line * font_height, buffer, font_nr);
802         current_line++;
803
804         last_line_was_empty = (buffer_len == 0);
805
806         buffer[0] = '\0';
807         buffer_len = 0;
808       }
809     }
810   }
811
812   fclose(file);
813
814   if (buffer_len > 0 && current_line < max_lines)
815   {
816     DrawText(x, y + current_line * font_height, buffer, font_nr);
817     current_line++;
818   }
819
820   return current_line;
821 }
822 #endif
823
824 static boolean getCheckedTokenValueFromString(char *string, char **token,
825                                               char **value)
826 {
827   char *ptr;
828
829   if (!getTokenValueFromString(string, token, value))
830     return FALSE;
831
832   if (**token != '.')                   /* token should begin with dot */
833     return FALSE;
834
835   for (ptr = *token; *ptr; ptr++)       /* token should contain no whitespace */
836     if (*ptr == ' ' || *ptr == '\t')
837       return FALSE;
838
839   for (ptr = *value; *ptr; ptr++)       /* value should contain no whitespace */
840     if (*ptr == ' ' || *ptr == '\t')
841       return FALSE;
842
843   return TRUE;
844 }
845
846 static void DrawTextBuffer_Flush(int x, int y, char *buffer, int font_nr,
847                                  int line_length, int cut_length,
848                                  int line_spacing, int mask_mode,
849                                  boolean centered, int current_line)
850 {
851   int buffer_len = strlen(buffer);
852   int font_width = getFontWidth(font_nr);
853   int font_height = getFontHeight(font_nr);
854   int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
855   int offset_xsize =
856     (centered ? font_width * (line_length - buffer_len) / 2 : 0);
857   int final_cut_length = MAX(0, cut_length - offset_chars);
858   int xx = x + offset_xsize;
859   int yy = y + current_line * (font_height + line_spacing);
860
861   buffer[final_cut_length] = '\0';
862
863   if (mask_mode != -1)
864     DrawTextExt(drawto, xx, yy, buffer, font_nr, mask_mode);
865   else
866     DrawText(xx, yy, buffer, font_nr);
867 }
868
869 int DrawTextBuffer(int x, int y, char *text_buffer, int font_nr,
870                    int line_length, int cut_length, int max_lines,
871                    int line_spacing, int mask_mode, boolean autowrap,
872                    boolean centered, boolean parse_comments)
873 {
874 #if 0
875   int font_width = getFontWidth(font_nr);
876   int font_height = getFontHeight(font_nr);
877 #endif
878   char buffer[line_length + 1];
879   int buffer_len;
880   int current_line = 0;
881
882   if (text_buffer == NULL || *text_buffer == '\0')
883     return 0;
884
885   if (current_line >= max_lines)
886     return 0;
887
888   if (cut_length == -1)
889     cut_length = line_length;
890
891   buffer[0] = '\0';
892   buffer_len = 0;
893
894   while (*text_buffer && current_line < max_lines)
895   {
896     char line[MAX_LINE_LEN + 1];
897     char *line_ptr;
898     boolean last_line_was_empty = TRUE;
899 #if 1
900     int num_line_chars = MAX_LINE_LEN;
901 #else
902     int num_line_chars = (autowrap ? MAX_LINE_LEN : line_length);
903 #endif
904     int i;
905
906     /* copy next line from text buffer to line buffer (nearly fgets() style) */
907     for (i = 0; i < num_line_chars && *text_buffer; i++)
908       if ((line[i] = *text_buffer++) == '\n')
909         break;
910     line[i] = '\0';
911
912     /* prevent 'num_line_chars' sized lines to cause additional empty line */
913     if (i == num_line_chars && *text_buffer == '\n')
914       text_buffer++;
915
916     /* skip comments (lines directly beginning with '#') */
917     if (line[0] == '#' && parse_comments)
918     {
919       char *token, *value;
920
921       /* try to read generic token/value pair definition after comment sign */
922       if (getCheckedTokenValueFromString(line + 1, &token, &value))
923       {
924         /* if found, flush the current buffer, if non-empty */
925         if (buffer_len > 0 && current_line < max_lines)
926         {
927           DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
928                                line_spacing, mask_mode, centered, current_line);
929
930           current_line++;
931
932           buffer[0] = '\0';
933           buffer_len = 0;
934         }
935
936         if (strEqual(token, ".font"))
937           font_nr = gfx.get_font_from_token_function(value);
938         else if (strEqual(token, ".autowrap"))
939           autowrap = get_boolean_from_string(value);
940         else if (strEqual(token, ".centered"))
941           centered = get_boolean_from_string(value);
942         else if (strEqual(token, ".parse_comments"))
943           parse_comments = get_boolean_from_string(value);
944       }
945
946       continue;
947     }
948
949     /* cut trailing newline and carriage return from input line */
950     for (line_ptr = line; *line_ptr; line_ptr++)
951     {
952       if (*line_ptr == '\n' || *line_ptr == '\r')
953       {
954         *line_ptr = '\0';
955         break;
956       }
957     }
958
959     if (strlen(line) == 0)              /* special case: force empty line */
960       strcpy(line, "\n");
961
962     line_ptr = line;
963
964     while (*line_ptr && current_line < max_lines)
965     {
966       boolean buffer_filled;
967
968       if (autowrap)
969       {
970         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
971                                            line_length, last_line_was_empty);
972       }
973       else
974       {
975         if (strlen(line_ptr) <= line_length)
976         {
977           buffer_len = strlen(line_ptr);
978           strcpy(buffer, line_ptr);
979         }
980         else
981         {
982           buffer_len = line_length;
983           strncpy(buffer, line_ptr, line_length);
984         }
985
986         buffer[buffer_len] = '\0';
987         line_ptr += buffer_len;
988
989         buffer_filled = TRUE;
990       }
991
992       if (buffer_filled)
993       {
994 #if 1
995         DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
996                              line_spacing, mask_mode, centered, current_line);
997 #else
998         int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
999         int offset_xsize =
1000           (centered ?  font_width * (line_length - buffer_len) / 2 : 0);
1001         int final_cut_length = MAX(0, cut_length - offset_chars);
1002         int xx = x + offset_xsize;
1003
1004         buffer[final_cut_length] = '\0';
1005
1006         if (mask_mode != -1)
1007           DrawTextExt(drawto, xx, y + current_line * font_height, buffer,
1008                       font_nr, mask_mode);
1009         else
1010           DrawText(xx, y + current_line * font_height, buffer, font_nr);
1011 #endif
1012
1013         current_line++;
1014
1015         last_line_was_empty = (buffer_len == 0);
1016
1017         buffer[0] = '\0';
1018         buffer_len = 0;
1019       }
1020     }
1021   }
1022
1023   if (buffer_len > 0 && current_line < max_lines)
1024   {
1025 #if 1
1026     DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
1027                          line_spacing, mask_mode, centered, current_line);
1028 #else
1029     int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
1030         int offset_xsize =
1031           (centered ?  font_width * (line_length - buffer_len) / 2 : 0);
1032     int final_cut_length = MAX(0, cut_length - offset_chars);
1033     int xx = x + offset_xsize;
1034
1035     buffer[final_cut_length] = '\0';
1036
1037     if (mask_mode != -1)
1038       DrawTextExt(drawto, xx, y + current_line * font_height, buffer,
1039                   font_nr, mask_mode);
1040     else
1041       DrawText(xx, y + current_line * font_height, buffer, font_nr);
1042 #endif
1043
1044     current_line++;
1045   }
1046
1047   return current_line;
1048 }
1049
1050 int DrawTextBufferVA(int x, int y, char *format, va_list ap, int font_nr,
1051                      int line_length, int cut_length, int max_lines,
1052                      int line_spacing, int mask_mode, boolean autowrap,
1053                      boolean centered, boolean parse_comments)
1054 {
1055   char text_buffer[MAX_OUTPUT_LINESIZE];
1056   int text_length = vsnprintf(text_buffer, MAX_OUTPUT_LINESIZE, format, ap);
1057
1058   if (text_length >= MAX_OUTPUT_LINESIZE)
1059     Error(ERR_WARN, "string too long in DrawTextBufferVA() -- truncated");
1060
1061   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
1062                                          line_length, cut_length, max_lines,
1063                                          line_spacing, mask_mode, autowrap,
1064                                          centered, parse_comments);
1065   return num_lines_printed;
1066 }
1067
1068 int DrawTextFile(int x, int y, char *filename, int font_nr,
1069                  int line_length, int cut_length, int max_lines,
1070                  int line_spacing, int mask_mode, boolean autowrap,
1071                  boolean centered, boolean parse_comments)
1072 {
1073   char *text_buffer = GetTextBufferFromFile(filename, MAX_LINES_FROM_FILE);
1074   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
1075                                          line_length, cut_length, max_lines,
1076                                          line_spacing, mask_mode, autowrap,
1077                                          centered, parse_comments);
1078   checked_free(text_buffer);
1079
1080   return num_lines_printed;
1081 }
1082
1083 #if 0
1084 void DrawTextWrapped(int x, int y, char *text, int font_nr, int line_length,
1085                      int max_lines)
1086 {
1087   DrawTextBuffer(x, y, text, font_nr, line_length, -1, max_lines, -1, TRUE,
1088                  FALSE, FALSE);
1089 }
1090
1091 void DrawTextToTextArea(int x, int y, char *text, int font_nr, int line_length,
1092                         int cut_length, int max_lines, int mask_mode)
1093 {
1094   DrawTextBuffer(x, y, text, font_nr, line_length, cut_length, max_lines,
1095                  mask_mode, FALSE, FALSE, FALSE);
1096 }
1097 #endif