From b31939375d09469e66a12d9ca19f58102931a00f Mon Sep 17 00:00:00 2001 From: Willy Unterkoefler Date: Thu, 16 Feb 2023 17:13:53 -0500 Subject: [PATCH] fix float precision bug in text box rendering --- lib/prawn/text/formatted/line_wrap.rb | 2 +- lib/prawn/text/formatted/wrap.rb | 2 +- lib/prawn/utilities.rb | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/prawn/text/formatted/line_wrap.rb b/lib/prawn/text/formatted/line_wrap.rb index eac14dff3..a2f5913b9 100644 --- a/lib/prawn/text/formatted/line_wrap.rb +++ b/lib/prawn/text/formatted/line_wrap.rb @@ -101,7 +101,7 @@ def add_fragment_to_line(fragment) @document.width_of(segment, kerning: @kerning) end - if @accumulated_width + segment_width <= @width + if @accumulated_width + segment_width <= @width + FLOAT_PRECISION_DELTA @accumulated_width += segment_width shy = soft_hyphen(segment.encoding) if segment[-1] == shy diff --git a/lib/prawn/text/formatted/wrap.rb b/lib/prawn/text/formatted/wrap.rb index 81b4fdac5..6227de671 100644 --- a/lib/prawn/text/formatted/wrap.rb +++ b/lib/prawn/text/formatted/wrap.rb @@ -131,7 +131,7 @@ def enough_height_for_this_line? @descender + @line_height + @leading end require_relatived_total_height = @baseline_y.abs + diff - if require_relatived_total_height > @height + 0.0001 + if require_relatived_total_height > @height + FLOAT_PRECISION_DELTA # no room for the full height of this line @arranger.repack_unretrieved false diff --git a/lib/prawn/utilities.rb b/lib/prawn/utilities.rb index ffe7ea6a6..f6e552e84 100644 --- a/lib/prawn/utilities.rb +++ b/lib/prawn/utilities.rb @@ -7,6 +7,10 @@ # This is free software. Please see the LICENSE and COPYING files for details. module Prawn + # Useful for comparing floats for equality to avoid precision errors. + # Based on pdf-core output precision: https://github.com/prawnpdf/pdf-core/blob/1021ffc94b9d8d37854ef5199d3cbaf220bb5ab2/lib/pdf/core/pdf_object.rb#L16 + FLOAT_PRECISION_DELTA = 1e-6 + # Throughout the Prawn codebase, repeated calculations which can benefit from # caching are made. # In some cases, caching and reusing results can not only save CPU cycles but