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