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