Sha256: 8a7a82866e54f5ff6e85a866326795f176be630f437135b9eb33ffd2ec113eef

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

# font_metric_cache.rb : The Prawn font class
#
# Copyright Dec 2012, Kenneth Kalmer. All Rights Reserved.
#
# This is free software. Please see the LICENSE and COPYING files for details.
#

module Prawn
  # Cache used internally by Prawn::Document instances to calculate the width
  # of various strings for layout purposes.
  #
  # @private
  class FontMetricCache
    CacheEntry = Struct.new(:font, :options, :string)

    def initialize(document)
      @document = document

      @cache = {}
    end

    def width_of(string, options)
      f = if options[:style]
            # override style with :style => :bold
            @document.find_font(@document.font.family, style: options[:style])
          else
            @document.font
          end

      encoded_string = f.normalize_encoding(string)

      key = CacheEntry.new(f, options, encoded_string)

      @cache[key] ||= f.compute_width_of(encoded_string, options)

      length = @cache[key]

      character_count = @document.font.character_count(encoded_string)
      if character_count.positive?
        length += @document.character_spacing * (character_count - 1)
      end

      length
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prawn-2.3.0 lib/prawn/font_metric_cache.rb