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