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