Module: Asciidoctor::Diagram::Meme

Includes:
Which
Included in:
MemeBlockMacroProcessor
Defined in:
lib/asciidoctor-diagram/meme/extension.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Which

which, #which

Class Method Details

.included(mod) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/asciidoctor-diagram/meme/extension.rb', line 13

def self.included(mod)
  [:png, :gif].each do |format|
    mod.register_format(format, :image) do |parent, source|
      meme(parent, source, format)
    end
  end
end

Instance Method Details

#meme(p, c, format) ⇒ Object



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
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
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/asciidoctor-diagram/meme/extension.rb', line 21

def meme(p, c, format)
  convert = which(p, 'convert')
  identify = which(p, 'identify')

  bg_img = c.attr('background')
  raise "background attribute is required" unless bg_img

  bg_img = p.normalize_system_path(bg_img, p.attr('imagesdir'))

  top_label = c.attr('top')
  bottom_label = c.attr('bottom')
  fill_color = c.attr('fillColor', 'white')
  stroke_color = c.attr('strokeColor', 'black')
  stroke_width = c.attr('strokeWidth', '2')
  font = c.attr('font', 'Impact')
  options = c.attr('options', '').split(',')
  noupcase = options.include?('noupcase')

  dimensions = Cli.run(identify, '-format', '%w %h', bg_img).match(/(?<w>\d+) (?<h>\d+)/)
  bg_width = dimensions['w'].to_i
  bg_height = dimensions['h'].to_i
  label_width = bg_width
  label_height = bg_height / 5

  if top_label
    top_img = Tempfile.new(['meme', '.png'])
    Cli.run(
        convert,
        '-background', 'none',
        '-fill', fill_color,
        '-stroke', stroke_color,
        '-strokewidth', stroke_width,
        '-font', font,
        '-size', "#{label_width}x#{label_height}",
        '-gravity', 'north',
        "label:#{prepare_label(top_label, noupcase)}",
        top_img.path
    )
  else
    top_img = nil
  end

  if bottom_label
    bottom_img = Tempfile.new(['meme', '.png'])
    Cli.run(
        convert,
        '-background', 'none',
        '-fill', fill_color,
        '-stroke', stroke_color,
        '-strokewidth', stroke_width,
        '-font', font,
        '-size', "#{label_width}x#{label_height}",
        '-gravity', 'south',
        "label:#{prepare_label(bottom_label, noupcase)}",
        bottom_img.path
    )
  else
    bottom_img = nil
  end

  final_img = Tempfile.new(['meme', ".#{format.to_s}"])

  args = [convert, bg_img]
  if top_img
    args << top_img.path << '-geometry'<< '+0+0' << '-composite'
  end

  if bottom_img
    args << bottom_img.path << '-geometry'<< "+0+#{bg_height - label_height}" << '-composite'
  end

  args << final_img.path

  Cli.run(*args)

  File.binread(final_img)
end