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