Class: Postsvg::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/postsvg/interpreter.rb

Overview

Stack-based PostScript interpreter

Constant Summary collapse

FILL_ONLY =
{ stroke: false, fill: true }.freeze
STROKE_ONLY =
{ stroke: true, fill: false }.freeze
FILL_AND_STROKE =
{ stroke: true, fill: true }.freeze
DEFAULT_IMAGE =
"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy" \
"53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj4KICA" \
"8dGV4dCB4PSIyNCIgeT0iMTk4IiBmaWxsPSJ3aGl0ZSIgZm9udC1zaXplPSIxM" \
"jgiPkltYWdlbTwvdGV4dD4KICA8dGV4dCB4PSIyNCIgeT0iMjk4IiBmaWxsPSJ" \
"3aGl0ZSIgZm9udC1zaXplPSIxMjgiPk5vdDwvdGV4dD4KICA8dGV4dCB4PSIyN" \
"CIgeT0iMzk4IiBmaWxsPSJ3aGl0ZSIgZm9udC1zaXplPSIxMjgiPkZvdW5kPC9" \
"0ZXh0Pgo8L3N2Zz4K"
PATH_TERMINATORS =
%w[stroke fill show moveto newpath].freeze
PATH_CONTINUATORS =
%w[lineto curveto rlineto rcurveto].freeze
STATE_MODIFIERS =
%w[
  setrgbcolor setgray setcmykcolor setlinewidth setlinecap
  setlinejoin setdash translate scale rotate
].freeze

Instance Method Summary collapse

Constructor Details

#initializeInterpreter

Returns a new instance of Interpreter.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/postsvg/interpreter.rb', line 30

def initialize
  @stack = []
  @g_stack = []
  @g_state = default_graphics_state
  @path = PathBuilder.new
  @current_x = 0
  @current_y = 0
  @id_counter = 0
  @svg_out = { defs: [], element_shapes: [], element_texts: [] }
  @global_dict = {}
  @dict_stack = [@global_dict]

  # Initialize path with correct transform mode
  update_path_transform_mode
end

Instance Method Details

#interpret(tokens, _bounding_box = nil) ⇒ Object



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
79
80
81
82
83
84
85
# File 'lib/postsvg/interpreter.rb', line 46

def interpret(tokens, _bounding_box = nil)
  i = 0
  while i < tokens.length
    token = tokens[i]

    case token.type
    when "number"
      @stack << token.value.to_f
    when "string", "hexstring", "name"
      @stack << token.value
    when "brace"
      if token.value == "{"
        proc_result = parse_procedure(tokens, i + 1)
        @stack << { type: "procedure", body: proc_result[:procedure] }
        i = proc_result[:next_index] - 1
      end
    when "bracket"
      if token.value == "["
        array_result = parse_array(tokens, i + 1)
        @stack << array_result[:array]
        i = array_result[:next_index] - 1
      end
    when "dict"
      if token.value == "<<"
        dict_result = parse_dict(tokens, i + 1)
        @stack << dict_result[:dict]
        i = dict_result[:next_index] - 1
      end
    when "operator"
      execute_operator(token.value, tokens, i)
    end

    i += 1
  end

  # Flush remaining path
  flush_path(STROKE_ONLY) if @path.length.positive?

  @svg_out
end