Class: Arrolio::TextLayout::Greedy

Inherits:
Object
  • Object
show all
Defined in:
lib/arrolio/text_layout/greedy.rb

Overview

First-fit greedy line breaker. FOP's default. Linear time.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(runs, measurer:, width:, align: :left) ⇒ Greedy

Returns a new instance of Greedy.



9
10
11
12
13
14
# File 'lib/arrolio/text_layout/greedy.rb', line 9

def initialize(runs, measurer:, width:, align: :left)
  @runs = runs
  @measurer = measurer
  @width = width.to_f
  @align = align
end

Instance Attribute Details

#alignObject (readonly)

Returns the value of attribute align.



7
8
9
# File 'lib/arrolio/text_layout/greedy.rb', line 7

def align
  @align
end

#measurerObject (readonly)

Returns the value of attribute measurer.



7
8
9
# File 'lib/arrolio/text_layout/greedy.rb', line 7

def measurer
  @measurer
end

#runsObject (readonly)

Returns the value of attribute runs.



7
8
9
# File 'lib/arrolio/text_layout/greedy.rb', line 7

def runs
  @runs
end

#widthObject (readonly)

Returns the value of attribute width.



7
8
9
# File 'lib/arrolio/text_layout/greedy.rb', line 7

def width
  @width
end

Instance Method Details

#layoutObject



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
# File 'lib/arrolio/text_layout/greedy.rb', line 16

def layout
  opps = opportunities
  return [] if opps.empty? || opps.length == 1

  lines = []
  line_start = 0
  i = 1
  while i < opps.length
    opp = opps[i]
    prev = opps[i - 1]

    if opp.forced?
      emit_line(lines, opps, line_start, i, prev.width_before)
      line_start = i + 1
      i += 2
      next
    end

    if overflows?(opps, line_start, opp) && (i - line_start > 1)
      emit_line(lines, opps, line_start, i - 1, prev.width_before)
      line_start = i - 1
    end
    i += 1
  end

  emit_final_line(lines, opps, line_start) unless lines_built_complete?(opps, line_start)
  lines
end