output: Remove support for bottom and right side headers.
[pspp] / src / output / render.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011, 2013, 2014, 2016 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 <math.h>
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "libpspp/assertion.h"
26 #include "libpspp/hash-functions.h"
27 #include "libpspp/hmap.h"
28 #include "libpspp/pool.h"
29 #include "output/pivot-output.h"
30 #include "output/pivot-table.h"
31 #include "output/render.h"
32 #include "output/table.h"
33
34 #include "gl/minmax.h"
35 #include "gl/xalloc.h"
36
37 #include "gettext.h"
38 #define _(msgid) gettext (msgid)
39
40 /* This file uses TABLE_HORZ and TABLE_VERT enough to warrant abbreviating. */
41 #define H TABLE_HORZ
42 #define V TABLE_VERT
43 \f
44 /* A layout for rendering a specific table on a specific device.
45
46    May represent the layout of an entire table presented to
47    render_page_create(), or a rectangular subregion of a table broken out using
48    render_break_next() to allow a table to be broken across multiple pages.
49
50    A page's size is not limited to the size passed in as part of render_params.
51    render_pager breaks a render_page into smaller render_pages that will fit in
52    the available space. */
53 struct render_page
54   {
55     const struct render_params *params; /* Parameters of the target device. */
56     struct table *table;                /* Table rendered. */
57     int ref_cnt;
58
59     /* Region of 'table' to render.
60
61        The horizontal cells rendered are the leftmost h[H], then
62        r[H] through r[H][1].
63
64        The vertical cells rendered are the topmost h[V], then r[V][0]
65        through r[V][1].
66
67        n[H] = h[H] + (r[H][1] - r[H][0])
68        n[V] = h[V] + (r[V][1] - r[V][0])
69     */
70     int h[TABLE_N_AXES];
71     int r[TABLE_N_AXES][2];
72     int n[TABLE_N_AXES];
73
74     /* "Cell positions".
75
76        cp[H] represents x positions within the table.
77        cp[H][0] = 0.
78        cp[H][1] = the width of the leftmost vertical rule.
79        cp[H][2] = cp[H][1] + the width of the leftmost column.
80        cp[H][3] = cp[H][2] + the width of the second-from-left vertical rule.
81        and so on:
82        cp[H][2 * n[H]] = x position of the rightmost vertical rule.
83        cp[H][2 * n[H] + 1] = total table width including all rules.
84
85        Similarly, cp[V] represents y positions within the table.
86        cp[V][0] = 0.
87        cp[V][1] = the height of the topmost horizontal rule.
88        cp[V][2] = cp[V][1] + the height of the topmost row.
89        cp[V][3] = cp[V][2] + the height of the second-from-top horizontal rule.
90        and so on:
91        cp[V][2 * n[V]] = y position of the bottommost horizontal rule.
92        cp[V][2 * n[V] + 1] = total table height including all rules.
93
94        Rules and columns can have width or height 0, in which case consecutive
95        values in this array are equal. */
96     int *cp[TABLE_N_AXES];
97
98     /* render_break_next() can break a table such that some cells are not fully
99        contained within a render_page.  This will happen if a cell is too wide
100        or two tall to fit on a single page, or if a cell spans multiple rows or
101        columns and the page only includes some of those rows or columns.
102
103        This hash table contains "struct render_overflow"s that represents each
104        such cell that doesn't completely fit on this page.
105
106        Each overflow cell borders at least one header edge of the table and may
107        border more.  (A single table cell that is so large that it fills the
108        entire page can overflow on all four sides!) */
109     struct hmap overflows;
110
111     /* If a single column (or row) is too wide (or tall) to fit on a page
112        reasonably, then render_break_next() will split a single row or column
113        across multiple render_pages.  This member indicates when this has
114        happened:
115
116        is_edge_cutoff[H][0] is true if pixels have been cut off the left side
117        of the leftmost column in this page, and false otherwise.
118
119        is_edge_cutoff[H][1] is true if pixels have been cut off the right side
120        of the rightmost column in this page, and false otherwise.
121
122        is_edge_cutoff[V][0] and is_edge_cutoff[V][1] are similar for the top
123        and bottom of the table.
124
125        The effect of is_edge_cutoff is to prevent rules along the edge in
126        question from being rendered.
127
128        When is_edge_cutoff is true for a given edge, the 'overflows' hmap will
129        contain a node for each cell along that edge. */
130     bool is_edge_cutoff[TABLE_N_AXES][2];
131   };
132
133 static struct render_page *render_page_create (const struct render_params *,
134                                                struct table *, int min_width);
135
136 struct render_page *render_page_ref (const struct render_page *page_);
137 static void render_page_unref (struct render_page *);
138
139 /* Returns the offset in struct render_page's cp[axis] array of the rule with
140    index RULE_IDX.  That is, if RULE_IDX is 0, then the offset is that of the
141    leftmost or topmost rule; if RULE_IDX is 1, then the offset is that of the
142    next rule to the right (or below); and so on. */
143 static int
144 rule_ofs (int rule_idx)
145 {
146   return rule_idx * 2;
147 }
148
149 /* Returns the offset in struct render_page's cp[axis] array of the rule with
150    index RULE_IDX_R, which counts from the right side (or bottom) of the page
151    left (or up), according to whether AXIS is H or V, respectively.  That is,
152    if RULE_IDX_R is 0, then the offset is that of the rightmost or bottommost
153    rule; if RULE_IDX is 1, then the offset is that of the next rule to the left
154    (or above); and so on. */
155 static int
156 rule_ofs_r (const struct render_page *page, int axis, int rule_idx_r)
157 {
158   return (page->n[axis] - rule_idx_r) * 2;
159 }
160
161 /* Returns the offset in struct render_page's cp[axis] array of the cell with
162    index CELL_IDX.  That is, if CELL_IDX is 0, then the offset is that of the
163    leftmost or topmost cell; if CELL_IDX is 1, then the offset is that of the
164    next cell to the right (or below); and so on. */
165 static int
166 cell_ofs (int cell_idx)
167 {
168   return cell_idx * 2 + 1;
169 }
170
171 /* Returns the width of PAGE along AXIS from OFS0 to OFS1, exclusive. */
172 static int
173 axis_width (const struct render_page *page, int axis, int ofs0, int ofs1)
174 {
175   return page->cp[axis][ofs1] - page->cp[axis][ofs0];
176 }
177
178 /* Returns the total width of PAGE along AXIS. */
179 static int
180 table_width (const struct render_page *page, int axis)
181 {
182   return page->cp[axis][2 * page->n[axis] + 1];
183 }
184
185 /* Returns the width of the headers in PAGE along AXIS. */
186 static int
187 headers_width (const struct render_page *page, int axis)
188 {
189   return axis_width (page, axis, rule_ofs (0), cell_ofs (page->h[axis]));
190 }
191
192 /* Returns the width of cell X along AXIS in PAGE. */
193 static int
194 cell_width (const struct render_page *page, int axis, int x)
195 {
196   return axis_width (page, axis, cell_ofs (x), cell_ofs (x) + 1);
197 }
198
199 /* Returns the width of rule X along AXIS in PAGE. */
200 static int
201 rule_width (const struct render_page *page, int axis, int x)
202 {
203   return axis_width (page, axis, rule_ofs (x), rule_ofs (x) + 1);
204 }
205
206 /* Returns the width of rule X along AXIS in PAGE. */
207 static int
208 rule_width_r (const struct render_page *page, int axis, int x)
209 {
210   int ofs = rule_ofs_r (page, axis, x);
211   return axis_width (page, axis, ofs, ofs + 1);
212 }
213
214 /* Returns the width of cells X0 through X1, exclusive, along AXIS in PAGE. */
215 static int
216 joined_width (const struct render_page *page, int axis, int x0, int x1)
217 {
218   return axis_width (page, axis, cell_ofs (x0), cell_ofs (x1) - 1);
219 }
220
221 /* Returns the width of the widest cell, excluding headers, along AXIS in
222    PAGE. */
223 static int
224 max_cell_width (const struct render_page *page, int axis)
225 {
226   int x0 = page->h[axis];
227   int x1 = page->n[axis];
228
229   int max = 0;
230   for (int x = x0; x < x1; x++)
231     {
232       int w = cell_width (page, axis, x);
233       if (w > max)
234         max = w;
235     }
236   return max;
237 }
238 \f
239 /* A cell that doesn't completely fit on the render_page. */
240 struct render_overflow
241   {
242     struct hmap_node node;      /* In render_page's 'overflows' hmap. */
243
244     /* Occupied region of page.
245
246        d[H][0] is the leftmost column.
247        d[H][1] is the rightmost column, plus 1.
248        d[V][0] is the top row.
249        d[V][1] is the bottom row, plus 1.
250
251        The cell in its original table might occupy a larger region.  This
252        member reflects the size of the cell in the current render_page, after
253        trimming off any rows or columns due to page-breaking. */
254     int d[TABLE_N_AXES];
255
256     /* The space that has been trimmed off the cell:
257
258        overflow[H][0]: space trimmed off its left side.
259        overflow[H][1]: space trimmed off its right side.
260        overflow[V][0]: space trimmed off its top.
261        overflow[V][1]: space trimmed off its bottom.
262
263        During rendering, this information is used to position the rendered
264        portion of the cell within the available space.
265
266        When a cell is rendered, sometimes it is permitted to spill over into
267        space that is ordinarily reserved for rules.  Either way, this space is
268        still included in overflow values.
269
270        Suppose, for example, that a cell that joins 2 columns has a width of 60
271        pixels and content "abcdef", that the 2 columns that it joins have
272        widths of 20 and 30 pixels, respectively, and that therefore the rule
273        between the two joined columns has a width of 10 (20 + 10 + 30 = 60).
274        It might render like this, if each character is 10x10, and showing a few
275        extra table cells for context:
276
277                                      +------+
278                                      |abcdef|
279                                      +--+---+
280                                      |gh|ijk|
281                                      +--+---+
282
283        If this render_page is broken at the rule that separates "gh" from
284        "ijk", then the page that contains the left side of the "abcdef" cell
285        will have overflow[H][1] of 10 + 30 = 40 for its portion of the cell,
286        and the page that contains the right side of the cell will have
287        overflow[H][0] of 20 + 10 = 30.  The two resulting pages would look like
288        this:
289
290
291                                        +---
292                                        |abc
293                                        +--+
294                                        |gh|
295                                        +--+
296
297        and:
298
299                                        ----+
300                                        cdef|
301                                        +---+
302                                        |ijk|
303                                        +---+
304     */
305     int overflow[TABLE_N_AXES][2];
306   };
307
308 /* Returns a hash value for (,Y). */
309 static unsigned int
310 hash_cell (int x, int y)
311 {
312   return hash_int (x + (y << 16), 0);
313 }
314
315 /* Searches PAGE's set of render_overflow for one whose top-left cell is
316    (X,Y).  Returns it, if there is one, otherwise a null pointer. */
317 static const struct render_overflow *
318 find_overflow (const struct render_page *page, int x, int y)
319 {
320   if (!hmap_is_empty (&page->overflows))
321     {
322       const struct render_overflow *of;
323
324       HMAP_FOR_EACH_WITH_HASH (of, struct render_overflow, node,
325                                hash_cell (x, y), &page->overflows)
326         if (x == of->d[H] && y == of->d[V])
327           return of;
328     }
329
330   return NULL;
331 }
332 \f
333 /* Row or column dimensions.  Used to figure the size of a table in
334    render_page_create() and discarded after that. */
335 struct render_row
336   {
337     /* Width without considering rows (or columns) that span more than one (or
338        column). */
339     int unspanned;
340
341     /* Width taking spanned rows (or columns) into consideration. */
342     int width;
343   };
344
345 /* Modifies the 'width' members of the N elements of ROWS so that their sum,
346    when added to rule widths RULES[1] through RULES[N - 1] inclusive, is at
347    least WIDTH. */
348 static void
349 distribute_spanned_width (int width,
350                           struct render_row *rows, const int *rules, int n)
351 {
352   /* Sum up the unspanned widths of the N rows for use as weights. */
353   int total_unspanned = 0;
354   for (int x = 0; x < n; x++)
355     total_unspanned += rows[x].unspanned;
356   for (int x = 0; x < n - 1; x++)
357     total_unspanned += rules[x + 1];
358   if (total_unspanned >= width)
359     return;
360
361   /* The algorithm used here is based on the following description from HTML 4:
362
363          For cells that span multiple columns, a simple approach consists of
364          apportioning the min/max widths evenly to each of the constituent
365          columns.  A slightly more complex approach is to use the min/max
366          widths of unspanned cells to weight how spanned widths are
367          apportioned.  Experiments suggest that a blend of the two approaches
368          gives good results for a wide range of tables.
369
370      We blend the two approaches half-and-half, except that we cannot use the
371      unspanned weights when 'total_unspanned' is 0 (because that would cause a
372      division by zero).
373
374      The calculation we want to do is this:
375
376         w0 = width / n
377         w1 = width * (column's unspanned width) / (total unspanned width)
378         (column's width) = (w0 + w1) / 2
379
380      We implement it as a precise calculation in integers by multiplying w0 and
381      w1 by the common denominator of all three calculations (d), dividing that
382      out in the column width calculation, and then keeping the remainder for
383      the next iteration.
384
385      (We actually compute the unspanned width of a column as twice the
386      unspanned width, plus the width of the rule on the left, plus the width of
387      the rule on the right.  That way each rule contributes to both the cell on
388      its left and on its right.)
389   */
390   long long int d0 = n;
391   long long int d1 = 2LL * MAX (total_unspanned, 1);
392   long long int d = d0 * d1;
393   if (total_unspanned > 0)
394     d *= 2;
395   long long int w = d / 2;
396   for (int x = 0; x < n; x++)
397     {
398       w += width * d1;
399       if (total_unspanned > 0)
400         {
401           long long int unspanned = rows[x].unspanned * 2LL;
402           if (x < n - 1)
403             unspanned += rules[x + 1];
404           if (x > 0)
405             unspanned += rules[x];
406           w += width * unspanned * d0;
407         }
408
409       rows[x].width = MAX (rows[x].width, w / d);
410       w -= rows[x].width * d;
411     }
412 }
413
414 /* Initializes PAGE->cp[AXIS] from the row widths in ROWS and the rule widths
415    in RULES. */
416 static void
417 accumulate_row_widths (const struct render_page *page, enum table_axis axis,
418                        const struct render_row *rows, const int *rules)
419 {
420   int n = page->n[axis];
421   int *cp = page->cp[axis];
422   cp[0] = 0;
423   for (int z = 0; z < n; z++)
424     {
425       cp[1] = cp[0] + rules[z];
426       cp[2] = cp[1] + rows[z].width;
427       cp += 2;
428     }
429   cp[1] = cp[0] + rules[n];
430 }
431
432 /* Returns the sum of widths of the N ROWS and N+1 RULES. */
433 static int
434 calculate_table_width (int n, const struct render_row *rows, int *rules)
435 {
436   int width = 0;
437   for (int x = 0; x < n; x++)
438     width += rows[x].width;
439   for (int x = 0; x <= n; x++)
440     width += rules[x];
441
442   return width;
443 }
444 \f
445 /* Rendering utility functions. */
446
447 /* Returns the width of the rule in TABLE that is at offset Z along axis A, if
448    rendered with PARAMS.  */
449 static int
450 measure_rule (const struct render_params *params, const struct table *table,
451               enum table_axis a, int z)
452 {
453   enum table_axis b = !a;
454
455   /* Determine all types of rules that are present, as a bitmap in 'rules'
456      where rule type 't' is present if bit 2**t is set. */
457   unsigned int rules = 0;
458   int d[TABLE_N_AXES];
459   d[a] = z;
460   for (d[b] = 0; d[b] < table->n[b]; d[b]++)
461     rules |= 1u << table_get_rule (table, a, d[H], d[V]).stroke;
462
463   /* Turn off TABLE_STROKE_NONE because it has width 0 and we needn't bother.
464      However, if the device doesn't support margins, make sure that there is at
465      least a small gap between cells (but we don't need any at the left or
466      right edge of the table). */
467   if (rules & (1u << TABLE_STROKE_NONE))
468     {
469       rules &= ~(1u << TABLE_STROKE_NONE);
470       if (z > 0 && z < table->n[a] && !params->supports_margins && a == H)
471         rules |= 1u << TABLE_STROKE_SOLID;
472     }
473
474   /* Calculate maximum width of the rules that are present. */
475   int width = 0;
476   for (size_t i = 0; i < TABLE_N_STROKES; i++)
477     if (rules & (1u << i))
478       width = MAX (width, params->line_widths[i]);
479   return width;
480 }
481
482 /* Allocates and returns a new render_page using PARAMS and TABLE.  Allocates
483    space for rendering a table with dimensions given in N.  The caller must
484    initialize most of the members itself. */
485 static struct render_page *
486 render_page_allocate__ (const struct render_params *params,
487                         struct table *table, int n[TABLE_N_AXES])
488 {
489   struct render_page *page = xmalloc (sizeof *page);
490   page->params = params;
491   page->table = table;
492   page->ref_cnt = 1;
493   page->n[H] = n[H];
494   page->n[V] = n[V];
495
496   for (int i = 0; i < TABLE_N_AXES; i++)
497     page->cp[i] = xcalloc ((2 * n[i] + 2) , sizeof *page->cp[i]);
498
499   hmap_init (&page->overflows);
500   memset (page->is_edge_cutoff, 0, sizeof page->is_edge_cutoff);
501
502   return page;
503 }
504
505 /* Allocates and returns a new render_page using PARAMS and TABLE.  Allocates
506    space for all of the members of the new page, but the caller must initialize
507    the 'cp' member itself. */
508 static struct render_page *
509 render_page_allocate (const struct render_params *params, struct table *table)
510 {
511   struct render_page *page = render_page_allocate__ (params, table, table->n);
512   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
513     {
514       page->h[a] = table->h[a];
515       page->r[a][0] = table->h[a];
516       page->r[a][1] = table->n[a];
517     }
518   return page;
519 }
520
521 /* Allocates and returns a new render_page for PARAMS and TABLE, initializing
522    cp[H] in the new page from ROWS and RULES.  The caller must still initialize
523    cp[V]. */
524 static struct render_page *
525 create_page_with_exact_widths (const struct render_params *params,
526                                struct table *table,
527                                const struct render_row *rows, int *rules)
528 {
529   struct render_page *page = render_page_allocate (params, table);
530   accumulate_row_widths (page, H, rows, rules);
531   return page;
532 }
533
534 /* Allocates and returns a new render_page for PARAMS and TABLE.
535
536    Initializes cp[H] in the new page by setting the width of each row 'i' to
537    somewhere between the minimum cell width ROW_MIN[i].width and the maximum
538    ROW_MAX[i].width.  Sets the width of rules to those in RULES.
539
540    W_MIN is the sum of ROWS_MIN[].width.
541
542    W_MAX is the sum of ROWS_MAX[].width.
543
544    The caller must still initialize cp[V]. */
545 static struct render_page *
546 create_page_with_interpolated_widths (const struct render_params *params,
547                                       struct table *table,
548                                       const struct render_row *rows_min,
549                                       const struct render_row *rows_max,
550                                       int w_min, int w_max, const int *rules)
551 {
552   const int n = table->n[H];
553   const long long int avail = params->size[H] - w_min;
554   const long long int wanted = w_max - w_min;
555
556   assert (wanted > 0);
557
558   struct render_page *page = render_page_allocate (params, table);
559
560   int *cph = page->cp[H];
561   *cph = 0;
562   long long int w = wanted / 2;
563   for (int x = 0; x < n; x++)
564     {
565       w += avail * (rows_max[x].width - rows_min[x].width);
566       int extra = w / wanted;
567       w -= extra * wanted;
568
569       cph[1] = cph[0] + rules[x];
570       cph[2] = cph[1] + rows_min[x].width + extra;
571       cph += 2;
572     }
573   cph[1] = cph[0] + rules[n];
574
575   assert (page->cp[H][n * 2 + 1] == params->size[H]);
576   return page;
577 }
578 \f
579 /* Maps a contiguous range of cells from a page to the underlying table along
580    the horizontal or vertical dimension. */
581 struct map
582   {
583     int p0;                     /* First ordinate in the page. */
584     int t0;                     /* First ordinate in the table. */
585     int n;                      /* Number of ordinates in page and table. */
586   };
587
588 /* Initializes M to a mapping from PAGE to PAGE->table along axis A.  The
589    mapping includes ordinate Z (in PAGE). */
590 static void
591 get_map (const struct render_page *page, enum table_axis a, int z,
592          struct map *m)
593 {
594   if (z < page->h[a])
595     {
596       m->p0 = 0;
597       m->t0 = 0;
598       m->n = page->h[a];
599     }
600   else
601     {
602       assert (z < page->n[a]);
603       m->p0 = page->h[a];
604       m->t0 = page->r[a][0];
605       m->n = page->r[a][1] - page->r[a][0];
606     }
607 }
608
609 /* Initializes CELL with the contents of the table cell at column X and row Y
610    within PAGE.  When CELL is no longer needed, the caller is responsible for
611    freeing it by calling table_cell_free(CELL).
612
613    The caller must ensure that CELL is destroyed before TABLE is unref'ed.
614
615    This is equivalent to table_get_cell(), except X and Y are in terms of the
616    page's rows and columns rather than the underlying table's. */
617 static void
618 render_get_cell (const struct render_page *page, int x, int y,
619                  struct table_cell *cell)
620 {
621   int d[TABLE_N_AXES] = { [H] = x, [V] = y };
622   struct map map[TABLE_N_AXES];
623
624   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
625     {
626       struct map *m = &map[a];
627       get_map (page, a, d[a], m);
628       d[a] += m->t0 - m->p0;
629     }
630   table_get_cell (page->table, d[H], d[V], cell);
631
632   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
633     {
634       struct map *m = &map[a];
635
636       for (int i = 0; i < 2; i++)
637         cell->d[a][i] -= m->t0 - m->p0;
638       cell->d[a][0] = MAX (cell->d[a][0], m->p0);
639       cell->d[a][1] = MIN (cell->d[a][1], m->p0 + m->n);
640     }
641 }
642
643 /* Creates and returns a new render_page for rendering TABLE on a device
644    described by PARAMS.
645
646    The new render_page will be suitable for rendering on a device whose page
647    size is PARAMS->size, but the caller is responsible for actually breaking it
648    up to fit on such a device, using the render_break abstraction.  */
649 static struct render_page *
650 render_page_create (const struct render_params *params, struct table *table,
651                     int min_width)
652 {
653   enum { MIN, MAX };
654
655   int nc = table->n[H];
656   int nr = table->n[V];
657
658   /* Figure out rule widths. */
659   int *rules[TABLE_N_AXES];
660   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
661     {
662       int n = table->n[axis] + 1;
663
664       rules[axis] = xnmalloc (n, sizeof *rules);
665       for (int z = 0; z < n; z++)
666         rules[axis][z] = measure_rule (params, table, axis, z);
667     }
668
669   /* Calculate minimum and maximum widths of cells that do not
670      span multiple columns. */
671   struct render_row *columns[2];
672   for (int i = 0; i < 2; i++)
673     columns[i] = xcalloc (nc, sizeof *columns[i]);
674   for (int y = 0; y < nr; y++)
675     for (int x = 0; x < nc;)
676       {
677         struct table_cell cell;
678
679         table_get_cell (table, x, y, &cell);
680         if (y == cell.d[V][0])
681           {
682             if (table_cell_colspan (&cell) == 1)
683               {
684                 int w[2];
685                 params->ops->measure_cell_width (params->aux, &cell,
686                                                  &w[MIN], &w[MAX]);
687                 for (int i = 0; i < 2; i++)
688                   if (columns[i][x].unspanned < w[i])
689                     columns[i][x].unspanned = w[i];
690               }
691           }
692         x = cell.d[H][1];
693       }
694
695   /* Distribute widths of spanned columns. */
696   for (int i = 0; i < 2; i++)
697     for (int x = 0; x < nc; x++)
698       columns[i][x].width = columns[i][x].unspanned;
699   for (int y = 0; y < nr; y++)
700     for (int x = 0; x < nc;)
701       {
702         struct table_cell cell;
703
704         table_get_cell (table, x, y, &cell);
705         if (y == cell.d[V][0] && table_cell_colspan (&cell) > 1)
706           {
707             int w[2];
708
709             params->ops->measure_cell_width (params->aux, &cell,
710                                              &w[MIN], &w[MAX]);
711             for (int i = 0; i < 2; i++)
712               distribute_spanned_width (w[i], &columns[i][cell.d[H][0]],
713                                         rules[H], table_cell_colspan (&cell));
714           }
715         x = cell.d[H][1];
716       }
717   if (min_width > 0)
718     for (int i = 0; i < 2; i++)
719       distribute_spanned_width (min_width, &columns[i][0], rules[H], nc);
720
721   /* In pathological cases, spans can cause the minimum width of a column to
722      exceed the maximum width.  This bollixes our interpolation algorithm
723      later, so fix it up. */
724   for (int i = 0; i < nc; i++)
725     if (columns[MIN][i].width > columns[MAX][i].width)
726       columns[MAX][i].width = columns[MIN][i].width;
727
728   /* Decide final column widths. */
729   int table_widths[2];
730   for (int i = 0; i < 2; i++)
731     table_widths[i] = calculate_table_width (table->n[H],
732                                              columns[i], rules[H]);
733
734   struct render_page *page;
735   if (table_widths[MAX] <= params->size[H])
736     {
737       /* Fits even with maximum widths.  Use them. */
738       page = create_page_with_exact_widths (params, table, columns[MAX],
739                                             rules[H]);
740     }
741   else if (table_widths[MIN] <= params->size[H])
742     {
743       /* Fits with minimum widths, so distribute the leftover space. */
744       page = create_page_with_interpolated_widths (
745         params, table, columns[MIN], columns[MAX],
746         table_widths[MIN], table_widths[MAX], rules[H]);
747     }
748   else
749     {
750       /* Doesn't fit even with minimum widths.  Assign minimums for now, and
751          later we can break it horizontally into multiple pages. */
752       page = create_page_with_exact_widths (params, table, columns[MIN],
753                                             rules[H]);
754     }
755
756   /* Calculate heights of cells that do not span multiple rows. */
757   struct render_row *rows = XCALLOC (nr, struct render_row);
758   for (int y = 0; y < nr; y++)
759     for (int x = 0; x < nc;)
760       {
761         struct render_row *r = &rows[y];
762         struct table_cell cell;
763
764         render_get_cell (page, x, y, &cell);
765         if (y == cell.d[V][0] && table_cell_rowspan (&cell) == 1)
766           {
767             int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
768             int h = params->ops->measure_cell_height (params->aux,
769                                                       &cell, w);
770             if (h > r->unspanned)
771               r->unspanned = r->width = h;
772           }
773         x = cell.d[H][1];
774       }
775   for (int i = 0; i < 2; i++)
776     free (columns[i]);
777
778   /* Distribute heights of spanned rows. */
779   for (int y = 0; y < nr; y++)
780     for (int x = 0; x < nc;)
781       {
782         struct table_cell cell;
783
784         render_get_cell (page, x, y, &cell);
785         if (y == cell.d[V][0] && table_cell_rowspan (&cell) > 1)
786           {
787             int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
788             int h = params->ops->measure_cell_height (params->aux, &cell, w);
789             distribute_spanned_width (h, &rows[cell.d[V][0]], rules[V],
790                                       table_cell_rowspan (&cell));
791           }
792         x = cell.d[H][1];
793       }
794
795   /* Decide final row heights. */
796   accumulate_row_widths (page, V, rows, rules[V]);
797   free (rows);
798
799   /* Measure headers.  If they are "too big", get rid of them.  */
800   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
801     {
802       int hw = headers_width (page, axis);
803       if (hw * 2 >= page->params->size[axis]
804           || hw + max_cell_width (page, axis) > page->params->size[axis])
805         {
806           page->h[axis] = 0;
807           page->r[axis][0] = 0;
808           page->r[axis][1] = page->n[axis];
809         }
810     }
811
812   free (rules[H]);
813   free (rules[V]);
814
815   return page;
816 }
817
818 /* Increases PAGE's reference count. */
819 struct render_page *
820 render_page_ref (const struct render_page *page_)
821 {
822   struct render_page *page = CONST_CAST (struct render_page *, page_);
823   page->ref_cnt++;
824   return page;
825 }
826
827 /* Decreases PAGE's reference count and destroys PAGE if this causes the
828    reference count to fall to zero. */
829 static void
830 render_page_unref (struct render_page *page)
831 {
832   if (page != NULL && --page->ref_cnt == 0)
833     {
834       struct render_overflow *overflow, *next;
835       HMAP_FOR_EACH_SAFE (overflow, next, struct render_overflow, node,
836                           &page->overflows)
837         free (overflow);
838       hmap_destroy (&page->overflows);
839
840       table_unref (page->table);
841
842       for (int i = 0; i < TABLE_N_AXES; ++i)
843         free (page->cp[i]);
844
845       free (page);
846     }
847 }
848
849 /* Returns the size of PAGE along AXIS.  (This might be larger than the page
850    size specified in the parameters passed to render_page_create().  Use a
851    render_break to break up a render_page into page-sized chunks.) */
852 static int
853 render_page_get_size (const struct render_page *page, enum table_axis axis)
854 {
855   return page->cp[axis][page->n[axis] * 2 + 1];
856 }
857
858 static int
859 render_page_get_best_breakpoint (const struct render_page *page, int height)
860 {
861   /* If there's no room for at least the top row and the rules above and below
862      it, don't include any of the table. */
863   if (page->cp[V][3] > height)
864     return 0;
865
866   /* Otherwise include as many rows and rules as we can. */
867   for (int y = 5; y <= 2 * page->n[V] + 1; y += 2)
868     if (page->cp[V][y] > height)
869       return page->cp[V][y - 2];
870   return height;
871 }
872 \f
873 /* Drawing render_pages. */
874
875 /* This is like table_get_rule() except that D is in terms of the page's rows
876    and column rather than the underlying table's. */
877 static struct table_border_style
878 get_rule (const struct render_page *page, enum table_axis axis,
879           const int d_[TABLE_N_AXES])
880 {
881   int d[TABLE_N_AXES] = { d_[0] / 2, d_[1] / 2 };
882   int d2 = -1;
883
884   enum table_axis a = axis;
885   if (d[a] < page->h[a])
886     /* Nothing to do */;
887   else if (d[a] <= page->n[a])
888     {
889       if (page->h[a] && d[a] == page->h[a])
890         d2 = page->h[a];
891       d[a] += page->r[a][0] - page->h[a];
892     }
893
894   enum table_axis b = !axis;
895   struct map m;
896   get_map (page, b, d[b], &m);
897   d[b] += m.t0 - m.p0;
898
899   struct table_border_style border
900     = table_get_rule (page->table, axis, d[H], d[V]);
901   if (d2 >= 0)
902     {
903       d[a] = d2;
904       struct table_border_style border2 = table_get_rule (page->table, axis,
905                                                           d[H], d[V]);
906       border.stroke = table_stroke_combine (border.stroke, border2.stroke);
907     }
908   return border;
909 }
910
911 static bool
912 is_rule (int z)
913 {
914   return !(z & 1);
915 }
916
917 bool
918 render_direction_rtl (void)
919 {
920   /* TRANSLATORS: Do not translate this string.  If the script of your language
921      reads from right to left (eg Persian, Arabic, Hebrew etc), then replace
922      this string with "output-direction-rtl".  Otherwise either leave it
923      untranslated or copy it verbatim. */
924   const char *dir = _("output-direction-ltr");
925   if (0 == strcmp ("output-direction-rtl", dir))
926     return true;
927
928   if (0 != strcmp ("output-direction-ltr", dir))
929     fprintf (stderr, "This localisation has been incorrectly translated.  "
930              "Complain to the translator.\n");
931
932   return false;
933 }
934
935 static void
936 render_rule (const struct render_page *page, const int ofs[TABLE_N_AXES],
937              const int d[TABLE_N_AXES])
938 {
939   const struct table_border_style none = { .stroke = TABLE_STROKE_NONE };
940   struct table_border_style styles[TABLE_N_AXES][2];
941
942   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
943     {
944       enum table_axis b = !a;
945
946       if (!is_rule (d[a])
947           || (page->is_edge_cutoff[a][0] && d[a] == 0)
948           || (page->is_edge_cutoff[a][1] && d[a] == page->n[a] * 2))
949         styles[a][0] = styles[a][1] = none;
950       else if (is_rule (d[b]))
951         {
952           if (d[b] > 0)
953             {
954               int e[TABLE_N_AXES];
955               e[H] = d[H];
956               e[V] = d[V];
957               e[b]--;
958               styles[a][0] = get_rule (page, a, e);
959             }
960           else
961             styles[a][0] = none;
962
963           if (d[b] / 2 < page->n[b])
964             styles[a][1] = get_rule (page, a, d);
965           else
966             styles[a][1] = none;
967         }
968       else
969         styles[a][0] = styles[a][1] = get_rule (page, a, d);
970     }
971
972   if (styles[H][0].stroke != TABLE_STROKE_NONE
973       || styles[H][1].stroke != TABLE_STROKE_NONE
974       || styles[V][0].stroke != TABLE_STROKE_NONE
975       || styles[V][1].stroke != TABLE_STROKE_NONE)
976     {
977       int bb[TABLE_N_AXES][2];
978
979       bb[H][0] = ofs[H] + page->cp[H][d[H]];
980       bb[H][1] = ofs[H] + page->cp[H][d[H] + 1];
981       if (page->params->rtl)
982         {
983           int temp = bb[H][0];
984           bb[H][0] = render_page_get_size (page, H) - bb[H][1];
985           bb[H][1] = render_page_get_size (page, H) - temp;
986         }
987       bb[V][0] = ofs[V] + page->cp[V][d[V]];
988       bb[V][1] = ofs[V] + page->cp[V][d[V] + 1];
989       page->params->ops->draw_line (page->params->aux, bb, styles);
990     }
991 }
992
993 static void
994 render_cell (const struct render_page *page, const int ofs[TABLE_N_AXES],
995              const struct table_cell *cell)
996 {
997   const bool debugging = false;
998   if (debugging)
999     {
1000       printf ("render ");
1001       if (cell->d[H][0] + 1 == cell->d[H][1])
1002         printf ("%d", cell->d[H][0]);
1003       else
1004         printf ("%d-%d", cell->d[H][0], cell->d[H][1] - 1);
1005       printf (",");
1006       if (cell->d[V][0] + 1 == cell->d[V][1])
1007         printf ("%d", cell->d[V][0]);
1008       else
1009         printf ("%d-%d", cell->d[V][0], cell->d[V][1] - 1);
1010
1011       char *value = pivot_value_to_string (cell->value, NULL);
1012       printf (": \"%s\"\n", value);
1013       free (value);
1014     }
1015
1016   int bb[TABLE_N_AXES][2];
1017   int clip[TABLE_N_AXES][2];
1018
1019   bb[H][0] = clip[H][0] = ofs[H] + page->cp[H][cell->d[H][0] * 2 + 1];
1020   bb[H][1] = clip[H][1] = ofs[H] + page->cp[H][cell->d[H][1] * 2];
1021   if (page->params->rtl)
1022     {
1023       int temp = bb[H][0];
1024       bb[H][0] = clip[H][0] = render_page_get_size (page, H) - bb[H][1];
1025       bb[H][1] = clip[H][1] = render_page_get_size (page, H) - temp;
1026     }
1027   bb[V][0] = clip[V][0] = ofs[V] + page->cp[V][cell->d[V][0] * 2 + 1];
1028   bb[V][1] = clip[V][1] = ofs[V] + page->cp[V][cell->d[V][1] * 2];
1029
1030   enum table_valign valign = cell->cell_style->valign;
1031   int valign_offset = 0;
1032   if (valign != TABLE_VALIGN_TOP)
1033     {
1034       int height = page->params->ops->measure_cell_height (
1035         page->params->aux, cell, bb[H][1] - bb[H][0]);
1036       int extra = bb[V][1] - bb[V][0] - height;
1037       if (extra > 0)
1038         {
1039           if (valign == TABLE_VALIGN_CENTER)
1040             extra /= 2;
1041           valign_offset += extra;
1042         }
1043     }
1044
1045   const struct render_overflow *of = find_overflow (
1046     page, cell->d[H][0], cell->d[V][0]);
1047   if (of)
1048     for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
1049       {
1050         if (of->overflow[axis][0])
1051           {
1052             bb[axis][0] -= of->overflow[axis][0];
1053             if (cell->d[axis][0] == 0 && !page->is_edge_cutoff[axis][0])
1054               clip[axis][0] = ofs[axis] + page->cp[axis][cell->d[axis][0] * 2];
1055           }
1056         if (of->overflow[axis][1])
1057           {
1058             bb[axis][1] += of->overflow[axis][1];
1059             if (cell->d[axis][1] == page->n[axis]
1060                 && !page->is_edge_cutoff[axis][1])
1061               clip[axis][1] = ofs[axis] + page->cp[axis][cell->d[axis][1] * 2
1062                                                          + 1];
1063           }
1064       }
1065
1066   int spill[TABLE_N_AXES][2];
1067   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
1068     {
1069       spill[axis][0] = rule_width (page, axis, cell->d[axis][0]) / 2;
1070       spill[axis][1] = rule_width (page, axis, cell->d[axis][1]) / 2;
1071     }
1072
1073   int color_idx = (cell->d[V][0] < page->h[V]
1074                    ? 0
1075                    : (cell->d[V][0] - page->h[V]) & 1);
1076   page->params->ops->draw_cell (page->params->aux, cell, color_idx,
1077                                 bb, valign_offset, spill, clip);
1078 }
1079
1080 /* Draws the cells of PAGE indicated in BB. */
1081 static void
1082 render_page_draw_cells (const struct render_page *page,
1083                         int ofs[TABLE_N_AXES], int bb[TABLE_N_AXES][2])
1084 {
1085   for (int y = bb[V][0]; y < bb[V][1]; y++)
1086     for (int x = bb[H][0]; x < bb[H][1];)
1087       if (!is_rule (x) && !is_rule (y))
1088         {
1089           struct table_cell cell;
1090
1091           render_get_cell (page, x / 2, y / 2, &cell);
1092           if (y / 2 == bb[V][0] / 2 || y / 2 == cell.d[V][0])
1093             render_cell (page, ofs, &cell);
1094           x = rule_ofs (cell.d[H][1]);
1095         }
1096       else
1097         x++;
1098
1099   for (int y = bb[V][0]; y < bb[V][1]; y++)
1100     for (int x = bb[H][0]; x < bb[H][1]; x++)
1101       if (is_rule (x) || is_rule (y))
1102         {
1103           int d[TABLE_N_AXES];
1104           d[H] = x;
1105           d[V] = y;
1106           render_rule (page, ofs, d);
1107         }
1108 }
1109
1110 /* Renders PAGE, by calling the 'draw_line' and 'draw_cell' functions from the
1111    render_params provided to render_page_create(). */
1112 static void
1113 render_page_draw (const struct render_page *page, int ofs[TABLE_N_AXES])
1114 {
1115   int bb[TABLE_N_AXES][2];
1116
1117   bb[H][0] = 0;
1118   bb[H][1] = page->n[H] * 2 + 1;
1119   bb[V][0] = 0;
1120   bb[V][1] = page->n[V] * 2 + 1;
1121
1122   render_page_draw_cells (page, ofs, bb);
1123 }
1124
1125 /* Returns the greatest value i, 0 <= i < n, such that cp[i] <= x0. */
1126 static int
1127 get_clip_min_extent (int x0, const int cp[], int n)
1128 {
1129   int low = 0;
1130   int high = n;
1131   int best = 0;
1132   while (low < high)
1133     {
1134       int middle = low + (high - low) / 2;
1135
1136       if (cp[middle] <= x0)
1137         {
1138           best = middle;
1139           low = middle + 1;
1140         }
1141       else
1142         high = middle;
1143     }
1144
1145   return best;
1146 }
1147
1148 /* Returns the least value i, 0 <= i < n, such that cp[i] >= x1. */
1149 static int
1150 get_clip_max_extent (int x1, const int cp[], int n)
1151 {
1152   int low = 0;
1153   int high = n;
1154   int best = n;
1155   while (low < high)
1156     {
1157       int middle = low + (high - low) / 2;
1158
1159       if (cp[middle] >= x1)
1160         best = high = middle;
1161       else
1162         low = middle + 1;
1163     }
1164
1165   while (best > 0 && cp[best - 1] == cp[best])
1166     best--;
1167
1168   return best;
1169 }
1170
1171 /* Renders the cells of PAGE that intersect (X,Y)-(X+W,Y+H), by calling the
1172    'draw_line' and 'draw_cell' functions from the render_params provided to
1173    render_page_create(). */
1174 static void
1175 render_page_draw_region (const struct render_page *page,
1176                          int ofs[TABLE_N_AXES], int clip[TABLE_N_AXES][2])
1177 {
1178   int bb[TABLE_N_AXES][2];
1179
1180   bb[H][0] = get_clip_min_extent (clip[H][0], page->cp[H], page->n[H] * 2 + 1);
1181   bb[H][1] = get_clip_max_extent (clip[H][1], page->cp[H], page->n[H] * 2 + 1);
1182   bb[V][0] = get_clip_min_extent (clip[V][0], page->cp[V], page->n[V] * 2 + 1);
1183   bb[V][1] = get_clip_max_extent (clip[V][1], page->cp[V], page->n[V] * 2 + 1);
1184
1185   render_page_draw_cells (page, ofs, bb);
1186 }
1187
1188 /* Breaking up tables to fit on a page. */
1189
1190 /* An iterator for breaking render_pages into smaller chunks. */
1191 struct render_break
1192   {
1193     struct render_page *page;   /* Page being broken up. */
1194     enum table_axis axis;       /* Axis along which 'page' is being broken. */
1195     int z;                      /* Next cell along 'axis'. */
1196     int pixel;                  /* Pixel offset within cell 'z' (usually 0). */
1197     int hw;                     /* Width of headers of 'page' along 'axis'. */
1198   };
1199
1200 static int needed_size (const struct render_break *, int cell);
1201 static bool cell_is_breakable (const struct render_break *, int cell);
1202 static struct render_page *render_page_select (const struct render_page *,
1203                                                enum table_axis,
1204                                                int z0, int p0,
1205                                                int z1, int p1);
1206
1207 /* Initializes render_break B for breaking PAGE along AXIS.
1208    Takes ownership of PAGE. */
1209 static void
1210 render_break_init (struct render_break *b, struct render_page *page,
1211                    enum table_axis axis)
1212 {
1213   b->page = page;
1214   b->axis = axis;
1215   b->z = page->h[axis];
1216   b->pixel = 0;
1217   b->hw = headers_width (page, axis);
1218 }
1219
1220 /* Initializes B as a render_break structure for which
1221    render_break_has_next() always returns false. */
1222 static void
1223 render_break_init_empty (struct render_break *b)
1224 {
1225   b->page = NULL;
1226   b->axis = TABLE_HORZ;
1227   b->z = 0;
1228   b->pixel = 0;
1229   b->hw = 0;
1230 }
1231
1232 /* Frees B and unrefs the render_page that it owns. */
1233 static void
1234 render_break_destroy (struct render_break *b)
1235 {
1236   if (b != NULL)
1237     {
1238       render_page_unref (b->page);
1239       b->page = NULL;
1240     }
1241 }
1242
1243 /* Returns true if B still has cells that are yet to be returned,
1244    false if all of B's page has been processed. */
1245 static bool
1246 render_break_has_next (const struct render_break *b)
1247 {
1248   const struct render_page *page = b->page;
1249   enum table_axis axis = b->axis;
1250
1251   return page != NULL && b->z < page->n[axis];
1252 }
1253
1254 /* Returns a new render_page that is up to SIZE pixels wide along B's axis.
1255    Returns a null pointer if B has already been completely broken up, or if
1256    SIZE is too small to reasonably render any cells.  The latter will never
1257    happen if SIZE is at least as large as the page size passed to
1258    render_page_create() along B's axis. */
1259 static struct render_page *
1260 render_break_next (struct render_break *b, int size)
1261 {
1262   const struct render_page *page = b->page;
1263   enum table_axis axis = b->axis;
1264   struct render_page *subpage;
1265
1266   if (!render_break_has_next (b))
1267     return NULL;
1268
1269   int pixel = 0;
1270   int z;
1271   for (z = b->z; z < page->n[axis]; z++)
1272     {
1273       int needed = needed_size (b, z + 1);
1274       if (needed > size)
1275         {
1276           if (cell_is_breakable (b, z))
1277             {
1278               /* If there is no right header and we render a partial cell on
1279                  the right side of the body, then we omit the rightmost rule of
1280                  the body.  Otherwise the rendering is deceptive because it
1281                  looks like the whole cell is present instead of a partial
1282                  cell.
1283
1284                  This is similar to code for the left side in needed_size(). */
1285               int rule_allowance = rule_width (page, axis, z);
1286
1287               /* The amount that, if we added cell 'z', the rendering would
1288                  overfill the allocated 'size'. */
1289               int overhang = needed - size - rule_allowance;
1290
1291               /* The width of cell 'z'. */
1292               int cell_size = cell_width (page, axis, z);
1293
1294               /* The amount trimmed off the left side of 'z',
1295                  and the amount left to render. */
1296               int cell_ofs = z == b->z ? b->pixel : 0;
1297               int cell_left = cell_size - cell_ofs;
1298
1299               /* A small but visible width.  */
1300               int em = page->params->font_size[axis];
1301
1302               /* If some of the cell remains to render,
1303                  and there would still be some of the cell left afterward,
1304                  then partially render that much of the cell. */
1305               pixel = (cell_left && cell_left > overhang
1306                        ? cell_left - overhang + cell_ofs
1307                        : 0);
1308
1309               /* If there would be only a tiny amount of the cell left after
1310                  rendering it partially, reduce the amount rendered slightly
1311                  to make the output look a little better. */
1312               if (pixel + em > cell_size)
1313                 pixel = MAX (pixel - em, 0);
1314
1315               /* If we're breaking vertically, then consider whether the cells
1316                  being broken have a better internal breakpoint than the exact
1317                  number of pixels available, which might look bad e.g. because
1318                  it breaks in the middle of a line of text. */
1319               if (axis == TABLE_VERT && page->params->ops->adjust_break)
1320                 for (int x = 0; x < page->n[H];)
1321                   {
1322                     struct table_cell cell;
1323
1324                     render_get_cell (page, x, z, &cell);
1325                     int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
1326                     int better_pixel = page->params->ops->adjust_break (
1327                       page->params->aux, &cell, w, pixel);
1328                     x = cell.d[H][1];
1329
1330                     if (better_pixel < pixel)
1331                       {
1332                         if (better_pixel > (z == b->z ? b->pixel : 0))
1333                           {
1334                             pixel = better_pixel;
1335                             break;
1336                           }
1337                         else if (better_pixel == 0 && z != b->z)
1338                           {
1339                             pixel = 0;
1340                             break;
1341                           }
1342                       }
1343                   }
1344             }
1345           break;
1346         }
1347     }
1348
1349   if (z == b->z && !pixel)
1350     return NULL;
1351
1352   subpage = render_page_select (page, axis, b->z, b->pixel,
1353                                 pixel ? z + 1 : z,
1354                                 pixel ? cell_width (page, axis, z) - pixel
1355                                 : 0);
1356   b->z = z;
1357   b->pixel = pixel;
1358   return subpage;
1359 }
1360
1361 /* Returns the width that would be required along B's axis to render a page
1362    from B's current position up to but not including CELL. */
1363 static int
1364 needed_size (const struct render_break *b, int cell)
1365 {
1366   const struct render_page *page = b->page;
1367   enum table_axis axis = b->axis;
1368
1369   /* Width of left header not including its rightmost rule.  */
1370   int size = axis_width (page, axis, 0, rule_ofs (page->h[axis]));
1371
1372   /* If we have a pixel offset and there is no left header, then we omit the
1373      leftmost rule of the body.  Otherwise the rendering is deceptive because
1374      it looks like the whole cell is present instead of a partial cell.
1375
1376      Otherwise (if there are headers) we will be merging two rules: the
1377      rightmost rule in the header and the leftmost rule in the body.  We assume
1378      that the width of a merged rule is the larger of the widths of either rule
1379      invidiually. */
1380   if (b->pixel == 0 || page->h[axis])
1381     size += MAX (rule_width (page, axis, page->h[axis]),
1382                  rule_width (page, axis, b->z));
1383
1384   /* Width of body, minus any pixel offset in the leftmost cell. */
1385   size += joined_width (page, axis, b->z, cell) - b->pixel;
1386
1387   /* Width of rightmost rule in body merged with leftmost rule in headers. */
1388   size += MAX (rule_width_r (page, axis, 0), rule_width (page, axis, cell));
1389
1390   return size;
1391 }
1392
1393 /* Returns true if CELL along B's axis may be broken across a page boundary.
1394
1395    This is just a heuristic.  Breaking cells across page boundaries can save
1396    space, but it looks ugly. */
1397 static bool
1398 cell_is_breakable (const struct render_break *b, int cell)
1399 {
1400   const struct render_page *page = b->page;
1401   enum table_axis axis = b->axis;
1402
1403   return cell_width (page, axis, cell) >= page->params->min_break[axis];
1404 }
1405 \f
1406 /* render_pager. */
1407
1408 struct render_pager
1409   {
1410     const struct render_params *params;
1411     double scale;
1412
1413     /* An array of "render_page"s to be rendered, in order, vertically.  There
1414        may be up to 5 pages, for the pivot table's title, layers, body,
1415        captions, and footnotes. */
1416     struct render_page *pages[5];
1417     size_t n_pages;
1418
1419     size_t cur_page;
1420     struct render_break x_break;
1421     struct render_break y_break;
1422   };
1423
1424 static void
1425 render_pager_add_table (struct render_pager *p, struct table *table,
1426                         int min_width)
1427 {
1428   if (table)
1429     p->pages[p->n_pages++] = render_page_create (p->params, table, min_width);
1430 }
1431
1432 static void
1433 render_pager_start_page (struct render_pager *p)
1434 {
1435   render_break_init (&p->x_break, render_page_ref (p->pages[p->cur_page++]),
1436                      H);
1437   render_break_init_empty (&p->y_break);
1438 }
1439
1440 /* Creates and returns a new render_pager for rendering PT on the device
1441    with the given PARAMS. */
1442 struct render_pager *
1443 render_pager_create (const struct render_params *params,
1444                      const struct pivot_table *pt,
1445                      const size_t *layer_indexes)
1446 {
1447   if (!layer_indexes)
1448     layer_indexes = pt->current_layer;
1449
1450   struct table *title, *layers, *body, *caption, *footnotes;
1451   pivot_output (pt, layer_indexes, params->printing,
1452                 &title, &layers, &body, &caption, &footnotes, NULL, NULL);
1453
1454   /* Figure out the width of the body of the table.  Use this to determine the
1455      base scale. */
1456   struct render_page *body_page = render_page_create (params, body, 0);
1457   int body_width = table_width (body_page, H);
1458   double scale = 1.0;
1459   if (body_width > params->size[H])
1460     {
1461       if (pt->look->shrink_to_fit[H] && params->ops->scale)
1462         scale = params->size[H] / (double) body_width;
1463       else
1464         {
1465           struct render_break b;
1466           render_break_init (&b, render_page_ref (body_page), H);
1467           struct render_page *subpage
1468             = render_break_next (&b, params->size[H]);
1469           body_width = subpage ? subpage->cp[H][2 * subpage->n[H] + 1] : 0;
1470           render_page_unref (subpage);
1471           render_break_destroy (&b);
1472         }
1473     }
1474
1475   /* Create the pager. */
1476   struct render_pager *p = xmalloc (sizeof *p);
1477   *p = (struct render_pager) { .params = params, .scale = scale };
1478   render_pager_add_table (p, title, body_width);
1479   render_pager_add_table (p, layers, body_width);
1480   p->pages[p->n_pages++] = body_page;
1481   render_pager_add_table (p, caption, 0);
1482   render_pager_add_table (p, footnotes, 0);
1483   assert (p->n_pages <= sizeof p->pages / sizeof *p->pages);
1484
1485   /* If we're shrinking tables to fit the page length, then adjust the scale
1486      factor.
1487
1488      XXX This will sometimes shrink more than needed, because adjusting the
1489      scale factor allows for cells to be "wider", which means that sometimes
1490      they won't break across as much vertical space, thus shrinking the table
1491      vertically more than the scale would imply.  Shrinking only as much as
1492      necessary would require an iterative search. */
1493   if (pt->look->shrink_to_fit[V] && params->ops->scale)
1494     {
1495       int total_height = 0;
1496       for (size_t i = 0; i < p->n_pages; i++)
1497         total_height += table_width (p->pages[i], V);
1498       if (total_height * p->scale >= params->size[V])
1499         p->scale *= params->size[V] / (double) total_height;
1500     }
1501
1502   render_pager_start_page (p);
1503
1504   return p;
1505 }
1506
1507 /* Destroys P. */
1508 void
1509 render_pager_destroy (struct render_pager *p)
1510 {
1511   if (p)
1512     {
1513       render_break_destroy (&p->x_break);
1514       render_break_destroy (&p->y_break);
1515       for (size_t i = 0; i < p->n_pages; i++)
1516         render_page_unref (p->pages[i]);
1517       free (p);
1518     }
1519 }
1520
1521 /* Returns true if P has content remaining to render, false if rendering is
1522    done. */
1523 bool
1524 render_pager_has_next (const struct render_pager *p_)
1525 {
1526   struct render_pager *p = CONST_CAST (struct render_pager *, p_);
1527
1528   while (!render_break_has_next (&p->y_break))
1529     {
1530       render_break_destroy (&p->y_break);
1531       if (!render_break_has_next (&p->x_break))
1532         {
1533           render_break_destroy (&p->x_break);
1534           if (p->cur_page >= p->n_pages)
1535             {
1536               render_break_init_empty (&p->x_break);
1537               render_break_init_empty (&p->y_break);
1538               return false;
1539             }
1540           render_pager_start_page (p);
1541         }
1542       else
1543         render_break_init (
1544           &p->y_break, render_break_next (&p->x_break,
1545                                           p->params->size[H] / p->scale), V);
1546     }
1547   return true;
1548 }
1549
1550 /* Draws a chunk of content from P to fit in a space that has vertical size
1551    SPACE and the horizontal size specified in the render_params passed to
1552    render_page_create().  Returns the amount of space actually used by the
1553    rendered chunk, which will be 0 if SPACE is too small to render anything or
1554    if no content remains (use render_pager_has_next() to distinguish these
1555    cases). */
1556 int
1557 render_pager_draw_next (struct render_pager *p, int space)
1558 {
1559   if (p->scale != 1.0)
1560     {
1561       p->params->ops->scale (p->params->aux, p->scale);
1562       space /= p->scale;
1563     }
1564
1565   int ofs[TABLE_N_AXES] = { 0, 0 };
1566   size_t start_page = SIZE_MAX;
1567
1568   while (render_pager_has_next (p))
1569     {
1570       if (start_page == p->cur_page)
1571         break;
1572       start_page = p->cur_page;
1573
1574       struct render_page *page
1575         = render_break_next (&p->y_break, space - ofs[V]);
1576       if (!page)
1577         break;
1578
1579       render_page_draw (page, ofs);
1580       ofs[V] += render_page_get_size (page, V);
1581       render_page_unref (page);
1582     }
1583
1584   if (p->scale != 1.0)
1585     ofs[V] *= p->scale;
1586
1587   return ofs[V];
1588 }
1589
1590 /* Draws all of P's content. */
1591 void
1592 render_pager_draw (const struct render_pager *p)
1593 {
1594   render_pager_draw_region (p, 0, 0, INT_MAX, INT_MAX);
1595 }
1596
1597 /* Draws the region of P's content that lies in the region (X,Y)-(X+W,Y+H).
1598    Some extra content might be drawn; the device should perform clipping as
1599    necessary. */
1600 void
1601 render_pager_draw_region (const struct render_pager *p,
1602                           int x, int y, int w, int h)
1603 {
1604   int ofs[TABLE_N_AXES] = { 0, 0 };
1605   int clip[TABLE_N_AXES][2];
1606
1607   clip[H][0] = x;
1608   clip[H][1] = x + w;
1609   for (size_t i = 0; i < p->n_pages; i++)
1610     {
1611       const struct render_page *page = p->pages[i];
1612       int size = render_page_get_size (page, V);
1613
1614       clip[V][0] = MAX (y, ofs[V]) - ofs[V];
1615       clip[V][1] = MIN (y + h, ofs[V] + size) - ofs[V];
1616       if (clip[V][1] > clip[V][0])
1617         render_page_draw_region (page, ofs, clip);
1618
1619       ofs[V] += size;
1620     }
1621 }
1622
1623 /* Returns the size of P's content along AXIS; i.e. the content's width if AXIS
1624    is TABLE_HORZ and its length if AXIS is TABLE_VERT. */
1625 int
1626 render_pager_get_size (const struct render_pager *p, enum table_axis axis)
1627 {
1628   int size = 0;
1629
1630   for (size_t i = 0; i < p->n_pages; i++)
1631     {
1632       int subsize = render_page_get_size (p->pages[i], axis);
1633       size = axis == H ? MAX (size, subsize) : size + subsize;
1634     }
1635
1636   return size;
1637 }
1638
1639 int
1640 render_pager_get_best_breakpoint (const struct render_pager *p, int height)
1641 {
1642   int y = 0;
1643   size_t i;
1644
1645   for (i = 0; i < p->n_pages; i++)
1646     {
1647       int size = render_page_get_size (p->pages[i], V);
1648       if (y + size >= height)
1649         return render_page_get_best_breakpoint (p->pages[i], height - y) + y;
1650       y += size;
1651     }
1652
1653   return height;
1654 }
1655 \f
1656 /* render_page_select() and helpers. */
1657
1658 struct render_page_selection
1659   {
1660     const struct render_page *page; /* Page whose slice we are selecting. */
1661     struct render_page *subpage; /* New page under construction. */
1662     enum table_axis a;   /* Axis of 'page' along which 'subpage' is a slice. */
1663     enum table_axis b;   /* The opposite of 'a'. */
1664     int z0;              /* First cell along 'a' being selected. */
1665     int z1;              /* Last cell being selected, plus 1. */
1666     int p0;              /* Number of pixels to trim off left side of z0. */
1667     int p1;              /* Number of pixels to trim off right side of z1-1. */
1668   };
1669
1670 static void cell_to_subpage (struct render_page_selection *,
1671                              const struct table_cell *,
1672                              int subcell[TABLE_N_AXES]);
1673 static const struct render_overflow *find_overflow_for_cell (
1674   struct render_page_selection *, const struct table_cell *);
1675 static struct render_overflow *insert_overflow (struct render_page_selection *,
1676                                                 const struct table_cell *);
1677
1678 /* Creates and returns a new render_page whose contents are a subregion of
1679    PAGE's contents.  The new render_page includes cells Z0 through Z1
1680    (exclusive) along AXIS, plus any headers on AXIS.
1681
1682    If P0 is nonzero, then it is a number of pixels to exclude from the left or
1683    top (according to AXIS) of cell Z0.  Similarly, P1 is a number of pixels to
1684    exclude from the right or bottom of cell Z1 - 1.  (P0 and P1 are used to
1685    render cells that are too large to fit on a single page.)
1686
1687    The whole of axis !AXIS is included.  (The caller may follow up with another
1688    call to render_page_select() to select on !AXIS to select on that axis as
1689    well.)
1690
1691    The caller retains ownership of PAGE, which is not modified. */
1692 static struct render_page *
1693 render_page_select (const struct render_page *page, enum table_axis axis,
1694                     int z0, int p0, int z1, int p1)
1695 {
1696   enum table_axis a = axis;
1697   enum table_axis b = !a;
1698
1699   /* Optimize case where all of PAGE is selected by just incrementing the
1700      reference count. */
1701   if (z0 == page->h[a] && p0 == 0 && z1 == page->n[a] && p1 == 0)
1702     {
1703       struct render_page *page_rw = CONST_CAST (struct render_page *, page);
1704       page_rw->ref_cnt++;
1705       return page_rw;
1706     }
1707
1708   /* Allocate subpage. */
1709   int trim[2] = { z0 - page->h[a], page->n[a] - z1 };
1710   int n[TABLE_N_AXES] = { [H] = page->n[H], [V] = page->n[V] };
1711   n[a] -= trim[0] + trim[1];
1712   struct render_page *subpage = render_page_allocate__ (
1713     page->params, table_ref (page->table), n);
1714   for (enum table_axis k = 0; k < TABLE_N_AXES; k++)
1715     {
1716       subpage->h[k] = page->h[k];
1717       subpage->r[k][0] = page->r[k][0];
1718       subpage->r[k][1] = page->r[k][1];
1719     }
1720   subpage->r[a][0] += trim[0];
1721   subpage->r[a][1] -= trim[1];
1722
1723   /* An edge is cut off if it was cut off in PAGE or if we're trimming pixels
1724      off that side of the page and there are no headers. */
1725   subpage->is_edge_cutoff[a][0] =
1726     subpage->h[a] == 0 && (p0 || (z0 == 0 && page->is_edge_cutoff[a][0]));
1727   subpage->is_edge_cutoff[a][1] =
1728     p1 || (z1 == page->n[a] && page->is_edge_cutoff[a][1]);
1729   subpage->is_edge_cutoff[b][0] = page->is_edge_cutoff[b][0];
1730   subpage->is_edge_cutoff[b][1] = page->is_edge_cutoff[b][1];
1731
1732   /* Select widths from PAGE into subpage. */
1733   int *scp = page->cp[a];
1734   int *dcp = subpage->cp[a];
1735   *dcp = 0;
1736   for (int z = 0; z <= rule_ofs (subpage->h[a]); z++, dcp++)
1737     {
1738       int w = !z && subpage->is_edge_cutoff[a][0] ? 0 : scp[z + 1] - scp[z];
1739       dcp[1] = dcp[0] + w;
1740     }
1741   for (int z = cell_ofs (z0); z <= cell_ofs (z1 - 1); z++, dcp++)
1742     {
1743       dcp[1] = dcp[0] + (scp[z + 1] - scp[z]);
1744       if (z == cell_ofs (z0))
1745         dcp[1] -= p0;
1746       if (z == cell_ofs (z1 - 1))
1747         dcp[1] -= p1;
1748     }
1749   for (int z = rule_ofs_r (page, a, 0);
1750        z <= rule_ofs_r (page, a, 0); z++, dcp++)
1751     {
1752       if (z == rule_ofs_r (page, a, 0) && subpage->is_edge_cutoff[a][1])
1753         dcp[1] = dcp[0];
1754       else
1755         dcp[1] = dcp[0] + (scp[z + 1] - scp[z]);
1756     }
1757   assert (dcp == &subpage->cp[a][2 * subpage->n[a] + 1]);
1758
1759   for (int z = 0; z < page->n[b] * 2 + 2; z++)
1760     subpage->cp[b][z] = page->cp[b][z];
1761
1762   /* Add new overflows. */
1763   struct render_page_selection s = {
1764     .page = page,
1765     .a = a,
1766     .b = b,
1767     .z0 = z0,
1768     .z1 = z1,
1769     .p0 = p0,
1770     .p1 = p1,
1771     .subpage = subpage,
1772   };
1773
1774   if (!page->h[a] || z0 > page->h[a] || p0)
1775     for (int z = 0; z < page->n[b];)
1776       {
1777         int d[TABLE_N_AXES];
1778         d[a] = z0;
1779         d[b] = z;
1780
1781         struct table_cell cell;
1782         render_get_cell (page, d[H], d[V], &cell);
1783         bool overflow0 = p0 || cell.d[a][0] < z0;
1784         bool overflow1 = cell.d[a][1] > z1 || (cell.d[a][1] == z1 && p1);
1785         if (overflow0 || overflow1)
1786           {
1787             struct render_overflow *ro = insert_overflow (&s, &cell);
1788
1789             if (overflow0)
1790               ro->overflow[a][0] += p0 + axis_width (
1791                 page, a, cell_ofs (cell.d[a][0]), cell_ofs (z0));
1792
1793             if (overflow1)
1794               ro->overflow[a][1] += p1 + axis_width (
1795                 page, a, cell_ofs (z1), cell_ofs (cell.d[a][1]));
1796           }
1797         z = cell.d[b][1];
1798       }
1799
1800   for (int z = 0; z < page->n[b];)
1801     {
1802       int d[TABLE_N_AXES];
1803       d[a] = z1 - 1;
1804       d[b] = z;
1805
1806       struct table_cell cell;
1807       render_get_cell (page, d[H], d[V], &cell);
1808       if ((cell.d[a][1] > z1 || (cell.d[a][1] == z1 && p1))
1809           && find_overflow_for_cell (&s, &cell) == NULL)
1810         {
1811           struct render_overflow *ro = insert_overflow (&s, &cell);
1812           ro->overflow[a][1] += p1 + axis_width (page, a, cell_ofs (z1),
1813                                                  cell_ofs (cell.d[a][1]));
1814         }
1815       z = cell.d[b][1];
1816     }
1817
1818   /* Copy overflows from PAGE into subpage. */
1819   struct render_overflow *ro;
1820   HMAP_FOR_EACH (ro, struct render_overflow, node, &page->overflows)
1821     {
1822       struct table_cell cell;
1823
1824       table_get_cell (page->table, ro->d[H], ro->d[V], &cell);
1825       if (cell.d[a][1] > z0 && cell.d[a][0] < z1
1826           && find_overflow_for_cell (&s, &cell) == NULL)
1827         insert_overflow (&s, &cell);
1828     }
1829
1830   return subpage;
1831 }
1832
1833 /* Given CELL, a table_cell within S->page, stores in SUBCELL the (x,y)
1834    coordinates of the top-left cell as it will appear in S->subpage.
1835
1836    CELL must actually intersect the region of S->page that is being selected
1837    by render_page_select() or the results will not make any sense. */
1838 static void
1839 cell_to_subpage (struct render_page_selection *s,
1840                  const struct table_cell *cell, int subcell[TABLE_N_AXES])
1841 {
1842   enum table_axis a = s->a;
1843   enum table_axis b = s->b;
1844   int ha0 = s->subpage->h[a];
1845
1846   subcell[a] = MAX (cell->d[a][0] - s->z0 + ha0, ha0);
1847   subcell[b] = cell->d[b][0];
1848 }
1849
1850 /* Given CELL, a table_cell within S->page, returns the render_overflow for
1851    that cell in S->subpage, if there is one, and a null pointer otherwise.
1852
1853    CELL must actually intersect the region of S->page that is being selected
1854    by render_page_select() or the results will not make any sense. */
1855 static const struct render_overflow *
1856 find_overflow_for_cell (struct render_page_selection *s,
1857                         const struct table_cell *cell)
1858 {
1859   int subcell[2];
1860
1861   cell_to_subpage (s, cell, subcell);
1862   return find_overflow (s->subpage, subcell[H], subcell[V]);
1863 }
1864
1865 /* Given CELL, a table_cell within S->page, inserts a render_overflow for that
1866    cell in S->subpage (which must not already exist).  Initializes the new
1867    render_overflow's 'overflow' member from the overflow for CELL in S->page,
1868    if there is one.
1869
1870    CELL must actually intersect the region of S->page that is being selected
1871    by render_page_select() or the results will not make any sense. */
1872 static struct render_overflow *
1873 insert_overflow (struct render_page_selection *s,
1874                  const struct table_cell *cell)
1875 {
1876   struct render_overflow *of = XZALLOC (struct render_overflow);
1877   cell_to_subpage (s, cell, of->d);
1878   hmap_insert (&s->subpage->overflows, &of->node,
1879                hash_cell (of->d[H], of->d[V]));
1880
1881   const struct render_overflow *old
1882     = find_overflow (s->page, cell->d[H][0], cell->d[V][0]);
1883   if (old != NULL)
1884     memcpy (of->overflow, old->overflow, sizeof of->overflow);
1885
1886   return of;
1887 }