File: font_metric_cache.rb

package info (click to toggle)
ruby-prawn 1.3.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,936 kB
  • ctags: 802
  • sloc: ruby: 13,906; sh: 43; makefile: 15
file content (47 lines) | stat: -rw-r--r-- 1,117 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# encoding: utf-8
#
# 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 ? @document.font.name : 'Helvetica',
                      :style => options[:style])
          else
            @document.font
          end

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

      unless length = @cache[ key ]
        length = @cache[ key ] = f.compute_width_of(string, options)
      end

      length +
        (@document.character_spacing * @document.font.character_count(string))
    end

  end

end