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