gamba 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1063 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # Boxes described first, measured, then placed: a stack puts its children one under the other and breaks pages
5
+ # between them, a row puts them side by side on one page.
6
+ module Layout
7
+ FIT_TOLERANCE_POINTS = Prawn::FLOAT_PRECISION
8
+ MEASURING_HEIGHT_POINTS = 100_000_000
9
+
10
+ # The top of the next box on the current page, in absolute coordinates.
11
+ class Cursor
12
+ attr_accessor :y
13
+
14
+ def initialize(prawn)
15
+ @prawn = prawn
16
+ @y = prawn.y
17
+ @page_top = prawn.bounds.absolute_top
18
+ end
19
+
20
+ def remaining
21
+ bounds = @prawn.bounds
22
+ y - (bounds.stretchy? ? @prawn.margin_box.absolute_bottom : bounds.absolute_bottom)
23
+ end
24
+
25
+ def fits?(height)
26
+ height <= remaining + FIT_TOLERANCE_POINTS
27
+ end
28
+
29
+ def at_page_top?
30
+ y == @page_top
31
+ end
32
+
33
+ # What a box has from the top of a page: more cannot be kept together.
34
+ def page_height
35
+ bounds = @prawn.bounds
36
+ @page_top - (bounds.stretchy? ? @prawn.margin_box.absolute_bottom : bounds.absolute_bottom)
37
+ end
38
+
39
+ def next_page
40
+ @prawn.bounds.move_past_bottom
41
+ @page_top = @y = @prawn.y
42
+ end
43
+
44
+ # Flows a decorated stack's children within its bounds, which keep its padding clear on every page.
45
+ def within(bounds)
46
+ @prawn.bounds = bounds
47
+ @page_top = bounds.absolute_top
48
+ yield
49
+ ensure
50
+ @prawn.bounds = bounds.outer
51
+ @page_top = @prawn.bounds.absolute_top
52
+ end
53
+ end
54
+
55
+ # The bounds of a stack with a background or a border while it flows across pages: its padding kept clear at
56
+ # the top and the bottom of each page, its decoration drawn on each page beneath what that page holds of it,
57
+ # as CSS's box-decoration-break: clone does. Text and tables break pages through these bounds, so each break
58
+ # closes the stack's part on one page and opens it on the next.
59
+ class DecoratedBounds < Prawn::Document::BoundingBox
60
+ def initialize(prawn, stack, left, width, padding_top, padding_bottom)
61
+ parent = prawn.bounds
62
+ super(prawn, parent, [parent.absolute_left, parent.absolute_top], width: parent.width, height: 0)
63
+ # The margin box is made anew on each page: bounds within it follow the current one.
64
+ @within_margins = parent.equal?(prawn.margin_box)
65
+ @stack = stack
66
+ @left = left
67
+ @box_width = width
68
+ @padding_top = padding_top
69
+ @padding_bottom = padding_bottom
70
+ end
71
+
72
+ def outer
73
+ @within_margins ? @document.margin_box : @parent
74
+ end
75
+
76
+ def absolute_left
77
+ outer.absolute_left + total_left_padding
78
+ end
79
+
80
+ def width
81
+ outer.width - total_left_padding - total_right_padding
82
+ end
83
+
84
+ def absolute_top
85
+ outer.absolute_top - @padding_top
86
+ end
87
+
88
+ def absolute_bottom
89
+ outer_bottom + @padding_bottom
90
+ end
91
+
92
+ def height
93
+ absolute_top - absolute_bottom
94
+ end
95
+
96
+ def stretchy?
97
+ false
98
+ end
99
+
100
+ # The stack's part on this page reaches down to the bottom of what holds it, and its next part starts at the
101
+ # top of the next page.
102
+ def move_past_bottom
103
+ end_part(outer_bottom, skip_empty: true)
104
+ outer.move_past_bottom
105
+ start_part(outer.absolute_top)
106
+ @document.y = absolute_top
107
+ end
108
+
109
+ # The stack's part on this page starts at top: what is drawn from here is drawn over its decoration.
110
+ def start_part(top)
111
+ @top = top
112
+ @offset = @document.page.content_stream.bytesize
113
+ @graphic_state = @document.graphic_state.dup
114
+ end
115
+
116
+ def end_part(bottom, skip_empty: false)
117
+ return if skip_empty && @document.page.content_stream.bytesize == @offset
118
+
119
+ @stack.decorate_beneath(@document, @offset, @graphic_state, @left, @top, @box_width, @top - bottom)
120
+ end
121
+
122
+ private
123
+
124
+ def outer_bottom
125
+ outer.stretchy? ? @document.margin_box.absolute_bottom : outer.absolute_bottom
126
+ end
127
+ end
128
+
129
+ # A box. Its role says what it is to a reader, for tagged PDF: a heading of a level, a paragraph, a list and
130
+ # its items, a table, a figure with its alternative text, or an artifact, which only decorates the page. lang
131
+ # is the language of its text, when it differs from the document's.
132
+ class Node
133
+ OPTIONS = %i[width grow keep_with_next role alt lang].freeze
134
+ ROLES = %i[artifact].freeze
135
+ DEFAULT_ROLE = nil
136
+ KIND = "a box"
137
+ # The standard structure type of each role (ISO 32000-1 §14.8.4).
138
+ STRUCTURE_TYPES = {
139
+ p: :P, h1: :H1, h2: :H2, h3: :H3, h4: :H4, h5: :H5, h6: :H6, list: :L, list_item: :LI, figure: :Figure, table: :Table
140
+ }.freeze
141
+
142
+ attr_reader :width, :grow, :keep_with_next, :role, :alt, :lang
143
+
144
+ def initialize(width: nil, grow: nil, keep_with_next: false, role: self.class::DEFAULT_ROLE, alt: nil, lang: nil)
145
+ raise ArgumentError, "width and grow exclude each other: a box is as wide as told, or shares what is left" if width && grow
146
+ accepted = self.class::ROLES + (self.class::DEFAULT_ROLE ? [] : [nil])
147
+ raise ArgumentError, "role is #{role.inspect}: #{self.class::KIND} takes #{self.class::ROLES.map(&:inspect).join(", ")}" unless accepted.include?(role)
148
+ raise ArgumentError, "alt is the alternative text of a figure: give it with role: :figure, not #{role.inspect}" if alt && role != :figure
149
+ alt = Gamba::Tagging.text(alt)
150
+ raise ArgumentError, "alt is #{alt.inspect}: give the text a reader hears in place of the figure" if alt && !Gamba::Tagging.visible_text?(alt)
151
+ raise ArgumentError, "lang is #{lang.inspect}: give a language tag, \"fr\" or \"en-GB\"" if lang && !(lang.is_a?(String) && lang.match?(Gamba::Tagging::LANGUAGE_TAG))
152
+
153
+ @width = width
154
+ @grow = grow
155
+ @keep_with_next = keep_with_next
156
+ @role = role
157
+ @alt = alt
158
+ @lang = lang
159
+ end
160
+
161
+ # A box is measured when it is placed and again by the boxes around it: once per width is enough.
162
+ def height(prawn, width)
163
+ (@height_by_width ||= {})[width] ||= measure(prawn, width)
164
+ end
165
+
166
+ # The least of this box that can start a page: all of it, unless it can be split.
167
+ def first_height(prawn, width)
168
+ height(prawn, width)
169
+ end
170
+
171
+ # What a container or the document calls: in a tagged document, the box flows or is painted within its
172
+ # structure element (Gamba::Tagging), or as an artifact.
173
+ def flow_tagged(prawn, cursor, left, width)
174
+ return flow(prawn, cursor, left, width) unless prawn.tagged?
175
+
176
+ tag(prawn) { flow(prawn, cursor, left, width) }
177
+ end
178
+
179
+ def paint_tagged(prawn, left, top, width, stretched_height = nil)
180
+ return paint_stretched(prawn, left, top, width, stretched_height) unless prawn.tagged?
181
+
182
+ tag(prawn) { paint_stretched(prawn, left, top, width, stretched_height) }
183
+ end
184
+
185
+ # A box that cannot be split goes to the next page when the rest of this one is too short for it.
186
+ def flow(prawn, cursor, left, width)
187
+ height = height(prawn, width)
188
+ cursor.next_page unless cursor.fits?(height) || cursor.at_page_top?
189
+ unless cursor.fits?(height)
190
+ raise Prawn::Errors::CannotFit, "#{description} is #{height.round(1)} pt high, the page has #{cursor.remaining.round(1)} pt: it cannot be split"
191
+ end
192
+
193
+ paint(prawn, left, cursor.y, width)
194
+ cursor.y -= height
195
+ end
196
+
197
+ private
198
+
199
+ # Only a container in a line of a grid is stretched to the line's height.
200
+ def paint_stretched(prawn, left, top, width, stretched_height)
201
+ stretched_height ? paint(prawn, left, top, width, stretched_height) : paint(prawn, left, top, width)
202
+ end
203
+
204
+ def relative(prawn, left, top)
205
+ [left - prawn.bounds.absolute_left, top - prawn.bounds.absolute_bottom]
206
+ end
207
+
208
+ # Without a role, a box makes no element unless it says its language; a list item's content goes in its body.
209
+ def tag(prawn, &)
210
+ return prawn.tag_artifact(&) if role == :artifact
211
+ return (lang ? prawn.tag_structure(:Div, Lang: lang, &) : yield) if role.nil?
212
+
213
+ prawn.tag_structure(STRUCTURE_TYPES.fetch(role), Alt: alt, Lang: lang) do
214
+ next prawn.tag_structure(:LBody) { tag_body(prawn, &) } if role == :list_item
215
+
216
+ tag_body(prawn, &)
217
+ end
218
+ end
219
+
220
+ # A box that draws content marks it as its element's.
221
+ def tag_body(prawn, &)
222
+ prawn.tag_content(&)
223
+ end
224
+ end
225
+
226
+ # A paragraph: its lines fill the page and the rest goes on to the next ones, never leaving fewer than
227
+ # `orphans` lines at the bottom of a page nor fewer than `widows` at the top of the next.
228
+ class Text < Node
229
+ DEFAULT_WIDOWS = 2
230
+ DEFAULT_ORPHANS = 2
231
+ HEADINGS = %i[h1 h2 h3 h4 h5 h6].freeze
232
+ ROLES = (%i[p] + HEADINGS + %i[list_item artifact]).freeze
233
+ DEFAULT_ROLE = :p
234
+ KIND = "a text"
235
+
236
+ def initialize(string, font:, font_options:, color:, text_options:, widows: DEFAULT_WIDOWS, orphans: DEFAULT_ORPHANS, bookmarks: nil, **)
237
+ super(**)
238
+ @bookmarks = bookmarks if HEADINGS.include?(role)
239
+ @fragments = [color ? {text: string, color:} : {text: string}]
240
+ @font = font
241
+ @font_options = font_options
242
+ @text_options = text_options
243
+ @widows = lines_option(:widows, widows)
244
+ @orphans = lines_option(:orphans, orphans)
245
+ end
246
+
247
+ # The lines wrapped to measure the text are drawn as they are, when Prawn's box can draw them again.
248
+ def paint(prawn, left, top, width)
249
+ bookmark(prawn, top)
250
+ at = relative(prawn, left, top)
251
+ with_font(prawn) do
252
+ if @measured_width == width && @measured_box.layout_reusable?
253
+ @measured_box.render_laid_out(at)
254
+ else
255
+ box(prawn, @fragments, at, width, MEASURING_HEIGHT_POINTS).render
256
+ end
257
+ end
258
+ end
259
+
260
+ def flow(prawn, cursor, left, width)
261
+ with_font(prawn) do
262
+ fragments = @fragments
263
+ # How high the rest of the paragraph is at most, once a page took its first lines.
264
+ rest_height = nil
265
+ loop do
266
+ at = relative(prawn, left, cursor.y)
267
+ # The rest fits whole: no rule can apply, and nothing needs to be wrapped twice.
268
+ if rest_height && cursor.fits?(rest_height)
269
+ cursor.y -= advance(box(prawn, fragments, at, width, MEASURING_HEIGHT_POINTS).tap(&:render))
270
+ break
271
+ end
272
+
273
+ # Measured already, by a box kept with this one: its lines serve again.
274
+ probe = (fragments.equal?(@fragments) && @measured_width == width) ? @measured_box : laid_out(prawn, fragments, width)
275
+ height = height_for_this_page(probe, cursor)
276
+ if height.zero?
277
+ cursor.next_page
278
+ next
279
+ end
280
+
281
+ bookmark(prawn, cursor.y) if fragments.equal?(@fragments)
282
+ # Most paragraphs fit whole: the lines wrapped to place them are drawn as they are.
283
+ if height == MEASURING_HEIGHT_POINTS && probe.layout_reusable?
284
+ probe.render_laid_out(at)
285
+ cursor.y -= advance(probe)
286
+ break
287
+ end
288
+
289
+ box = box(prawn, fragments, at, width, height)
290
+ unprinted = box.render
291
+ cursor.y -= advance(box)
292
+ break if unprinted.empty?
293
+
294
+ # A first line takes no more than the line spacing it had below the line before it.
295
+ rest_height = probe.height - height
296
+ fragments = unprinted
297
+ cursor.next_page
298
+ end
299
+ end
300
+ end
301
+
302
+ # A page can start with this paragraph's first `orphans` lines, or with all of it when it is shorter.
303
+ def first_height(prawn, width)
304
+ height(prawn, width)
305
+ bottoms = @measured_box.line_bottoms
306
+ return height(prawn, width) if bottoms.size <= @orphans
307
+
308
+ bottoms[@orphans - 1]
309
+ end
310
+
311
+ private
312
+
313
+ # A heading is bookmarked where its first line is drawn, under the last heading of a higher level.
314
+ def bookmark(prawn, top)
315
+ @bookmarks&.add(HEADINGS.index(role) + 1, @fragments.sum("") { _1[:text] }.split.join(" "), top)
316
+ end
317
+
318
+ def lines_option(name, lines)
319
+ return lines if lines.is_a?(Integer) && lines >= 1
320
+
321
+ raise ArgumentError, "#{name} is #{lines.inspect}: give a number of lines, 1 or more"
322
+ end
323
+
324
+ def measure(prawn, width)
325
+ with_font(prawn) do
326
+ @measured_width = width
327
+ @measured_box = laid_out(prawn, @fragments, width)
328
+ advance(@measured_box)
329
+ end
330
+ end
331
+
332
+ # The fragments wrapped at this width, with no height to stop them, their lines kept.
333
+ def laid_out(prawn, fragments, width)
334
+ box = box(prawn, fragments, [0, 0], width, MEASURING_HEIGHT_POINTS)
335
+ box.render(dry_run: true, keep_layout: true)
336
+ box
337
+ end
338
+
339
+ # The height to give this page's box, 0 when the paragraph moves on to the next page: as many lines as fit,
340
+ # fewer when the rest would leave widows, none when what fits would leave orphans. At the top of a page,
341
+ # a paragraph takes what fits whatever its rules: no other page would do better.
342
+ def height_for_this_page(probe, cursor)
343
+ return MEASURING_HEIGHT_POINTS if cursor.fits?(probe.height)
344
+
345
+ bottoms = probe.line_bottoms
346
+ fitting = bottoms.count { |bottom| bottom <= cursor.remaining + FIT_TOLERANCE_POINTS }
347
+ if fitting.zero?
348
+ raise Prawn::Errors::CannotFit, "#{description} has a line higher than the page" if cursor.at_page_top?
349
+
350
+ return 0
351
+ end
352
+ return MEASURING_HEIGHT_POINTS if fitting == bottoms.size
353
+ return bottoms[fitting - 1] if cursor.at_page_top?
354
+
355
+ kept = [fitting, bottoms.size - @widows].min
356
+ (kept >= @orphans) ? bottoms[kept - 1] : 0
357
+ end
358
+
359
+ def description
360
+ "the text #{@fragments.first[:text][0, 30].inspect}"
361
+ end
362
+
363
+ # Prawn's font answers the font, not what its block returns.
364
+ def with_font(prawn)
365
+ return yield unless @font
366
+
367
+ returned = nil
368
+ prawn.font(@font, @font_options) { returned = yield }
369
+ returned
370
+ end
371
+
372
+ def box(prawn, fragments, at, width, height)
373
+ Prawn::Text::Formatted::Box.new(fragments, {document: prawn, at:, width:, height:, **@text_options})
374
+ end
375
+
376
+ # What Prawn's text moves the cursor by: the lines, and the gap that separates the last one from what follows.
377
+ def advance(box)
378
+ box.height + box.line_gap + box.leading
379
+ end
380
+ end
381
+
382
+ # An image as a box: at its own size unless told a width or a height, never wider than its box, never distorted.
383
+ class Image < Node
384
+ OPTIONS = (Node::OPTIONS + %i[height align]).freeze
385
+ ALIGNMENTS = %i[left center right].freeze
386
+ ROLES = %i[figure artifact].freeze
387
+ DEFAULT_ROLE = :figure
388
+ KIND = "an image"
389
+
390
+ def initialize(source, height: nil, align: :left, **)
391
+ raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{ALIGNMENTS.map(&:inspect).join(", ")}" unless ALIGNMENTS.include?(align)
392
+
393
+ super(**)
394
+ @source = source
395
+ @height = height
396
+ @align = align
397
+ end
398
+
399
+ def paint(prawn, left, top, width)
400
+ image_width, image_height = size(prawn, width)
401
+ offset = {left: 0, center: (width - image_width) / 2.0, right: width - image_width}.fetch(@align)
402
+ prawn.embed_image(*image(prawn), at: relative(prawn, left + offset, top), width: image_width, height: image_height)
403
+ end
404
+
405
+ private
406
+
407
+ def measure(prawn, width)
408
+ size(prawn, width).last
409
+ end
410
+
411
+ def description
412
+ "an image"
413
+ end
414
+
415
+ def image(prawn)
416
+ @image ||= prawn.build_image_object(@source)
417
+ end
418
+
419
+ def size(prawn, available_width)
420
+ info = image(prawn).last
421
+ ratio = info.width / info.height.to_f
422
+ image_width = @height ? @height * ratio : (width || info.width)
423
+ image_width = [image_width, available_width].min
424
+ [image_width, image_width / ratio]
425
+ end
426
+ end
427
+
428
+ # A page of another PDF as a box, sized and aligned as an image is.
429
+ class PdfPage < Image
430
+ def initialize(source, page: 1, **)
431
+ super(source, **)
432
+ @page = page
433
+ end
434
+
435
+ private
436
+
437
+ def description
438
+ "a PDF page"
439
+ end
440
+
441
+ def image(prawn)
442
+ @image ||= prawn.build_pdf_page_object(@source, @page)
443
+ end
444
+ end
445
+
446
+ # A QR code or a DataMatrix as a box: size wide, its quiet zone included, or as many points per module as
447
+ # module_size says; never wider than its box.
448
+ class MatrixCode < Node
449
+ OPTIONS = (Node::OPTIONS + %i[size module_size quiet_zone color align]).freeze
450
+ ROLES = Image::ROLES
451
+ DEFAULT_ROLE = :figure
452
+ KIND = "a code"
453
+
454
+ def initialize(symbol, size: nil, module_size: Prawn::Barcodes::DEFAULT_MODULE_SIZE, quiet_zone: true, color: "000000", align: :left, **)
455
+ raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{Image::ALIGNMENTS.map(&:inspect).join(", ")}" unless Image::ALIGNMENTS.include?(align)
456
+
457
+ super(**)
458
+ @symbol = symbol
459
+ @size = size
460
+ @module_size = module_size
461
+ @quiet_zone = quiet_zone
462
+ @color = color
463
+ @align = align
464
+ end
465
+
466
+ def paint(prawn, left, top, width)
467
+ size = side(width)
468
+ offset = {left: 0, center: (width - size) / 2.0, right: width - size}.fetch(@align)
469
+ prawn.draw_matrix_code(@symbol, at: relative(prawn, left + offset, top), size:, quiet_zone: @quiet_zone, color: @color)
470
+ end
471
+
472
+ private
473
+
474
+ def measure(_prawn, width)
475
+ side(width)
476
+ end
477
+
478
+ def side(available_width)
479
+ modules = @symbol.size + (@quiet_zone ? 2 * @symbol.quiet_zone : 0)
480
+ [@size || width || (modules * @module_size), available_width].min
481
+ end
482
+
483
+ def description
484
+ @symbol.is_a?(Gamba::Barcodes::QRCode) ? "a QR code" : "a DataMatrix"
485
+ end
486
+ end
487
+
488
+ # A linear barcode as a box: as wide as told, quiet zones included, or as many points per module as
489
+ # module_size says; never wider than its box.
490
+ class Barcode < Node
491
+ OPTIONS = (Node::OPTIONS + %i[type module_size height text text_size color quiet_zone align]).freeze
492
+ ROLES = Image::ROLES
493
+ DEFAULT_ROLE = :figure
494
+ KIND = "a barcode"
495
+
496
+ def initialize(data, type:, align: :left, **options)
497
+ raise ArgumentError, "align is #{align.inspect}: accepted alignments are #{Image::ALIGNMENTS.map(&:inspect).join(", ")}" unless Image::ALIGNMENTS.include?(align)
498
+
499
+ super(**options.slice(*Node::OPTIONS))
500
+ @symbol = Gamba::Barcodes::Linear.new(data, type:)
501
+ @options = options.except(*Node::OPTIONS)
502
+ @align = align
503
+ end
504
+
505
+ def paint(prawn, left, top, width)
506
+ options = drawn(width)
507
+ offset = {left: 0, center: (width - options[:width]) / 2.0, right: width - options[:width]}.fetch(@align)
508
+ prawn.draw_barcode(@symbol, at: relative(prawn, left + offset, top), **options)
509
+ end
510
+
511
+ private
512
+
513
+ def measure(_prawn, width)
514
+ Prawn::Barcodes.linear_dimensions(@symbol, drawn(width)).last
515
+ end
516
+
517
+ # The options to draw it with: its width at most the box's.
518
+ def drawn(available_width)
519
+ natural = Prawn::Barcodes.linear_dimensions(@symbol, {width: width}.compact.merge(@options))[4]
520
+ @options.merge(width: [natural, available_width].min)
521
+ end
522
+
523
+ def description
524
+ "a barcode"
525
+ end
526
+ end
527
+
528
+ # What a document and its containers share: the calls that add a box.
529
+ module Builder
530
+ # Rows are hashes, or objects answering the columns' names. The block receives the Prawn::Table before it
531
+ # is laid out, for what the options do not cover: spans, the style of one cell.
532
+ def table(rows, **options, &styling)
533
+ add(Table.new(rows, styling, @styles, **options))
534
+ end
535
+
536
+ def image(source, **options)
537
+ Styles.check_options(options, Image::OPTIONS)
538
+ add(Image.new(source, **options))
539
+ end
540
+
541
+ def barcode(data, **options)
542
+ Styles.check_options(options, Barcode::OPTIONS)
543
+ add(Barcode.new(data, **options))
544
+ end
545
+
546
+ def qr_code(text, level: :m, **options)
547
+ Styles.check_options(options, MatrixCode::OPTIONS)
548
+ add(MatrixCode.new(Gamba::Barcodes::QRCode.new(text, level:), **options))
549
+ end
550
+
551
+ def data_matrix(data, **options)
552
+ Styles.check_options(options, MatrixCode::OPTIONS)
553
+ add(MatrixCode.new(Gamba::Barcodes::DataMatrix.new(data), **options))
554
+ end
555
+
556
+ # A page of another PDF (a path, an IO or its bytes), from 1, as a box sized like an image.
557
+ def pdf_page(source, page: 1, **options)
558
+ Styles.check_options(options, Image::OPTIONS)
559
+ add(PdfPage.new(source, page:, **options))
560
+ end
561
+
562
+ def stack(**options)
563
+ container = Stack.new(@styles, **options)
564
+ yield container
565
+ add(container)
566
+ end
567
+
568
+ def row(**options)
569
+ container = Row.new(@styles, **options)
570
+ yield container
571
+ add(container)
572
+ end
573
+
574
+ # Cells side by side, `columns` to a line, all as wide; a line is as high as its tallest cell.
575
+ def grid(columns:, **options)
576
+ container = Grid.new(@styles, columns:, **options)
577
+ yield container
578
+ add(container)
579
+ end
580
+
581
+ # Draws anything that answers call(builder): a document is made of small objects, each tested alone.
582
+ def draw(component)
583
+ component.call(self)
584
+ self
585
+ end
586
+ end
587
+
588
+ class Container < Node
589
+ include Builder
590
+
591
+ OPTIONS = (Node::OPTIONS + %i[gap padding background border_width border_color]).freeze
592
+ DEFAULT_BORDER_COLOR = "000000"
593
+ # Without a role, a container only groups its children.
594
+ ROLES = %i[list list_item figure artifact].freeze
595
+ KIND = "a container"
596
+
597
+ def initialize(styles, gap: 0, padding: 0, background: nil, border_width: nil, border_color: nil, **)
598
+ super(**)
599
+ @styles = styles
600
+ @gap = gap
601
+ @padding_top, @padding_right, @padding_bottom, @padding_left = edges(padding)
602
+ @background = background
603
+ @border_width = border_width || (0.5 if border_color)
604
+ @border_color = border_color || DEFAULT_BORDER_COLOR
605
+ @children = []
606
+ end
607
+
608
+ def text(string, style: nil, width: nil, grow: nil, **attributes)
609
+ add(Text.new(string, width:, grow:, **@styles.text_arguments(style, attributes)))
610
+ end
611
+
612
+ # Draws the decoration under what the page's content stream holds from offset on, in the graphic state the
613
+ # stream was in there.
614
+ def decorate_beneath(prawn, offset, graphic_state, left, top, width, height)
615
+ stream = prawn.page.content_stream
616
+ start = stream.bytesize
617
+ decorate(prawn, left, top, width, height, graphic_state)
618
+ stream.insert(offset, stream.slice!(start..))
619
+ end
620
+
621
+ private
622
+
623
+ def add(node)
624
+ @children << node
625
+ self
626
+ end
627
+
628
+ def decorated?
629
+ @background || @border_width
630
+ end
631
+
632
+ def decorate(prawn, left, top, width, height, graphic_state = nil)
633
+ return unless decorated?
634
+
635
+ prawn.tag_artifact do
636
+ prawn.save_graphics_state(graphic_state) do
637
+ corner = relative(prawn, left, top)
638
+ if @background
639
+ prawn.fill_color(@background)
640
+ prawn.fill_rectangle(corner, width, height)
641
+ end
642
+ if @border_width
643
+ prawn.line_width(@border_width)
644
+ prawn.stroke_color(@border_color)
645
+ prawn.stroke_rectangle(corner, width, height)
646
+ end
647
+ end
648
+ end
649
+ end
650
+
651
+ # A container's element groups its children's.
652
+ def tag_body(_prawn)
653
+ yield
654
+ end
655
+
656
+ def inner_width(width)
657
+ width - @padding_left - @padding_right
658
+ end
659
+
660
+ # CSS's order: one value for the four edges, [vertical, horizontal], or [top, right, bottom, left].
661
+ def edges(padding)
662
+ case padding
663
+ in Numeric then [padding] * 4
664
+ in [Numeric => vertical, Numeric => horizontal] then [vertical, horizontal, vertical, horizontal]
665
+ in [Numeric, Numeric, Numeric, Numeric] then padding
666
+ else raise ArgumentError, "padding is #{padding.inspect}: give one number, [vertical, horizontal] or [top, right, bottom, left]"
667
+ end
668
+ end
669
+ end
670
+
671
+ class Stack < Container
672
+ OPTIONS = (Container::OPTIONS + %i[keep_together]).freeze
673
+
674
+ def initialize(styles, **options)
675
+ Styles.check_options(options, OPTIONS)
676
+ @keep_together = options.delete(:keep_together)
677
+ super
678
+ end
679
+
680
+ # In a line of a grid, the background and the border reach down to the bottom of the line.
681
+ def paint(prawn, left, top, width, stretched_height = nil)
682
+ decorate(prawn, left, top, width, stretched_height || height(prawn, width))
683
+ child_top = top - @padding_top
684
+ @children.each do |child|
685
+ child_width = child_width(child, width)
686
+ child.paint_tagged(prawn, left + @padding_left, child_top, child_width)
687
+ child_top -= child.height(prawn, child_width) + @gap
688
+ end
689
+ end
690
+
691
+ # A stack breaks pages between its children, and a text among them between its lines; one kept together
692
+ # moves as one box. A background or a border is drawn on each page around what it holds of the stack.
693
+ def flow(prawn, cursor, left, width)
694
+ return super if @keep_together || (decorated? && cursor.fits?(height(prawn, width)))
695
+ return flow_children(prawn, cursor, left, width) unless decorated?
696
+
697
+ cursor.next_page unless cursor.at_page_top? || cursor.fits?(first_height(prawn, width) + @padding_bottom)
698
+ bounds = DecoratedBounds.new(prawn, self, left, width, @padding_top, @padding_bottom)
699
+ bounds.start_part(cursor.y)
700
+ cursor.within(bounds) { flow_children(prawn, cursor, left, width) }
701
+ bounds.end_part(cursor.y)
702
+ end
703
+
704
+ # A page can start with the top of this stack's first child, unless the stack is kept together.
705
+ def first_height(prawn, width)
706
+ return height(prawn, width) if @keep_together || @children.empty?
707
+
708
+ first = @children.first
709
+ @padding_top + first.first_height(prawn, child_width(first, width))
710
+ end
711
+
712
+ private
713
+
714
+ def flow_children(prawn, cursor, left, width)
715
+ cursor.y -= @padding_top
716
+ @children.each_with_index do |child, index|
717
+ cursor.y -= @gap unless index.zero? || cursor.at_page_top?
718
+ keep_with_what_follows(prawn, cursor, width, index)
719
+ child.flow_tagged(prawn, cursor, left + @padding_left, child_width(child, width))
720
+ end
721
+ # The bottom padding of a plain stack ends with the page, so that a decorated stack holding it is not drawn
722
+ # past the page. A decorated stack's own is kept clear on every page, and the gap below its last line ends
723
+ # where its padding starts.
724
+ if decorated?
725
+ cursor.y -= cursor.remaining if cursor.remaining.negative?
726
+ cursor.y -= @padding_bottom
727
+ else
728
+ cursor.y -= @padding_bottom.clamp(0, [cursor.remaining, 0].max)
729
+ end
730
+ end
731
+
732
+ # Children kept with the next go to the next page together with the start of the one after them, when this
733
+ # page is too short for all of it and a page is not.
734
+ def keep_with_what_follows(prawn, cursor, width, index)
735
+ return if cursor.at_page_top? || (index.positive? && @children[index - 1].keep_with_next)
736
+
737
+ kept = @children[index..].take_while(&:keep_with_next)
738
+ following = @children[index + kept.size]
739
+ return if kept.empty? || following.nil?
740
+
741
+ needed = kept.sum { |child| child.height(prawn, child_width(child, width)) + @gap } +
742
+ following.first_height(prawn, child_width(following, width))
743
+ cursor.next_page if !cursor.fits?(needed) && needed <= cursor.page_height + FIT_TOLERANCE_POINTS
744
+ end
745
+
746
+ def measure(prawn, width)
747
+ @padding_top + @padding_bottom + (@gap * [@children.size - 1, 0].max) +
748
+ @children.sum { |child| child.height(prawn, child_width(child, width)) }
749
+ end
750
+
751
+ def description
752
+ "a stack kept together"
753
+ end
754
+
755
+ def child_width(child, width)
756
+ raise ArgumentError, "grow shares the width of a row: it means nothing in a stack" if child.grow
757
+
758
+ [child.width || inner_width(width), inner_width(width)].min
759
+ end
760
+ end
761
+
762
+ # The boxes of a document kept with what follows them, waiting for it to be placed together.
763
+ class Group < Stack
764
+ def push(node)
765
+ add(node)
766
+ end
767
+ end
768
+
769
+ class Row < Container
770
+ def initialize(styles, **options)
771
+ Styles.check_options(options, OPTIONS)
772
+ super
773
+ end
774
+
775
+ def paint(prawn, left, top, width, stretched_height = nil)
776
+ decorate(prawn, left, top, width, stretched_height || height(prawn, width))
777
+ child_left = left + @padding_left
778
+ paint_children(prawn, child_left, top, width)
779
+ end
780
+
781
+ private
782
+
783
+ def paint_children(prawn, child_left, top, width)
784
+ @children.zip(child_widths(width)) do |child, child_width|
785
+ child.paint_tagged(prawn, child_left, top - @padding_top, child_width)
786
+ child_left += child_width + @gap
787
+ end
788
+ end
789
+
790
+ def measure(prawn, width)
791
+ widths = child_widths(width)
792
+ tallest = 0
793
+ @children.each_with_index do |child, index|
794
+ height = child.height(prawn, widths[index])
795
+ tallest = height if height > tallest
796
+ end
797
+ @padding_top + @padding_bottom + tallest
798
+ end
799
+
800
+ def description
801
+ "a row"
802
+ end
803
+
804
+ # Children told their width take it; the others share what is left by their grow, 1 unless told.
805
+ def child_widths(width)
806
+ shared = inner_width(width) - (@gap * [@children.size - 1, 0].max) - @children.sum { |child| child.width || 0 }
807
+ total_grow = @children.sum { |child| child.width ? 0 : child.grow || 1 }
808
+ raise Prawn::Errors::CannotFit, "a row's children are #{-shared.round(1)} pt wider than the row" if shared.negative?
809
+
810
+ @children.map { |child| child.width || (shared * (child.grow || 1) / total_grow.to_f) }
811
+ end
812
+ end
813
+
814
+ # Cells in lines of `columns`: a stack of rows whose cells are all as wide, the last line's included. Pages
815
+ # break between lines, never inside one. gap is one number, or [between lines, between columns].
816
+ class Grid < Stack
817
+ OPTIONS = (Stack::OPTIONS + %i[columns]).freeze
818
+
819
+ def initialize(styles, columns:, gap: 0, **options)
820
+ unless columns.is_a?(Integer) && columns.positive?
821
+ raise ArgumentError, "columns is #{columns.inspect}: give the number of cells on a line, 1 or more"
822
+ end
823
+
824
+ Styles.check_options(options, OPTIONS)
825
+ line_gap, @column_gap = grid_gaps(gap)
826
+ @columns = columns
827
+ super(styles, gap: line_gap, **options)
828
+ end
829
+
830
+ private
831
+
832
+ def add(node)
833
+ if node.width || node.grow
834
+ raise ArgumentError, "width and grow mean nothing in a grid: its columns share its width equally"
835
+ end
836
+
837
+ @children << Line.new(@styles, @columns, @column_gap) if @children.empty? || @children.last.full?
838
+ @children.last.push(node)
839
+ self
840
+ end
841
+
842
+ def description
843
+ "a grid kept together"
844
+ end
845
+
846
+ def grid_gaps(gap)
847
+ case gap
848
+ in Numeric then [gap, gap]
849
+ in [Numeric => line_gap, Numeric => column_gap] then [line_gap, column_gap]
850
+ else raise ArgumentError, "gap is #{gap.inspect}: give one number, or [between lines, between columns]"
851
+ end
852
+ end
853
+
854
+ # A line of a grid: a row whose cells take a column each, however many it holds.
855
+ class Line < Row
856
+ def initialize(styles, columns, column_gap)
857
+ super(styles, gap: column_gap)
858
+ @columns = columns
859
+ end
860
+
861
+ def push(node)
862
+ @children << node
863
+ end
864
+
865
+ def full?
866
+ @children.size == @columns
867
+ end
868
+
869
+ # Kept with the next line when one of its cells is, a heading in a cell for instance.
870
+ def keep_with_next
871
+ @children.any?(&:keep_with_next)
872
+ end
873
+
874
+ private
875
+
876
+ # Cells with a background or a border are drawn as high as the line, like those of a CSS grid.
877
+ def paint_children(prawn, child_left, top, width)
878
+ line_height = height(prawn, width)
879
+ @children.zip(child_widths(width)) do |child, child_width|
880
+ if child.is_a?(Container)
881
+ child.paint_tagged(prawn, child_left, top, child_width, line_height)
882
+ else
883
+ child.paint_tagged(prawn, child_left, top, child_width)
884
+ end
885
+ child_left += child_width + @gap
886
+ end
887
+ end
888
+
889
+ def description
890
+ "a line of a grid"
891
+ end
892
+
893
+ def child_widths(width)
894
+ gaps = @gap * (@columns - 1)
895
+ raise Prawn::Errors::CannotFit, "a grid's gaps are #{(gaps - width).round(1)} pt wider than the grid" if gaps > width
896
+
897
+ Array.new(@children.size, (width - gaps) / @columns.to_f)
898
+ end
899
+ end
900
+ end
901
+
902
+ # The PDF's outline built from the headings as they are placed: each one under the last heading of a higher
903
+ # level, pointing at the top of its first line.
904
+ class Bookmarks
905
+ def initialize(prawn)
906
+ @prawn = prawn
907
+ # The headings that can still receive subsections, by level: [level, outline item].
908
+ @open = []
909
+ end
910
+
911
+ # Prawn's outline adds after its current item: it is pointed at the parent, then back at the end of the root.
912
+ def add(level, title, top)
913
+ @open.pop while @open.any? && @open.last.first >= level
914
+ outline = @prawn.outline
915
+ root = @prawn.outlines_reference
916
+ parent = @open.empty? ? root : @open.last.last
917
+ begin
918
+ outline.parent = parent
919
+ outline.prev = parent.data.last
920
+ outline.section(title, destination: [@prawn.page.dictionary, :XYZ, nil, top, nil])
921
+ ensure
922
+ outline.parent = root
923
+ outline.prev = root.data.last
924
+ end
925
+ @open << [level, parent.data.last]
926
+ end
927
+ end
928
+
929
+ # Named text attributes, and what they come to for Prawn once a call's own are added.
930
+ class Styles
931
+ TEXT_ATTRIBUTES = %i[font size weight italic color align leading widows orphans keep_with_next role lang].freeze
932
+ # Attributes of the paragraph's place on the page, not of its glyphs: the layout reads them, Prawn does not.
933
+ LAYOUT_ATTRIBUTES = %i[widows orphans keep_with_next role lang].freeze
934
+ FONT_STYLES = %i[normal bold italic bold_italic].freeze
935
+ DEFAULT_STYLE = :default
936
+
937
+ def self.check_options(given, accepted)
938
+ unknown = given.keys - accepted
939
+ return if unknown.empty?
940
+
941
+ raise ArgumentError, "unknown option#{"s" if unknown.size > 1} #{unknown.map(&:inspect).join(", ")}: " \
942
+ "accepted options are #{accepted.map(&:inspect).join(", ")}"
943
+ end
944
+
945
+ # Prawn's name for a weight and a slant.
946
+ def self.font_style(weight, italic)
947
+ weight ||= :normal
948
+ raise ArgumentError, "weight is #{weight.inspect}: accepted weights are :normal, :bold" unless %i[normal bold].include?(weight)
949
+
950
+ FONT_STYLES[((weight == :bold) ? 1 : 0) + (italic ? 2 : 0)]
951
+ end
952
+
953
+ def initialize(prawn, default_font_features)
954
+ @prawn = prawn
955
+ @default_font_features = default_font_features
956
+ @attributes_by_name = {}
957
+ @bookmarks = Bookmarks.new(prawn)
958
+ end
959
+
960
+ # The same styles for a header or a footer, whose headings are drawn on every page and bookmark none.
961
+ def without_bookmarks
962
+ dup.tap { _1.instance_variable_set(:@bookmarks, nil) }
963
+ end
964
+
965
+ def define(name, attributes)
966
+ self.class.check_options(attributes, TEXT_ATTRIBUTES)
967
+ @attributes_by_name[name] = attributes.freeze
968
+ end
969
+
970
+ # The default style's font, size and colour, which a table's cells start from.
971
+ def cell_defaults
972
+ @attributes_by_name.fetch(DEFAULT_STYLE, {}).slice(:font, :size, :color)
973
+ end
974
+
975
+ # The font to set around the text, if any, and the options of the Prawn call.
976
+ def text_arguments(style, attributes)
977
+ self.class.check_options(attributes, TEXT_ATTRIBUTES)
978
+ attributes = {**@attributes_by_name.fetch(DEFAULT_STYLE, {}), **named(style), **attributes}
979
+ layout = attributes.slice(*LAYOUT_ATTRIBUTES)
980
+ attributes = attributes.except(*LAYOUT_ATTRIBUTES)
981
+ font = attributes.delete(:font)
982
+ font_options = single_face?(font) ? {features: @default_font_features} : {}
983
+ color = attributes.delete(:color)
984
+ text_options = text_options(attributes)
985
+ check_face(font, text_options[:style])
986
+ {font:, font_options:, color:, text_options:, bookmarks: @bookmarks, **layout}
987
+ end
988
+
989
+ # A font given by its file, or by the name of one standard face (Courier-Bold), rather than a family.
990
+ def single_face?(font)
991
+ return false if font.nil? || @prawn.font_families.key?(font.to_s)
992
+
993
+ (@single_faces ||= {}).fetch(font.to_s) do |name|
994
+ @single_faces[name] = Prawn::Fonts::AFM::BUILT_INS.include?(name) || File.file?(name)
995
+ end
996
+ end
997
+
998
+ # A face the font lacks: Prawn raises BadFontFamily or UnknownFont, which say neither what is missing nor how to
999
+ # add it.
1000
+ def check_face(font, font_style, alternative = nil, in_table: false)
1001
+ return if font.nil? || font_style.nil? || font_style == :normal
1002
+
1003
+ name = font.to_s
1004
+ faces = @prawn.font_families[name]
1005
+ if faces
1006
+ # A family named after a standard font falls back on it, as in Prawn.
1007
+ return if faces.key?(font_style) || Prawn::Fonts::AFM::BUILT_INS.include?(name)
1008
+
1009
+ lacking = "#{name.inspect} is registered without #{font_style}"
1010
+ elsif !single_face?(font)
1011
+ return
1012
+ elsif (family, styled = standard_family(name, font_style, in_table))
1013
+ raise ArgumentError, "#{name.inspect} is one face of #{family}: name the family, font: #{family.inspect}, " \
1014
+ "#{styled}#{alternative}"
1015
+ elsif %w[Symbol ZapfDingbats].include?(name)
1016
+ raise ArgumentError, "#{name.inspect} is a standard font of one face, without #{font_style}#{alternative}"
1017
+ elsif Prawn::Fonts::AFM::BUILT_INS.include?(name)
1018
+ lacking = "#{name.inspect} is one face of a standard font, without #{font_style}"
1019
+ else
1020
+ lacking = "#{name.inspect} is a single face, without #{font_style}"
1021
+ end
1022
+ raise ArgumentError, "#{lacking}: register its faces, document.register_font \"Name\", normal: \"Name.ttf\", " \
1023
+ "#{font_style}: \"Name-#{font_style}.ttf\", then font: \"Name\"#{alternative}"
1024
+ end
1025
+
1026
+ private
1027
+
1028
+ # Courier for Courier-Bold, and the options that reach the face it would take, while the document still has that
1029
+ # standard face. Out of a table, that face joins its own style to the one asked; in a table, the header or the
1030
+ # styling block asked the rest, so the columns take its own style alone.
1031
+ def standard_family(name, font_style, in_table)
1032
+ family, faces = Prawn::Document::BUILT_IN_FONT_FAMILIES.find { |_family, standard| standard.value?(name) }
1033
+ return unless family
1034
+
1035
+ styles = in_table ? [faces.key(name)] : [faces.key(name), font_style]
1036
+ bold, italic = %w[bold italic].map { |part| styles.any? { |style| style.to_s.include?(part) } }
1037
+ face = Styles.font_style(bold ? :bold : nil, italic)
1038
+ return unless @prawn.font_families.dig(family, face) == faces[face] && @prawn.font_families.dig(family, font_style)
1039
+
1040
+ options = [("weight: :bold" if bold), ("italic: true" if italic)].compact.join(", ")
1041
+ [family, in_table ? "with #{options} in its columns" : "with #{options}"]
1042
+ end
1043
+
1044
+ def named(name)
1045
+ return {} unless name
1046
+
1047
+ @attributes_by_name.fetch(name) do
1048
+ raise ArgumentError, "unknown style #{name.inspect}: defined styles are #{@attributes_by_name.keys.map(&:inspect).join(", ")}"
1049
+ end
1050
+ end
1051
+
1052
+ def text_options(attributes)
1053
+ font_style = self.class.font_style(attributes.delete(:weight), attributes.delete(:italic))
1054
+ attributes[:style] = font_style unless font_style == :normal
1055
+ attributes.compact
1056
+ end
1057
+ end
1058
+ end
1059
+ end
1060
+
1061
+ # The other boxes, so that Gamba::Layout loaded alone defines them all.
1062
+ require_relative "table"
1063
+ require_relative "band"