File: resource_scale_factors.py

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (122 lines) | stat: -rw-r--r-- 4,848 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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
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
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Presubmit script for Chromium browser resources.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools, and see
https://chromium.googlesource.com/chromium/src/+/main/styleguide/web/web.md
for the rules we're checking against here.
"""


import os
import struct


class InvalidPNGException(Exception):
  pass


class ResourceScaleFactors(object):
  """Verifier of image dimensions for Chromium resources.

  This class verifies the image dimensions of resources in the various
  resource subdirectories.

  Attributes:
      paths: An array of tuples giving the folders to check and their
          relevant scale factors. For example:

          [(100, 'default_100_percent'), (200, 'default_200_percent')]
  """

  def __init__(self, input_api, output_api, paths):
    """ Initializes ResourceScaleFactors with paths."""
    self.input_api = input_api
    self.output_api = output_api
    self.paths = paths

  def RunChecks(self):
    """Verifies the scale factors of resources being added or modified.

    Returns:
        An array of presubmit errors if any images were detected not
        having the correct dimensions.
    """
    def ImageSize(filename):
      with open(filename, 'rb', buffering=0) as f:
        data = f.read(24)
      if data[:8] != b'\x89PNG\r\n\x1A\n' or data[12:16] != b'IHDR':
        raise InvalidPNGException
      return struct.unpack('>ii', data[16:24])

    # Returns a list of valid scaled image sizes. The valid sizes are the
    # floor and ceiling of (base_size * scale_percent / 100). This is equivalent
    # to requiring that the actual scaled size is less than one pixel away from
    # the exact scaled size.
    def ValidSizes(base_size, scale_percent):
      return sorted(set([(base_size * scale_percent) / 100,
                         (base_size * scale_percent + 99) / 100]))

    repository_path = self.input_api.os_path.relpath(
        self.input_api.PresubmitLocalPath(),
        self.input_api.change.RepositoryRoot())
    results = []

    # Check for affected files in any of the paths specified.
    affected_files = self.input_api.AffectedFiles(include_deletes=False)
    files = []
    for f in affected_files:
      for path_spec in self.paths:
        path_root = self.input_api.os_path.join(
            repository_path, path_spec[1])
        if (f.LocalPath().endswith('.png') and
            f.LocalPath().startswith(path_root)):
          # Only save the relative path from the resource directory.
          relative_path = self.input_api.os_path.relpath(f.LocalPath(),
              path_root)
          if relative_path not in files:
            files.append(relative_path)

    corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not '
        'correctly uploaded to the code review tool and must be directly '
        'submitted using the dcommit command.')
    for f in files:
      base_image = self.input_api.os_path.join(self.paths[0][1], f)
      if not os.path.exists(base_image):
        results.append(self.output_api.PresubmitError(
            'Base image %s does not exist' % self.input_api.os_path.join(
            repository_path, base_image)))
        continue
      try:
        base_dimensions = ImageSize(base_image)
      except InvalidPNGException:
        results.append(self.output_api.PresubmitError(corrupt_png_error %
            self.input_api.os_path.join(repository_path, base_image)))
        continue
      # Find all scaled versions of the base image and verify their sizes.
      for i in range(1, len(self.paths)):
        image_path = self.input_api.os_path.join(self.paths[i][1], f)
        if not os.path.exists(image_path):
          continue
        # Ensure that each image for a particular scale factor is the
        # correct scale of the base image.
        try:
          scaled_dimensions = ImageSize(image_path)
        except InvalidPNGException:
          results.append(self.output_api.PresubmitError(corrupt_png_error %
              self.input_api.os_path.join(repository_path, image_path)))
          continue
        for dimension_name, base_size, scaled_size in zip(
            ('width', 'height'), base_dimensions, scaled_dimensions):
          valid_sizes = ValidSizes(base_size, self.paths[i][0])
          if scaled_size not in valid_sizes:
            results.append(self.output_api.PresubmitError(
                'Image %s has %s %d, expected to be %s' % (
                self.input_api.os_path.join(repository_path, image_path),
                dimension_name,
                scaled_size,
                ' or '.join(map(str, valid_sizes)))))
    return results