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