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