Class: Idml::TextEngine::LineBreaker

Inherits:
Object
  • Object
show all
Defined in:
lib/idml/text_engine/line_breaker.rb

Overview

Greedy word-wrap line breaker. Accumulates glyphs until exceeding the frame width, then breaks at the last space. CJK runs get a kinsoku shori post-pass (no line starts or ends with a forbidden character).

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(frame_width) ⇒ LineBreaker

CJK text wraps per character (no word boundaries): an overflow whose trailing glyph is CJK breaks before it instead of emitting an overlong line.



29
30
31
# File 'lib/idml/text_engine/line_breaker.rb', line 29

def initialize(frame_width)
  @frame_width = frame_width
end

Class Method Details

.break(glyphs:, frame_width:) ⇒ Object



13
14
15
16
17
18
# File 'lib/idml/text_engine/line_breaker.rb', line 13

def self.break(glyphs:, frame_width:)
  lines = new(frame_width).break(glyphs)
  return lines unless cjk_run?(glyphs)

  CjkLayout.apply_kinsoku(lines)
end

Instance Method Details

#break(glyphs) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/idml/text_engine/line_breaker.rb', line 41

def break(glyphs)
  lines = []
  current = []
  current_width = 0
  last_space_idx = -1
  width_at_space = 0

  glyphs.each_with_index do |glyph, _idx|
    current << glyph
    current_width += glyph.width

    if glyph.is_space
      last_space_idx = current.length - 1
      width_at_space = current_width
    end

    next unless current_width > @frame_width && current.length > 1

    if last_space_idx >= 0
      line_glyphs = current[0..last_space_idx]
      lines << Line.new(line_glyphs, width_at_space, 0)
      current = current[(last_space_idx + 1)..]
      current_width = current.sum(&:width)
      last_space_idx = -1
    elsif cjk_break?(current)
      lines << Line.new(current[0..-2], current_width - glyph.width, 0)
      current = [glyph]
      current_width = glyph.width
    else
      lines << Line.new(current, current_width, 0)
      current = []
      current_width = 0
    end
  end

  lines << Line.new(current, current_width, 0) if current.any?
  lines
end