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