render: Fix spanned width distribution for cells not at top or left.
[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, headers in H, and
484    content in R.  The caller must initialize most of the members itself. */
485 static struct render_page *
486 render_page_allocate__ (const struct render_params *params,
487                         struct table *table,
488                         const int n[TABLE_N_AXES],
489                         const int h[TABLE_N_AXES],
490                         const int r[TABLE_N_AXES][2])
491 {
492   struct render_page *page = xmalloc (sizeof *page);
493   *page = (struct render_page) {
494     .params = params,
495     .table = table,
496     .ref_cnt = 1,
497     .n = { [H] = n[H], [V] = n[V] },
498     .h = { [H] = h[H], [V] = h[V] },
499     .r = { [H] = { r[H][0], r[H][1] }, [V] = { r[V][0], r[V][1] } },
500     .cp = { [H] = xcalloc (2 * n[H] + 2, sizeof *page->cp[H]),
501             [V] = xcalloc (2 * n[V] + 2, sizeof *page->cp[V]) },
502     .overflows = HMAP_INITIALIZER (page->overflows),
503   };
504   return page;
505 }
506
507 /* Allocates and returns a new render_page using PARAMS and TABLE.  Allocates
508    space for all of the members of the new page, but the caller must initialize
509    the 'cp' member itself. */
510 static struct render_page *
511 render_page_allocate (const struct render_params *params, struct table *table)
512 {
513   int h[TABLE_N_AXES];
514   int r[TABLE_N_AXES][2];
515   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
516     {
517       h[a] = table->h[a];
518       r[a][0] = table->h[a];
519       r[a][1] = table->n[a];
520     }
521   return render_page_allocate__ (params, table, table->n, h, r);
522 }
523
524 /* Allocates and returns a new render_page for PARAMS and TABLE, initializing
525    cp[H] in the new page from ROWS and RULES.  The caller must still initialize
526    cp[V]. */
527 static struct render_page *
528 create_page_with_exact_widths (const struct render_params *params,
529                                struct table *table,
530                                const struct render_row *rows, int *rules)
531 {
532   struct render_page *page = render_page_allocate (params, table);
533   accumulate_row_widths (page, H, rows, rules);
534   return page;
535 }
536
537 /* Allocates and returns a new render_page for PARAMS and TABLE.
538
539    Initializes cp[H] in the new page by setting the width of each row 'i' to
540    somewhere between the minimum cell width ROW_MIN[i].width and the maximum
541    ROW_MAX[i].width.  Sets the width of rules to those in RULES.
542
543    W_MIN is the sum of ROWS_MIN[].width.
544
545    W_MAX is the sum of ROWS_MAX[].width.
546
547    The caller must still initialize cp[V]. */
548 static struct render_page *
549 create_page_with_interpolated_widths (const struct render_params *params,
550                                       struct table *table,
551                                       const struct render_row *rows_min,
552                                       const struct render_row *rows_max,
553                                       int w_min, int w_max, const int *rules)
554 {
555   const int n = table->n[H];
556   const long long int avail = params->size[H] - w_min;
557   const long long int wanted = w_max - w_min;
558
559   assert (wanted > 0);
560
561   struct render_page *page = render_page_allocate (params, table);
562
563   int *cph = page->cp[H];
564   *cph = 0;
565   long long int w = wanted / 2;
566   for (int x = 0; x < n; x++)
567     {
568       w += avail * (rows_max[x].width - rows_min[x].width);
569       int extra = w / wanted;
570       w -= extra * wanted;
571
572       cph[1] = cph[0] + rules[x];
573       cph[2] = cph[1] + rows_min[x].width + extra;
574       cph += 2;
575     }
576   cph[1] = cph[0] + rules[n];
577
578   assert (page->cp[H][n * 2 + 1] == params->size[H]);
579   return page;
580 }
581 \f
582 /* Maps a contiguous range of cells from a page to the underlying table along
583    the horizontal or vertical dimension. */
584 struct map
585   {
586     int p0;                     /* First ordinate in the page. */
587     int t0;                     /* First ordinate in the table. */
588     int n;                      /* Number of ordinates in page and table. */
589   };
590
591 /* Initializes M to a mapping from PAGE to PAGE->table along axis A.  The
592    mapping includes ordinate Z (in PAGE). */
593 static void
594 get_map (const struct render_page *page, enum table_axis a, int z,
595          struct map *m)
596 {
597   if (z < page->h[a])
598     {
599       m->p0 = 0;
600       m->t0 = 0;
601       m->n = page->h[a];
602     }
603   else
604     {
605       assert (z < page->n[a]);
606       m->p0 = page->h[a];
607       m->t0 = page->r[a][0];
608       m->n = page->r[a][1] - page->r[a][0];
609     }
610 }
611
612 /* Initializes CELL with the contents of the table cell at column X and row Y
613    within PAGE.  When CELL is no longer needed, the caller is responsible for
614    freeing it by calling table_cell_free(CELL).
615
616    The caller must ensure that CELL is destroyed before TABLE is unref'ed.
617
618    This is equivalent to table_get_cell(), except X and Y are in terms of the
619    page's rows and columns rather than the underlying table's. */
620 static void
621 render_get_cell (const struct render_page *page, int x, int y,
622                  struct table_cell *cell)
623 {
624   int d[TABLE_N_AXES] = { [H] = x, [V] = y };
625   struct map map[TABLE_N_AXES];
626
627   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
628     {
629       struct map *m = &map[a];
630       get_map (page, a, d[a], m);
631       d[a] += m->t0 - m->p0;
632     }
633   table_get_cell (page->table, d[H], d[V], cell);
634
635   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
636     {
637       struct map *m = &map[a];
638
639       for (int i = 0; i < 2; i++)
640         cell->d[a][i] -= m->t0 - m->p0;
641       cell->d[a][0] = MAX (cell->d[a][0], m->p0);
642       cell->d[a][1] = MIN (cell->d[a][1], m->p0 + m->n);
643     }
644
645   if (cell->options & TABLE_CELL_FULL_WIDTH)
646     {
647       cell->d[H][0] = 0;
648       cell->d[H][1] = page->n[H];
649     }
650 }
651
652 /* Creates and returns a new render_page for rendering TABLE on a device
653    described by PARAMS.
654
655    The new render_page will be suitable for rendering on a device whose page
656    size is PARAMS->size, but the caller is responsible for actually breaking it
657    up to fit on such a device, using the render_break abstraction.  */
658 static struct render_page *
659 render_page_create (const struct render_params *params, struct table *table,
660                     int min_width)
661 {
662   enum { MIN, MAX };
663
664   int nc = table->n[H];
665   int nr = table->n[V];
666
667   /* Figure out rule widths. */
668   int *rules[TABLE_N_AXES];
669   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
670     {
671       int n = table->n[axis] + 1;
672
673       rules[axis] = xnmalloc (n, sizeof *rules);
674       for (int z = 0; z < n; z++)
675         rules[axis][z] = measure_rule (params, table, axis, z);
676     }
677
678   /* Calculate minimum and maximum widths of cells that do not
679      span multiple columns. */
680   struct render_row *columns[2];
681   for (int i = 0; i < 2; i++)
682     columns[i] = xcalloc (nc, sizeof *columns[i]);
683   for (int y = 0; y < nr; y++)
684     for (int x = 0; x < nc;)
685       {
686         struct table_cell cell;
687
688         table_get_cell (table, x, y, &cell);
689         if (y == cell.d[V][0])
690           {
691             if (table_cell_colspan (&cell) == 1)
692               {
693                 int w[2];
694                 params->ops->measure_cell_width (params->aux, &cell,
695                                                  &w[MIN], &w[MAX]);
696                 for (int i = 0; i < 2; i++)
697                   if (columns[i][x].unspanned < w[i])
698                     columns[i][x].unspanned = w[i];
699               }
700           }
701         x = cell.d[H][1];
702       }
703
704   /* Distribute widths of spanned columns. */
705   for (int i = 0; i < 2; i++)
706     for (int x = 0; x < nc; x++)
707       columns[i][x].width = columns[i][x].unspanned;
708   for (int y = 0; y < nr; y++)
709     for (int x = 0; x < nc;)
710       {
711         struct table_cell cell;
712
713         table_get_cell (table, x, y, &cell);
714         if (y == cell.d[V][0] && table_cell_colspan (&cell) > 1)
715           {
716             int w[2];
717
718             params->ops->measure_cell_width (params->aux, &cell,
719                                              &w[MIN], &w[MAX]);
720             for (int i = 0; i < 2; i++)
721               distribute_spanned_width (w[i],
722                                         &columns[i][cell.d[H][0]],
723                                         &rules[H][cell.d[H][0]],
724                                         table_cell_colspan (&cell));
725           }
726         x = cell.d[H][1];
727       }
728   if (min_width > 0)
729     for (int i = 0; i < 2; i++)
730       distribute_spanned_width (min_width, &columns[i][0], rules[H], nc);
731
732   /* In pathological cases, spans can cause the minimum width of a column to
733      exceed the maximum width.  This bollixes our interpolation algorithm
734      later, so fix it up. */
735   for (int i = 0; i < nc; i++)
736     if (columns[MIN][i].width > columns[MAX][i].width)
737       columns[MAX][i].width = columns[MIN][i].width;
738
739   /* Decide final column widths. */
740   int table_widths[2];
741   for (int i = 0; i < 2; i++)
742     table_widths[i] = calculate_table_width (table->n[H],
743                                              columns[i], rules[H]);
744
745   struct render_page *page;
746   if (table_widths[MAX] <= params->size[H])
747     {
748       /* Fits even with maximum widths.  Use them. */
749       page = create_page_with_exact_widths (params, table, columns[MAX],
750                                             rules[H]);
751     }
752   else if (table_widths[MIN] <= params->size[H])
753     {
754       /* Fits with minimum widths, so distribute the leftover space. */
755       page = create_page_with_interpolated_widths (
756         params, table, columns[MIN], columns[MAX],
757         table_widths[MIN], table_widths[MAX], rules[H]);
758     }
759   else
760     {
761       /* Doesn't fit even with minimum widths.  Assign minimums for now, and
762          later we can break it horizontally into multiple pages. */
763       page = create_page_with_exact_widths (params, table, columns[MIN],
764                                             rules[H]);
765     }
766
767   /* Calculate heights of cells that do not span multiple rows. */
768   struct render_row *rows = XCALLOC (nr, struct render_row);
769   for (int y = 0; y < nr; y++)
770     for (int x = 0; x < nc;)
771       {
772         struct render_row *r = &rows[y];
773         struct table_cell cell;
774
775         render_get_cell (page, x, y, &cell);
776         if (y == cell.d[V][0] && table_cell_rowspan (&cell) == 1)
777           {
778             int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
779             int h = params->ops->measure_cell_height (params->aux,
780                                                       &cell, w);
781             if (h > r->unspanned)
782               r->unspanned = r->width = h;
783           }
784         x = cell.d[H][1];
785       }
786   for (int i = 0; i < 2; i++)
787     free (columns[i]);
788
789   /* Distribute heights of spanned rows. */
790   for (int y = 0; y < nr; y++)
791     for (int x = 0; x < nc;)
792       {
793         struct table_cell cell;
794
795         render_get_cell (page, x, y, &cell);
796         if (y == cell.d[V][0] && table_cell_rowspan (&cell) > 1)
797           {
798             int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
799             int h = params->ops->measure_cell_height (params->aux, &cell, w);
800             distribute_spanned_width (h,
801                                       &rows[cell.d[V][0]],
802                                       &rules[V][cell.d[V][0]],
803                                       table_cell_rowspan (&cell));
804           }
805         x = cell.d[H][1];
806       }
807
808   /* Decide final row heights. */
809   accumulate_row_widths (page, V, rows, rules[V]);
810   free (rows);
811
812   /* Measure headers.  If they are "too big", get rid of them.  */
813   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
814     {
815       int hw = headers_width (page, axis);
816       if (hw * 2 >= page->params->size[axis]
817           || hw + max_cell_width (page, axis) > page->params->size[axis])
818         {
819           page->h[axis] = 0;
820           page->r[axis][0] = 0;
821           page->r[axis][1] = page->n[axis];
822         }
823     }
824
825   free (rules[H]);
826   free (rules[V]);
827
828   return page;
829 }
830
831 /* Increases PAGE's reference count. */
832 struct render_page *
833 render_page_ref (const struct render_page *page_)
834 {
835   struct render_page *page = CONST_CAST (struct render_page *, page_);
836   page->ref_cnt++;
837   return page;
838 }
839
840 /* Decreases PAGE's reference count and destroys PAGE if this causes the
841    reference count to fall to zero. */
842 static void
843 render_page_unref (struct render_page *page)
844 {
845   if (page != NULL && --page->ref_cnt == 0)
846     {
847       struct render_overflow *overflow, *next;
848       HMAP_FOR_EACH_SAFE (overflow, next, struct render_overflow, node,
849                           &page->overflows)
850         free (overflow);
851       hmap_destroy (&page->overflows);
852
853       table_unref (page->table);
854
855       for (int i = 0; i < TABLE_N_AXES; ++i)
856         free (page->cp[i]);
857
858       free (page);
859     }
860 }
861
862 /* Returns the size of PAGE along AXIS.  (This might be larger than the page
863    size specified in the parameters passed to render_page_create().  Use a
864    render_break to break up a render_page into page-sized chunks.) */
865 static int
866 render_page_get_size (const struct render_page *page, enum table_axis axis)
867 {
868   return page->cp[axis][page->n[axis] * 2 + 1];
869 }
870
871 static int
872 render_page_get_best_breakpoint (const struct render_page *page, int height)
873 {
874   /* If there's no room for at least the top row and the rules above and below
875      it, don't include any of the table. */
876   if (page->cp[V][3] > height)
877     return 0;
878
879   /* Otherwise include as many rows and rules as we can. */
880   for (int y = 5; y <= 2 * page->n[V] + 1; y += 2)
881     if (page->cp[V][y] > height)
882       return page->cp[V][y - 2];
883   return height;
884 }
885 \f
886 /* Drawing render_pages. */
887
888 /* This is like table_get_rule() except that D is in terms of the page's rows
889    and column rather than the underlying table's. */
890 static struct table_border_style
891 get_rule (const struct render_page *page, enum table_axis axis,
892           const int d_[TABLE_N_AXES])
893 {
894   int d[TABLE_N_AXES] = { d_[0] / 2, d_[1] / 2 };
895   int d2 = -1;
896
897   enum table_axis a = axis;
898   if (d[a] < page->h[a])
899     /* Nothing to do */;
900   else if (d[a] <= page->n[a])
901     {
902       if (page->h[a] && d[a] == page->h[a])
903         d2 = page->h[a];
904       d[a] += page->r[a][0] - page->h[a];
905     }
906
907   enum table_axis b = !axis;
908   struct map m;
909   get_map (page, b, d[b], &m);
910   d[b] += m.t0 - m.p0;
911
912   struct table_border_style border
913     = table_get_rule (page->table, axis, d[H], d[V]);
914   if (d2 >= 0)
915     {
916       d[a] = d2;
917       struct table_border_style border2 = table_get_rule (page->table, axis,
918                                                           d[H], d[V]);
919       border.stroke = table_stroke_combine (border.stroke, border2.stroke);
920     }
921   return border;
922 }
923
924 static bool
925 is_rule (int z)
926 {
927   return !(z & 1);
928 }
929
930 bool
931 render_direction_rtl (void)
932 {
933   /* TRANSLATORS: Do not translate this string.  If the script of your language
934      reads from right to left (eg Persian, Arabic, Hebrew etc), then replace
935      this string with "output-direction-rtl".  Otherwise either leave it
936      untranslated or copy it verbatim. */
937   const char *dir = _("output-direction-ltr");
938   if (0 == strcmp ("output-direction-rtl", dir))
939     return true;
940
941   if (0 != strcmp ("output-direction-ltr", dir))
942     fprintf (stderr, "This localisation has been incorrectly translated.  "
943              "Complain to the translator.\n");
944
945   return false;
946 }
947
948 static void
949 render_rule (const struct render_page *page, const int ofs[TABLE_N_AXES],
950              const int d[TABLE_N_AXES])
951 {
952   const struct table_border_style none = { .stroke = TABLE_STROKE_NONE };
953   struct table_border_style styles[TABLE_N_AXES][2];
954
955   for (enum table_axis a = 0; a < TABLE_N_AXES; a++)
956     {
957       enum table_axis b = !a;
958
959       if (!is_rule (d[a])
960           || (page->is_edge_cutoff[a][0] && d[a] == 0)
961           || (page->is_edge_cutoff[a][1] && d[a] == page->n[a] * 2))
962         styles[a][0] = styles[a][1] = none;
963       else if (is_rule (d[b]))
964         {
965           if (d[b] > 0)
966             {
967               int e[TABLE_N_AXES];
968               e[H] = d[H];
969               e[V] = d[V];
970               e[b]--;
971               styles[a][0] = get_rule (page, a, e);
972             }
973           else
974             styles[a][0] = none;
975
976           if (d[b] / 2 < page->n[b])
977             styles[a][1] = get_rule (page, a, d);
978           else
979             styles[a][1] = none;
980         }
981       else
982         styles[a][0] = styles[a][1] = get_rule (page, a, d);
983     }
984
985   if (styles[H][0].stroke != TABLE_STROKE_NONE
986       || styles[H][1].stroke != TABLE_STROKE_NONE
987       || styles[V][0].stroke != TABLE_STROKE_NONE
988       || styles[V][1].stroke != TABLE_STROKE_NONE)
989     {
990       int bb[TABLE_N_AXES][2];
991
992       bb[H][0] = ofs[H] + page->cp[H][d[H]];
993       bb[H][1] = ofs[H] + page->cp[H][d[H] + 1];
994       if (page->params->rtl)
995         {
996           int temp = bb[H][0];
997           bb[H][0] = render_page_get_size (page, H) - bb[H][1];
998           bb[H][1] = render_page_get_size (page, H) - temp;
999         }
1000       bb[V][0] = ofs[V] + page->cp[V][d[V]];
1001       bb[V][1] = ofs[V] + page->cp[V][d[V] + 1];
1002       page->params->ops->draw_line (page->params->aux, bb, styles);
1003     }
1004 }
1005
1006 static void
1007 render_cell (const struct render_page *page, const int ofs[TABLE_N_AXES],
1008              const struct table_cell *cell)
1009 {
1010   const bool debugging = false;
1011   if (debugging)
1012     {
1013       printf ("render ");
1014       if (cell->d[H][0] + 1 == cell->d[H][1])
1015         printf ("%d", cell->d[H][0]);
1016       else
1017         printf ("%d-%d", cell->d[H][0], cell->d[H][1] - 1);
1018       printf (",");
1019       if (cell->d[V][0] + 1 == cell->d[V][1])
1020         printf ("%d", cell->d[V][0]);
1021       else
1022         printf ("%d-%d", cell->d[V][0], cell->d[V][1] - 1);
1023
1024       char *value = pivot_value_to_string (cell->value, NULL);
1025       printf (": \"%s\"\n", value);
1026       free (value);
1027     }
1028
1029   int bb[TABLE_N_AXES][2];
1030   int clip[TABLE_N_AXES][2];
1031
1032   bb[H][0] = clip[H][0] = ofs[H] + page->cp[H][cell->d[H][0] * 2 + 1];
1033   bb[H][1] = clip[H][1] = ofs[H] + page->cp[H][cell->d[H][1] * 2];
1034   if (page->params->rtl)
1035     {
1036       int temp = bb[H][0];
1037       bb[H][0] = clip[H][0] = render_page_get_size (page, H) - bb[H][1];
1038       bb[H][1] = clip[H][1] = render_page_get_size (page, H) - temp;
1039     }
1040   bb[V][0] = clip[V][0] = ofs[V] + page->cp[V][cell->d[V][0] * 2 + 1];
1041   bb[V][1] = clip[V][1] = ofs[V] + page->cp[V][cell->d[V][1] * 2];
1042
1043   enum table_valign valign = cell->cell_style->valign;
1044   int valign_offset = 0;
1045   if (valign != TABLE_VALIGN_TOP)
1046     {
1047       int height = page->params->ops->measure_cell_height (
1048         page->params->aux, cell, bb[H][1] - bb[H][0]);
1049       int extra = bb[V][1] - bb[V][0] - height;
1050       if (extra > 0)
1051         {
1052           if (valign == TABLE_VALIGN_CENTER)
1053             extra /= 2;
1054           valign_offset += extra;
1055         }
1056     }
1057
1058   const struct render_overflow *of = find_overflow (
1059     page, cell->d[H][0], cell->d[V][0]);
1060   if (of)
1061     for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
1062       {
1063         if (of->overflow[axis][0])
1064           {
1065             bb[axis][0] -= of->overflow[axis][0];
1066             if (cell->d[axis][0] == 0 && !page->is_edge_cutoff[axis][0])
1067               clip[axis][0] = ofs[axis] + page->cp[axis][cell->d[axis][0] * 2];
1068           }
1069         if (of->overflow[axis][1])
1070           {
1071             bb[axis][1] += of->overflow[axis][1];
1072             if (cell->d[axis][1] == page->n[axis]
1073                 && !page->is_edge_cutoff[axis][1])
1074               clip[axis][1] = ofs[axis] + page->cp[axis][cell->d[axis][1] * 2
1075                                                          + 1];
1076           }
1077       }
1078
1079   int spill[TABLE_N_AXES][2];
1080   for (enum table_axis axis = 0; axis < TABLE_N_AXES; axis++)
1081     {
1082       spill[axis][0] = rule_width (page, axis, cell->d[axis][0]) / 2;
1083       spill[axis][1] = rule_width (page, axis, cell->d[axis][1]) / 2;
1084     }
1085
1086   int color_idx = (cell->d[V][0] < page->h[V]
1087                    ? 0
1088                    : (cell->d[V][0] - page->h[V]) & 1);
1089   page->params->ops->draw_cell (page->params->aux, cell, color_idx,
1090                                 bb, valign_offset, spill, clip);
1091 }
1092
1093 /* Draws the cells of PAGE indicated in BB. */
1094 static void
1095 render_page_draw_cells (const struct render_page *page,
1096                         int ofs[TABLE_N_AXES], int bb[TABLE_N_AXES][2])
1097 {
1098   for (int y = bb[V][0]; y < bb[V][1]; y++)
1099     for (int x = bb[H][0]; x < bb[H][1];)
1100       if (!is_rule (x) && !is_rule (y))
1101         {
1102           struct table_cell cell;
1103
1104           render_get_cell (page, x / 2, y / 2, &cell);
1105           if (y / 2 == bb[V][0] / 2 || y / 2 == cell.d[V][0])
1106             render_cell (page, ofs, &cell);
1107           x = rule_ofs (cell.d[H][1]);
1108         }
1109       else
1110         x++;
1111
1112   for (int y = bb[V][0]; y < bb[V][1]; y++)
1113     for (int x = bb[H][0]; x < bb[H][1]; x++)
1114       if (is_rule (x) || is_rule (y))
1115         {
1116           int d[TABLE_N_AXES];
1117           d[H] = x;
1118           d[V] = y;
1119           render_rule (page, ofs, d);
1120         }
1121 }
1122
1123 /* Renders PAGE, by calling the 'draw_line' and 'draw_cell' functions from the
1124    render_params provided to render_page_create(). */
1125 static void
1126 render_page_draw (const struct render_page *page, int ofs[TABLE_N_AXES])
1127 {
1128   int bb[TABLE_N_AXES][2];
1129
1130   bb[H][0] = 0;
1131   bb[H][1] = page->n[H] * 2 + 1;
1132   bb[V][0] = 0;
1133   bb[V][1] = page->n[V] * 2 + 1;
1134
1135   render_page_draw_cells (page, ofs, bb);
1136 }
1137
1138 /* Returns the greatest value i, 0 <= i < n, such that cp[i] <= x0. */
1139 static int
1140 get_clip_min_extent (int x0, const int cp[], int n)
1141 {
1142   int low = 0;
1143   int high = n;
1144   int best = 0;
1145   while (low < high)
1146     {
1147       int middle = low + (high - low) / 2;
1148
1149       if (cp[middle] <= x0)
1150         {
1151           best = middle;
1152           low = middle + 1;
1153         }
1154       else
1155         high = middle;
1156     }
1157
1158   return best;
1159 }
1160
1161 /* Returns the least value i, 0 <= i < n, such that cp[i] >= x1. */
1162 static int
1163 get_clip_max_extent (int x1, const int cp[], int n)
1164 {
1165   int low = 0;
1166   int high = n;
1167   int best = n;
1168   while (low < high)
1169     {
1170       int middle = low + (high - low) / 2;
1171
1172       if (cp[middle] >= x1)
1173         best = high = middle;
1174       else
1175         low = middle + 1;
1176     }
1177
1178   while (best > 0 && cp[best - 1] == cp[best])
1179     best--;
1180
1181   return best;
1182 }
1183
1184 /* Renders the cells of PAGE that intersect (X,Y)-(X+W,Y+H), by calling the
1185    'draw_line' and 'draw_cell' functions from the render_params provided to
1186    render_page_create(). */
1187 static void
1188 render_page_draw_region (const struct render_page *page,
1189                          int ofs[TABLE_N_AXES], int clip[TABLE_N_AXES][2])
1190 {
1191   int bb[TABLE_N_AXES][2];
1192
1193   bb[H][0] = get_clip_min_extent (clip[H][0], page->cp[H], page->n[H] * 2 + 1);
1194   bb[H][1] = get_clip_max_extent (clip[H][1], page->cp[H], page->n[H] * 2 + 1);
1195   bb[V][0] = get_clip_min_extent (clip[V][0], page->cp[V], page->n[V] * 2 + 1);
1196   bb[V][1] = get_clip_max_extent (clip[V][1], page->cp[V], page->n[V] * 2 + 1);
1197
1198   render_page_draw_cells (page, ofs, bb);
1199 }
1200
1201 /* Breaking up tables to fit on a page. */
1202
1203 /* An iterator for breaking render_pages into smaller chunks. */
1204 struct render_break
1205   {
1206     struct render_page *page;   /* Page being broken up. */
1207     enum table_axis axis;       /* Axis along which 'page' is being broken. */
1208     int z;                      /* Next cell along 'axis'. */
1209     int pixel;                  /* Pixel offset within cell 'z' (usually 0). */
1210     int hw;                     /* Width of headers of 'page' along 'axis'. */
1211   };
1212
1213 static int needed_size (const struct render_break *, int cell);
1214 static bool cell_is_breakable (const struct render_break *, int cell);
1215 static struct render_page *render_page_select (const struct render_page *,
1216                                                enum table_axis,
1217                                                int z0, int p0,
1218                                                int z1, int p1);
1219
1220 /* Initializes render_break B for breaking PAGE along AXIS.
1221    Takes ownership of PAGE. */
1222 static void
1223 render_break_init (struct render_break *b, struct render_page *page,
1224                    enum table_axis axis)
1225 {
1226   b->page = page;
1227   b->axis = axis;
1228   b->z = page->h[axis];
1229   b->pixel = 0;
1230   b->hw = headers_width (page, axis);
1231 }
1232
1233 /* Initializes B as a render_break structure for which
1234    render_break_has_next() always returns false. */
1235 static void
1236 render_break_init_empty (struct render_break *b)
1237 {
1238   b->page = NULL;
1239   b->axis = TABLE_HORZ;
1240   b->z = 0;
1241   b->pixel = 0;
1242   b->hw = 0;
1243 }
1244
1245 /* Frees B and unrefs the render_page that it owns. */
1246 static void
1247 render_break_destroy (struct render_break *b)
1248 {
1249   if (b != NULL)
1250     {
1251       render_page_unref (b->page);
1252       b->page = NULL;
1253     }
1254 }
1255
1256 /* Returns true if B still has cells that are yet to be returned,
1257    false if all of B's page has been processed. */
1258 static bool
1259 render_break_has_next (const struct render_break *b)
1260 {
1261   const struct render_page *page = b->page;
1262   enum table_axis axis = b->axis;
1263
1264   return page != NULL && b->z < page->n[axis];
1265 }
1266
1267 /* Returns a new render_page that is up to SIZE pixels wide along B's axis.
1268    Returns a null pointer if B has already been completely broken up, or if
1269    SIZE is too small to reasonably render any cells.  The latter will never
1270    happen if SIZE is at least as large as the page size passed to
1271    render_page_create() along B's axis. */
1272 static struct render_page *
1273 render_break_next (struct render_break *b, int size)
1274 {
1275   const struct render_page *page = b->page;
1276   enum table_axis axis = b->axis;
1277   struct render_page *subpage;
1278
1279   if (!render_break_has_next (b))
1280     return NULL;
1281
1282   int pixel = 0;
1283   int z;
1284   for (z = b->z; z < page->n[axis]; z++)
1285     {
1286       int needed = needed_size (b, z + 1);
1287       if (needed > size)
1288         {
1289           if (cell_is_breakable (b, z))
1290             {
1291               /* If there is no right header and we render a partial cell on
1292                  the right side of the body, then we omit the rightmost rule of
1293                  the body.  Otherwise the rendering is deceptive because it
1294                  looks like the whole cell is present instead of a partial
1295                  cell.
1296
1297                  This is similar to code for the left side in needed_size(). */
1298               int rule_allowance = rule_width (page, axis, z);
1299
1300               /* The amount that, if we added cell 'z', the rendering would
1301                  overfill the allocated 'size'. */
1302               int overhang = needed - size - rule_allowance;
1303
1304               /* The width of cell 'z'. */
1305               int cell_size = cell_width (page, axis, z);
1306
1307               /* The amount trimmed off the left side of 'z',
1308                  and the amount left to render. */
1309               int cell_ofs = z == b->z ? b->pixel : 0;
1310               int cell_left = cell_size - cell_ofs;
1311
1312               /* A small but visible width.  */
1313               int em = page->params->font_size[axis];
1314
1315               /* If some of the cell remains to render,
1316                  and there would still be some of the cell left afterward,
1317                  then partially render that much of the cell. */
1318               pixel = (cell_left && cell_left > overhang
1319                        ? cell_left - overhang + cell_ofs
1320                        : 0);
1321
1322               /* If there would be only a tiny amount of the cell left after
1323                  rendering it partially, reduce the amount rendered slightly
1324                  to make the output look a little better. */
1325               if (pixel + em > cell_size)
1326                 pixel = MAX (pixel - em, 0);
1327
1328               /* If we're breaking vertically, then consider whether the cells
1329                  being broken have a better internal breakpoint than the exact
1330                  number of pixels available, which might look bad e.g. because
1331                  it breaks in the middle of a line of text. */
1332               if (axis == TABLE_VERT && page->params->ops->adjust_break)
1333                 for (int x = 0; x < page->n[H];)
1334                   {
1335                     struct table_cell cell;
1336
1337                     render_get_cell (page, x, z, &cell);
1338                     int w = joined_width (page, H, cell.d[H][0], cell.d[H][1]);
1339                     int better_pixel = page->params->ops->adjust_break (
1340                       page->params->aux, &cell, w, pixel);
1341                     x = cell.d[H][1];
1342
1343                     if (better_pixel < pixel)
1344                       {
1345                         if (better_pixel > (z == b->z ? b->pixel : 0))
1346                           {
1347                             pixel = better_pixel;
1348                             break;
1349                           }
1350                         else if (better_pixel == 0 && z != b->z)
1351                           {
1352                             pixel = 0;
1353                             break;
1354                           }
1355                       }
1356                   }
1357             }
1358           break;
1359         }
1360     }
1361
1362   if (z == b->z && !pixel)
1363     return NULL;
1364
1365   subpage = render_page_select (page, axis, b->z, b->pixel,
1366                                 pixel ? z + 1 : z,
1367                                 pixel ? cell_width (page, axis, z) - pixel
1368                                 : 0);
1369   b->z = z;
1370   b->pixel = pixel;
1371   return subpage;
1372 }
1373
1374 /* Returns the width that would be required along B's axis to render a page
1375    from B's current position up to but not including CELL. */
1376 static int
1377 needed_size (const struct render_break *b, int cell)
1378 {
1379   const struct render_page *page = b->page;
1380   enum table_axis axis = b->axis;
1381
1382   /* Width of left header not including its rightmost rule.  */
1383   int size = axis_width (page, axis, 0, rule_ofs (page->h[axis]));
1384
1385   /* If we have a pixel offset and there is no left header, then we omit the
1386      leftmost rule of the body.  Otherwise the rendering is deceptive because
1387      it looks like the whole cell is present instead of a partial cell.
1388
1389      Otherwise (if there are headers) we will be merging two rules: the
1390      rightmost rule in the header and the leftmost rule in the body.  We assume
1391      that the width of a merged rule is the larger of the widths of either rule
1392      invidiually. */
1393   if (b->pixel == 0 || page->h[axis])
1394     size += MAX (rule_width (page, axis, page->h[axis]),
1395                  rule_width (page, axis, b->z));
1396
1397   /* Width of body, minus any pixel offset in the leftmost cell. */
1398   size += joined_width (page, axis, b->z, cell) - b->pixel;
1399
1400   /* Width of rightmost rule in body merged with leftmost rule in headers. */
1401   size += MAX (rule_width_r (page, axis, 0), rule_width (page, axis, cell));
1402
1403   return size;
1404 }
1405
1406 /* Returns true if CELL along B's axis may be broken across a page boundary.
1407
1408    This is just a heuristic.  Breaking cells across page boundaries can save
1409    space, but it looks ugly. */
1410 static bool
1411 cell_is_breakable (const struct render_break *b, int cell)
1412 {
1413   const struct render_page *page = b->page;
1414   enum table_axis axis = b->axis;
1415
1416   return cell_width (page, axis, cell) >= page->params->min_break[axis];
1417 }
1418 \f
1419 /* render_pager. */
1420
1421 struct render_pager
1422   {
1423     const struct render_params *params;
1424     double scale;
1425
1426     struct render_page *page;
1427
1428     struct render_break x_break;
1429     struct render_break y_break;
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->page), H);
1436   render_break_init_empty (&p->y_break);
1437 }
1438
1439 /* Creates and returns a new render_pager for rendering PT on the device
1440    with the given PARAMS. */
1441 struct render_pager *
1442 render_pager_create (const struct render_params *params,
1443                      const struct pivot_table *pt,
1444                      const size_t *layer_indexes)
1445 {
1446   if (!layer_indexes)
1447     layer_indexes = pt->current_layer;
1448
1449   struct table *table = pivot_output_monolithic (pt, layer_indexes,
1450                                                  params->printing);
1451
1452   /* Measure the table width and use it to determine the base scale. */
1453   struct render_page *page = render_page_create (params, table, 0);
1454   int width = table_width (page, H);
1455   double scale = 1.0;
1456   if (width > params->size[H])
1457     {
1458       if (pt->look->shrink_to_fit[H] && params->ops->scale)
1459         scale = params->size[H] / (double) width;
1460       else
1461         {
1462           struct render_break b;
1463           render_break_init (&b, render_page_ref (page), H);
1464           struct render_page *subpage
1465             = render_break_next (&b, params->size[H]);
1466           width = subpage ? subpage->cp[H][2 * subpage->n[H] + 1] : 0;
1467           render_page_unref (subpage);
1468           render_break_destroy (&b);
1469         }
1470     }
1471
1472   /* Create the pager. */
1473   struct render_pager *p = xmalloc (sizeof *p);
1474   *p = (struct render_pager) { .params = params, .scale = scale, .page = page };
1475
1476   /* If we're shrinking tables to fit the page length, then adjust the scale
1477      factor.
1478
1479      XXX This will sometimes shrink more than needed, because adjusting the
1480      scale factor allows for cells to be "wider", which means that sometimes
1481      they won't break across as much vertical space, thus shrinking the table
1482      vertically more than the scale would imply.  Shrinking only as much as
1483      necessary would require an iterative search. */
1484   if (pt->look->shrink_to_fit[V] && params->ops->scale)
1485     {
1486       double height = table_width (p->page, V);
1487       if (height * p->scale >= params->size[V])
1488         p->scale *= params->size[V] / height;
1489     }
1490
1491   render_pager_start_page (p);
1492
1493   return p;
1494 }
1495
1496 /* Destroys P. */
1497 void
1498 render_pager_destroy (struct render_pager *p)
1499 {
1500   if (p)
1501     {
1502       render_break_destroy (&p->x_break);
1503       render_break_destroy (&p->y_break);
1504       render_page_unref (p->page);
1505       free (p);
1506     }
1507 }
1508
1509 /* Returns true if P has content remaining to render, false if rendering is
1510    done. */
1511 bool
1512 render_pager_has_next (const struct render_pager *p_)
1513 {
1514   struct render_pager *p = CONST_CAST (struct render_pager *, p_);
1515
1516   while (!render_break_has_next (&p->y_break))
1517     {
1518       render_break_destroy (&p->y_break);
1519       if (!render_break_has_next (&p->x_break))
1520         {
1521           render_break_destroy (&p->x_break);
1522           render_break_init_empty (&p->x_break);
1523           render_break_init_empty (&p->y_break);
1524           return false;
1525         }
1526       else
1527         render_break_init (
1528           &p->y_break, render_break_next (&p->x_break,
1529                                           p->params->size[H] / p->scale), V);
1530     }
1531   return true;
1532 }
1533
1534 /* Draws a chunk of content from P to fit in a space that has vertical size
1535    SPACE and the horizontal size specified in the render_params passed to
1536    render_page_create().  Returns the amount of space actually used by the
1537    rendered chunk, which will be 0 if SPACE is too small to render anything or
1538    if no content remains (use render_pager_has_next() to distinguish these
1539    cases). */
1540 int
1541 render_pager_draw_next (struct render_pager *p, int space)
1542 {
1543   if (p->scale != 1.0)
1544     {
1545       p->params->ops->scale (p->params->aux, p->scale);
1546       space /= p->scale;
1547     }
1548
1549   int ofs[TABLE_N_AXES] = { 0, 0 };
1550
1551   if (render_pager_has_next (p))
1552     {
1553       struct render_page *page
1554         = render_break_next (&p->y_break, space - ofs[V]);
1555       if (page)
1556         {
1557           render_page_draw (page, ofs);
1558           ofs[V] += render_page_get_size (page, V);
1559           render_page_unref (page);
1560         }
1561     }
1562
1563   if (p->scale != 1.0)
1564     ofs[V] *= p->scale;
1565
1566   return ofs[V];
1567 }
1568
1569 /* Draws all of P's content. */
1570 void
1571 render_pager_draw (const struct render_pager *p)
1572 {
1573   render_pager_draw_region (p, 0, 0, INT_MAX, INT_MAX);
1574 }
1575
1576 /* Draws the region of P's content that lies in the region (X,Y)-(X+W,Y+H).
1577    Some extra content might be drawn; the device should perform clipping as
1578    necessary. */
1579 void
1580 render_pager_draw_region (const struct render_pager *p,
1581                           int x, int y, int w, int h)
1582 {
1583   int ofs[TABLE_N_AXES] = { 0, 0 };
1584   int clip[TABLE_N_AXES][2];
1585
1586   clip[H][0] = x;
1587   clip[H][1] = x + w;
1588   int size = render_page_get_size (p->page, V);
1589
1590   clip[V][0] = MAX (y, ofs[V]) - ofs[V];
1591   clip[V][1] = MIN (y + h, ofs[V] + size) - ofs[V];
1592   if (clip[V][1] > clip[V][0])
1593     render_page_draw_region (p->page, ofs, clip);
1594
1595   ofs[V] += size;
1596 }
1597
1598 /* Returns the size of P's content along AXIS; i.e. the content's width if AXIS
1599    is TABLE_HORZ and its length if AXIS is TABLE_VERT. */
1600 int
1601 render_pager_get_size (const struct render_pager *p, enum table_axis axis)
1602 {
1603   return render_page_get_size (p->page, axis);
1604 }
1605
1606 int
1607 render_pager_get_best_breakpoint (const struct render_pager *p, int height)
1608 {
1609   int size = render_page_get_size (p->page, V);
1610   return (size < height
1611           ? height
1612           : render_page_get_best_breakpoint (p->page, height));
1613 }
1614 \f
1615 /* render_page_select() and helpers. */
1616
1617 struct render_page_selection
1618   {
1619     const struct render_page *page; /* Page whose slice we are selecting. */
1620     struct render_page *subpage; /* New page under construction. */
1621     enum table_axis a;   /* Axis of 'page' along which 'subpage' is a slice. */
1622     enum table_axis b;   /* The opposite of 'a'. */
1623     int z0;              /* First cell along 'a' being selected. */
1624     int z1;              /* Last cell being selected, plus 1. */
1625     int p0;              /* Number of pixels to trim off left side of z0. */
1626     int p1;              /* Number of pixels to trim off right side of z1-1. */
1627   };
1628
1629 static void cell_to_subpage (struct render_page_selection *,
1630                              const struct table_cell *,
1631                              int subcell[TABLE_N_AXES]);
1632 static const struct render_overflow *find_overflow_for_cell (
1633   struct render_page_selection *, const struct table_cell *);
1634 static struct render_overflow *insert_overflow (struct render_page_selection *,
1635                                                 const struct table_cell *);
1636
1637 /* Creates and returns a new render_page whose contents are a subregion of
1638    PAGE's contents.  The new render_page includes cells Z0 through Z1
1639    (exclusive) along AXIS, plus any headers on AXIS.
1640
1641    If P0 is nonzero, then it is a number of pixels to exclude from the left or
1642    top (according to AXIS) of cell Z0.  Similarly, P1 is a number of pixels to
1643    exclude from the right or bottom of cell Z1 - 1.  (P0 and P1 are used to
1644    render cells that are too large to fit on a single page.)
1645
1646    The whole of axis !AXIS is included.  (The caller may follow up with another
1647    call to render_page_select() to select on !AXIS to select on that axis as
1648    well.)
1649
1650    The caller retains ownership of PAGE, which is not modified. */
1651 static struct render_page *
1652 render_page_select (const struct render_page *page, enum table_axis axis,
1653                     int z0, int p0, int z1, int p1)
1654 {
1655   enum table_axis a = axis;
1656   enum table_axis b = !a;
1657
1658   /* Optimize case where all of PAGE is selected by just incrementing the
1659      reference count. */
1660   if (z0 == page->h[a] && p0 == 0 && z1 == page->n[a] && p1 == 0)
1661     {
1662       struct render_page *page_rw = CONST_CAST (struct render_page *, page);
1663       page_rw->ref_cnt++;
1664       return page_rw;
1665     }
1666
1667   /* Allocate subpage. */
1668   int trim[2] = { z0 - page->h[a], page->n[a] - z1 };
1669
1670   int n[TABLE_N_AXES] = { [H] = page->n[H], [V] = page->n[V] };
1671   n[a] -= trim[0] + trim[1];
1672
1673   int r[TABLE_N_AXES][2];
1674   for (enum table_axis k = 0; k < TABLE_N_AXES; k++)
1675     {
1676       r[k][0] = page->r[k][0];
1677       r[k][1] = page->r[k][1];
1678     }
1679   r[a][0] += trim[0];
1680   r[a][1] -= trim[1];
1681
1682   struct render_page *subpage = render_page_allocate__ (
1683     page->params, table_ref (page->table), n, page->h, r);
1684
1685   /* An edge is cut off if it was cut off in PAGE or if we're trimming pixels
1686      off that side of the page and there are no headers. */
1687   subpage->is_edge_cutoff[a][0] =
1688     subpage->h[a] == 0 && (p0 || (z0 == 0 && page->is_edge_cutoff[a][0]));
1689   subpage->is_edge_cutoff[a][1] =
1690     p1 || (z1 == page->n[a] && page->is_edge_cutoff[a][1]);
1691   subpage->is_edge_cutoff[b][0] = page->is_edge_cutoff[b][0];
1692   subpage->is_edge_cutoff[b][1] = page->is_edge_cutoff[b][1];
1693
1694   /* Select widths from PAGE into subpage. */
1695   int *scp = page->cp[a];
1696   int *dcp = subpage->cp[a];
1697   *dcp = 0;
1698   for (int z = 0; z <= rule_ofs (subpage->h[a]); z++, dcp++)
1699     {
1700       int w = !z && subpage->is_edge_cutoff[a][0] ? 0 : scp[z + 1] - scp[z];
1701       dcp[1] = dcp[0] + w;
1702     }
1703   for (int z = cell_ofs (z0); z <= cell_ofs (z1 - 1); z++, dcp++)
1704     {
1705       dcp[1] = dcp[0] + (scp[z + 1] - scp[z]);
1706       if (z == cell_ofs (z0))
1707         dcp[1] -= p0;
1708       if (z == cell_ofs (z1 - 1))
1709         dcp[1] -= p1;
1710     }
1711   for (int z = rule_ofs_r (page, a, 0);
1712        z <= rule_ofs_r (page, a, 0); z++, dcp++)
1713     {
1714       if (z == rule_ofs_r (page, a, 0) && subpage->is_edge_cutoff[a][1])
1715         dcp[1] = dcp[0];
1716       else
1717         dcp[1] = dcp[0] + (scp[z + 1] - scp[z]);
1718     }
1719   assert (dcp == &subpage->cp[a][2 * subpage->n[a] + 1]);
1720
1721   for (int z = 0; z < page->n[b] * 2 + 2; z++)
1722     subpage->cp[b][z] = page->cp[b][z];
1723
1724   /* Add new overflows. */
1725   struct render_page_selection s = {
1726     .page = page,
1727     .a = a,
1728     .b = b,
1729     .z0 = z0,
1730     .z1 = z1,
1731     .p0 = p0,
1732     .p1 = p1,
1733     .subpage = subpage,
1734   };
1735
1736   if (!page->h[a] || z0 > page->h[a] || p0)
1737     for (int z = 0; z < page->n[b];)
1738       {
1739         int d[TABLE_N_AXES];
1740         d[a] = z0;
1741         d[b] = z;
1742
1743         struct table_cell cell;
1744         render_get_cell (page, d[H], d[V], &cell);
1745         bool overflow0 = p0 || cell.d[a][0] < z0;
1746         bool overflow1 = cell.d[a][1] > z1 || (cell.d[a][1] == z1 && p1);
1747         if (overflow0 || overflow1)
1748           {
1749             struct render_overflow *ro = insert_overflow (&s, &cell);
1750
1751             if (overflow0)
1752               ro->overflow[a][0] += p0 + axis_width (
1753                 page, a, cell_ofs (cell.d[a][0]), cell_ofs (z0));
1754
1755             if (overflow1)
1756               ro->overflow[a][1] += p1 + axis_width (
1757                 page, a, cell_ofs (z1), cell_ofs (cell.d[a][1]));
1758           }
1759         z = cell.d[b][1];
1760       }
1761
1762   for (int z = 0; z < page->n[b];)
1763     {
1764       int d[TABLE_N_AXES];
1765       d[a] = z1 - 1;
1766       d[b] = z;
1767
1768       struct table_cell cell;
1769       render_get_cell (page, d[H], d[V], &cell);
1770       if ((cell.d[a][1] > z1 || (cell.d[a][1] == z1 && p1))
1771           && find_overflow_for_cell (&s, &cell) == NULL)
1772         {
1773           struct render_overflow *ro = insert_overflow (&s, &cell);
1774           ro->overflow[a][1] += p1 + axis_width (page, a, cell_ofs (z1),
1775                                                  cell_ofs (cell.d[a][1]));
1776         }
1777       z = cell.d[b][1];
1778     }
1779
1780   /* Copy overflows from PAGE into subpage. */
1781   struct render_overflow *ro;
1782   HMAP_FOR_EACH (ro, struct render_overflow, node, &page->overflows)
1783     {
1784       struct table_cell cell;
1785
1786       table_get_cell (page->table, ro->d[H], ro->d[V], &cell);
1787       if (cell.d[a][1] > z0 && cell.d[a][0] < z1
1788           && find_overflow_for_cell (&s, &cell) == NULL)
1789         insert_overflow (&s, &cell);
1790     }
1791
1792   return subpage;
1793 }
1794
1795 /* Given CELL, a table_cell within S->page, stores in SUBCELL the (x,y)
1796    coordinates of the top-left cell as it will appear in S->subpage.
1797
1798    CELL must actually intersect the region of S->page that is being selected
1799    by render_page_select() or the results will not make any sense. */
1800 static void
1801 cell_to_subpage (struct render_page_selection *s,
1802                  const struct table_cell *cell, int subcell[TABLE_N_AXES])
1803 {
1804   enum table_axis a = s->a;
1805   enum table_axis b = s->b;
1806   int ha0 = s->subpage->h[a];
1807
1808   subcell[a] = MAX (cell->d[a][0] - s->z0 + ha0, ha0);
1809   subcell[b] = cell->d[b][0];
1810 }
1811
1812 /* Given CELL, a table_cell within S->page, returns the render_overflow for
1813    that cell in S->subpage, if there is one, and a null pointer otherwise.
1814
1815    CELL must actually intersect the region of S->page that is being selected
1816    by render_page_select() or the results will not make any sense. */
1817 static const struct render_overflow *
1818 find_overflow_for_cell (struct render_page_selection *s,
1819                         const struct table_cell *cell)
1820 {
1821   int subcell[2];
1822
1823   cell_to_subpage (s, cell, subcell);
1824   return find_overflow (s->subpage, subcell[H], subcell[V]);
1825 }
1826
1827 /* Given CELL, a table_cell within S->page, inserts a render_overflow for that
1828    cell in S->subpage (which must not already exist).  Initializes the new
1829    render_overflow's 'overflow' member from the overflow for CELL in S->page,
1830    if there is one.
1831
1832    CELL must actually intersect the region of S->page that is being selected
1833    by render_page_select() or the results will not make any sense. */
1834 static struct render_overflow *
1835 insert_overflow (struct render_page_selection *s,
1836                  const struct table_cell *cell)
1837 {
1838   struct render_overflow *of = XZALLOC (struct render_overflow);
1839   cell_to_subpage (s, cell, of->d);
1840   hmap_insert (&s->subpage->overflows, &of->node,
1841                hash_cell (of->d[H], of->d[V]));
1842
1843   const struct render_overflow *old
1844     = find_overflow (s->page, cell->d[H][0], cell->d[V][0]);
1845   if (old != NULL)
1846     memcpy (of->overflow, old->overflow, sizeof of->overflow);
1847
1848   return of;
1849 }