ascii: Refactor definition of box characters.
[pspp] / src / output / ascii.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <signal.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <unilbrk.h>
26 #include <unistd.h>
27 #include <unistr.h>
28 #include <uniwidth.h>
29
30 #ifdef HAVE_TERMIOS_H
31 # include <termios.h>
32 #endif
33
34 #ifdef GWINSZ_IN_SYS_IOCTL
35 # include <sys/ioctl.h>
36 #endif
37
38 #include "data/file-name.h"
39 #include "data/file-handle-def.h"
40 #include "data/settings.h"
41 #include "libpspp/assertion.h"
42 #include "libpspp/cast.h"
43 #include "libpspp/compiler.h"
44 #include "libpspp/message.h"
45 #include "libpspp/start-date.h"
46 #include "libpspp/string-map.h"
47 #include "libpspp/u8-line.h"
48 #include "libpspp/version.h"
49 #include "output/ascii.h"
50 #ifdef HAVE_CAIRO
51 #include "output/cairo-chart.h"
52 #endif
53 #include "output/chart-item-provider.h"
54 #include "output/driver-provider.h"
55 #include "output/message-item.h"
56 #include "output/options.h"
57 #include "output/render.h"
58 #include "output/table-item.h"
59 #include "output/text-item.h"
60
61 #include "gl/minmax.h"
62 #include "gl/xalloc.h"
63 #include "gl/xsize.h"
64
65 #include "gettext.h"
66 #define _(msgid) gettext (msgid)
67
68 /* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
69 #define H TABLE_HORZ
70 #define V TABLE_VERT
71
72 enum
73   {
74     ASCII_LINE_NONE,
75     ASCII_LINE_SINGLE,
76     ASCII_LINE_DOUBLE,
77     ASCII_N_LINES
78   };
79
80 struct box_chars
81   {
82     ucs4_t c[ASCII_N_LINES][ASCII_N_LINES][ASCII_N_LINES][ASCII_N_LINES];
83   };
84
85 static const struct box_chars *
86 get_ascii_box (void)
87 {
88   enum {
89     _ = ASCII_LINE_NONE,
90     S = ASCII_LINE_SINGLE,
91     D = ASCII_LINE_DOUBLE,
92   };
93
94   static const struct box_chars ascii_box =
95     {
96       /* r  b  l   t:  _    S    D */
97       .c[_][_][_] = { ' ', '|', '#', },
98       .c[_][_][S] = { '-', '+', '#', },
99       .c[_][_][D] = { '=', '#', '#', },
100       .c[_][S][_] = { '|', '|', '#', },
101       .c[_][S][S] = { '+', '+', '#', },
102       .c[_][S][D] = { '#', '#', '#', },
103       .c[_][D][_] = { '#', '#', '#', },
104       .c[_][D][S] = { '#', '#', '#', },
105       .c[_][D][D] = { '#', '#', '#', },
106       .c[S][_][_] = { '-', '+', '#', },
107       .c[S][_][S] = { '-', '+', '#', },
108       .c[S][_][D] = { '#', '#', '#', },
109       .c[S][S][_] = { '+', '+', '#', },
110       .c[S][S][S] = { '+', '+', '#', },
111       .c[S][S][D] = { '#', '#', '#', },
112       .c[S][D][_] = { '#', '#', '#', },
113       .c[S][D][S] = { '#', '#', '#', },
114       .c[S][D][D] = { '#', '#', '#', },
115       .c[D][_][_] = { '=', '#', '#', },
116       .c[D][_][S] = { '#', '#', '#', },
117       .c[D][_][D] = { '=', '#', '#', },
118       .c[D][S][_] = { '#', '#', '#', },
119       .c[D][S][S] = { '#', '#', '#', },
120       .c[D][S][D] = { '#', '#', '#', },
121       .c[D][D][_] = { '#', '#', '#', },
122       .c[D][D][S] = { '#', '#', '#', },
123       .c[D][D][D] = { '#', '#', '#', },
124     };
125   return &ascii_box;
126 }
127
128 static const struct box_chars *
129 get_unicode_box (void)
130 {
131   enum {
132     _ = ASCII_LINE_NONE,
133     S = ASCII_LINE_SINGLE,
134     D = ASCII_LINE_DOUBLE,
135   };
136
137   static const struct box_chars unicode_box =
138     {
139       /* r  b  l   t:   _       S       D */
140       .c[_][_][_] = { 0x0020, 0x2575, 0x2551, }, /*  ╵║ */
141       .c[_][_][S] = { 0x2574, 0x256f, 0x255c, }, /* ╴╯╜ */
142       .c[_][_][D] = { 0x2550, 0x255b, 0x255d, }, /* ═╛╝ */
143       .c[_][S][_] = { 0x2577, 0x2502, 0x2551, }, /* ╷│║ */
144       .c[_][S][S] = { 0x256e, 0x2524, 0x2562, }, /* ╮┤╢ */
145       .c[_][S][D] = { 0x2555, 0x2561, 0x2563, }, /* ╕╡╣ */
146       .c[_][D][_] = { 0x2551, 0x2551, 0x2551, }, /* ║║║ */
147       .c[_][D][S] = { 0x2556, 0x2562, 0x2562, }, /* ╖╢╢ */
148       .c[_][D][D] = { 0x2557, 0x2563, 0x2563, }, /* ╗╣╣ */
149       .c[S][_][_] = { 0x2576, 0x2570, 0x2559, }, /* ╶╰╙ */
150       .c[S][_][S] = { 0x2500, 0x2534, 0x2568, }, /* ─┴╨ */
151       .c[S][_][D] = { 0x2550, 0x2567, 0x2569, }, /* ═╧╩ */
152       .c[S][S][_] = { 0x256d, 0x251c, 0x255f, }, /* ╭├╟ */
153       .c[S][S][S] = { 0x252c, 0x253c, 0x256a, }, /* ┬┼╪ */
154       .c[S][S][D] = { 0x2564, 0x256a, 0x256c, }, /* ╤╪╬ */
155       .c[S][D][_] = { 0x2553, 0x255f, 0x255f, }, /* ╓╟╟ */
156       .c[S][D][S] = { 0x2565, 0x256b, 0x256b, }, /* ╥╫╫ */
157       .c[S][D][D] = { 0x2566, 0x256c, 0x256c, }, /* ╦╬╬ */
158       .c[D][_][_] = { 0x2550, 0x2558, 0x255a, }, /* ═╘╚ */
159       .c[D][_][S] = { 0x2550, 0x2567, 0x2569, }, /* ═╧╩ */
160       .c[D][_][D] = { 0x2550, 0x2567, 0x2569, }, /* ═╧╩ */
161       .c[D][S][_] = { 0x2552, 0x255e, 0x2560, }, /* ╒╞╠ */
162       .c[D][S][S] = { 0x2564, 0x256a, 0x256c, }, /* ╤╪╬ */
163       .c[D][S][D] = { 0x2564, 0x256a, 0x256c, }, /* ╤╪╬ */
164       .c[D][D][_] = { 0x2554, 0x2560, 0x2560, }, /* ╔╠╠ */
165       .c[D][D][S] = { 0x2560, 0x256c, 0x256c, }, /* ╠╬╬ */
166       .c[D][D][D] = { 0x2566, 0x256c, 0x256c, }, /* ╦╬╬ */
167     };
168   return &unicode_box;
169 }
170
171 static int
172 ascii_line_from_render_line (int render_line)
173 {
174   switch (render_line)
175     {
176     case RENDER_LINE_NONE:
177       return ASCII_LINE_NONE;
178
179     case RENDER_LINE_SINGLE:
180     case RENDER_LINE_DASHED:
181     case RENDER_LINE_THICK:
182     case RENDER_LINE_THIN:
183       return ASCII_LINE_SINGLE;
184
185     case RENDER_LINE_DOUBLE:
186       return ASCII_LINE_DOUBLE;
187
188     default:
189       return ASCII_LINE_NONE;
190     }
191
192 }
193
194 static ucs4_t
195 box_get (const struct box_chars *box,
196          int left_, int right_, int top_, int bottom_)
197 {
198   bool rtl = render_direction_rtl ();
199   int left = ascii_line_from_render_line (rtl ? right_ : left_);
200   int right = ascii_line_from_render_line (rtl ? left_ : right_);
201   int top = ascii_line_from_render_line (top_);
202   int bottom = ascii_line_from_render_line (bottom_);
203
204   return box->c[right][bottom][left][top];
205 }
206
207 /* ASCII output driver. */
208 struct ascii_driver
209   {
210     struct output_driver driver;
211
212     /* User parameters. */
213     bool append;                /* Append if output file already exists? */
214     bool emphasis;              /* Enable bold and underline in output? */
215     char *chart_file_name;      /* Name of files used for charts. */
216
217 #ifdef HAVE_CAIRO
218     /* Colours for charts */
219     struct cell_color fg;
220     struct cell_color bg;
221 #endif
222
223     /* How the page width is determined: */
224     enum {
225       FIXED_WIDTH,              /* Specified by configuration. */
226       VIEW_WIDTH,               /* From SET WIDTH. */
227       TERMINAL_WIDTH            /* From the terminal's width. */
228     } width_mode;
229     int width;                  /* Page width. */
230
231     int min_hbreak;             /* Min cell size to break across pages. */
232
233     const struct box_chars *box; /* Line & box drawing characters. */
234
235     /* Internal state. */
236     struct file_handle *handle;
237     FILE *file;                 /* Output file. */
238     bool error;                 /* Output error? */
239     struct u8_line *lines;      /* Page content. */
240     int allocated_lines;        /* Number of lines allocated. */
241     int chart_cnt;              /* Number of charts so far. */
242     int object_cnt;             /* Number of objects so far. */
243     struct render_params params;
244   };
245
246 static const struct output_driver_class ascii_driver_class;
247
248 static void ascii_submit (struct output_driver *, const struct output_item *);
249
250 static int get_terminal_width (void);
251
252 static bool update_page_size (struct ascii_driver *, bool issue_error);
253 static int parse_page_size (struct driver_option *);
254
255 static void ascii_draw_line (void *, int bb[TABLE_N_AXES][2],
256                              enum render_line_style styles[TABLE_N_AXES][2],
257                              struct cell_color colors[TABLE_N_AXES][2]);
258 static void ascii_measure_cell_width (void *, const struct table_cell *,
259                                       int *min, int *max);
260 static int ascii_measure_cell_height (void *, const struct table_cell *,
261                                       int width);
262 static void ascii_draw_cell (void *, const struct table_cell *, int color_idx,
263                              int bb[TABLE_N_AXES][2], int valign_offset,
264                              int spill[TABLE_N_AXES][2],
265                              int clip[TABLE_N_AXES][2]);
266
267 static struct ascii_driver *
268 ascii_driver_cast (struct output_driver *driver)
269 {
270   assert (driver->class == &ascii_driver_class);
271   return UP_CAST (driver, struct ascii_driver, driver);
272 }
273
274 static struct driver_option *
275 opt (struct output_driver *d, struct string_map *options, const char *key,
276      const char *default_value)
277 {
278   return driver_option_get (d, options, key, default_value);
279 }
280
281 /* Return true iff the terminal appears to be an xterm with
282    UTF-8 capabilities */
283 static bool
284 term_is_utf8_xterm (void)
285 {
286   const char *term = getenv ("TERM");
287   const char *xterm_locale = getenv ("XTERM_LOCAL");
288   return (term && xterm_locale
289           && !strcmp (term, "xterm")
290           && (strcasestr (xterm_locale, "utf8")
291               || strcasestr (xterm_locale, "utf-8")));
292 }
293
294 static struct output_driver *
295 ascii_create (struct  file_handle *fh, enum settings_output_devices device_type,
296               struct string_map *o)
297 {
298   enum { BOX_ASCII, BOX_UNICODE } box;
299   struct output_driver *d;
300   struct ascii_driver *a;
301
302   a = xzalloc (sizeof *a);
303   d = &a->driver;
304   output_driver_init (&a->driver, &ascii_driver_class, fh_get_file_name (fh), device_type);
305   a->append = parse_boolean (opt (d, o, "append", "false"));
306   a->emphasis = parse_boolean (opt (d, o, "emphasis", "false"));
307
308   a->chart_file_name = parse_chart_file_name (opt (d, o, "charts", fh_get_file_name (fh)));
309   a->handle = fh;
310
311
312   bool terminal = !strcmp (fh_get_file_name (fh), "-") && isatty (1);
313   a->width = parse_page_size (opt (d, o, "width", "-1"));
314   a->width_mode = (a->width > 0 ? FIXED_WIDTH
315                    : terminal ? TERMINAL_WIDTH
316                    : VIEW_WIDTH);
317   a->min_hbreak = parse_int (opt (d, o, "min-hbreak", "-1"), -1, INT_MAX);
318
319 #ifdef HAVE_CAIRO
320   a->bg = parse_color (opt (d, o, "background-color", "#FFFFFFFFFFFF"));
321   a->fg = parse_color (opt (d, o, "foreground-color", "#000000000000"));
322 #endif
323
324   const char *default_box = (terminal && (!strcmp (locale_charset (), "UTF-8")
325                                           || term_is_utf8_xterm ())
326                              ? "unicode" : "ascii");
327   box = parse_enum (opt (d, o, "box", default_box),
328                     "ascii", BOX_ASCII,
329                     "unicode", BOX_UNICODE,
330                     NULL_SENTINEL);
331   a->box = box == BOX_ASCII ? get_ascii_box () : get_unicode_box ();
332
333   a->file = NULL;
334   a->error = false;
335   a->lines = NULL;
336   a->allocated_lines = 0;
337   a->chart_cnt = 0;
338   a->object_cnt = 0;
339
340   static const struct render_ops ascii_render_ops = {
341     .draw_line = ascii_draw_line,
342     .measure_cell_width = ascii_measure_cell_width,
343     .measure_cell_height = ascii_measure_cell_height,
344     .adjust_break = NULL,
345     .draw_cell = ascii_draw_cell,
346   };
347   a->params.ops = &ascii_render_ops;
348   a->params.aux = a;
349   a->params.size[H] = a->width;
350   a->params.size[V] = INT_MAX;
351   a->params.font_size[H] = 1;
352   a->params.font_size[V] = 1;
353
354   static const int ascii_line_widths[RENDER_N_LINES] = {
355     [RENDER_LINE_NONE] = 0,
356     [RENDER_LINE_SINGLE] = 1,
357     [RENDER_LINE_DASHED] = 1,
358     [RENDER_LINE_THICK] = 1,
359     [RENDER_LINE_THIN] = 1,
360     [RENDER_LINE_DOUBLE] = 1,
361   };
362   a->params.line_widths = ascii_line_widths;
363   a->params.supports_margins = false;
364   a->params.rtl = render_direction_rtl ();
365
366   if (!update_page_size (a, true))
367     goto error;
368
369   a->file = fn_open (a->handle, a->append ? "a" : "w");
370   if (!a->file)
371     {
372       msg_error (errno, _("ascii: opening output file `%s'"),
373                  fh_get_file_name (a->handle));
374       goto error;
375     }
376
377   return d;
378
379 error:
380   output_driver_destroy (d);
381   return NULL;
382 }
383
384 static int
385 parse_page_size (struct driver_option *option)
386 {
387   int dim = atol (option->default_value);
388
389   if (option->value != NULL)
390     {
391       if (!strcmp (option->value, "auto"))
392         dim = -1;
393       else
394         {
395           int value;
396           char *tail;
397
398           errno = 0;
399           value = strtol (option->value, &tail, 0);
400           if (value >= 1 && errno != ERANGE && *tail == '\0')
401             dim = value;
402           else
403             msg (MW, _("%s: %s must be positive integer or `auto'"),
404                    option->driver_name, option->name);
405         }
406     }
407
408   driver_option_destroy (option);
409
410   return dim;
411 }
412
413 /* Re-calculates the page width based on settings, margins, and, if "auto" is
414    set, the size of the user's terminal window or GUI output window. */
415 static bool
416 update_page_size (struct ascii_driver *a, bool issue_error)
417 {
418   enum { MIN_WIDTH = 6 };
419
420   int want_width = (a->width_mode == VIEW_WIDTH ? settings_get_viewwidth ()
421                     : a->width_mode == TERMINAL_WIDTH ? get_terminal_width ()
422                     : a->width);
423   bool ok = want_width >= MIN_WIDTH;
424   if (!ok && issue_error)
425     msg (ME, _("ascii: page must be at least %d characters wide, but "
426                "as configured is only %d characters"),
427          MIN_WIDTH, want_width);
428
429   a->width = ok ? want_width : MIN_WIDTH;
430   a->params.size[H] = a->width;
431   a->params.min_break[H] = a->min_hbreak >= 0 ? a->min_hbreak : a->width / 2;
432
433   return ok;
434 }
435
436 static void
437 ascii_destroy (struct output_driver *driver)
438 {
439   struct ascii_driver *a = ascii_driver_cast (driver);
440   int i;
441
442   if (a->file != NULL)
443     fn_close (a->handle, a->file);
444   fh_unref (a->handle);
445   free (a->chart_file_name);
446   for (i = 0; i < a->allocated_lines; i++)
447     u8_line_destroy (&a->lines[i]);
448   free (a->lines);
449   free (a);
450 }
451
452 static void
453 ascii_flush (struct output_driver *driver)
454 {
455   struct ascii_driver *a = ascii_driver_cast (driver);
456   if (a->file)
457     fflush (a->file);
458 }
459
460 static void
461 ascii_output_lines (struct ascii_driver *a, size_t n_lines)
462 {
463   for (size_t y = 0; y < n_lines; y++)
464     {
465       if (y < a->allocated_lines)
466         {
467           struct u8_line *line = &a->lines[y];
468
469           while (ds_chomp_byte (&line->s, ' '))
470             continue;
471           fwrite (ds_data (&line->s), 1, ds_length (&line->s), a->file);
472           u8_line_clear (&a->lines[y]);
473         }
474       putc ('\n', a->file);
475     }
476 }
477
478 static void
479 ascii_output_table_item (struct ascii_driver *a,
480                          const struct table_item *table_item)
481 {
482   struct render_pager *p;
483
484   update_page_size (a, false);
485
486   if (a->object_cnt++)
487     putc ('\n', a->file);
488
489   p = render_pager_create (&a->params, table_item);
490   for (int i = 0; render_pager_has_next (p); i++)
491     {
492       if (i)
493         putc ('\n', a->file);
494       ascii_output_lines (a, render_pager_draw_next (p, INT_MAX));
495     }
496   render_pager_destroy (p);
497 }
498
499 static void
500 ascii_output_table_item_unref (struct ascii_driver *a,
501                                struct table_item *table_item)
502 {
503   ascii_output_table_item (a, table_item);
504   table_item_unref (table_item);
505 }
506
507 static void
508 ascii_submit (struct output_driver *driver,
509               const struct output_item *output_item)
510 {
511   struct ascii_driver *a = ascii_driver_cast (driver);
512
513   if (a->error)
514     return;
515
516   if (is_table_item (output_item))
517     ascii_output_table_item (a, to_table_item (output_item));
518 #ifdef HAVE_CAIRO
519   else if (is_chart_item (output_item) && a->chart_file_name != NULL)
520     {
521       struct chart_item *chart_item = to_chart_item (output_item);
522       char *file_name;
523
524       file_name = xr_draw_png_chart (chart_item, a->chart_file_name,
525                                      ++a->chart_cnt,
526                                      &a->fg,
527                                      &a->bg);
528       if (file_name != NULL)
529         {
530           struct text_item *text_item;
531
532           text_item = text_item_create_format (
533             TEXT_ITEM_LOG, _("See %s for a chart."), file_name);
534
535           ascii_submit (driver, &text_item->output_item);
536           text_item_unref (text_item);
537           free (file_name);
538         }
539     }
540 #endif  /* HAVE_CAIRO */
541   else if (is_text_item (output_item))
542     {
543       const struct text_item *text_item = to_text_item (output_item);
544       enum text_item_type type = text_item_get_type (text_item);
545
546       if (type != TEXT_ITEM_PAGE_TITLE)
547         ascii_output_table_item_unref (
548           a, text_item_to_table_item (text_item_ref (text_item)));
549     }
550   else if (is_message_item (output_item))
551     ascii_output_table_item_unref (
552       a, text_item_to_table_item (
553         message_item_to_text_item (
554           to_message_item (
555             output_item_ref (output_item)))));
556 }
557
558 const struct output_driver_factory txt_driver_factory =
559   { "txt", "-", ascii_create };
560 const struct output_driver_factory list_driver_factory =
561   { "list", "-", ascii_create };
562
563 static const struct output_driver_class ascii_driver_class =
564   {
565     "text",
566     ascii_destroy,
567     ascii_submit,
568     ascii_flush,
569   };
570 \f
571 static char *ascii_reserve (struct ascii_driver *, int y, int x0, int x1,
572                             int n);
573 static void ascii_layout_cell (struct ascii_driver *,
574                                const struct table_cell *,
575                                int bb[TABLE_N_AXES][2],
576                                int clip[TABLE_N_AXES][2],
577                                int *width, int *height);
578
579 static void
580 ascii_draw_line (void *a_, int bb[TABLE_N_AXES][2],
581                  enum render_line_style styles[TABLE_N_AXES][2],
582                  struct cell_color colors[TABLE_N_AXES][2] UNUSED)
583 {
584   struct ascii_driver *a = a_;
585   char mbchar[6];
586   int x0, y0, x1, y1;
587   ucs4_t uc;
588   int mblen;
589   int x, y;
590
591   /* Clip to the page. */
592   x0 = MAX (bb[H][0], 0);
593   y0 = MAX (bb[V][0], 0);
594   x1 = MIN (bb[H][1], a->width);
595   y1 = bb[V][1];
596   if (x1 <= 0 || y1 <= 0 || x0 >= a->width)
597     return;
598
599   /* Draw. */
600   uc = box_get (a->box, styles[V][0], styles[V][1], styles[H][0], styles[H][1]);
601   mblen = u8_uctomb (CHAR_CAST (uint8_t *, mbchar), uc, 6);
602   for (y = y0; y < y1; y++)
603     {
604       char *p = ascii_reserve (a, y, x0, x1, mblen * (x1 - x0));
605       for (x = x0; x < x1; x++)
606         {
607           memcpy (p, mbchar, mblen);
608           p += mblen;
609         }
610     }
611 }
612
613 static void
614 ascii_measure_cell_width (void *a_, const struct table_cell *cell,
615                           int *min_width, int *max_width)
616 {
617   struct ascii_driver *a = a_;
618   int bb[TABLE_N_AXES][2];
619   int clip[TABLE_N_AXES][2];
620   int h;
621
622   bb[H][0] = 0;
623   bb[H][1] = INT_MAX;
624   bb[V][0] = 0;
625   bb[V][1] = INT_MAX;
626   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
627   ascii_layout_cell (a, cell, bb, clip, max_width, &h);
628
629   if (cell->n_footnotes || strchr (cell->text, ' ')
630       || cell->n_subscripts || cell->superscript)
631     {
632       bb[H][1] = 1;
633       ascii_layout_cell (a, cell, bb, clip, min_width, &h);
634     }
635   else
636     *min_width = *max_width;
637 }
638
639 static int
640 ascii_measure_cell_height (void *a_, const struct table_cell *cell, int width)
641 {
642   struct ascii_driver *a = a_;
643   int bb[TABLE_N_AXES][2];
644   int clip[TABLE_N_AXES][2];
645   int w, h;
646
647   bb[H][0] = 0;
648   bb[H][1] = width;
649   bb[V][0] = 0;
650   bb[V][1] = INT_MAX;
651   clip[H][0] = clip[H][1] = clip[V][0] = clip[V][1] = 0;
652   ascii_layout_cell (a, cell, bb, clip, &w, &h);
653   return h;
654 }
655
656 static void
657 ascii_draw_cell (void *a_, const struct table_cell *cell, int color_idx UNUSED,
658                  int bb[TABLE_N_AXES][2], int valign_offset,
659                  int spill[TABLE_N_AXES][2] UNUSED,
660                  int clip[TABLE_N_AXES][2])
661 {
662   struct ascii_driver *a = a_;
663   int w, h;
664
665   bb[V][0] += valign_offset;
666   ascii_layout_cell (a, cell, bb, clip, &w, &h);
667 }
668
669 static char *
670 ascii_reserve (struct ascii_driver *a, int y, int x0, int x1, int n)
671 {
672   if (y >= a->allocated_lines)
673     {
674       size_t new_alloc = MAX (25, a->allocated_lines);
675       while (new_alloc <= y)
676         new_alloc = xtimes (new_alloc, 2);
677       a->lines = xnrealloc (a->lines, new_alloc, sizeof *a->lines);
678       for (size_t i = a->allocated_lines; i < new_alloc; i++)
679         u8_line_init (&a->lines[i]);
680       a->allocated_lines = new_alloc;
681     }
682   return u8_line_reserve (&a->lines[y], x0, x1, n);
683 }
684
685 static void
686 text_draw (struct ascii_driver *a, enum table_halign halign, int options,
687            bool bold, bool underline,
688            int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
689            int y, const uint8_t *string, int n, size_t width)
690 {
691   int x0 = MAX (0, clip[H][0]);
692   int y0 = MAX (0, clip[V][0]);
693   int x1 = MIN (a->width, clip[H][1]);
694   int y1 = clip[V][1];
695   int x;
696
697   if (y < y0 || y >= y1)
698     return;
699
700   switch (table_halign_interpret (halign, options & TAB_NUMERIC))
701     {
702     case TABLE_HALIGN_LEFT:
703       x = bb[H][0];
704       break;
705     case TABLE_HALIGN_CENTER:
706       x = (bb[H][0] + bb[H][1] - width + 1) / 2;
707       break;
708     case TABLE_HALIGN_RIGHT:
709     case TABLE_HALIGN_DECIMAL:
710       x = bb[H][1] - width;
711       break;
712     default:
713       NOT_REACHED ();
714     }
715   if (x >= x1)
716     return;
717
718   while (x < x0)
719     {
720       ucs4_t uc;
721       int mblen;
722       int w;
723
724       if (n == 0)
725         return;
726       mblen = u8_mbtouc (&uc, string, n);
727
728       string += mblen;
729       n -= mblen;
730
731       w = uc_width (uc, "UTF-8");
732       if (w > 0)
733         {
734           x += w;
735           width -= w;
736         }
737     }
738   if (n == 0)
739     return;
740
741   if (x + width > x1)
742     {
743       int ofs;
744
745       ofs = width = 0;
746       for (ofs = 0; ofs < n;)
747         {
748           ucs4_t uc;
749           int mblen;
750           int w;
751
752           mblen = u8_mbtouc (&uc, string + ofs, n - ofs);
753
754           w = uc_width (uc, "UTF-8");
755           if (w > 0)
756             {
757               if (width + w > x1 - x)
758                 break;
759               width += w;
760             }
761           ofs += mblen;
762         }
763       n = ofs;
764       if (n == 0)
765         return;
766     }
767
768   if (!a->emphasis || (!bold && !underline))
769     memcpy (ascii_reserve (a, y, x, x + width, n), string, n);
770   else
771     {
772       size_t n_out;
773       size_t ofs;
774       char *out;
775       int mblen;
776
777       /* First figure out how many bytes need to be inserted. */
778       n_out = n;
779       for (ofs = 0; ofs < n; ofs += mblen)
780         {
781           ucs4_t uc;
782           int w;
783
784           mblen = u8_mbtouc (&uc, string + ofs, n - ofs);
785           w = uc_width (uc, "UTF-8");
786
787           if (w > 0)
788             {
789               if (bold)
790                 n_out += 1 + mblen;
791               if (underline)
792                 n_out += 2;
793             }
794         }
795
796       /* Then insert them. */
797       out = ascii_reserve (a, y, x, x + width, n_out);
798       for (ofs = 0; ofs < n; ofs += mblen)
799         {
800           ucs4_t uc;
801           int w;
802
803           mblen = u8_mbtouc (&uc, string + ofs, n - ofs);
804           w = uc_width (uc, "UTF-8");
805
806           if (w > 0)
807             {
808               if (bold)
809                 {
810                   out = mempcpy (out, string + ofs, mblen);
811                   *out++ = '\b';
812                 }
813               if (underline)
814                 {
815                   *out++ = '_';
816                   *out++ = '\b';
817                 }
818             }
819           out = mempcpy (out, string + ofs, mblen);
820         }
821     }
822 }
823
824 static char *
825 add_markers (const char *text, const struct table_cell *cell)
826 {
827   struct string s = DS_EMPTY_INITIALIZER;
828   ds_put_cstr (&s, text);
829   for (size_t i = 0; i < cell->n_subscripts; i++)
830     ds_put_format (&s, "%c%s", i ? ',' : '_', cell->subscripts[i]);
831   if (cell->superscript)
832     ds_put_format (&s, "^%s", cell->superscript);
833   for (size_t i = 0; i < cell->n_footnotes; i++)
834     ds_put_format (&s, "[%s]", cell->footnotes[i]->marker);
835   return ds_steal_cstr (&s);
836 }
837
838 static void
839 ascii_layout_cell (struct ascii_driver *a, const struct table_cell *cell,
840                    int bb[TABLE_N_AXES][2], int clip[TABLE_N_AXES][2],
841                    int *widthp, int *heightp)
842 {
843   *widthp = 0;
844   *heightp = 0;
845
846   /* Get the basic textual contents. */
847   const char *plain_text = (cell->options & TAB_MARKUP
848                             ? output_get_text_from_markup (cell->text)
849                             : cell->text);
850
851   /* Append footnotes, subscripts, superscript if any. */
852   const char *text;
853   if (cell->n_footnotes || cell->n_subscripts || cell->superscript)
854     {
855       text = add_markers (plain_text, cell);
856       if (plain_text != cell->text)
857         free (CONST_CAST (char *, plain_text));
858     }
859   else
860     text = plain_text;
861
862   /* Calculate length; if it's zero, then there's nothing to do. */
863   size_t length = strlen (text);
864   if (!length)
865     {
866       if (text != cell->text)
867         free (CONST_CAST (char *, text));
868       return;
869     }
870
871   char *breaks = xmalloc (length + 1);
872   u8_possible_linebreaks (CHAR_CAST (const uint8_t *, text), length,
873                           "UTF-8", breaks);
874   breaks[length] = (breaks[length - 1] == UC_BREAK_MANDATORY
875                     ? UC_BREAK_PROHIBITED : UC_BREAK_POSSIBLE);
876
877   size_t pos = 0;
878   int bb_width = bb[H][1] - bb[H][0];
879   for (int y = bb[V][0]; y < bb[V][1] && pos < length; y++)
880     {
881       const uint8_t *line = CHAR_CAST (const uint8_t *, text + pos);
882       const char *b = breaks + pos;
883       size_t n = length - pos;
884
885       size_t last_break_ofs = 0;
886       int last_break_width = 0;
887       int width = 0;
888       size_t graph_ofs;
889       size_t ofs;
890
891       for (ofs = 0; ofs < n;)
892         {
893           ucs4_t uc;
894           int mblen;
895           int w;
896
897           mblen = u8_mbtouc (&uc, line + ofs, n - ofs);
898           if (b[ofs] == UC_BREAK_MANDATORY)
899             break;
900           else if (b[ofs] == UC_BREAK_POSSIBLE)
901             {
902               last_break_ofs = ofs;
903               last_break_width = width;
904             }
905
906           w = uc_width (uc, "UTF-8");
907           if (w > 0)
908             {
909               if (width + w > bb_width)
910                 {
911                   if (isspace (line[ofs]))
912                     break;
913                   else if (last_break_ofs != 0)
914                     {
915                       ofs = last_break_ofs;
916                       width = last_break_width;
917                       break;
918                     }
919                 }
920               width += w;
921             }
922           ofs += mblen;
923         }
924
925       /* Trim any trailing spaces off the end of the text to be drawn. */
926       for (graph_ofs = ofs; graph_ofs > 0; graph_ofs--)
927         if (!isspace (line[graph_ofs - 1]))
928           break;
929       width -= ofs - graph_ofs;
930
931       /* Draw text. */
932       text_draw (a, cell->style->cell_style.halign, cell->options,
933                  cell->style->font_style.bold,
934                  cell->style->font_style.underline,
935                  bb, clip, y, line, graph_ofs, width);
936
937       /* If a new-line ended the line, just skip the new-line.  Otherwise, skip
938          past any spaces past the end of the line (but not past a new-line). */
939       if (b[ofs] == UC_BREAK_MANDATORY)
940         ofs++;
941       else
942         while (ofs < n && isspace (line[ofs]) && b[ofs] != UC_BREAK_MANDATORY)
943           ofs++;
944
945       if (width > *widthp)
946         *widthp = width;
947       ++*heightp;
948       pos += ofs;
949     }
950
951   free (breaks);
952   if (text != cell->text)
953     free (CONST_CAST (char *, text));
954 }
955
956 void
957 ascii_test_write (struct output_driver *driver,
958                   const char *s, int x, int y, bool bold, bool underline)
959 {
960   struct ascii_driver *a = ascii_driver_cast (driver);
961   int bb[TABLE_N_AXES][2];
962   int width, height;
963
964   if (!a->file)
965     return;
966
967   struct table_area_style style = {
968     .cell_style.halign = TABLE_HALIGN_LEFT,
969     .font_style.bold = bold,
970     .font_style.underline = underline,
971   };
972   struct table_cell cell = {
973     .text = CONST_CAST (char *, s),
974     .style = &style,
975   };
976
977   bb[TABLE_HORZ][0] = x;
978   bb[TABLE_HORZ][1] = a->width;
979   bb[TABLE_VERT][0] = y;
980   bb[TABLE_VERT][1] = INT_MAX;
981
982   ascii_layout_cell (a, &cell, bb, bb, &width, &height);
983 }
984
985 void
986 ascii_test_set_length (struct output_driver *driver, int y, int length)
987 {
988   struct ascii_driver *a = ascii_driver_cast (driver);
989
990   if (!a->file)
991     return;
992
993   if (y < 0)
994     return;
995   u8_line_set_length (&a->lines[y], length);
996 }
997
998 void
999 ascii_test_flush (struct output_driver *driver)
1000 {
1001   struct ascii_driver *a = ascii_driver_cast (driver);
1002
1003   for (size_t i = a->allocated_lines; i-- > 0;)
1004     if (a->lines[i].width)
1005       {
1006         ascii_output_lines (a, i + 1);
1007         break;
1008       }
1009 }
1010 \f
1011 static sig_atomic_t terminal_changed = true;
1012 static int terminal_width;
1013
1014 #if HAVE_DECL_SIGWINCH
1015 static void
1016 winch_handler (int signum UNUSED)
1017 {
1018   terminal_changed = true;
1019 }
1020 #endif
1021
1022 int
1023 get_terminal_width (void)
1024 {
1025 #if HAVE_DECL_SIGWINCH
1026   static bool setup_signal;
1027   if (!setup_signal)
1028     {
1029       setup_signal = true;
1030
1031       struct sigaction action = { .sa_handler = winch_handler };
1032       sigemptyset (&action.sa_mask);
1033       sigaction (SIGWINCH, &action, NULL);
1034     }
1035 #endif
1036
1037   if (terminal_changed)
1038     {
1039       terminal_changed = false;
1040
1041 #ifdef HAVE_TERMIOS_H
1042       struct winsize ws;
1043       if (!ioctl (0, TIOCGWINSZ, &ws))
1044         terminal_width = ws.ws_col;
1045       else
1046 #endif
1047         {
1048           if (getenv ("COLUMNS"))
1049             terminal_width = atoi (getenv ("COLUMNS"));
1050         }
1051
1052       if (terminal_width <= 0 || terminal_width > 1024)
1053         terminal_width = 79;
1054     }
1055
1056   return terminal_width;
1057 }