Class: Fastlane::Helper::PromoScreenshots

Inherits:
Object
  • Object
show all
Defined in:
lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb

Instance Method Summary collapse

Constructor Details

#initializePromoScreenshots

Returns a new instance of PromoScreenshots.



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 23

def initialize
  if $skip_magick
    message = "PromoScreenshots feature is currently disabled.\n"
    message << "Please, install RMagick if you aim to generate the PromoScreenshots.\n"
    message << "\'bundle install --with screenshots\' should do it if your project is configured for PromoScreenshots.\n"
    message << 'Aborting.'
    UI.user_error!(message)
  end

  UI.user_error!('`drawText` not found – install it using `brew install automattic/build-tools/drawText`.') unless system('command -v drawText')
end

Instance Method Details

#apply_operation(image, operation, canvas) ⇒ Object



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 250

def apply_operation(image, operation, canvas)
  case operation['type']
  when 'crop'
    x_pos = operation['at'][0]
    y_pos = operation['at'][1]

    width = operation['to'][0]
    height = operation['to'][1]

    crop_image(image, x_pos, y_pos, width, height)

  when 'resize'
    width = operation['to'][0]
    height = operation['to'][1]

    resize_image(image, width, height)

  when 'composite'

    x_pos = operation['at'][0]
    y_pos = operation['at'][1]

    if operation.member?('offset')
      x_pos += operation['offset'][0]
      y_pos += operation['offset'][1]
    end

    composite_image(canvas, image, x_pos, y_pos)
  end
end

#can_resolve_path(path) ⇒ Object



407
408
409
410
411
412
413
414
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 407

def can_resolve_path(path)
  begin
    resolve_path(path)
    return true
  rescue
    return false
  end
end

#check_fonts_installed!(config:) ⇒ Object

Checks that all required fonts are installed

- Visits the JSON config to find all the stylesheets referenced in it
- For each stylesheet, extract the first font of each `font-family` attribute found
- Finally, for each of those fonts, check that they exist and are activated.

Parameters:

  • config (Hash)

    The promo screenshots configuration, as returned by #read_config

Raises:

  • (UserError)

    Raises if at least one font is missing.



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 57

def check_fonts_installed!(config:)
  # Find all stylesheets in the config
  all_stylesheets = ([config['stylesheet']] + config['entries'].flat_map do |entry|
    entry['attachments']&.map { |att| att['stylesheet'] }
  end).compact.uniq

  # Parse the first font in each `font-family` attribute found in all found CSS files.
  # Only the first in each `font-family` font list matters, as others are fallbacks we don't want to use anyway.
  font_families = all_stylesheets.flat_map do |s|
    File.readlines(s).flat_map do |line|
      attr = line.match(/font-family: (.*);/)&.captures&.first
      attr.split(',').first.strip.gsub(/'(.*)'/, '\1').gsub(/"(.*)"/, '\1') unless attr.nil?
    end
  end.compact.uniq

  # Verify that all fonts exists and are active—using a small swift script as there's no nice CLI for that
  swift_script = <<~SWIFT
    import AppKit

    var exitCode: Int32 = 0
    for fontName in CommandLine.arguments.dropFirst() {
        if NSFont(name: fontName, size: NSFont.systemFontSize) != nil {
            print(" ✅ Font \\"\\(fontName)\\" found and active")
        } else {
            print(" ❌ Font \\"\\(fontName)\\" not found, it is either not installed or disabled. Please install it using FontBook first.")
            exitCode = 1
        }
    }
    exit(exitCode)
  SWIFT

  Tempfile.create(['fonts-check-', '.swift']) do |f|
    f.write(swift_script)
    f.close
    oe, s = Open3.capture2e('/usr/bin/env', 'xcrun', 'swift', f.path, *font_families)
    UI.command_output(oe)
    UI.user_error!('Some fonts required by your stylesheets are missing. Please install them and try again.') unless s.success?
  end
end

#composite_image(original, child, x_position, y_position, starting_position = NorthWestGravity) ⇒ Magick::Image

composite_image

Examples:


image = open_image("image-path")
other = open_image("other-path")
composite_image(image, other, 0, 0)

Parameters:

  • original (Magick::Image)

    The original image.

  • child (Magick::Image)

    The image that will be placed onto the original image.

  • x_position (Integer)

    The horizontal position for the image to be placed.

  • y_position (Integer)

    The vertical position for the image to be placed.

Returns:

  • (Magick::Image)

    The resized image



351
352
353
354
355
356
357
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 351

def composite_image(original, child, x_position, y_position, starting_position = NorthWestGravity)
  UI.user_error!('You must pass an image object as the first argument to `composite_image`.') unless original.is_a?(Magick::Image)

  UI.user_error!('You must pass an image object as the second argument to `composite_image`.') unless child.is_a?(Magick::Image)

  original.composite(child, starting_position, x_position, y_position, Magick::OverCompositeOp)
end

#composite_image_center(original, child, x_position, y_position) ⇒ Object



367
368
369
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 367

def composite_image_center(original, child, x_position, y_position)
  composite_image(original, child, x_position, y_position, CenterGravity)
end

#composite_image_left(original, child, x_position, y_position) ⇒ Object



363
364
365
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 363

def composite_image_left(original, child, x_position, y_position)
  composite_image(original, child, x_position, y_position, WestGravity)
end

#composite_image_top(original, child, x_position, y_position) ⇒ Object



359
360
361
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 359

def composite_image_top(original, child, x_position, y_position)
  composite_image(original, child, x_position, y_position, NorthGravity)
end

#create_image(width, height, background = 'transparent') ⇒ Object



399
400
401
402
403
404
405
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 399

def create_image(width, height, background = 'transparent')
  background_color = background.paint.to_hex

  Image.new(width, height) do
    self.background_color = background
  end
end

#crop_image(original, x_position, y_position, width, height) ⇒ Magick::Image

crop_image

Examples:


image = open_image("image-path")
crop_image(image, other, 0, 0)

Parameters:

  • original (Magick::Image)

    The original image.

  • x_position (Integer)

    The horizontal position to start cropping from.

  • y_position (Integer)

    The vertical position to start cropping from.

  • width (Integer)

    The width of the final image.

  • height (Integer)

    The height of the final image.

Returns:

  • (Magick::Image)

    The resized image



385
386
387
388
389
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 385

def crop_image(original, x_position, y_position, width, height)
  UI.user_error!('You must pass an image object to `crop_image`.') unless original.is_a?(Magick::Image)

  original.crop(x_position, y_position, width, height)
end

#draw_attachments_to_canvas(entry, canvas) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 185

def draw_attachments_to_canvas(entry, canvas)
  entry['attachments'].each do |attachment|
    if !attachment['file'].nil?
      canvas = draw_file_attachment_to_canvas(attachment, canvas, entry)
    elsif !attachment['text'].nil?
      canvas = draw_text_attachment_to_canvas(attachment, canvas, entry['locale'])
    end
  end

  return canvas
end

#draw_background_to_canvas(canvas, entry) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 131

def draw_background_to_canvas(canvas, entry)
  unless entry['background'].nil?

    # If we're passed an image path, let's open it and paint it to the canvas
    if can_resolve_path(entry['background'])
      background_image = open_image(entry['background'])
      return composite_image(canvas, background_image, 0, 0)
    else # Otherwise, let's assume this is a colour code
      background_image = create_image(canvas.columns, canvas.rows, entry['background'])
      canvas = composite_image(canvas, background_image, 0, 0)
    end
  end

  canvas
end

#draw_caption_to_canvas(entry, canvas, device, stylesheet_path = '') ⇒ Object



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 97

def draw_caption_to_canvas(entry, canvas, device, stylesheet_path = '')
  # If no caption is provided, it's ok to skip the body of this method
  return canvas if entry['text'].nil?

  text = entry['text']
  text_size = device['text_size']
  font_size = device['font_size']
  locale = entry['locale']

  text = resolve_text_into_path(text, locale)

  stylesheet_path = resolve_path(stylesheet_path) if can_resolve_path(stylesheet_path)

  width = text_size[0]
  height = text_size[1]

  x_position = 0
  y_position = 0

  unless device['text_offset'].nil?
    x_position = device['text_offset'][0]
    y_position = device['text_offset'][1]
  end

  draw_text_to_canvas(canvas,
                      text,
                      width,
                      height,
                      x_position,
                      y_position,
                      font_size,
                      stylesheet_path)
end

#draw_device_frame_to_canvas(device, canvas) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 147

def draw_device_frame_to_canvas(device, canvas)
  # Apply the device frame to the canvas, but only if one is provided
  return canvas if device['device_frame_size'].nil?

  w = device['device_frame_size'][0]
  h = device['device_frame_size'][1]

  x = 0
  y = 0

  unless device['device_frame_size'].nil?
    x = device['device_frame_offset'][0]
    y = device['device_frame_offset'][1]
  end

  device_frame = open_image(device['device_frame'])
  device_frame = resize_image(device_frame, w, h)
  composite_image(canvas, device_frame, x, y)
end

#draw_file_attachment_to_canvas(attachment, canvas, entry) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 197

def draw_file_attachment_to_canvas(attachment, canvas, entry)
  file = resolve_path(attachment['file'])

  image = open_image(file)

  if attachment.member?('operations')

    attachment['operations'].each do |operation|
      image = apply_operation(image, operation, canvas)
    end

  end

  size = attachment['size']

  x_pos = attachment['position'][0]
  y_pos = attachment['position'][1]

  unless attachment['offset'].nil?
    x_pos += attachment['offset'][0]
    y_pos += attachment['offset'][1]
  end

  image = resize_image(image, size[0], size[1])
  canvas = composite_image(canvas, image, x_pos, y_pos)
end

#draw_screenshot_to_canvas(entry, canvas, device) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 167

def draw_screenshot_to_canvas(entry, canvas, device)
  # Don't require a screenshot to be present – we can just skip this function if one doesn't exist.
  return canvas if entry['screenshot'].nil?

  device_mask = device['screenshot_mask']
  screenshot_size = device['screenshot_size']
  screenshot_offset = device['screenshot_offset']

  screenshot = entry['screenshot']

  screenshot = open_image(screenshot)

  screenshot = mask_image(screenshot, open_image(device_mask)) unless device_mask.nil?

  screenshot = resize_image(screenshot, screenshot_size[0], screenshot_size[1])
  composite_image(canvas, screenshot, screenshot_offset[0], screenshot_offset[1])
end

#draw_text_attachment_to_canvas(attachment, canvas, locale) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 224

def draw_text_attachment_to_canvas(attachment, canvas, locale)
  text = resolve_text_into_path(attachment['text'], locale)
  font_size = attachment['font-size'] ||= 12

  width  = attachment['size'][0]
  height = attachment['size'][1]

  x_position = attachment['position'][0] ||= 0
  y_position = attachment['position'][1] ||= 0

  stylesheet_path = attachment['stylesheet']
  stylesheet_path = resolve_path(stylesheet_path) if can_resolve_path(stylesheet_path)

  alignment = attachment['alignment'] ||= 'center'

  draw_text_to_canvas(canvas,
                      text,
                      width,
                      height,
                      x_position,
                      y_position,
                      font_size,
                      stylesheet_path,
                      alignment)
end

#draw_text_to_canvas(canvas, text, width, height, x_position, y_position, font_size, stylesheet_path, position = 'center') ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 281

def draw_text_to_canvas(canvas, text, width, height, x_position, y_position, font_size, stylesheet_path, position = 'center')
  begin
    tempTextFile = Tempfile.new()

    Action.sh('drawText', "html=#{text}", "maxWidth=#{width}", "maxHeight=#{height}", "output=#{tempTextFile.path}", "fontSize=#{font_size}", "stylesheet=#{stylesheet_path}", "alignment=#{position}")

    text_content = open_image(tempTextFile.path).trim
    text_frame = create_image(width, height)
    text_frame = case position
                 when 'left' then composite_image_left(text_frame, text_content, 0, 0)
                 when 'center' then composite_image_center(text_frame, text_content, 0, 0)
                 when 'top' then composite_image_top(text_frame, text_content, 0, 0)
                 end
  ensure
    tempTextFile.close
    tempTextFile.unlink
  end

  composite_image(canvas, text_frame, x_position, y_position)
end

#mask_image(image, mask, offset_x = 0, offset_y = 0) ⇒ Magick::Image

mask_image

Examples:


image = open_image("image-path")
mask  = open_image("mask-path")

mask_image(image, mask)

Parameters:

  • image (Magick::Image)

    An ImageMagick object containing the image to be masked.

  • mask (Magick::Image)

    An ImageMagick object containing the mask to be be applied.

Returns:

  • (Magick::Image)

    The masked image



315
316
317
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 315

def mask_image(image, mask, offset_x = 0, offset_y = 0)
  image.composite(mask, offset_x, offset_y, CopyAlphaCompositeOp)
end

#open_image(path) ⇒ Object



391
392
393
394
395
396
397
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 391

def open_image(path)
  path = resolve_path(path)

  Magick::Image.read(path) do |image|
    image.background_color = 'transparent'
  end.first
end

#read_config(configFilePath) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 35

def read_config(configFilePath)
  configFilePath = resolve_path(configFilePath)

  begin
    # NOTE: While JSON is a subset of YAML and thus YAML.load_file would technically cover both cases at once, in practice
    # `JSON.parse` is more lenient with JSON files than `YAML.load_file` is — especially, it accepts `// comments` in the
    # JSON file, despite this not being allowed in the spec — hence why we still try with `JSON.parse` for `.json` files.
    return File.extname(configFilePath) == '.json' ? JSON.parse(File.read(configFilePath)) : YAML.load_file(configFilePath)
  rescue StandardError => e
    UI.error(e)
    UI.user_error!('Invalid JSON/YAML configuration. Please lint your config file to check for syntax errors.')
  end
end

#resize_image(original, width, height) ⇒ Magick::Image

resize_image

Examples:


image = open_image("image-path")
resize_image(image, 640, 480)

Parameters:

  • original (Magick::Image)

    An ImageMagick object containing the image to be masked.

  • width (Integer)

    The new width for the image.

  • height (Integer)

    The new height for the image.

Returns:

  • (Magick::Image)

    The resized image



331
332
333
334
335
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 331

def resize_image(original, width, height)
  UI.user_error!('You must pass an image object to `resize_image`.') unless original.is_a?(Magick::Image)

  original.adaptive_resize(width, height)
end

#resolve_path(path) ⇒ Object



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 416

def resolve_path(path)
  UI.crash!('Path not provided – you must provide one to continue') if path.nil?

  [
    Pathname.new(path),                                                           # Absolute Path
    Pathname.new(FastlaneCore::FastlaneFolder.fastfile_path).dirname + path,      # Path Relative to the fastfile
    Fastlane::Helper::FilesystemHelper.plugin_root + path,                        # Path Relative to the plugin
    Fastlane::Helper::FilesystemHelper.plugin_root + 'spec/test-data/' + path, # Path Relative to the test data
  ]
    .each do |resolved_path|
    return resolved_path if !resolved_path.nil? && resolved_path.exist?
  end

  message = "Unable to locate #{path}"
  UI.crash!(message)
end

#resolve_text_into_path(text, locale) ⇒ Object



433
434
435
436
437
438
439
440
441
442
443
# File 'lib/fastlane/plugin/wpmreleasetoolkit/helper/promo_screenshots_helper.rb', line 433

def resolve_text_into_path(text, locale)
  localizedFile = format(text, locale)

  text = if File.exist?(localizedFile)
           localizedFile
         elsif can_resolve_path(localizedFile)
           resolve_path(localizedFile).realpath.to_s
         else
           format(text, 'source')
         end
end