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