Class: DYI::Formatter::SvgFormatter

Inherits:
XmlFormatter show all
Defined in:
lib/dyi/formatter/svg_formatter.rb

Overview

Since:

  • 0.0.0

Constant Summary

Constants included from XmlChar

XmlChar::ATTR_PREDEFINED, XmlChar::CP1252, XmlChar::PREDEFINED, XmlChar::VALID

Instance Attribute Summary

Attributes inherited from XmlFormatter

#namespace

Instance Method Summary collapse

Methods inherited from XmlFormatter

#generator_comment, #inline_mode=, #inline_mode?, #stylesheet_instruction, #xml_instruction

Methods inherited from Base

#save, #string

Constructor Details

#initialize(canvas, options = {}) ⇒ SvgFormatter

Returns a new instance of SvgFormatter.

Since:

  • 0.0.0



30
31
32
33
34
35
36
37
38
# File 'lib/dyi/formatter/svg_formatter.rb', line 30

def initialize(canvas, options={})
  super
  version = options[:version] || '1.1'
  unless ['1.0', '1.1'].include?(@version = version.to_s)
    raise ArgumentError, "version `#{version}' is unknown version"
  end
  @defs = {}
  @text_border_elements = []
end

Instance Method Details

#declarationObject

Since:

  • 0.0.0



40
41
42
43
44
45
# File 'lib/dyi/formatter/svg_formatter.rb', line 40

def declaration
  case @version
    when '1.0' then %Q{<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd">}
    when '1.1' then %Q{<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">}
  end
end

#puts(io = $>) ⇒ Object

Since:

  • 0.0.0



47
48
49
50
51
# File 'lib/dyi/formatter/svg_formatter.rb', line 47

def puts(io=$>)
  StringFormat.set_default_formats(:coordinate => 'x,y') {
    super
  }
end

#write_canvas(canvas, io) ⇒ Object

Since:

  • 0.0.0



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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/dyi/formatter/svg_formatter.rb', line 53

def write_canvas(canvas, io)
  @defs = {}
  @xmlns = if namespace
             {:"xmlns:#{namespace}" => "http://www.w3.org/2000/svg"}
           else
             {:xmlns => "http://www.w3.org/2000/svg"}
           end
  pre_write
  unless @text_border_elements.empty?
    @canvas.add_initialize_script(Script::EcmaScript::DomLevel2.draw_text_border(*@text_border_elements))
  end
  attrs = @xmlns.merge(:version => @version,
                       :width => @canvas.real_width,
                       :height => @canvas.real_height,
                       :viewBox => @canvas.view_box,
                       :preserveAspectRatio => @canvas.preserve_aspect_ratio)
  attrs[:'pointer-events'] = 'none' if @canvas.receive_event?
  attrs[:class] = @canvas.css_class if @canvas.css_class
  @canvas.event_listeners.each do |event_name, listeners|
    unless listeners.empty?
      methods = listeners.map do |listener|
                  if listener.name
                    "#{listener.name}(evt)"
                  end
                end
      methods.compact!
      attrs["on#{event_name}"] = methods.join(';') unless methods.empty?
    end
  end
  sio = StringIO.new
  create_node(sio, 'svg', attrs) {
    create_leaf_node(sio, 'title', @canvas.title) if @canvas.title
    create_leaf_node(sio, 'desc', @canvas.description) if @canvas.description
    if @canvas.
      create_cdata_node(sio, 'metadata'){
        puts_line(sio) {
          (@canvas., sio)
        }
      }
    end
    @root_info = [sio.pos, @level]
    i = 0
    length = @canvas.scripts.size
    while i < length
      script = @canvas.scripts[i]
      if script.include_external_file?
        create_leaf_node(sio, 'script',
                         :'xlink:href' => script.href,
                         :type => script.content_type)
        break if length <= (i += 1)
      else
        content_type = script.content_type
        create_cdata_node(sio, 'script',
                          :type => content_type) {
          sio << script.contents
          if (i += 1) < length
            script = @canvas.scripts[i]
            while !script.has_uri_reference? && content_type == script.content_type
              sio << script.contents
              break if length <= (i += 1)
              script = @canvas.scripts[i]
            end
          end
        }
      end
    end
    @canvas.child_elements.each do |element|
      element.write_as(self, sio)
    end
  }
  if @defs.empty? && !@canvas.stylesheets.any?{|style| !style.include_external_file?}
    io << sio.string
  else
    sio.rewind
    io << sio.read(@root_info[0])

    _level = @level
    @level = @root_info[1]
    create_node(io, 'defs') {
      @canvas.stylesheets.each do |stylesheet|
        stylesheet.write_as(self, io)
      end
      @defs.each do |def_id, def_item|
        def_item.write_as(self, io)
      end
    }
    @level = _level

    io << sio.read
  end
end

#write_circle(shape, io) ⇒ Object

Since:

  • 0.0.0



156
157
158
159
160
# File 'lib/dyi/formatter/svg_formatter.rb', line 156

def write_circle(shape, io)
  attrs = {:cx=>shape.center.x, :cy=>shape.center.y, :r=>shape.radius}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'circle')
end

#write_clipping(clipping, io) ⇒ Object

Since:

  • 0.0.0



396
397
398
399
400
401
402
403
# File 'lib/dyi/formatter/svg_formatter.rb', line 396

def write_clipping(clipping, io)
  attrs = {:id => clipping.id}
  create_node(io, 'clipPath', attrs) {
    clipping.shapes.each_with_index do |shape, i|
      shape.write_as(self, io)
    end
  }
end

#write_ellipse(shape, io) ⇒ Object

Since:

  • 0.0.0



162
163
164
165
166
167
168
169
# File 'lib/dyi/formatter/svg_formatter.rb', line 162

def write_ellipse(shape, io)
  attrs = {:cx=>shape.center.x,
           :cy=>shape.center.y,
           :rx=>shape.radius_x,
           :ry=>shape.radius_y}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'ellipse')
end

#write_gradient_stop(shape, io) ⇒ Object

Since:

  • 0.0.0



389
390
391
392
393
394
# File 'lib/dyi/formatter/svg_formatter.rb', line 389

def write_gradient_stop(shape, io)
  attrs = {:offset=>shape.offset}
  attrs[:"stop-color"] = shape.color if shape.color
  attrs[:"stop-opacity"] = shape.opacity if shape.opacity
  create_leaf_node(io, 'stop', attrs)
end

#write_group(shape, io) ⇒ Object

Since:

  • 0.0.0



321
322
323
324
325
326
327
328
329
330
# File 'lib/dyi/formatter/svg_formatter.rb', line 321

def write_group(shape, io)
  unless shape.child_elements.empty?
    attrs = common_attributes(shape)
    write_node(shape, io, attrs, 'g') {
      shape.child_elements.each do |element|
        element.write_as(self, io)
      end
    }
  end
end

#write_image(shape, io) ⇒ Object

Since:

  • 1.0.0



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/dyi/formatter/svg_formatter.rb', line 199

def write_image(shape, io)
  attrs = {:x=>shape.left,
           :y=>shape.top,
           :width=>shape.width,
           :height=>shape.height}
  if shape.include_external_file?
    attrs[:'xlink:href'] = shape.file_path
  else
    content_type = shape.attributes[:content_type].to_s
    content_type = if content_type.empty?
                     shape.file_path =~ /\.([^\.]+)\z/
                     case $1
                     when 'png'
                       'image/png'
                     when 'jpg', 'jpeg'
                       'image/jpeg'
                     else
                       'image/svg+xml'
                     end
                   else
                     case content_type
                     when 'svg'
                       'image/svg+xml'
                     when 'png'
                       'image/png'
                     when 'jpeg'
                       'image/jpeg'
                     else
                       content_type
                     end
                   end
    open(shape.file_path, 'rb') {|f|
      content = f.read
      attrs[:'xlink:href'] = 
          ['data:', content_type, ";base64,\n", [content].pack('m')[0..-2]].join
    }
  end
  attrs.merge!(common_attributes(shape))
  attrs.reject! do |key, value|
    key.to_s =~ /^(fill|stroke)/
  end
  attrs[:preserveAspectRatio] = shape.attributes[:preserve_aspect_ratio] || 'none'
  write_node(shape, io, attrs, 'image')
end

#write_line(shape, io) ⇒ Object

Since:

  • 0.0.0



171
172
173
174
175
176
177
178
# File 'lib/dyi/formatter/svg_formatter.rb', line 171

def write_line(shape, io)
  attrs = {:x1 => shape.start_point.x,
           :y1 => shape.start_point.y,
           :x2 => shape.end_point.x,
           :y2 => shape.end_point.y}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'line')
end

#write_linear_gradient(shape, io) ⇒ Object

Since:

  • 0.0.0



357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/dyi/formatter/svg_formatter.rb', line 357

def write_linear_gradient(shape, io)
  attrs = {:id => @defs.find{|key, value| value==shape}[0],
           :gradientUnit => 'objectBoundingBox',
           :x1 => shape.start_point[0],
           :y1 => shape.start_point[1],
           :x2 => shape.stop_point[0],
           :y2 => shape.stop_point[1]}
  attrs[:"spreadMethod"] = shape.spread_method if shape.spread_method
  create_node(io, 'linearGradient', attrs) {
    shape.child_elements.each do |element|
      element.write_as(self, io)
    end
  }
end

#write_marker(marker, io) ⇒ Object

Since:

  • 1.2.0



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/dyi/formatter/svg_formatter.rb', line 406

def write_marker(marker, io)
  attrs = {:id => marker.id,
           :viewBox => marker.view_box,
           :refX => marker.ref_point.x,
           :refY => marker.ref_point.y,
           :markerUnits => marker.marker_units,
           :markerWidth => marker.width,
           :markerHeight => marker.height}
  attrs[:orient] = marker.orient.to_s if marker.orient
  create_node(io, 'marker', attrs) {
    marker.shapes.each_with_index do |shape, i|
      shape.write_as(self, io)
    end
  }
end

#write_painting_animation(anim, shape, io) ⇒ Object

Since:

  • 1.0.0



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/dyi/formatter/svg_formatter.rb', line 423

def write_painting_animation(anim, shape, io)
  anim.animation_attributes.each do |anim_attr, values|
    attrs = {:attributeName => name_to_attribute(anim_attr),
             :attributeType => 'CSS'}
    if values.size == 2
      attrs[:from] = values[0] if values[0]
      attrs[:to] = values[1]
    else
      attrs[:values] = values.join(';')
      key_times = [0].push(*anim.relay_times[0, anim.relays.size])
      if anim.relay_times.size < anim.relays.size
        step = (1.0 - key_times.last) / (anim.relays.size - anim.relay_times.size + 1)
        (anim.relays.size - anim.relay_times.size).times do |i|
          key_times << key_times.last + step
        end
      end
      key_times << 1
      attrs[:keyTimes] = key_times.map{|num| num.strfnum('0.###')}.join(';')
    end
    merge_anim_attributes(anim, shape, attrs)
    if anim.duration && anim.duration != 0
      create_leaf_node(io, 'animate', attrs)
    else
      create_leaf_node(io, 'set', attrs)
    end
  end
end

#write_path(shape, io) ⇒ Object

Since:

  • 0.0.0



192
193
194
195
196
# File 'lib/dyi/formatter/svg_formatter.rb', line 192

def write_path(shape, io)
  attrs = {:d => shape.concise_path_data}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'path')
end

#write_polygon(shape, io) ⇒ Object

Since:

  • 0.0.0



186
187
188
189
190
# File 'lib/dyi/formatter/svg_formatter.rb', line 186

def write_polygon(shape, io)
  attrs = {:points => shape.points.join(' ')}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'polygon')
end

#write_polyline(shape, io) ⇒ Object

Since:

  • 0.0.0



180
181
182
183
184
# File 'lib/dyi/formatter/svg_formatter.rb', line 180

def write_polyline(shape, io)
  attrs = {:points => shape.points.join(' ')}
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'polyline')
end

#write_radial_gradient(shape, io) ⇒ Object

Since:

  • 1.3.0



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/dyi/formatter/svg_formatter.rb', line 373

def write_radial_gradient(shape, io)
  attrs = {:id => @defs.find{|key, value| value==shape}[0],
           :gradientUnit => 'objectBoundingBox',
           :cx => shape.center_point.x,
           :cy => shape.center_point.y,
           :r => shape.radius,
           :fx => shape.focal_point.x,
           :fy => shape.focal_point.y}
  attrs[:"spreadMethod"] = shape.spread_method if shape.spread_method
  create_node(io, 'radialGradient', attrs) {
    shape.child_elements.each do |element|
      element.write_as(self, io)
    end
  }
end

#write_rectangle(shape, io) ⇒ Object

Since:

  • 0.0.0



145
146
147
148
149
150
151
152
153
154
# File 'lib/dyi/formatter/svg_formatter.rb', line 145

def write_rectangle(shape, io)
  attrs = {:x=>shape.left,
           :y=>shape.top,
           :width=>shape.width,
           :height=>shape.height}
  attrs.merge!(common_attributes(shape))
  attrs[:rx] = shape.attributes[:rx] if shape.attributes[:rx]
  attrs[:ry] = shape.attributes[:ry] if shape.attributes[:ry]
  write_node(shape, io, attrs, 'rect')
end

#write_reused_shape(shape, io) ⇒ Object

Since:

  • 1.3.0



347
348
349
350
351
352
353
354
355
# File 'lib/dyi/formatter/svg_formatter.rb', line 347

def write_reused_shape(shape, io)
  attrs = {:x=>shape.left,
           :y=>shape.top,
           :'xlink:href'=>"##{shape.source_element.id}"}
  attrs[:width] = shape.width if shape.width
  attrs[:height] = shape.height if shape.height
  attrs.merge!(common_attributes(shape))
  write_node(shape, io, attrs, 'use')
end

#write_script(script, io) ⇒ Object

Since:

  • 1.0.0



485
486
487
488
489
490
491
492
493
# File 'lib/dyi/formatter/svg_formatter.rb', line 485

def write_script(script, io)
  if script.include_external_file?
    create_leaf_node(io, 'script',
                     :'xlink:href' => script.href,
                     :type => script.content_type)
  else
    io << script.contents
  end
end

#write_style(stylesheet, io) ⇒ Object

Since:

  • 1.0.0



496
497
498
499
500
501
502
503
504
505
# File 'lib/dyi/formatter/svg_formatter.rb', line 496

def write_style(stylesheet, io)
  unless stylesheet.include_external_file?
    attrs = {:type => stylesheet.content_type}
    attrs[:media] = stylesheet.media if stylesheet.media
    attrs[:title] = stylesheet.title if stylesheet.title
    create_cdata_node(io, 'style', attrs){
      io << stylesheet.body
    }
  end
end

#write_template(shape, io) ⇒ Object

Since:

  • 1.3.0



333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/dyi/formatter/svg_formatter.rb', line 333

def write_template(shape, io)
  unless shape.child_elements.empty?
    attrs = {:viewBox => shape.view_box,
             :preserveAspectRatio => shape.preserve_aspect_ratio}
    attrs.merge!(common_attributes(shape))
    write_node(shape, io, attrs, 'symbol') {
      shape.child_elements.each do |element|
        element.write_as(self, io)
      end
    }
  end
end

#write_text(shape, io) ⇒ Object

Since:

  • 0.0.0



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/dyi/formatter/svg_formatter.rb', line 244

def write_text(shape, io)
  attrs = common_attributes(shape)
  txt_attrs = {}
  if shape.attributes[:text_decoration]
    attrs[:"text-decoration"] = shape.attributes[:text_decoration]
  end
  if shape.attributes[:text_anchor]
    attrs[:"text-anchor"] = shape.attributes[:text_anchor]
  end
  if shape.attributes[:writing_mode]
    attrs[:"writing-mode"] = shape.attributes[:writing_mode]
  end
  if shape.attributes[:text_length]
    txt_attrs[:textLength] = shape.attributes[:text_length]
  end
  if shape.attributes[:length_adjust]
    txt_attrs[:lengthAdjust] = shape.attributes[:length_adjust]
  end

  text = shape.formated_text
  if text =~ /(\r\n|\n|\r)/ ||  shape.animate? || shape.attributes[:show_border]
    shape.publish_id if shape.attributes[:show_border]
    create_text_group = proc {|tag_name, attrs|
      create_node(io, tag_name, attrs) {
        create_border_node(shape, io)
        line_number = 0
        txt_attrs.merge!(:x => shape.point.x, :y => shape.point.y)
        # FIXME: Implementation of baseline attribute are not suitable
        case shape.attributes[:alignment_baseline]
          when 'top' then txt_attrs[:y] += shape.font_height * 0.85
          when 'middle' then txt_attrs[:y] += shape.font_height * 0.35
          when 'bottom' then txt_attrs[:y] -= shape.font_height * 0.15
        end
        txt_attrs[:id] = shape.id + '_%02d' % line_number if shape.inner_id
        current_line = $` || text
        create_leaf_node(io, 'text', current_line.strip, txt_attrs)
        $'.each_line do |line|
          line_number += 1
          txt_attrs = {:x => txt_attrs[:x], :y => txt_attrs[:y] + shape.dy}
          txt_attrs[:id] = shape.id + '_%02d' % line_number if shape.inner_id
          create_leaf_node(io, 'text', line.strip, txt_attrs)
        end if $'
        write_animations(shape, io)
      }
    }
    if shape.anchor_href
      attrs[:'xlink:href'] = shape.anchor_href
      attrs[:target] = shape.anchor_target if shape.anchor_target
      attrs[:'pointer-events'] = 'visiblePainted'
      create_text_group.call('a', attrs)
    else
      create_text_group.call('g', attrs)
    end
  else
    create_text_group = proc {
      attrs.merge!(:x => shape.point.x, :y => shape.point.y)
      # FIXME: Implementation of baseline attribute are not suitable
      case shape.attributes[:alignment_baseline]
        when 'top' then attrs[:y] += shape.font_height * 0.85
        when 'middle' then attrs[:y] += shape.font_height * 0.35
        when 'bottom' then attrs[:y] -= shape.font_height * 0.15
      end
      create_leaf_node(io, 'text', text, attrs.merge(txt_attrs))
    }
    if shape.anchor_href
      link_attrs = {:'xlink:href' => shape.anchor_href}
      link_attrs[:target] = shape.anchor_target if shape.anchor_target
      link_attrs[:'pointer-events'] = 'visiblePainted'
      create_node(io, 'a', link_attrs) {
        create_text_group.call
      }
    else
      create_text_group.call
    end
  end
end

#write_transform_animation(anim, shape, io) ⇒ Object

Since:

  • 1.0.0



452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/dyi/formatter/svg_formatter.rb', line 452

def write_transform_animation(anim, shape, io)
  attrs = {:attributeName => 'transform',
           :attributeType => 'XML',
           :type => anim.type}
  if anim.relays.empty?
    if anim.from.is_a?(Array)
      attrs[:from] = anim.from.join(',')
    elsif anim.from
      attrs[:from] = anim.from.to_s
    end
    attrs[:to] = anim.to.is_a?(Array) ? anim.to.join(',') : anim.to.to_s
  else
    values = [anim.from].push(*anim.relays).push(anim.to)
    attrs[:values] = values.map{|v| v.is_a?(Array) ? v.join(',') : v.to_s}.join(';')
    key_times = [0].push(*anim.relay_times[0, anim.relays.size])
    if anim.relay_times.size < anim.relays.size
      step = (1.0 - key_times.last) / (anim.relays.size - anim.relay_times.size + 1)
      (anim.relays.size - anim.relay_times.size).times do |i|
        key_times << key_times.last + step
      end
    end
    key_times << 1
    attrs[:keyTimes] = key_times.map{|num| num.strfnum('0.###')}.join(';')
  end
  merge_anim_attributes(anim, shape, attrs)
  if anim.duration && anim.duration != 0
    create_leaf_node(io, 'animateTransform', attrs)
  else
    create_leaf_node(io, 'set', attrs)
  end
end