repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_whitespace_ink | def com_google_fonts_check_whitespace_ink(ttFont):
"""Whitespace glyphs have ink?"""
from fontbakery.utils import get_glyph_name, glyph_has_ink
# code-points for all "whitespace" chars:
WHITESPACE_CHARACTERS = [
0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x0085, 0x00A0, 0x1680,
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008,
0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0x180E, 0x200B,
0x2060, 0xFEFF
]
failed = False
for codepoint in WHITESPACE_CHARACTERS:
g = get_glyph_name(ttFont, codepoint)
if g is not None and glyph_has_ink(ttFont, g):
failed = True
yield FAIL, ("Glyph \"{}\" has ink."
" It needs to be replaced by"
" an empty glyph.").format(g)
if not failed:
yield PASS, "There is no whitespace glyph with ink." | python | def com_google_fonts_check_whitespace_ink(ttFont):
"""Whitespace glyphs have ink?"""
from fontbakery.utils import get_glyph_name, glyph_has_ink
# code-points for all "whitespace" chars:
WHITESPACE_CHARACTERS = [
0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x0085, 0x00A0, 0x1680,
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008,
0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0x180E, 0x200B,
0x2060, 0xFEFF
]
failed = False
for codepoint in WHITESPACE_CHARACTERS:
g = get_glyph_name(ttFont, codepoint)
if g is not None and glyph_has_ink(ttFont, g):
failed = True
yield FAIL, ("Glyph \"{}\" has ink."
" It needs to be replaced by"
" an empty glyph.").format(g)
if not failed:
yield PASS, "There is no whitespace glyph with ink." | [
"def",
"com_google_fonts_check_whitespace_ink",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_glyph_name",
",",
"glyph_has_ink",
"# code-points for all \"whitespace\" chars:",
"WHITESPACE_CHARACTERS",
"=",
"[",
"0x0009",
",",
"0x000A",
",",
"0x000B",
",",
"0x000C",
",",
"0x000D",
",",
"0x0020",
",",
"0x0085",
",",
"0x00A0",
",",
"0x1680",
",",
"0x2000",
",",
"0x2001",
",",
"0x2002",
",",
"0x2003",
",",
"0x2004",
",",
"0x2005",
",",
"0x2006",
",",
"0x2007",
",",
"0x2008",
",",
"0x2009",
",",
"0x200A",
",",
"0x2028",
",",
"0x2029",
",",
"0x202F",
",",
"0x205F",
",",
"0x3000",
",",
"0x180E",
",",
"0x200B",
",",
"0x2060",
",",
"0xFEFF",
"]",
"failed",
"=",
"False",
"for",
"codepoint",
"in",
"WHITESPACE_CHARACTERS",
":",
"g",
"=",
"get_glyph_name",
"(",
"ttFont",
",",
"codepoint",
")",
"if",
"g",
"is",
"not",
"None",
"and",
"glyph_has_ink",
"(",
"ttFont",
",",
"g",
")",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Glyph \\\"{}\\\" has ink.\"",
"\" It needs to be replaced by\"",
"\" an empty glyph.\"",
")",
".",
"format",
"(",
"g",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"There is no whitespace glyph with ink.\""
] | Whitespace glyphs have ink? | [
"Whitespace",
"glyphs",
"have",
"ink?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L652-L672 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_required_tables | def com_google_fonts_check_required_tables(ttFont):
"""Font contains all required tables?"""
from .shared_conditions import is_variable_font
REQUIRED_TABLES = {
"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post"}
OPTIONAL_TABLES = {
"cvt ", "fpgm", "loca", "prep", "VORG", "EBDT", "EBLC", "EBSC", "BASE",
"GPOS", "GSUB", "JSTF", "DSIG", "gasp", "hdmx", "LTSH", "PCLT", "VDMX",
"vhea", "vmtx", "kern"
}
# See https://github.com/googlefonts/fontbakery/issues/617
#
# We should collect the rationale behind the need for each of the
# required tables above. Perhaps split it into individual checks
# with the correspondent rationales for each subset of required tables.
#
# com.google.fonts/check/kern_table is a good example of a separate
# check for a specific table providing a detailed description of
# the rationale behind it.
optional_tables = [opt for opt in OPTIONAL_TABLES if opt in ttFont.keys()]
if optional_tables:
yield INFO, ("This font contains the following"
" optional tables [{}]").format(", ".join(optional_tables))
if is_variable_font(ttFont):
# According to https://github.com/googlefonts/fontbakery/issues/1671
# STAT table is required on WebKit on MacOS 10.12 for variable fonts.
REQUIRED_TABLES.add("STAT")
missing_tables = [req for req in REQUIRED_TABLES if req not in ttFont.keys()]
if "glyf" not in ttFont.keys() and "CFF " not in ttFont.keys():
missing_tables.append("CFF ' or 'glyf")
if missing_tables:
yield FAIL, ("This font is missing the following required tables:"
" ['{}']").format("', '".join(missing_tables))
else:
yield PASS, "Font contains all required tables." | python | def com_google_fonts_check_required_tables(ttFont):
"""Font contains all required tables?"""
from .shared_conditions import is_variable_font
REQUIRED_TABLES = {
"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post"}
OPTIONAL_TABLES = {
"cvt ", "fpgm", "loca", "prep", "VORG", "EBDT", "EBLC", "EBSC", "BASE",
"GPOS", "GSUB", "JSTF", "DSIG", "gasp", "hdmx", "LTSH", "PCLT", "VDMX",
"vhea", "vmtx", "kern"
}
# See https://github.com/googlefonts/fontbakery/issues/617
#
# We should collect the rationale behind the need for each of the
# required tables above. Perhaps split it into individual checks
# with the correspondent rationales for each subset of required tables.
#
# com.google.fonts/check/kern_table is a good example of a separate
# check for a specific table providing a detailed description of
# the rationale behind it.
optional_tables = [opt for opt in OPTIONAL_TABLES if opt in ttFont.keys()]
if optional_tables:
yield INFO, ("This font contains the following"
" optional tables [{}]").format(", ".join(optional_tables))
if is_variable_font(ttFont):
# According to https://github.com/googlefonts/fontbakery/issues/1671
# STAT table is required on WebKit on MacOS 10.12 for variable fonts.
REQUIRED_TABLES.add("STAT")
missing_tables = [req for req in REQUIRED_TABLES if req not in ttFont.keys()]
if "glyf" not in ttFont.keys() and "CFF " not in ttFont.keys():
missing_tables.append("CFF ' or 'glyf")
if missing_tables:
yield FAIL, ("This font is missing the following required tables:"
" ['{}']").format("', '".join(missing_tables))
else:
yield PASS, "Font contains all required tables." | [
"def",
"com_google_fonts_check_required_tables",
"(",
"ttFont",
")",
":",
"from",
".",
"shared_conditions",
"import",
"is_variable_font",
"REQUIRED_TABLES",
"=",
"{",
"\"cmap\"",
",",
"\"head\"",
",",
"\"hhea\"",
",",
"\"hmtx\"",
",",
"\"maxp\"",
",",
"\"name\"",
",",
"\"OS/2\"",
",",
"\"post\"",
"}",
"OPTIONAL_TABLES",
"=",
"{",
"\"cvt \"",
",",
"\"fpgm\"",
",",
"\"loca\"",
",",
"\"prep\"",
",",
"\"VORG\"",
",",
"\"EBDT\"",
",",
"\"EBLC\"",
",",
"\"EBSC\"",
",",
"\"BASE\"",
",",
"\"GPOS\"",
",",
"\"GSUB\"",
",",
"\"JSTF\"",
",",
"\"DSIG\"",
",",
"\"gasp\"",
",",
"\"hdmx\"",
",",
"\"LTSH\"",
",",
"\"PCLT\"",
",",
"\"VDMX\"",
",",
"\"vhea\"",
",",
"\"vmtx\"",
",",
"\"kern\"",
"}",
"# See https://github.com/googlefonts/fontbakery/issues/617",
"#",
"# We should collect the rationale behind the need for each of the",
"# required tables above. Perhaps split it into individual checks",
"# with the correspondent rationales for each subset of required tables.",
"#",
"# com.google.fonts/check/kern_table is a good example of a separate",
"# check for a specific table providing a detailed description of",
"# the rationale behind it.",
"optional_tables",
"=",
"[",
"opt",
"for",
"opt",
"in",
"OPTIONAL_TABLES",
"if",
"opt",
"in",
"ttFont",
".",
"keys",
"(",
")",
"]",
"if",
"optional_tables",
":",
"yield",
"INFO",
",",
"(",
"\"This font contains the following\"",
"\" optional tables [{}]\"",
")",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"optional_tables",
")",
")",
"if",
"is_variable_font",
"(",
"ttFont",
")",
":",
"# According to https://github.com/googlefonts/fontbakery/issues/1671",
"# STAT table is required on WebKit on MacOS 10.12 for variable fonts.",
"REQUIRED_TABLES",
".",
"add",
"(",
"\"STAT\"",
")",
"missing_tables",
"=",
"[",
"req",
"for",
"req",
"in",
"REQUIRED_TABLES",
"if",
"req",
"not",
"in",
"ttFont",
".",
"keys",
"(",
")",
"]",
"if",
"\"glyf\"",
"not",
"in",
"ttFont",
".",
"keys",
"(",
")",
"and",
"\"CFF \"",
"not",
"in",
"ttFont",
".",
"keys",
"(",
")",
":",
"missing_tables",
".",
"append",
"(",
"\"CFF ' or 'glyf\"",
")",
"if",
"missing_tables",
":",
"yield",
"FAIL",
",",
"(",
"\"This font is missing the following required tables:\"",
"\" ['{}']\"",
")",
".",
"format",
"(",
"\"', '\"",
".",
"join",
"(",
"missing_tables",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Font contains all required tables.\""
] | Font contains all required tables? | [
"Font",
"contains",
"all",
"required",
"tables?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L689-L728 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_unwanted_tables | def com_google_fonts_check_unwanted_tables(ttFont):
"""Are there unwanted tables?"""
UNWANTED_TABLES = {
'FFTM': '(from FontForge)',
'TTFA': '(from TTFAutohint)',
'TSI0': '(from VTT)',
'TSI1': '(from VTT)',
'TSI2': '(from VTT)',
'TSI3': '(from VTT)',
'TSI5': '(from VTT)',
'prop': '' # FIXME: why is this one unwanted?
}
unwanted_tables_found = []
for table in ttFont.keys():
if table in UNWANTED_TABLES.keys():
info = UNWANTED_TABLES[table]
unwanted_tables_found.append(f"{table} {info}")
if len(unwanted_tables_found) > 0:
yield FAIL, ("Unwanted tables were found"
" in the font and should be removed, either by"
" fonttools/ttx or by editing them using the tool"
" they are from:"
" {}").format(", ".join(unwanted_tables_found))
else:
yield PASS, "There are no unwanted tables." | python | def com_google_fonts_check_unwanted_tables(ttFont):
"""Are there unwanted tables?"""
UNWANTED_TABLES = {
'FFTM': '(from FontForge)',
'TTFA': '(from TTFAutohint)',
'TSI0': '(from VTT)',
'TSI1': '(from VTT)',
'TSI2': '(from VTT)',
'TSI3': '(from VTT)',
'TSI5': '(from VTT)',
'prop': '' # FIXME: why is this one unwanted?
}
unwanted_tables_found = []
for table in ttFont.keys():
if table in UNWANTED_TABLES.keys():
info = UNWANTED_TABLES[table]
unwanted_tables_found.append(f"{table} {info}")
if len(unwanted_tables_found) > 0:
yield FAIL, ("Unwanted tables were found"
" in the font and should be removed, either by"
" fonttools/ttx or by editing them using the tool"
" they are from:"
" {}").format(", ".join(unwanted_tables_found))
else:
yield PASS, "There are no unwanted tables." | [
"def",
"com_google_fonts_check_unwanted_tables",
"(",
"ttFont",
")",
":",
"UNWANTED_TABLES",
"=",
"{",
"'FFTM'",
":",
"'(from FontForge)'",
",",
"'TTFA'",
":",
"'(from TTFAutohint)'",
",",
"'TSI0'",
":",
"'(from VTT)'",
",",
"'TSI1'",
":",
"'(from VTT)'",
",",
"'TSI2'",
":",
"'(from VTT)'",
",",
"'TSI3'",
":",
"'(from VTT)'",
",",
"'TSI5'",
":",
"'(from VTT)'",
",",
"'prop'",
":",
"''",
"# FIXME: why is this one unwanted?",
"}",
"unwanted_tables_found",
"=",
"[",
"]",
"for",
"table",
"in",
"ttFont",
".",
"keys",
"(",
")",
":",
"if",
"table",
"in",
"UNWANTED_TABLES",
".",
"keys",
"(",
")",
":",
"info",
"=",
"UNWANTED_TABLES",
"[",
"table",
"]",
"unwanted_tables_found",
".",
"append",
"(",
"f\"{table} {info}\"",
")",
"if",
"len",
"(",
"unwanted_tables_found",
")",
">",
"0",
":",
"yield",
"FAIL",
",",
"(",
"\"Unwanted tables were found\"",
"\" in the font and should be removed, either by\"",
"\" fonttools/ttx or by editing them using the tool\"",
"\" they are from:\"",
"\" {}\"",
")",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"unwanted_tables_found",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"There are no unwanted tables.\""
] | Are there unwanted tables? | [
"Are",
"there",
"unwanted",
"tables?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L737-L762 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_valid_glyphnames | def com_google_fonts_check_valid_glyphnames(ttFont):
"""Glyph names are all valid?"""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield SKIP, ("TrueType fonts with a format 3.0 post table contain no"
" glyph names.")
else:
import re
bad_names = []
for _, glyphName in enumerate(ttFont.getGlyphOrder()):
if glyphName in [".null", ".notdef", ".ttfautohint"]:
# These 2 names are explicit exceptions
# in the glyph naming rules
continue
if not re.match(r'^(?![.0-9])[a-zA-Z._0-9]{1,31}$', glyphName):
bad_names.append(glyphName)
if len(bad_names) == 0:
yield PASS, "Glyph names are all valid."
else:
from fontbakery.utils import pretty_print_list
yield FAIL, ("The following glyph names do not comply"
" with naming conventions: {}\n\n"
" A glyph name may be up to 31 characters in length,"
" must be entirely comprised of characters from"
" the following set:"
" A-Z a-z 0-9 .(period) _(underscore). and must not"
" start with a digit or period."
" There are a few exceptions"
" such as the special character \".notdef\"."
" The glyph names \"twocents\", \"a1\", and \"_\""
" are all valid, while \"2cents\""
" and \".twocents\" are not."
"").format(pretty_print_list(bad_names)) | python | def com_google_fonts_check_valid_glyphnames(ttFont):
"""Glyph names are all valid?"""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield SKIP, ("TrueType fonts with a format 3.0 post table contain no"
" glyph names.")
else:
import re
bad_names = []
for _, glyphName in enumerate(ttFont.getGlyphOrder()):
if glyphName in [".null", ".notdef", ".ttfautohint"]:
# These 2 names are explicit exceptions
# in the glyph naming rules
continue
if not re.match(r'^(?![.0-9])[a-zA-Z._0-9]{1,31}$', glyphName):
bad_names.append(glyphName)
if len(bad_names) == 0:
yield PASS, "Glyph names are all valid."
else:
from fontbakery.utils import pretty_print_list
yield FAIL, ("The following glyph names do not comply"
" with naming conventions: {}\n\n"
" A glyph name may be up to 31 characters in length,"
" must be entirely comprised of characters from"
" the following set:"
" A-Z a-z 0-9 .(period) _(underscore). and must not"
" start with a digit or period."
" There are a few exceptions"
" such as the special character \".notdef\"."
" The glyph names \"twocents\", \"a1\", and \"_\""
" are all valid, while \"2cents\""
" and \".twocents\" are not."
"").format(pretty_print_list(bad_names)) | [
"def",
"com_google_fonts_check_valid_glyphnames",
"(",
"ttFont",
")",
":",
"if",
"ttFont",
".",
"sfntVersion",
"==",
"b'\\x00\\x01\\x00\\x00'",
"and",
"ttFont",
".",
"get",
"(",
"\"post\"",
")",
"and",
"ttFont",
"[",
"\"post\"",
"]",
".",
"formatType",
"==",
"3.0",
":",
"yield",
"SKIP",
",",
"(",
"\"TrueType fonts with a format 3.0 post table contain no\"",
"\" glyph names.\"",
")",
"else",
":",
"import",
"re",
"bad_names",
"=",
"[",
"]",
"for",
"_",
",",
"glyphName",
"in",
"enumerate",
"(",
"ttFont",
".",
"getGlyphOrder",
"(",
")",
")",
":",
"if",
"glyphName",
"in",
"[",
"\".null\"",
",",
"\".notdef\"",
",",
"\".ttfautohint\"",
"]",
":",
"# These 2 names are explicit exceptions",
"# in the glyph naming rules",
"continue",
"if",
"not",
"re",
".",
"match",
"(",
"r'^(?![.0-9])[a-zA-Z._0-9]{1,31}$'",
",",
"glyphName",
")",
":",
"bad_names",
".",
"append",
"(",
"glyphName",
")",
"if",
"len",
"(",
"bad_names",
")",
"==",
"0",
":",
"yield",
"PASS",
",",
"\"Glyph names are all valid.\"",
"else",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"pretty_print_list",
"yield",
"FAIL",
",",
"(",
"\"The following glyph names do not comply\"",
"\" with naming conventions: {}\\n\\n\"",
"\" A glyph name may be up to 31 characters in length,\"",
"\" must be entirely comprised of characters from\"",
"\" the following set:\"",
"\" A-Z a-z 0-9 .(period) _(underscore). and must not\"",
"\" start with a digit or period.\"",
"\" There are a few exceptions\"",
"\" such as the special character \\\".notdef\\\".\"",
"\" The glyph names \\\"twocents\\\", \\\"a1\\\", and \\\"_\\\"\"",
"\" are all valid, while \\\"2cents\\\"\"",
"\" and \\\".twocents\\\" are not.\"",
"\"\"",
")",
".",
"format",
"(",
"pretty_print_list",
"(",
"bad_names",
")",
")"
] | Glyph names are all valid? | [
"Glyph",
"names",
"are",
"all",
"valid?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L777-L810 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_unique_glyphnames | def com_google_fonts_check_unique_glyphnames(ttFont):
"""Font contains unique glyph names?"""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield SKIP, ("TrueType fonts with a format 3.0 post table contain no"
" glyph names.")
else:
import re
glyphs = []
duplicated_glyphIDs = []
for _, g in enumerate(ttFont.getGlyphOrder()):
glyphID = re.sub(r'#\w+', '', g)
if glyphID in glyphs:
duplicated_glyphIDs.append(glyphID)
else:
glyphs.append(glyphID)
if len(duplicated_glyphIDs) == 0:
yield PASS, "Font contains unique glyph names."
else:
yield FAIL, ("The following glyph names"
" occur twice: {}").format(duplicated_glyphIDs) | python | def com_google_fonts_check_unique_glyphnames(ttFont):
"""Font contains unique glyph names?"""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield SKIP, ("TrueType fonts with a format 3.0 post table contain no"
" glyph names.")
else:
import re
glyphs = []
duplicated_glyphIDs = []
for _, g in enumerate(ttFont.getGlyphOrder()):
glyphID = re.sub(r'#\w+', '', g)
if glyphID in glyphs:
duplicated_glyphIDs.append(glyphID)
else:
glyphs.append(glyphID)
if len(duplicated_glyphIDs) == 0:
yield PASS, "Font contains unique glyph names."
else:
yield FAIL, ("The following glyph names"
" occur twice: {}").format(duplicated_glyphIDs) | [
"def",
"com_google_fonts_check_unique_glyphnames",
"(",
"ttFont",
")",
":",
"if",
"ttFont",
".",
"sfntVersion",
"==",
"b'\\x00\\x01\\x00\\x00'",
"and",
"ttFont",
".",
"get",
"(",
"\"post\"",
")",
"and",
"ttFont",
"[",
"\"post\"",
"]",
".",
"formatType",
"==",
"3.0",
":",
"yield",
"SKIP",
",",
"(",
"\"TrueType fonts with a format 3.0 post table contain no\"",
"\" glyph names.\"",
")",
"else",
":",
"import",
"re",
"glyphs",
"=",
"[",
"]",
"duplicated_glyphIDs",
"=",
"[",
"]",
"for",
"_",
",",
"g",
"in",
"enumerate",
"(",
"ttFont",
".",
"getGlyphOrder",
"(",
")",
")",
":",
"glyphID",
"=",
"re",
".",
"sub",
"(",
"r'#\\w+'",
",",
"''",
",",
"g",
")",
"if",
"glyphID",
"in",
"glyphs",
":",
"duplicated_glyphIDs",
".",
"append",
"(",
"glyphID",
")",
"else",
":",
"glyphs",
".",
"append",
"(",
"glyphID",
")",
"if",
"len",
"(",
"duplicated_glyphIDs",
")",
"==",
"0",
":",
"yield",
"PASS",
",",
"\"Font contains unique glyph names.\"",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"The following glyph names\"",
"\" occur twice: {}\"",
")",
".",
"format",
"(",
"duplicated_glyphIDs",
")"
] | Font contains unique glyph names? | [
"Font",
"contains",
"unique",
"glyph",
"names?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L822-L843 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_glyphnames_max_length | def com_google_fonts_check_glyphnames_max_length(ttFont):
"""Check that glyph names do not exceed max length."""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield PASS, ("TrueType fonts with a format 3.0 post table contain no "
"glyph names.")
else:
failed = False
for name in ttFont.getGlyphOrder():
if len(name) > 109:
failed = True
yield FAIL, ("Glyph name is too long:" " '{}'").format(name)
if not failed:
yield PASS, "No glyph names exceed max allowed length." | python | def com_google_fonts_check_glyphnames_max_length(ttFont):
"""Check that glyph names do not exceed max length."""
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield PASS, ("TrueType fonts with a format 3.0 post table contain no "
"glyph names.")
else:
failed = False
for name in ttFont.getGlyphOrder():
if len(name) > 109:
failed = True
yield FAIL, ("Glyph name is too long:" " '{}'").format(name)
if not failed:
yield PASS, "No glyph names exceed max allowed length." | [
"def",
"com_google_fonts_check_glyphnames_max_length",
"(",
"ttFont",
")",
":",
"if",
"ttFont",
".",
"sfntVersion",
"==",
"b'\\x00\\x01\\x00\\x00'",
"and",
"ttFont",
".",
"get",
"(",
"\"post\"",
")",
"and",
"ttFont",
"[",
"\"post\"",
"]",
".",
"formatType",
"==",
"3.0",
":",
"yield",
"PASS",
",",
"(",
"\"TrueType fonts with a format 3.0 post table contain no \"",
"\"glyph names.\"",
")",
"else",
":",
"failed",
"=",
"False",
"for",
"name",
"in",
"ttFont",
".",
"getGlyphOrder",
"(",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"109",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Glyph name is too long:\"",
"\" '{}'\"",
")",
".",
"format",
"(",
"name",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"No glyph names exceed max allowed length.\""
] | Check that glyph names do not exceed max length. | [
"Check",
"that",
"glyph",
"names",
"do",
"not",
"exceed",
"max",
"length",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L857-L870 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_ttx_roundtrip | def com_google_fonts_check_ttx_roundtrip(font):
"""Checking with fontTools.ttx"""
from fontTools import ttx
import sys
ttFont = ttx.TTFont(font)
failed = False
class TTXLogger:
msgs = []
def __init__(self):
self.original_stderr = sys.stderr
self.original_stdout = sys.stdout
sys.stderr = self
sys.stdout = self
def write(self, data):
if data not in self.msgs:
self.msgs.append(data)
def restore(self):
sys.stderr = self.original_stderr
sys.stdout = self.original_stdout
from xml.parsers.expat import ExpatError
try:
logger = TTXLogger()
xml_file = font + ".xml"
ttFont.saveXML(xml_file)
export_error_msgs = logger.msgs
if len(export_error_msgs):
failed = True
yield INFO, ("While converting TTF into an XML file,"
" ttx emited the messages listed below.")
for msg in export_error_msgs:
yield FAIL, msg.strip()
f = ttx.TTFont()
f.importXML(font + ".xml")
import_error_msgs = [msg for msg in logger.msgs if msg not in export_error_msgs]
if len(import_error_msgs):
failed = True
yield INFO, ("While importing an XML file and converting"
" it back to TTF, ttx emited the messages"
" listed below.")
for msg in import_error_msgs:
yield FAIL, msg.strip()
logger.restore()
except ExpatError as e:
failed = True
yield FAIL, ("TTX had some problem parsing the generated XML file."
" This most likely mean there's some problem in the font."
" Please inspect the output of ttx in order to find more"
" on what went wrong. A common problem is the presence of"
" control characteres outside the accepted character range"
" as defined in the XML spec. FontTools has got a bug which"
" causes TTX to generate corrupt XML files in those cases."
" So, check the entries of the name table and remove any"
" control chars that you find there."
" The full ttx error message was:\n"
"======\n{}\n======".format(e))
if not failed:
yield PASS, "Hey! It all looks good!"
# and then we need to cleanup our mess...
if os.path.exists(xml_file):
os.remove(xml_file) | python | def com_google_fonts_check_ttx_roundtrip(font):
"""Checking with fontTools.ttx"""
from fontTools import ttx
import sys
ttFont = ttx.TTFont(font)
failed = False
class TTXLogger:
msgs = []
def __init__(self):
self.original_stderr = sys.stderr
self.original_stdout = sys.stdout
sys.stderr = self
sys.stdout = self
def write(self, data):
if data not in self.msgs:
self.msgs.append(data)
def restore(self):
sys.stderr = self.original_stderr
sys.stdout = self.original_stdout
from xml.parsers.expat import ExpatError
try:
logger = TTXLogger()
xml_file = font + ".xml"
ttFont.saveXML(xml_file)
export_error_msgs = logger.msgs
if len(export_error_msgs):
failed = True
yield INFO, ("While converting TTF into an XML file,"
" ttx emited the messages listed below.")
for msg in export_error_msgs:
yield FAIL, msg.strip()
f = ttx.TTFont()
f.importXML(font + ".xml")
import_error_msgs = [msg for msg in logger.msgs if msg not in export_error_msgs]
if len(import_error_msgs):
failed = True
yield INFO, ("While importing an XML file and converting"
" it back to TTF, ttx emited the messages"
" listed below.")
for msg in import_error_msgs:
yield FAIL, msg.strip()
logger.restore()
except ExpatError as e:
failed = True
yield FAIL, ("TTX had some problem parsing the generated XML file."
" This most likely mean there's some problem in the font."
" Please inspect the output of ttx in order to find more"
" on what went wrong. A common problem is the presence of"
" control characteres outside the accepted character range"
" as defined in the XML spec. FontTools has got a bug which"
" causes TTX to generate corrupt XML files in those cases."
" So, check the entries of the name table and remove any"
" control chars that you find there."
" The full ttx error message was:\n"
"======\n{}\n======".format(e))
if not failed:
yield PASS, "Hey! It all looks good!"
# and then we need to cleanup our mess...
if os.path.exists(xml_file):
os.remove(xml_file) | [
"def",
"com_google_fonts_check_ttx_roundtrip",
"(",
"font",
")",
":",
"from",
"fontTools",
"import",
"ttx",
"import",
"sys",
"ttFont",
"=",
"ttx",
".",
"TTFont",
"(",
"font",
")",
"failed",
"=",
"False",
"class",
"TTXLogger",
":",
"msgs",
"=",
"[",
"]",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"original_stderr",
"=",
"sys",
".",
"stderr",
"self",
".",
"original_stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stderr",
"=",
"self",
"sys",
".",
"stdout",
"=",
"self",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"not",
"in",
"self",
".",
"msgs",
":",
"self",
".",
"msgs",
".",
"append",
"(",
"data",
")",
"def",
"restore",
"(",
"self",
")",
":",
"sys",
".",
"stderr",
"=",
"self",
".",
"original_stderr",
"sys",
".",
"stdout",
"=",
"self",
".",
"original_stdout",
"from",
"xml",
".",
"parsers",
".",
"expat",
"import",
"ExpatError",
"try",
":",
"logger",
"=",
"TTXLogger",
"(",
")",
"xml_file",
"=",
"font",
"+",
"\".xml\"",
"ttFont",
".",
"saveXML",
"(",
"xml_file",
")",
"export_error_msgs",
"=",
"logger",
".",
"msgs",
"if",
"len",
"(",
"export_error_msgs",
")",
":",
"failed",
"=",
"True",
"yield",
"INFO",
",",
"(",
"\"While converting TTF into an XML file,\"",
"\" ttx emited the messages listed below.\"",
")",
"for",
"msg",
"in",
"export_error_msgs",
":",
"yield",
"FAIL",
",",
"msg",
".",
"strip",
"(",
")",
"f",
"=",
"ttx",
".",
"TTFont",
"(",
")",
"f",
".",
"importXML",
"(",
"font",
"+",
"\".xml\"",
")",
"import_error_msgs",
"=",
"[",
"msg",
"for",
"msg",
"in",
"logger",
".",
"msgs",
"if",
"msg",
"not",
"in",
"export_error_msgs",
"]",
"if",
"len",
"(",
"import_error_msgs",
")",
":",
"failed",
"=",
"True",
"yield",
"INFO",
",",
"(",
"\"While importing an XML file and converting\"",
"\" it back to TTF, ttx emited the messages\"",
"\" listed below.\"",
")",
"for",
"msg",
"in",
"import_error_msgs",
":",
"yield",
"FAIL",
",",
"msg",
".",
"strip",
"(",
")",
"logger",
".",
"restore",
"(",
")",
"except",
"ExpatError",
"as",
"e",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"TTX had some problem parsing the generated XML file.\"",
"\" This most likely mean there's some problem in the font.\"",
"\" Please inspect the output of ttx in order to find more\"",
"\" on what went wrong. A common problem is the presence of\"",
"\" control characteres outside the accepted character range\"",
"\" as defined in the XML spec. FontTools has got a bug which\"",
"\" causes TTX to generate corrupt XML files in those cases.\"",
"\" So, check the entries of the name table and remove any\"",
"\" control chars that you find there.\"",
"\" The full ttx error message was:\\n\"",
"\"======\\n{}\\n======\"",
".",
"format",
"(",
"e",
")",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Hey! It all looks good!\"",
"# and then we need to cleanup our mess...",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"xml_file",
")",
":",
"os",
".",
"remove",
"(",
"xml_file",
")"
] | Checking with fontTools.ttx | [
"Checking",
"with",
"fontTools",
".",
"ttx"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L877-L946 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/universal.py | com_google_fonts_check_family_vertical_metrics | def com_google_fonts_check_family_vertical_metrics(ttFonts):
"""Each font in a family must have the same vertical metrics values."""
failed = []
vmetrics = {
"sTypoAscender": {},
"sTypoDescender": {},
"sTypoLineGap": {},
"usWinAscent": {},
"usWinDescent": {},
"ascent": {},
"descent": {}
}
for ttfont in ttFonts:
full_font_name = ttfont['name'].getName(4, 3, 1, 1033).toUnicode()
vmetrics['sTypoAscender'][full_font_name] = ttfont['OS/2'].sTypoAscender
vmetrics['sTypoDescender'][full_font_name] = ttfont['OS/2'].sTypoDescender
vmetrics['sTypoLineGap'][full_font_name] = ttfont['OS/2'].sTypoLineGap
vmetrics['usWinAscent'][full_font_name] = ttfont['OS/2'].usWinAscent
vmetrics['usWinDescent'][full_font_name] = ttfont['OS/2'].usWinDescent
vmetrics['ascent'][full_font_name] = ttfont['hhea'].ascent
vmetrics['descent'][full_font_name] = ttfont['hhea'].descent
for k, v in vmetrics.items():
metric_vals = set(vmetrics[k].values())
if len(metric_vals) != 1:
failed.append(k)
if failed:
for k in failed:
s = ["{}: {}".format(k, v) for k, v in vmetrics[k].items()]
yield FAIL, ("{} is not the same across the family:\n:"
"{}".format(k, "\n".join(s)))
else:
yield PASS, "Vertical metrics are the same across the family" | python | def com_google_fonts_check_family_vertical_metrics(ttFonts):
"""Each font in a family must have the same vertical metrics values."""
failed = []
vmetrics = {
"sTypoAscender": {},
"sTypoDescender": {},
"sTypoLineGap": {},
"usWinAscent": {},
"usWinDescent": {},
"ascent": {},
"descent": {}
}
for ttfont in ttFonts:
full_font_name = ttfont['name'].getName(4, 3, 1, 1033).toUnicode()
vmetrics['sTypoAscender'][full_font_name] = ttfont['OS/2'].sTypoAscender
vmetrics['sTypoDescender'][full_font_name] = ttfont['OS/2'].sTypoDescender
vmetrics['sTypoLineGap'][full_font_name] = ttfont['OS/2'].sTypoLineGap
vmetrics['usWinAscent'][full_font_name] = ttfont['OS/2'].usWinAscent
vmetrics['usWinDescent'][full_font_name] = ttfont['OS/2'].usWinDescent
vmetrics['ascent'][full_font_name] = ttfont['hhea'].ascent
vmetrics['descent'][full_font_name] = ttfont['hhea'].descent
for k, v in vmetrics.items():
metric_vals = set(vmetrics[k].values())
if len(metric_vals) != 1:
failed.append(k)
if failed:
for k in failed:
s = ["{}: {}".format(k, v) for k, v in vmetrics[k].items()]
yield FAIL, ("{} is not the same across the family:\n:"
"{}".format(k, "\n".join(s)))
else:
yield PASS, "Vertical metrics are the same across the family" | [
"def",
"com_google_fonts_check_family_vertical_metrics",
"(",
"ttFonts",
")",
":",
"failed",
"=",
"[",
"]",
"vmetrics",
"=",
"{",
"\"sTypoAscender\"",
":",
"{",
"}",
",",
"\"sTypoDescender\"",
":",
"{",
"}",
",",
"\"sTypoLineGap\"",
":",
"{",
"}",
",",
"\"usWinAscent\"",
":",
"{",
"}",
",",
"\"usWinDescent\"",
":",
"{",
"}",
",",
"\"ascent\"",
":",
"{",
"}",
",",
"\"descent\"",
":",
"{",
"}",
"}",
"for",
"ttfont",
"in",
"ttFonts",
":",
"full_font_name",
"=",
"ttfont",
"[",
"'name'",
"]",
".",
"getName",
"(",
"4",
",",
"3",
",",
"1",
",",
"1033",
")",
".",
"toUnicode",
"(",
")",
"vmetrics",
"[",
"'sTypoAscender'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'OS/2'",
"]",
".",
"sTypoAscender",
"vmetrics",
"[",
"'sTypoDescender'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'OS/2'",
"]",
".",
"sTypoDescender",
"vmetrics",
"[",
"'sTypoLineGap'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'OS/2'",
"]",
".",
"sTypoLineGap",
"vmetrics",
"[",
"'usWinAscent'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'OS/2'",
"]",
".",
"usWinAscent",
"vmetrics",
"[",
"'usWinDescent'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'OS/2'",
"]",
".",
"usWinDescent",
"vmetrics",
"[",
"'ascent'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'hhea'",
"]",
".",
"ascent",
"vmetrics",
"[",
"'descent'",
"]",
"[",
"full_font_name",
"]",
"=",
"ttfont",
"[",
"'hhea'",
"]",
".",
"descent",
"for",
"k",
",",
"v",
"in",
"vmetrics",
".",
"items",
"(",
")",
":",
"metric_vals",
"=",
"set",
"(",
"vmetrics",
"[",
"k",
"]",
".",
"values",
"(",
")",
")",
"if",
"len",
"(",
"metric_vals",
")",
"!=",
"1",
":",
"failed",
".",
"append",
"(",
"k",
")",
"if",
"failed",
":",
"for",
"k",
"in",
"failed",
":",
"s",
"=",
"[",
"\"{}: {}\"",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"vmetrics",
"[",
"k",
"]",
".",
"items",
"(",
")",
"]",
"yield",
"FAIL",
",",
"(",
"\"{} is not the same across the family:\\n:\"",
"\"{}\"",
".",
"format",
"(",
"k",
",",
"\"\\n\"",
".",
"join",
"(",
"s",
")",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Vertical metrics are the same across the family\""
] | Each font in a family must have the same vertical metrics values. | [
"Each",
"font",
"in",
"a",
"family",
"must",
"have",
"the",
"same",
"vertical",
"metrics",
"values",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L956-L990 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/hhea.py | com_google_fonts_check_linegaps | def com_google_fonts_check_linegaps(ttFont):
"""Checking Vertical Metric Linegaps."""
if ttFont["hhea"].lineGap != 0:
yield WARN, Message("hhea", "hhea lineGap is not equal to 0.")
elif ttFont["OS/2"].sTypoLineGap != 0:
yield WARN, Message("OS/2", "OS/2 sTypoLineGap is not equal to 0.")
else:
yield PASS, "OS/2 sTypoLineGap and hhea lineGap are both 0." | python | def com_google_fonts_check_linegaps(ttFont):
"""Checking Vertical Metric Linegaps."""
if ttFont["hhea"].lineGap != 0:
yield WARN, Message("hhea", "hhea lineGap is not equal to 0.")
elif ttFont["OS/2"].sTypoLineGap != 0:
yield WARN, Message("OS/2", "OS/2 sTypoLineGap is not equal to 0.")
else:
yield PASS, "OS/2 sTypoLineGap and hhea lineGap are both 0." | [
"def",
"com_google_fonts_check_linegaps",
"(",
"ttFont",
")",
":",
"if",
"ttFont",
"[",
"\"hhea\"",
"]",
".",
"lineGap",
"!=",
"0",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"hhea\"",
",",
"\"hhea lineGap is not equal to 0.\"",
")",
"elif",
"ttFont",
"[",
"\"OS/2\"",
"]",
".",
"sTypoLineGap",
"!=",
"0",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"OS/2\"",
",",
"\"OS/2 sTypoLineGap is not equal to 0.\"",
")",
"else",
":",
"yield",
"PASS",
",",
"\"OS/2 sTypoLineGap and hhea lineGap are both 0.\""
] | Checking Vertical Metric Linegaps. | [
"Checking",
"Vertical",
"Metric",
"Linegaps",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/hhea.py#L14-L21 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/hhea.py | com_google_fonts_check_maxadvancewidth | def com_google_fonts_check_maxadvancewidth(ttFont):
"""MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?"""
hhea_advance_width_max = ttFont['hhea'].advanceWidthMax
hmtx_advance_width_max = None
for g in ttFont['hmtx'].metrics.values():
if hmtx_advance_width_max is None:
hmtx_advance_width_max = max(0, g[0])
else:
hmtx_advance_width_max = max(g[0], hmtx_advance_width_max)
if hmtx_advance_width_max != hhea_advance_width_max:
yield FAIL, ("AdvanceWidthMax mismatch: expected {} (from hmtx);"
" got {} (from hhea)").format(hmtx_advance_width_max,
hhea_advance_width_max)
else:
yield PASS, ("MaxAdvanceWidth is consistent"
" with values in the Hmtx and Hhea tables.") | python | def com_google_fonts_check_maxadvancewidth(ttFont):
"""MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?"""
hhea_advance_width_max = ttFont['hhea'].advanceWidthMax
hmtx_advance_width_max = None
for g in ttFont['hmtx'].metrics.values():
if hmtx_advance_width_max is None:
hmtx_advance_width_max = max(0, g[0])
else:
hmtx_advance_width_max = max(g[0], hmtx_advance_width_max)
if hmtx_advance_width_max != hhea_advance_width_max:
yield FAIL, ("AdvanceWidthMax mismatch: expected {} (from hmtx);"
" got {} (from hhea)").format(hmtx_advance_width_max,
hhea_advance_width_max)
else:
yield PASS, ("MaxAdvanceWidth is consistent"
" with values in the Hmtx and Hhea tables.") | [
"def",
"com_google_fonts_check_maxadvancewidth",
"(",
"ttFont",
")",
":",
"hhea_advance_width_max",
"=",
"ttFont",
"[",
"'hhea'",
"]",
".",
"advanceWidthMax",
"hmtx_advance_width_max",
"=",
"None",
"for",
"g",
"in",
"ttFont",
"[",
"'hmtx'",
"]",
".",
"metrics",
".",
"values",
"(",
")",
":",
"if",
"hmtx_advance_width_max",
"is",
"None",
":",
"hmtx_advance_width_max",
"=",
"max",
"(",
"0",
",",
"g",
"[",
"0",
"]",
")",
"else",
":",
"hmtx_advance_width_max",
"=",
"max",
"(",
"g",
"[",
"0",
"]",
",",
"hmtx_advance_width_max",
")",
"if",
"hmtx_advance_width_max",
"!=",
"hhea_advance_width_max",
":",
"yield",
"FAIL",
",",
"(",
"\"AdvanceWidthMax mismatch: expected {} (from hmtx);\"",
"\" got {} (from hhea)\"",
")",
".",
"format",
"(",
"hmtx_advance_width_max",
",",
"hhea_advance_width_max",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"MaxAdvanceWidth is consistent\"",
"\" with values in the Hmtx and Hhea tables.\"",
")"
] | MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables? | [
"MaxAdvanceWidth",
"is",
"consistent",
"with",
"values",
"in",
"the",
"Hmtx",
"and",
"Hhea",
"tables?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/hhea.py#L27-L43 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/hhea.py | com_google_fonts_check_monospace_max_advancewidth | def com_google_fonts_check_monospace_max_advancewidth(ttFont, glyph_metrics_stats):
"""Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth?"""
from fontbakery.utils import pretty_print_list
seems_monospaced = glyph_metrics_stats["seems_monospaced"]
if not seems_monospaced:
yield SKIP, ("Font is not monospaced.")
return
# hhea:advanceWidthMax is treated as source of truth here.
max_advw = ttFont['hhea'].advanceWidthMax
outliers = []
zero_or_double_width_outliers = []
glyphSet = ttFont.getGlyphSet().keys() # TODO: remove .keys() when fonttools is updated to 3.27
glyphs = [
g for g in glyphSet if g not in ['.notdef', '.null', 'NULL']
]
for glyph_id in glyphs:
width = ttFont['hmtx'].metrics[glyph_id][0]
if width != max_advw:
outliers.append(glyph_id)
if width == 0 or width == 2 * max_advw:
zero_or_double_width_outliers.append(glyph_id)
if outliers:
outliers_percentage = float(len(outliers)) / len(glyphSet)
yield WARN, Message("should-be-monospaced",
"This seems to be a monospaced font,"
" so advanceWidth value should be the same"
" across all glyphs, but {}% of them"
" have a different value: {}"
"".format(round(100 * outliers_percentage, 2),
pretty_print_list(outliers)))
if zero_or_double_width_outliers:
yield WARN, Message("variable-monospaced",
"Double-width and/or zero-width glyphs"
" were detected. These glyphs should be set"
" to the same width as all others"
" and then add GPOS single pos lookups"
" that zeros/doubles the widths as needed:"
" {}".format(pretty_print_list(
zero_or_double_width_outliers)))
else:
yield PASS, ("hhea.advanceWidthMax is equal"
" to all glyphs' advanceWidth in this monospaced font.") | python | def com_google_fonts_check_monospace_max_advancewidth(ttFont, glyph_metrics_stats):
"""Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth?"""
from fontbakery.utils import pretty_print_list
seems_monospaced = glyph_metrics_stats["seems_monospaced"]
if not seems_monospaced:
yield SKIP, ("Font is not monospaced.")
return
# hhea:advanceWidthMax is treated as source of truth here.
max_advw = ttFont['hhea'].advanceWidthMax
outliers = []
zero_or_double_width_outliers = []
glyphSet = ttFont.getGlyphSet().keys() # TODO: remove .keys() when fonttools is updated to 3.27
glyphs = [
g for g in glyphSet if g not in ['.notdef', '.null', 'NULL']
]
for glyph_id in glyphs:
width = ttFont['hmtx'].metrics[glyph_id][0]
if width != max_advw:
outliers.append(glyph_id)
if width == 0 or width == 2 * max_advw:
zero_or_double_width_outliers.append(glyph_id)
if outliers:
outliers_percentage = float(len(outliers)) / len(glyphSet)
yield WARN, Message("should-be-monospaced",
"This seems to be a monospaced font,"
" so advanceWidth value should be the same"
" across all glyphs, but {}% of them"
" have a different value: {}"
"".format(round(100 * outliers_percentage, 2),
pretty_print_list(outliers)))
if zero_or_double_width_outliers:
yield WARN, Message("variable-monospaced",
"Double-width and/or zero-width glyphs"
" were detected. These glyphs should be set"
" to the same width as all others"
" and then add GPOS single pos lookups"
" that zeros/doubles the widths as needed:"
" {}".format(pretty_print_list(
zero_or_double_width_outliers)))
else:
yield PASS, ("hhea.advanceWidthMax is equal"
" to all glyphs' advanceWidth in this monospaced font.") | [
"def",
"com_google_fonts_check_monospace_max_advancewidth",
"(",
"ttFont",
",",
"glyph_metrics_stats",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"pretty_print_list",
"seems_monospaced",
"=",
"glyph_metrics_stats",
"[",
"\"seems_monospaced\"",
"]",
"if",
"not",
"seems_monospaced",
":",
"yield",
"SKIP",
",",
"(",
"\"Font is not monospaced.\"",
")",
"return",
"# hhea:advanceWidthMax is treated as source of truth here.",
"max_advw",
"=",
"ttFont",
"[",
"'hhea'",
"]",
".",
"advanceWidthMax",
"outliers",
"=",
"[",
"]",
"zero_or_double_width_outliers",
"=",
"[",
"]",
"glyphSet",
"=",
"ttFont",
".",
"getGlyphSet",
"(",
")",
".",
"keys",
"(",
")",
"# TODO: remove .keys() when fonttools is updated to 3.27",
"glyphs",
"=",
"[",
"g",
"for",
"g",
"in",
"glyphSet",
"if",
"g",
"not",
"in",
"[",
"'.notdef'",
",",
"'.null'",
",",
"'NULL'",
"]",
"]",
"for",
"glyph_id",
"in",
"glyphs",
":",
"width",
"=",
"ttFont",
"[",
"'hmtx'",
"]",
".",
"metrics",
"[",
"glyph_id",
"]",
"[",
"0",
"]",
"if",
"width",
"!=",
"max_advw",
":",
"outliers",
".",
"append",
"(",
"glyph_id",
")",
"if",
"width",
"==",
"0",
"or",
"width",
"==",
"2",
"*",
"max_advw",
":",
"zero_or_double_width_outliers",
".",
"append",
"(",
"glyph_id",
")",
"if",
"outliers",
":",
"outliers_percentage",
"=",
"float",
"(",
"len",
"(",
"outliers",
")",
")",
"/",
"len",
"(",
"glyphSet",
")",
"yield",
"WARN",
",",
"Message",
"(",
"\"should-be-monospaced\"",
",",
"\"This seems to be a monospaced font,\"",
"\" so advanceWidth value should be the same\"",
"\" across all glyphs, but {}% of them\"",
"\" have a different value: {}\"",
"\"\"",
".",
"format",
"(",
"round",
"(",
"100",
"*",
"outliers_percentage",
",",
"2",
")",
",",
"pretty_print_list",
"(",
"outliers",
")",
")",
")",
"if",
"zero_or_double_width_outliers",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"variable-monospaced\"",
",",
"\"Double-width and/or zero-width glyphs\"",
"\" were detected. These glyphs should be set\"",
"\" to the same width as all others\"",
"\" and then add GPOS single pos lookups\"",
"\" that zeros/doubles the widths as needed:\"",
"\" {}\"",
".",
"format",
"(",
"pretty_print_list",
"(",
"zero_or_double_width_outliers",
")",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"hhea.advanceWidthMax is equal\"",
"\" to all glyphs' advanceWidth in this monospaced font.\"",
")"
] | Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth? | [
"Monospace",
"font",
"has",
"hhea",
".",
"advanceWidthMax",
"equal",
"to",
"each",
"glyph",
"s",
"advanceWidth?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/hhea.py#L50-L95 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/shared_conditions.py | glyph_metrics_stats | def glyph_metrics_stats(ttFont):
"""Returns a dict containing whether the font seems_monospaced,
what's the maximum glyph width and what's the most common width.
For a font to be considered monospaced, at least 80% of
the ascii glyphs must have the same width."""
glyph_metrics = ttFont['hmtx'].metrics
ascii_glyph_names = [ttFont.getBestCmap()[c] for c in range(32, 128)
if c in ttFont.getBestCmap()]
ascii_widths = [adv for name, (adv, lsb) in glyph_metrics.items()
if name in ascii_glyph_names]
ascii_width_count = Counter(ascii_widths)
ascii_most_common_width = ascii_width_count.most_common(1)[0][1]
seems_monospaced = ascii_most_common_width >= len(ascii_widths) * 0.8
width_max = max([adv for k, (adv, lsb) in glyph_metrics.items()])
most_common_width = Counter(glyph_metrics.values()).most_common(1)[0][0][0]
return {
"seems_monospaced": seems_monospaced,
"width_max": width_max,
"most_common_width": most_common_width,
} | python | def glyph_metrics_stats(ttFont):
"""Returns a dict containing whether the font seems_monospaced,
what's the maximum glyph width and what's the most common width.
For a font to be considered monospaced, at least 80% of
the ascii glyphs must have the same width."""
glyph_metrics = ttFont['hmtx'].metrics
ascii_glyph_names = [ttFont.getBestCmap()[c] for c in range(32, 128)
if c in ttFont.getBestCmap()]
ascii_widths = [adv for name, (adv, lsb) in glyph_metrics.items()
if name in ascii_glyph_names]
ascii_width_count = Counter(ascii_widths)
ascii_most_common_width = ascii_width_count.most_common(1)[0][1]
seems_monospaced = ascii_most_common_width >= len(ascii_widths) * 0.8
width_max = max([adv for k, (adv, lsb) in glyph_metrics.items()])
most_common_width = Counter(glyph_metrics.values()).most_common(1)[0][0][0]
return {
"seems_monospaced": seems_monospaced,
"width_max": width_max,
"most_common_width": most_common_width,
} | [
"def",
"glyph_metrics_stats",
"(",
"ttFont",
")",
":",
"glyph_metrics",
"=",
"ttFont",
"[",
"'hmtx'",
"]",
".",
"metrics",
"ascii_glyph_names",
"=",
"[",
"ttFont",
".",
"getBestCmap",
"(",
")",
"[",
"c",
"]",
"for",
"c",
"in",
"range",
"(",
"32",
",",
"128",
")",
"if",
"c",
"in",
"ttFont",
".",
"getBestCmap",
"(",
")",
"]",
"ascii_widths",
"=",
"[",
"adv",
"for",
"name",
",",
"(",
"adv",
",",
"lsb",
")",
"in",
"glyph_metrics",
".",
"items",
"(",
")",
"if",
"name",
"in",
"ascii_glyph_names",
"]",
"ascii_width_count",
"=",
"Counter",
"(",
"ascii_widths",
")",
"ascii_most_common_width",
"=",
"ascii_width_count",
".",
"most_common",
"(",
"1",
")",
"[",
"0",
"]",
"[",
"1",
"]",
"seems_monospaced",
"=",
"ascii_most_common_width",
">=",
"len",
"(",
"ascii_widths",
")",
"*",
"0.8",
"width_max",
"=",
"max",
"(",
"[",
"adv",
"for",
"k",
",",
"(",
"adv",
",",
"lsb",
")",
"in",
"glyph_metrics",
".",
"items",
"(",
")",
"]",
")",
"most_common_width",
"=",
"Counter",
"(",
"glyph_metrics",
".",
"values",
"(",
")",
")",
".",
"most_common",
"(",
"1",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"return",
"{",
"\"seems_monospaced\"",
":",
"seems_monospaced",
",",
"\"width_max\"",
":",
"width_max",
",",
"\"most_common_width\"",
":",
"most_common_width",
",",
"}"
] | Returns a dict containing whether the font seems_monospaced,
what's the maximum glyph width and what's the most common width.
For a font to be considered monospaced, at least 80% of
the ascii glyphs must have the same width. | [
"Returns",
"a",
"dict",
"containing",
"whether",
"the",
"font",
"seems_monospaced",
"what",
"s",
"the",
"maximum",
"glyph",
"width",
"and",
"what",
"s",
"the",
"most",
"common",
"width",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/shared_conditions.py#L77-L98 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/shared_conditions.py | vtt_talk_sources | def vtt_talk_sources(ttFont) -> List[str]:
"""Return the tags of VTT source tables found in a font."""
VTT_SOURCE_TABLES = {'TSI0', 'TSI1', 'TSI2', 'TSI3', 'TSI5'}
tables_found = [tag for tag in ttFont.keys() if tag in VTT_SOURCE_TABLES]
return tables_found | python | def vtt_talk_sources(ttFont) -> List[str]:
"""Return the tags of VTT source tables found in a font."""
VTT_SOURCE_TABLES = {'TSI0', 'TSI1', 'TSI2', 'TSI3', 'TSI5'}
tables_found = [tag for tag in ttFont.keys() if tag in VTT_SOURCE_TABLES]
return tables_found | [
"def",
"vtt_talk_sources",
"(",
"ttFont",
")",
"->",
"List",
"[",
"str",
"]",
":",
"VTT_SOURCE_TABLES",
"=",
"{",
"'TSI0'",
",",
"'TSI1'",
",",
"'TSI2'",
",",
"'TSI3'",
",",
"'TSI5'",
"}",
"tables_found",
"=",
"[",
"tag",
"for",
"tag",
"in",
"ttFont",
".",
"keys",
"(",
")",
"if",
"tag",
"in",
"VTT_SOURCE_TABLES",
"]",
"return",
"tables_found"
] | Return the tags of VTT source tables found in a font. | [
"Return",
"the",
"tags",
"of",
"VTT",
"source",
"tables",
"found",
"in",
"a",
"font",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/shared_conditions.py#L180-L184 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/terminal.py | ThrottledOut.write | def write(self, data):
"""only put to stdout every now and then"""
self._buffer.append(data)
self._current_ticks += 1
# first entry ever will be flushed immediately
flush=False
if self._last_flush_time is None or \
(self._holdback_time is None and self._max_ticks == 0):
flush = True
elif self._max_ticks and self._current_ticks >= self._max_ticks or \
self._holdback_time and time() - self._holdback_time >= self._last_flush_time:
flush=True
if flush:
self.flush() | python | def write(self, data):
"""only put to stdout every now and then"""
self._buffer.append(data)
self._current_ticks += 1
# first entry ever will be flushed immediately
flush=False
if self._last_flush_time is None or \
(self._holdback_time is None and self._max_ticks == 0):
flush = True
elif self._max_ticks and self._current_ticks >= self._max_ticks or \
self._holdback_time and time() - self._holdback_time >= self._last_flush_time:
flush=True
if flush:
self.flush() | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_buffer",
".",
"append",
"(",
"data",
")",
"self",
".",
"_current_ticks",
"+=",
"1",
"# first entry ever will be flushed immediately",
"flush",
"=",
"False",
"if",
"self",
".",
"_last_flush_time",
"is",
"None",
"or",
"(",
"self",
".",
"_holdback_time",
"is",
"None",
"and",
"self",
".",
"_max_ticks",
"==",
"0",
")",
":",
"flush",
"=",
"True",
"elif",
"self",
".",
"_max_ticks",
"and",
"self",
".",
"_current_ticks",
">=",
"self",
".",
"_max_ticks",
"or",
"self",
".",
"_holdback_time",
"and",
"time",
"(",
")",
"-",
"self",
".",
"_holdback_time",
">=",
"self",
".",
"_last_flush_time",
":",
"flush",
"=",
"True",
"if",
"flush",
":",
"self",
".",
"flush",
"(",
")"
] | only put to stdout every now and then | [
"only",
"put",
"to",
"stdout",
"every",
"now",
"and",
"then"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/terminal.py#L139-L154 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/terminal.py | ThrottledOut.flush | def flush(self, draw_progress=True):
"""call this at the very end, so that we can output the rest"""
reset_progressbar = None
if self._draw_progressbar and draw_progress:
progressbar, reset_progressbar = self._draw_progressbar()
self._buffer.append(progressbar)
for line in self._buffer:
self._outFile.write(line)
#self._outFile.flush() needed?
self._buffer = []
if reset_progressbar:
# first thing on next flush is to reset the current progressbar
self._buffer.append(reset_progressbar)
self._current_ticks = 0
self._last_flush_time = time() | python | def flush(self, draw_progress=True):
"""call this at the very end, so that we can output the rest"""
reset_progressbar = None
if self._draw_progressbar and draw_progress:
progressbar, reset_progressbar = self._draw_progressbar()
self._buffer.append(progressbar)
for line in self._buffer:
self._outFile.write(line)
#self._outFile.flush() needed?
self._buffer = []
if reset_progressbar:
# first thing on next flush is to reset the current progressbar
self._buffer.append(reset_progressbar)
self._current_ticks = 0
self._last_flush_time = time() | [
"def",
"flush",
"(",
"self",
",",
"draw_progress",
"=",
"True",
")",
":",
"reset_progressbar",
"=",
"None",
"if",
"self",
".",
"_draw_progressbar",
"and",
"draw_progress",
":",
"progressbar",
",",
"reset_progressbar",
"=",
"self",
".",
"_draw_progressbar",
"(",
")",
"self",
".",
"_buffer",
".",
"append",
"(",
"progressbar",
")",
"for",
"line",
"in",
"self",
".",
"_buffer",
":",
"self",
".",
"_outFile",
".",
"write",
"(",
"line",
")",
"#self._outFile.flush() needed?",
"self",
".",
"_buffer",
"=",
"[",
"]",
"if",
"reset_progressbar",
":",
"# first thing on next flush is to reset the current progressbar",
"self",
".",
"_buffer",
".",
"append",
"(",
"reset_progressbar",
")",
"self",
".",
"_current_ticks",
"=",
"0",
"self",
".",
"_last_flush_time",
"=",
"time",
"(",
")"
] | call this at the very end, so that we can output the rest | [
"call",
"this",
"at",
"the",
"very",
"end",
"so",
"that",
"we",
"can",
"output",
"the",
"rest"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/terminal.py#L156-L171 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/terminal.py | TerminalProgress._draw_progressbar | def _draw_progressbar(self, columns=None, len_prefix=0, right_margin=0):
"""
if columns is None, don't insert any extra line breaks
"""
if self._order == None:
total = len(self._results)
else:
total = max(len(self._order), len(self._results))
percent = int(round(len(self._results)/total*100)) if total else 0
needs_break = lambda count: columns and count > columns \
and (count % (columns - right_margin))
# together with unicode_literals `str('status')` seems the best
# py2 and py3 compatible solution
status = type(str('status'), (object,), dict(count=0,progressbar=[]))
def _append(status, item, length=1, separator=''):
# * assuming a standard item will take one column in the tty
# * length must not be bigger than columns (=very narrow columns)
progressbar = status.progressbar
if needs_break(status.count + length + len(separator)):
progressbar.append('\n')
status.count = 0
else:
progressbar.append(separator)
status.count += length + len(separator)
progressbar.append(item)
append=partial(_append, status)
progressbar = status.progressbar
append('', len_prefix)
append('[')
for item in self._progressbar:
append(item)
append(']')
percentstring = f'{percent:3d}%'
append(percentstring, len(percentstring), ' ')
return ''.join(progressbar) | python | def _draw_progressbar(self, columns=None, len_prefix=0, right_margin=0):
"""
if columns is None, don't insert any extra line breaks
"""
if self._order == None:
total = len(self._results)
else:
total = max(len(self._order), len(self._results))
percent = int(round(len(self._results)/total*100)) if total else 0
needs_break = lambda count: columns and count > columns \
and (count % (columns - right_margin))
# together with unicode_literals `str('status')` seems the best
# py2 and py3 compatible solution
status = type(str('status'), (object,), dict(count=0,progressbar=[]))
def _append(status, item, length=1, separator=''):
# * assuming a standard item will take one column in the tty
# * length must not be bigger than columns (=very narrow columns)
progressbar = status.progressbar
if needs_break(status.count + length + len(separator)):
progressbar.append('\n')
status.count = 0
else:
progressbar.append(separator)
status.count += length + len(separator)
progressbar.append(item)
append=partial(_append, status)
progressbar = status.progressbar
append('', len_prefix)
append('[')
for item in self._progressbar:
append(item)
append(']')
percentstring = f'{percent:3d}%'
append(percentstring, len(percentstring), ' ')
return ''.join(progressbar) | [
"def",
"_draw_progressbar",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"len_prefix",
"=",
"0",
",",
"right_margin",
"=",
"0",
")",
":",
"if",
"self",
".",
"_order",
"==",
"None",
":",
"total",
"=",
"len",
"(",
"self",
".",
"_results",
")",
"else",
":",
"total",
"=",
"max",
"(",
"len",
"(",
"self",
".",
"_order",
")",
",",
"len",
"(",
"self",
".",
"_results",
")",
")",
"percent",
"=",
"int",
"(",
"round",
"(",
"len",
"(",
"self",
".",
"_results",
")",
"/",
"total",
"*",
"100",
")",
")",
"if",
"total",
"else",
"0",
"needs_break",
"=",
"lambda",
"count",
":",
"columns",
"and",
"count",
">",
"columns",
"and",
"(",
"count",
"%",
"(",
"columns",
"-",
"right_margin",
")",
")",
"# together with unicode_literals `str('status')` seems the best",
"# py2 and py3 compatible solution",
"status",
"=",
"type",
"(",
"str",
"(",
"'status'",
")",
",",
"(",
"object",
",",
")",
",",
"dict",
"(",
"count",
"=",
"0",
",",
"progressbar",
"=",
"[",
"]",
")",
")",
"def",
"_append",
"(",
"status",
",",
"item",
",",
"length",
"=",
"1",
",",
"separator",
"=",
"''",
")",
":",
"# * assuming a standard item will take one column in the tty",
"# * length must not be bigger than columns (=very narrow columns)",
"progressbar",
"=",
"status",
".",
"progressbar",
"if",
"needs_break",
"(",
"status",
".",
"count",
"+",
"length",
"+",
"len",
"(",
"separator",
")",
")",
":",
"progressbar",
".",
"append",
"(",
"'\\n'",
")",
"status",
".",
"count",
"=",
"0",
"else",
":",
"progressbar",
".",
"append",
"(",
"separator",
")",
"status",
".",
"count",
"+=",
"length",
"+",
"len",
"(",
"separator",
")",
"progressbar",
".",
"append",
"(",
"item",
")",
"append",
"=",
"partial",
"(",
"_append",
",",
"status",
")",
"progressbar",
"=",
"status",
".",
"progressbar",
"append",
"(",
"''",
",",
"len_prefix",
")",
"append",
"(",
"'['",
")",
"for",
"item",
"in",
"self",
".",
"_progressbar",
":",
"append",
"(",
"item",
")",
"append",
"(",
"']'",
")",
"percentstring",
"=",
"f'{percent:3d}%'",
"append",
"(",
"percentstring",
",",
"len",
"(",
"percentstring",
")",
",",
"' '",
")",
"return",
"''",
".",
"join",
"(",
"progressbar",
")"
] | if columns is None, don't insert any extra line breaks | [
"if",
"columns",
"is",
"None",
"don",
"t",
"insert",
"any",
"extra",
"line",
"breaks"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/terminal.py#L281-L319 | train |
googlefonts/fontbakery | snippets/fontbakery-check-upstream.py | download_file | def download_file(url, dst_path):
"""Download a file from a url"""
request = requests.get(url, stream=True)
with open(dst_path, 'wb') as downloaded_file:
request.raw.decode_content = True
shutil.copyfileobj(request.raw, downloaded_file) | python | def download_file(url, dst_path):
"""Download a file from a url"""
request = requests.get(url, stream=True)
with open(dst_path, 'wb') as downloaded_file:
request.raw.decode_content = True
shutil.copyfileobj(request.raw, downloaded_file) | [
"def",
"download_file",
"(",
"url",
",",
"dst_path",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"dst_path",
",",
"'wb'",
")",
"as",
"downloaded_file",
":",
"request",
".",
"raw",
".",
"decode_content",
"=",
"True",
"shutil",
".",
"copyfileobj",
"(",
"request",
".",
"raw",
",",
"downloaded_file",
")"
] | Download a file from a url | [
"Download",
"a",
"file",
"from",
"a",
"url"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/snippets/fontbakery-check-upstream.py#L32-L37 | train |
googlefonts/fontbakery | snippets/fontbakery-check-upstream.py | download_fonts | def download_fonts(gh_url, dst):
"""Download fonts from a github dir"""
font_paths = []
r = requests.get(gh_url)
for item in r.json():
if item['name'].endswith(".ttf"):
f = item['download_url']
dl_path = os.path.join(dst, os.path.basename(f))
download_file(f, dl_path)
font_paths.append(dl_path)
return font_paths | python | def download_fonts(gh_url, dst):
"""Download fonts from a github dir"""
font_paths = []
r = requests.get(gh_url)
for item in r.json():
if item['name'].endswith(".ttf"):
f = item['download_url']
dl_path = os.path.join(dst, os.path.basename(f))
download_file(f, dl_path)
font_paths.append(dl_path)
return font_paths | [
"def",
"download_fonts",
"(",
"gh_url",
",",
"dst",
")",
":",
"font_paths",
"=",
"[",
"]",
"r",
"=",
"requests",
".",
"get",
"(",
"gh_url",
")",
"for",
"item",
"in",
"r",
".",
"json",
"(",
")",
":",
"if",
"item",
"[",
"'name'",
"]",
".",
"endswith",
"(",
"\".ttf\"",
")",
":",
"f",
"=",
"item",
"[",
"'download_url'",
"]",
"dl_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"download_file",
"(",
"f",
",",
"dl_path",
")",
"font_paths",
".",
"append",
"(",
"dl_path",
")",
"return",
"font_paths"
] | Download fonts from a github dir | [
"Download",
"fonts",
"from",
"a",
"github",
"dir"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/snippets/fontbakery-check-upstream.py#L40-L50 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/head.py | com_google_fonts_check_family_equal_font_versions | def com_google_fonts_check_family_equal_font_versions(ttFonts):
"""Make sure all font files have the same version value."""
all_detected_versions = []
fontfile_versions = {}
for ttFont in ttFonts:
v = ttFont['head'].fontRevision
fontfile_versions[ttFont] = v
if v not in all_detected_versions:
all_detected_versions.append(v)
if len(all_detected_versions) != 1:
versions_list = ""
for v in fontfile_versions.keys():
versions_list += "* {}: {}\n".format(v.reader.file.name,
fontfile_versions[v])
yield WARN, ("version info differs among font"
" files of the same font project.\n"
"These were the version values found:\n"
"{}").format(versions_list)
else:
yield PASS, "All font files have the same version." | python | def com_google_fonts_check_family_equal_font_versions(ttFonts):
"""Make sure all font files have the same version value."""
all_detected_versions = []
fontfile_versions = {}
for ttFont in ttFonts:
v = ttFont['head'].fontRevision
fontfile_versions[ttFont] = v
if v not in all_detected_versions:
all_detected_versions.append(v)
if len(all_detected_versions) != 1:
versions_list = ""
for v in fontfile_versions.keys():
versions_list += "* {}: {}\n".format(v.reader.file.name,
fontfile_versions[v])
yield WARN, ("version info differs among font"
" files of the same font project.\n"
"These were the version values found:\n"
"{}").format(versions_list)
else:
yield PASS, "All font files have the same version." | [
"def",
"com_google_fonts_check_family_equal_font_versions",
"(",
"ttFonts",
")",
":",
"all_detected_versions",
"=",
"[",
"]",
"fontfile_versions",
"=",
"{",
"}",
"for",
"ttFont",
"in",
"ttFonts",
":",
"v",
"=",
"ttFont",
"[",
"'head'",
"]",
".",
"fontRevision",
"fontfile_versions",
"[",
"ttFont",
"]",
"=",
"v",
"if",
"v",
"not",
"in",
"all_detected_versions",
":",
"all_detected_versions",
".",
"append",
"(",
"v",
")",
"if",
"len",
"(",
"all_detected_versions",
")",
"!=",
"1",
":",
"versions_list",
"=",
"\"\"",
"for",
"v",
"in",
"fontfile_versions",
".",
"keys",
"(",
")",
":",
"versions_list",
"+=",
"\"* {}: {}\\n\"",
".",
"format",
"(",
"v",
".",
"reader",
".",
"file",
".",
"name",
",",
"fontfile_versions",
"[",
"v",
"]",
")",
"yield",
"WARN",
",",
"(",
"\"version info differs among font\"",
"\" files of the same font project.\\n\"",
"\"These were the version values found:\\n\"",
"\"{}\"",
")",
".",
"format",
"(",
"versions_list",
")",
"else",
":",
"yield",
"PASS",
",",
"\"All font files have the same version.\""
] | Make sure all font files have the same version value. | [
"Make",
"sure",
"all",
"font",
"files",
"have",
"the",
"same",
"version",
"value",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/head.py#L13-L33 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/head.py | com_google_fonts_check_unitsperem | def com_google_fonts_check_unitsperem(ttFont):
"""Checking unitsPerEm value is reasonable."""
upem = ttFont['head'].unitsPerEm
target_upem = [2**i for i in range(4, 15)]
target_upem.append(1000)
target_upem.append(2000)
if upem < 16 or upem > 16384:
yield FAIL, ("The value of unitsPerEm at the head table"
" must be a value between 16 and 16384."
" Got '{}' instead.").format(upem)
elif upem not in target_upem:
yield WARN, ("In order to optimize performance on some"
" legacy renderers, the value of unitsPerEm"
" at the head table should idealy be"
" a power of between 16 to 16384."
" And values of 1000 and 2000 are also"
" common and may be just fine as well."
" But we got upm={} instead.").format(upem)
else:
yield PASS, ("unitsPerEm value ({}) on the 'head' table"
" is reasonable.").format(upem) | python | def com_google_fonts_check_unitsperem(ttFont):
"""Checking unitsPerEm value is reasonable."""
upem = ttFont['head'].unitsPerEm
target_upem = [2**i for i in range(4, 15)]
target_upem.append(1000)
target_upem.append(2000)
if upem < 16 or upem > 16384:
yield FAIL, ("The value of unitsPerEm at the head table"
" must be a value between 16 and 16384."
" Got '{}' instead.").format(upem)
elif upem not in target_upem:
yield WARN, ("In order to optimize performance on some"
" legacy renderers, the value of unitsPerEm"
" at the head table should idealy be"
" a power of between 16 to 16384."
" And values of 1000 and 2000 are also"
" common and may be just fine as well."
" But we got upm={} instead.").format(upem)
else:
yield PASS, ("unitsPerEm value ({}) on the 'head' table"
" is reasonable.").format(upem) | [
"def",
"com_google_fonts_check_unitsperem",
"(",
"ttFont",
")",
":",
"upem",
"=",
"ttFont",
"[",
"'head'",
"]",
".",
"unitsPerEm",
"target_upem",
"=",
"[",
"2",
"**",
"i",
"for",
"i",
"in",
"range",
"(",
"4",
",",
"15",
")",
"]",
"target_upem",
".",
"append",
"(",
"1000",
")",
"target_upem",
".",
"append",
"(",
"2000",
")",
"if",
"upem",
"<",
"16",
"or",
"upem",
">",
"16384",
":",
"yield",
"FAIL",
",",
"(",
"\"The value of unitsPerEm at the head table\"",
"\" must be a value between 16 and 16384.\"",
"\" Got '{}' instead.\"",
")",
".",
"format",
"(",
"upem",
")",
"elif",
"upem",
"not",
"in",
"target_upem",
":",
"yield",
"WARN",
",",
"(",
"\"In order to optimize performance on some\"",
"\" legacy renderers, the value of unitsPerEm\"",
"\" at the head table should idealy be\"",
"\" a power of between 16 to 16384.\"",
"\" And values of 1000 and 2000 are also\"",
"\" common and may be just fine as well.\"",
"\" But we got upm={} instead.\"",
")",
".",
"format",
"(",
"upem",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"unitsPerEm value ({}) on the 'head' table\"",
"\" is reasonable.\"",
")",
".",
"format",
"(",
"upem",
")"
] | Checking unitsPerEm value is reasonable. | [
"Checking",
"unitsPerEm",
"value",
"is",
"reasonable",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/head.py#L53-L73 | train |
googlefonts/fontbakery | Lib/fontbakery/callable.py | cached_getter | def cached_getter(func):
"""Decorate a property by executing it at instatiation time and cache the
result on the instance object."""
@wraps(func)
def wrapper(self):
attribute = f'_{func.__name__}'
value = getattr(self, attribute, None)
if value is None:
value = func(self)
setattr(self, attribute, value)
return value
return wrapper | python | def cached_getter(func):
"""Decorate a property by executing it at instatiation time and cache the
result on the instance object."""
@wraps(func)
def wrapper(self):
attribute = f'_{func.__name__}'
value = getattr(self, attribute, None)
if value is None:
value = func(self)
setattr(self, attribute, value)
return value
return wrapper | [
"def",
"cached_getter",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
")",
":",
"attribute",
"=",
"f'_{func.__name__}'",
"value",
"=",
"getattr",
"(",
"self",
",",
"attribute",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"func",
"(",
"self",
")",
"setattr",
"(",
"self",
",",
"attribute",
",",
"value",
")",
"return",
"value",
"return",
"wrapper"
] | Decorate a property by executing it at instatiation time and cache the
result on the instance object. | [
"Decorate",
"a",
"property",
"by",
"executing",
"it",
"at",
"instatiation",
"time",
"and",
"cache",
"the",
"result",
"on",
"the",
"instance",
"object",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/callable.py#L18-L29 | train |
googlefonts/fontbakery | Lib/fontbakery/callable.py | condition | def condition(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCondition
Requires all arguments of FontBakeryCondition but not `func`
which is passed via the decorator syntax.
"""
if len(args) == 1 and len(kwds) == 0 and callable(args[0]):
# used as `@decorator`
func = args[0]
return wraps(func)(FontBakeryCondition(func))
else:
# used as `@decorator()` maybe with args
def wrapper(func):
return wraps(func)(FontBakeryCondition(func, *args, **kwds))
return wrapper | python | def condition(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCondition
Requires all arguments of FontBakeryCondition but not `func`
which is passed via the decorator syntax.
"""
if len(args) == 1 and len(kwds) == 0 and callable(args[0]):
# used as `@decorator`
func = args[0]
return wraps(func)(FontBakeryCondition(func))
else:
# used as `@decorator()` maybe with args
def wrapper(func):
return wraps(func)(FontBakeryCondition(func, *args, **kwds))
return wrapper | [
"def",
"condition",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwds",
")",
"==",
"0",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"# used as `@decorator`",
"func",
"=",
"args",
"[",
"0",
"]",
"return",
"wraps",
"(",
"func",
")",
"(",
"FontBakeryCondition",
"(",
"func",
")",
")",
"else",
":",
"# used as `@decorator()` maybe with args",
"def",
"wrapper",
"(",
"func",
")",
":",
"return",
"wraps",
"(",
"func",
")",
"(",
"FontBakeryCondition",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
")",
"return",
"wrapper"
] | Check wrapper, a factory for FontBakeryCondition
Requires all arguments of FontBakeryCondition but not `func`
which is passed via the decorator syntax. | [
"Check",
"wrapper",
"a",
"factory",
"for",
"FontBakeryCondition"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/callable.py#L211-L225 | train |
googlefonts/fontbakery | Lib/fontbakery/callable.py | check | def check(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCheck
Requires all arguments of FontBakeryCheck but not `checkfunc`
which is passed via the decorator syntax.
"""
def wrapper(checkfunc):
return wraps(checkfunc)(FontBakeryCheck(checkfunc, *args, **kwds))
return wrapper | python | def check(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCheck
Requires all arguments of FontBakeryCheck but not `checkfunc`
which is passed via the decorator syntax.
"""
def wrapper(checkfunc):
return wraps(checkfunc)(FontBakeryCheck(checkfunc, *args, **kwds))
return wrapper | [
"def",
"check",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"def",
"wrapper",
"(",
"checkfunc",
")",
":",
"return",
"wraps",
"(",
"checkfunc",
")",
"(",
"FontBakeryCheck",
"(",
"checkfunc",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
")",
"return",
"wrapper"
] | Check wrapper, a factory for FontBakeryCheck
Requires all arguments of FontBakeryCheck but not `checkfunc`
which is passed via the decorator syntax. | [
"Check",
"wrapper",
"a",
"factory",
"for",
"FontBakeryCheck"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/callable.py#L227-L235 | train |
googlefonts/fontbakery | Lib/fontbakery/utils.py | get_bounding_box | def get_bounding_box(font):
""" Returns max and min bbox of given truetype font """
ymin = 0
ymax = 0
if font.sfntVersion == 'OTTO':
ymin = font['head'].yMin
ymax = font['head'].yMax
else:
for g in font['glyf'].glyphs:
char = font['glyf'][g]
if hasattr(char, 'yMin') and ymin > char.yMin:
ymin = char.yMin
if hasattr(char, 'yMax') and ymax < char.yMax:
ymax = char.yMax
return ymin, ymax | python | def get_bounding_box(font):
""" Returns max and min bbox of given truetype font """
ymin = 0
ymax = 0
if font.sfntVersion == 'OTTO':
ymin = font['head'].yMin
ymax = font['head'].yMax
else:
for g in font['glyf'].glyphs:
char = font['glyf'][g]
if hasattr(char, 'yMin') and ymin > char.yMin:
ymin = char.yMin
if hasattr(char, 'yMax') and ymax < char.yMax:
ymax = char.yMax
return ymin, ymax | [
"def",
"get_bounding_box",
"(",
"font",
")",
":",
"ymin",
"=",
"0",
"ymax",
"=",
"0",
"if",
"font",
".",
"sfntVersion",
"==",
"'OTTO'",
":",
"ymin",
"=",
"font",
"[",
"'head'",
"]",
".",
"yMin",
"ymax",
"=",
"font",
"[",
"'head'",
"]",
".",
"yMax",
"else",
":",
"for",
"g",
"in",
"font",
"[",
"'glyf'",
"]",
".",
"glyphs",
":",
"char",
"=",
"font",
"[",
"'glyf'",
"]",
"[",
"g",
"]",
"if",
"hasattr",
"(",
"char",
",",
"'yMin'",
")",
"and",
"ymin",
">",
"char",
".",
"yMin",
":",
"ymin",
"=",
"char",
".",
"yMin",
"if",
"hasattr",
"(",
"char",
",",
"'yMax'",
")",
"and",
"ymax",
"<",
"char",
".",
"yMax",
":",
"ymax",
"=",
"char",
".",
"yMax",
"return",
"ymin",
",",
"ymax"
] | Returns max and min bbox of given truetype font | [
"Returns",
"max",
"and",
"min",
"bbox",
"of",
"given",
"truetype",
"font"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/utils.py#L57-L71 | train |
googlefonts/fontbakery | Lib/fontbakery/utils.py | glyph_contour_count | def glyph_contour_count(font, name):
"""Contour count for specified glyph.
This implementation will also return contour count for
composite glyphs.
"""
contour_count = 0
items = [font['glyf'][name]]
while items:
g = items.pop(0)
if g.isComposite():
for comp in g.components:
if comp.glyphName != ".ttfautohint":
items.append(font['glyf'][comp.glyphName])
if g.numberOfContours != -1:
contour_count += g.numberOfContours
return contour_count | python | def glyph_contour_count(font, name):
"""Contour count for specified glyph.
This implementation will also return contour count for
composite glyphs.
"""
contour_count = 0
items = [font['glyf'][name]]
while items:
g = items.pop(0)
if g.isComposite():
for comp in g.components:
if comp.glyphName != ".ttfautohint":
items.append(font['glyf'][comp.glyphName])
if g.numberOfContours != -1:
contour_count += g.numberOfContours
return contour_count | [
"def",
"glyph_contour_count",
"(",
"font",
",",
"name",
")",
":",
"contour_count",
"=",
"0",
"items",
"=",
"[",
"font",
"[",
"'glyf'",
"]",
"[",
"name",
"]",
"]",
"while",
"items",
":",
"g",
"=",
"items",
".",
"pop",
"(",
"0",
")",
"if",
"g",
".",
"isComposite",
"(",
")",
":",
"for",
"comp",
"in",
"g",
".",
"components",
":",
"if",
"comp",
".",
"glyphName",
"!=",
"\".ttfautohint\"",
":",
"items",
".",
"append",
"(",
"font",
"[",
"'glyf'",
"]",
"[",
"comp",
".",
"glyphName",
"]",
")",
"if",
"g",
".",
"numberOfContours",
"!=",
"-",
"1",
":",
"contour_count",
"+=",
"g",
".",
"numberOfContours",
"return",
"contour_count"
] | Contour count for specified glyph.
This implementation will also return contour count for
composite glyphs. | [
"Contour",
"count",
"for",
"specified",
"glyph",
".",
"This",
"implementation",
"will",
"also",
"return",
"contour",
"count",
"for",
"composite",
"glyphs",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/utils.py#L116-L132 | train |
googlefonts/fontbakery | Lib/fontbakery/utils.py | get_font_glyph_data | def get_font_glyph_data(font):
"""Return information for each glyph in a font"""
from fontbakery.constants import (PlatformID,
WindowsEncodingID)
font_data = []
try:
subtable = font['cmap'].getcmap(PlatformID.WINDOWS,
WindowsEncodingID.UNICODE_BMP)
if not subtable:
# Well... Give it a chance here...
# It may be using a different Encoding_ID value
subtable = font['cmap'].tables[0]
cmap = subtable.cmap
except:
return None
cmap_reversed = dict(zip(cmap.values(), cmap.keys()))
for glyph_name in font.getGlyphSet().keys():
if glyph_name in cmap_reversed:
uni_glyph = cmap_reversed[glyph_name]
contours = glyph_contour_count(font, glyph_name)
font_data.append({
'unicode': uni_glyph,
'name': glyph_name,
'contours': {contours}
})
return font_data | python | def get_font_glyph_data(font):
"""Return information for each glyph in a font"""
from fontbakery.constants import (PlatformID,
WindowsEncodingID)
font_data = []
try:
subtable = font['cmap'].getcmap(PlatformID.WINDOWS,
WindowsEncodingID.UNICODE_BMP)
if not subtable:
# Well... Give it a chance here...
# It may be using a different Encoding_ID value
subtable = font['cmap'].tables[0]
cmap = subtable.cmap
except:
return None
cmap_reversed = dict(zip(cmap.values(), cmap.keys()))
for glyph_name in font.getGlyphSet().keys():
if glyph_name in cmap_reversed:
uni_glyph = cmap_reversed[glyph_name]
contours = glyph_contour_count(font, glyph_name)
font_data.append({
'unicode': uni_glyph,
'name': glyph_name,
'contours': {contours}
})
return font_data | [
"def",
"get_font_glyph_data",
"(",
"font",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"(",
"PlatformID",
",",
"WindowsEncodingID",
")",
"font_data",
"=",
"[",
"]",
"try",
":",
"subtable",
"=",
"font",
"[",
"'cmap'",
"]",
".",
"getcmap",
"(",
"PlatformID",
".",
"WINDOWS",
",",
"WindowsEncodingID",
".",
"UNICODE_BMP",
")",
"if",
"not",
"subtable",
":",
"# Well... Give it a chance here...",
"# It may be using a different Encoding_ID value",
"subtable",
"=",
"font",
"[",
"'cmap'",
"]",
".",
"tables",
"[",
"0",
"]",
"cmap",
"=",
"subtable",
".",
"cmap",
"except",
":",
"return",
"None",
"cmap_reversed",
"=",
"dict",
"(",
"zip",
"(",
"cmap",
".",
"values",
"(",
")",
",",
"cmap",
".",
"keys",
"(",
")",
")",
")",
"for",
"glyph_name",
"in",
"font",
".",
"getGlyphSet",
"(",
")",
".",
"keys",
"(",
")",
":",
"if",
"glyph_name",
"in",
"cmap_reversed",
":",
"uni_glyph",
"=",
"cmap_reversed",
"[",
"glyph_name",
"]",
"contours",
"=",
"glyph_contour_count",
"(",
"font",
",",
"glyph_name",
")",
"font_data",
".",
"append",
"(",
"{",
"'unicode'",
":",
"uni_glyph",
",",
"'name'",
":",
"glyph_name",
",",
"'contours'",
":",
"{",
"contours",
"}",
"}",
")",
"return",
"font_data"
] | Return information for each glyph in a font | [
"Return",
"information",
"for",
"each",
"glyph",
"in",
"a",
"font"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/utils.py#L135-L164 | train |
googlefonts/fontbakery | Lib/fontbakery/utils.py | glyph_has_ink | def glyph_has_ink(font: TTFont, name: Text) -> bool:
"""Checks if specified glyph has any ink.
That is, that it has at least one defined contour associated.
Composites are considered to have ink if any of their components have ink.
Args:
font: the font
glyph_name: The name of the glyph to check for ink.
Returns:
True if the font has at least one contour associated with it.
"""
if 'glyf' in font:
return ttf_glyph_has_ink(font, name)
elif ('CFF ' in font) or ('CFF2' in font):
return cff_glyph_has_ink(font, name)
else:
raise Exception("Could not find 'glyf', 'CFF ', or 'CFF2' table.") | python | def glyph_has_ink(font: TTFont, name: Text) -> bool:
"""Checks if specified glyph has any ink.
That is, that it has at least one defined contour associated.
Composites are considered to have ink if any of their components have ink.
Args:
font: the font
glyph_name: The name of the glyph to check for ink.
Returns:
True if the font has at least one contour associated with it.
"""
if 'glyf' in font:
return ttf_glyph_has_ink(font, name)
elif ('CFF ' in font) or ('CFF2' in font):
return cff_glyph_has_ink(font, name)
else:
raise Exception("Could not find 'glyf', 'CFF ', or 'CFF2' table.") | [
"def",
"glyph_has_ink",
"(",
"font",
":",
"TTFont",
",",
"name",
":",
"Text",
")",
"->",
"bool",
":",
"if",
"'glyf'",
"in",
"font",
":",
"return",
"ttf_glyph_has_ink",
"(",
"font",
",",
"name",
")",
"elif",
"(",
"'CFF '",
"in",
"font",
")",
"or",
"(",
"'CFF2'",
"in",
"font",
")",
":",
"return",
"cff_glyph_has_ink",
"(",
"font",
",",
"name",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Could not find 'glyf', 'CFF ', or 'CFF2' table.\"",
")"
] | Checks if specified glyph has any ink.
That is, that it has at least one defined contour associated.
Composites are considered to have ink if any of their components have ink.
Args:
font: the font
glyph_name: The name of the glyph to check for ink.
Returns:
True if the font has at least one contour associated with it. | [
"Checks",
"if",
"specified",
"glyph",
"has",
"any",
"ink",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/utils.py#L245-L261 | train |
googlefonts/fontbakery | Lib/fontbakery/utils.py | assert_results_contain | def assert_results_contain(check_results, expected_status, expected_msgcode=None):
"""
This helper function is useful when we want to make sure that
a certain log message is emited by a check but it can be in any
order among other log messages.
"""
found = False
for status, message in check_results:
if status == expected_status and message.code == expected_msgcode:
found = True
break
assert(found) | python | def assert_results_contain(check_results, expected_status, expected_msgcode=None):
"""
This helper function is useful when we want to make sure that
a certain log message is emited by a check but it can be in any
order among other log messages.
"""
found = False
for status, message in check_results:
if status == expected_status and message.code == expected_msgcode:
found = True
break
assert(found) | [
"def",
"assert_results_contain",
"(",
"check_results",
",",
"expected_status",
",",
"expected_msgcode",
"=",
"None",
")",
":",
"found",
"=",
"False",
"for",
"status",
",",
"message",
"in",
"check_results",
":",
"if",
"status",
"==",
"expected_status",
"and",
"message",
".",
"code",
"==",
"expected_msgcode",
":",
"found",
"=",
"True",
"break",
"assert",
"(",
"found",
")"
] | This helper function is useful when we want to make sure that
a certain log message is emited by a check but it can be in any
order among other log messages. | [
"This",
"helper",
"function",
"is",
"useful",
"when",
"we",
"want",
"to",
"make",
"sure",
"that",
"a",
"certain",
"log",
"message",
"is",
"emited",
"by",
"a",
"check",
"but",
"it",
"can",
"be",
"in",
"any",
"order",
"among",
"other",
"log",
"messages",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/utils.py#L264-L275 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/post.py | com_google_fonts_check_family_underline_thickness | def com_google_fonts_check_family_underline_thickness(ttFonts):
"""Fonts have consistent underline thickness?"""
underTs = {}
underlineThickness = None
failed = False
for ttfont in ttFonts:
fontname = ttfont.reader.file.name
# stylename = style(fontname)
ut = ttfont['post'].underlineThickness
underTs[fontname] = ut
if underlineThickness is None:
underlineThickness = ut
if ut != underlineThickness:
failed = True
if failed:
msg = ("Thickness of the underline is not"
" the same accross this family. In order to fix this,"
" please make sure that the underlineThickness value"
" is the same in the 'post' table of all of this family"
" font files.\n"
"Detected underlineThickness values are:\n")
for style in underTs.keys():
msg += "\t{}: {}\n".format(style, underTs[style])
yield FAIL, msg
else:
yield PASS, "Fonts have consistent underline thickness." | python | def com_google_fonts_check_family_underline_thickness(ttFonts):
"""Fonts have consistent underline thickness?"""
underTs = {}
underlineThickness = None
failed = False
for ttfont in ttFonts:
fontname = ttfont.reader.file.name
# stylename = style(fontname)
ut = ttfont['post'].underlineThickness
underTs[fontname] = ut
if underlineThickness is None:
underlineThickness = ut
if ut != underlineThickness:
failed = True
if failed:
msg = ("Thickness of the underline is not"
" the same accross this family. In order to fix this,"
" please make sure that the underlineThickness value"
" is the same in the 'post' table of all of this family"
" font files.\n"
"Detected underlineThickness values are:\n")
for style in underTs.keys():
msg += "\t{}: {}\n".format(style, underTs[style])
yield FAIL, msg
else:
yield PASS, "Fonts have consistent underline thickness." | [
"def",
"com_google_fonts_check_family_underline_thickness",
"(",
"ttFonts",
")",
":",
"underTs",
"=",
"{",
"}",
"underlineThickness",
"=",
"None",
"failed",
"=",
"False",
"for",
"ttfont",
"in",
"ttFonts",
":",
"fontname",
"=",
"ttfont",
".",
"reader",
".",
"file",
".",
"name",
"# stylename = style(fontname)",
"ut",
"=",
"ttfont",
"[",
"'post'",
"]",
".",
"underlineThickness",
"underTs",
"[",
"fontname",
"]",
"=",
"ut",
"if",
"underlineThickness",
"is",
"None",
":",
"underlineThickness",
"=",
"ut",
"if",
"ut",
"!=",
"underlineThickness",
":",
"failed",
"=",
"True",
"if",
"failed",
":",
"msg",
"=",
"(",
"\"Thickness of the underline is not\"",
"\" the same accross this family. In order to fix this,\"",
"\" please make sure that the underlineThickness value\"",
"\" is the same in the 'post' table of all of this family\"",
"\" font files.\\n\"",
"\"Detected underlineThickness values are:\\n\"",
")",
"for",
"style",
"in",
"underTs",
".",
"keys",
"(",
")",
":",
"msg",
"+=",
"\"\\t{}: {}\\n\"",
".",
"format",
"(",
"style",
",",
"underTs",
"[",
"style",
"]",
")",
"yield",
"FAIL",
",",
"msg",
"else",
":",
"yield",
"PASS",
",",
"\"Fonts have consistent underline thickness.\""
] | Fonts have consistent underline thickness? | [
"Fonts",
"have",
"consistent",
"underline",
"thickness?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/post.py#L21-L47 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/html.py | summary_table | def summary_table(
errors: int, fails: int, warns: int, skips: int, infos: int, passes: int, total: int
) -> str:
"""Return summary table with statistics."""
return f"""<h2>Summary</h2>
<table>
<tr>
<th>{EMOTICON['ERROR']} ERROR</th>
<th>{EMOTICON['FAIL']} FAIL</th>
<th>{EMOTICON['WARN']} WARN</th>
<th>{EMOTICON['SKIP']} SKIP</th>
<th>{EMOTICON['INFO']} INFO</th>
<th>{EMOTICON['PASS']} PASS</th>
</tr>
<tr>
<td>{errors}</td>
<td>{fails}</td>
<td>{warns}</td>
<td>{skips}</td>
<td>{infos}</td>
<td>{passes}</td>
</tr>
<tr>
<td>{round(errors / total * 100)}%</td>
<td>{round(fails / total * 100)}%</td>
<td>{round(warns / total * 100)}%</td>
<td>{round(skips / total * 100)}%</td>
<td>{round(infos / total * 100)}%</td>
<td>{round(passes / total * 100)}%</td>
</tr>
</table>
""" | python | def summary_table(
errors: int, fails: int, warns: int, skips: int, infos: int, passes: int, total: int
) -> str:
"""Return summary table with statistics."""
return f"""<h2>Summary</h2>
<table>
<tr>
<th>{EMOTICON['ERROR']} ERROR</th>
<th>{EMOTICON['FAIL']} FAIL</th>
<th>{EMOTICON['WARN']} WARN</th>
<th>{EMOTICON['SKIP']} SKIP</th>
<th>{EMOTICON['INFO']} INFO</th>
<th>{EMOTICON['PASS']} PASS</th>
</tr>
<tr>
<td>{errors}</td>
<td>{fails}</td>
<td>{warns}</td>
<td>{skips}</td>
<td>{infos}</td>
<td>{passes}</td>
</tr>
<tr>
<td>{round(errors / total * 100)}%</td>
<td>{round(fails / total * 100)}%</td>
<td>{round(warns / total * 100)}%</td>
<td>{round(skips / total * 100)}%</td>
<td>{round(infos / total * 100)}%</td>
<td>{round(passes / total * 100)}%</td>
</tr>
</table>
""" | [
"def",
"summary_table",
"(",
"errors",
":",
"int",
",",
"fails",
":",
"int",
",",
"warns",
":",
"int",
",",
"skips",
":",
"int",
",",
"infos",
":",
"int",
",",
"passes",
":",
"int",
",",
"total",
":",
"int",
")",
"->",
"str",
":",
"return",
"f\"\"\"<h2>Summary</h2>\n <table>\n <tr>\n <th>{EMOTICON['ERROR']} ERROR</th>\n <th>{EMOTICON['FAIL']} FAIL</th>\n <th>{EMOTICON['WARN']} WARN</th>\n <th>{EMOTICON['SKIP']} SKIP</th>\n <th>{EMOTICON['INFO']} INFO</th>\n <th>{EMOTICON['PASS']} PASS</th>\n </tr>\n <tr>\n <td>{errors}</td>\n <td>{fails}</td>\n <td>{warns}</td>\n <td>{skips}</td>\n <td>{infos}</td>\n <td>{passes}</td>\n </tr>\n <tr>\n <td>{round(errors / total * 100)}%</td>\n <td>{round(fails / total * 100)}%</td>\n <td>{round(warns / total * 100)}%</td>\n <td>{round(skips / total * 100)}%</td>\n <td>{round(infos / total * 100)}%</td>\n <td>{round(passes / total * 100)}%</td>\n </tr>\n </table>\n \"\"\""
] | Return summary table with statistics. | [
"Return",
"summary",
"table",
"with",
"statistics",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L204-L236 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/html.py | HTMLReporter.get_html | def get_html(self) -> str:
"""Return complete report as a HTML string."""
data = self.getdoc()
num_checks = 0
body_elements = []
# Order by section first...
for section in data["sections"]:
section_name = html.escape(section["key"][0])
section_stati_of_note = (
e for e in section["result"].elements() if e != "PASS"
)
section_stati = "".join(
EMOTICON[s] for s in sorted(section_stati_of_note, key=LOGLEVELS.index)
)
body_elements.append(f"<h2>{section_name} {section_stati}</h2>")
checks_by_id: Dict[str, List[Dict[str, str]]] = collections.defaultdict(
list
)
# ...and check second.
for cluster in section["checks"]:
if not isinstance(cluster, list):
cluster = [cluster]
num_checks += len(cluster)
for check in cluster:
checks_by_id[check["key"][1]].append(check)
for check, results in checks_by_id.items():
check_name = html.escape(check)
body_elements.append(f"<h3>{results[0]['description']}</h3>")
body_elements.append(f"<div>Check ID: {check_name}</div>")
for result in results:
if "filename" in result:
body_elements.append(
html5_collapsible(
f"{EMOTICON[result['result']]} <strong>{result['filename']}</strong>",
self.html_for_check(result),
)
)
else:
body_elements.append(
html5_collapsible(
f"{EMOTICON[result['result']]} <strong>Family check</strong>",
self.html_for_check(result),
)
)
body_top = [
"<h1>Fontbakery Technical Report</h1>",
"<div>If you think a check is flawed or have an idea for a check, please "
f" file an issue at <a href='{ISSUE_URL}'>{ISSUE_URL}</a> and remember "
"to include a pointer to the repo and branch you're checking.</div>",
]
if num_checks:
results_summary = [data["result"][k] for k in LOGLEVELS]
body_top.append(summary_table(*results_summary, num_checks))
omitted = [l for l in LOGLEVELS if self.omit_loglevel(l)]
if omitted:
body_top.append(
"<p><strong>Note:</strong>"
" The following loglevels were omitted in this report:"
f" {', '.join(omitted)}</p>"
)
body_elements[0:0] = body_top
return html5_document(body_elements) | python | def get_html(self) -> str:
"""Return complete report as a HTML string."""
data = self.getdoc()
num_checks = 0
body_elements = []
# Order by section first...
for section in data["sections"]:
section_name = html.escape(section["key"][0])
section_stati_of_note = (
e for e in section["result"].elements() if e != "PASS"
)
section_stati = "".join(
EMOTICON[s] for s in sorted(section_stati_of_note, key=LOGLEVELS.index)
)
body_elements.append(f"<h2>{section_name} {section_stati}</h2>")
checks_by_id: Dict[str, List[Dict[str, str]]] = collections.defaultdict(
list
)
# ...and check second.
for cluster in section["checks"]:
if not isinstance(cluster, list):
cluster = [cluster]
num_checks += len(cluster)
for check in cluster:
checks_by_id[check["key"][1]].append(check)
for check, results in checks_by_id.items():
check_name = html.escape(check)
body_elements.append(f"<h3>{results[0]['description']}</h3>")
body_elements.append(f"<div>Check ID: {check_name}</div>")
for result in results:
if "filename" in result:
body_elements.append(
html5_collapsible(
f"{EMOTICON[result['result']]} <strong>{result['filename']}</strong>",
self.html_for_check(result),
)
)
else:
body_elements.append(
html5_collapsible(
f"{EMOTICON[result['result']]} <strong>Family check</strong>",
self.html_for_check(result),
)
)
body_top = [
"<h1>Fontbakery Technical Report</h1>",
"<div>If you think a check is flawed or have an idea for a check, please "
f" file an issue at <a href='{ISSUE_URL}'>{ISSUE_URL}</a> and remember "
"to include a pointer to the repo and branch you're checking.</div>",
]
if num_checks:
results_summary = [data["result"][k] for k in LOGLEVELS]
body_top.append(summary_table(*results_summary, num_checks))
omitted = [l for l in LOGLEVELS if self.omit_loglevel(l)]
if omitted:
body_top.append(
"<p><strong>Note:</strong>"
" The following loglevels were omitted in this report:"
f" {', '.join(omitted)}</p>"
)
body_elements[0:0] = body_top
return html5_document(body_elements) | [
"def",
"get_html",
"(",
"self",
")",
"->",
"str",
":",
"data",
"=",
"self",
".",
"getdoc",
"(",
")",
"num_checks",
"=",
"0",
"body_elements",
"=",
"[",
"]",
"# Order by section first...",
"for",
"section",
"in",
"data",
"[",
"\"sections\"",
"]",
":",
"section_name",
"=",
"html",
".",
"escape",
"(",
"section",
"[",
"\"key\"",
"]",
"[",
"0",
"]",
")",
"section_stati_of_note",
"=",
"(",
"e",
"for",
"e",
"in",
"section",
"[",
"\"result\"",
"]",
".",
"elements",
"(",
")",
"if",
"e",
"!=",
"\"PASS\"",
")",
"section_stati",
"=",
"\"\"",
".",
"join",
"(",
"EMOTICON",
"[",
"s",
"]",
"for",
"s",
"in",
"sorted",
"(",
"section_stati_of_note",
",",
"key",
"=",
"LOGLEVELS",
".",
"index",
")",
")",
"body_elements",
".",
"append",
"(",
"f\"<h2>{section_name} {section_stati}</h2>\"",
")",
"checks_by_id",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"]",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"# ...and check second.",
"for",
"cluster",
"in",
"section",
"[",
"\"checks\"",
"]",
":",
"if",
"not",
"isinstance",
"(",
"cluster",
",",
"list",
")",
":",
"cluster",
"=",
"[",
"cluster",
"]",
"num_checks",
"+=",
"len",
"(",
"cluster",
")",
"for",
"check",
"in",
"cluster",
":",
"checks_by_id",
"[",
"check",
"[",
"\"key\"",
"]",
"[",
"1",
"]",
"]",
".",
"append",
"(",
"check",
")",
"for",
"check",
",",
"results",
"in",
"checks_by_id",
".",
"items",
"(",
")",
":",
"check_name",
"=",
"html",
".",
"escape",
"(",
"check",
")",
"body_elements",
".",
"append",
"(",
"f\"<h3>{results[0]['description']}</h3>\"",
")",
"body_elements",
".",
"append",
"(",
"f\"<div>Check ID: {check_name}</div>\"",
")",
"for",
"result",
"in",
"results",
":",
"if",
"\"filename\"",
"in",
"result",
":",
"body_elements",
".",
"append",
"(",
"html5_collapsible",
"(",
"f\"{EMOTICON[result['result']]} <strong>{result['filename']}</strong>\"",
",",
"self",
".",
"html_for_check",
"(",
"result",
")",
",",
")",
")",
"else",
":",
"body_elements",
".",
"append",
"(",
"html5_collapsible",
"(",
"f\"{EMOTICON[result['result']]} <strong>Family check</strong>\"",
",",
"self",
".",
"html_for_check",
"(",
"result",
")",
",",
")",
")",
"body_top",
"=",
"[",
"\"<h1>Fontbakery Technical Report</h1>\"",
",",
"\"<div>If you think a check is flawed or have an idea for a check, please \"",
"f\" file an issue at <a href='{ISSUE_URL}'>{ISSUE_URL}</a> and remember \"",
"\"to include a pointer to the repo and branch you're checking.</div>\"",
",",
"]",
"if",
"num_checks",
":",
"results_summary",
"=",
"[",
"data",
"[",
"\"result\"",
"]",
"[",
"k",
"]",
"for",
"k",
"in",
"LOGLEVELS",
"]",
"body_top",
".",
"append",
"(",
"summary_table",
"(",
"*",
"results_summary",
",",
"num_checks",
")",
")",
"omitted",
"=",
"[",
"l",
"for",
"l",
"in",
"LOGLEVELS",
"if",
"self",
".",
"omit_loglevel",
"(",
"l",
")",
"]",
"if",
"omitted",
":",
"body_top",
".",
"append",
"(",
"\"<p><strong>Note:</strong>\"",
"\" The following loglevels were omitted in this report:\"",
"f\" {', '.join(omitted)}</p>\"",
")",
"body_elements",
"[",
"0",
":",
"0",
"]",
"=",
"body_top",
"return",
"html5_document",
"(",
"body_elements",
")"
] | Return complete report as a HTML string. | [
"Return",
"complete",
"report",
"as",
"a",
"HTML",
"string",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L29-L96 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/html.py | HTMLReporter.omit_loglevel | def omit_loglevel(self, msg) -> bool:
"""Determine if message is below log level."""
return self.loglevels and (
self.loglevels[0] > fontbakery.checkrunner.Status(msg)
) | python | def omit_loglevel(self, msg) -> bool:
"""Determine if message is below log level."""
return self.loglevels and (
self.loglevels[0] > fontbakery.checkrunner.Status(msg)
) | [
"def",
"omit_loglevel",
"(",
"self",
",",
"msg",
")",
"->",
"bool",
":",
"return",
"self",
".",
"loglevels",
"and",
"(",
"self",
".",
"loglevels",
"[",
"0",
"]",
">",
"fontbakery",
".",
"checkrunner",
".",
"Status",
"(",
"msg",
")",
")"
] | Determine if message is below log level. | [
"Determine",
"if",
"message",
"is",
"below",
"log",
"level",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L98-L102 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/html.py | HTMLReporter.html_for_check | def html_for_check(self, check) -> str:
"""Return HTML string for complete single check."""
check["logs"].sort(key=lambda c: LOGLEVELS.index(c["status"]))
logs = "<ul>" + "".join([self.log_html(log) for log in check["logs"]]) + "</ul>"
return logs | python | def html_for_check(self, check) -> str:
"""Return HTML string for complete single check."""
check["logs"].sort(key=lambda c: LOGLEVELS.index(c["status"]))
logs = "<ul>" + "".join([self.log_html(log) for log in check["logs"]]) + "</ul>"
return logs | [
"def",
"html_for_check",
"(",
"self",
",",
"check",
")",
"->",
"str",
":",
"check",
"[",
"\"logs\"",
"]",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"LOGLEVELS",
".",
"index",
"(",
"c",
"[",
"\"status\"",
"]",
")",
")",
"logs",
"=",
"\"<ul>\"",
"+",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"log_html",
"(",
"log",
")",
"for",
"log",
"in",
"check",
"[",
"\"logs\"",
"]",
"]",
")",
"+",
"\"</ul>\"",
"return",
"logs"
] | Return HTML string for complete single check. | [
"Return",
"HTML",
"string",
"for",
"complete",
"single",
"check",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L104-L108 | train |
googlefonts/fontbakery | Lib/fontbakery/reporters/html.py | HTMLReporter.log_html | def log_html(self, log) -> str:
"""Return single check sub-result string as HTML or not if below log
level."""
if not self.omit_loglevel(log["status"]):
emoticon = EMOTICON[log["status"]]
status = log["status"]
message = html.escape(log["message"]).replace("\n", "<br/>")
return (
"<li class='details_item'>"
f"<span class='details_indicator'>{emoticon} {status}</span>"
f"<span class='details_text'>{message}</span>"
"</li>"
)
return "" | python | def log_html(self, log) -> str:
"""Return single check sub-result string as HTML or not if below log
level."""
if not self.omit_loglevel(log["status"]):
emoticon = EMOTICON[log["status"]]
status = log["status"]
message = html.escape(log["message"]).replace("\n", "<br/>")
return (
"<li class='details_item'>"
f"<span class='details_indicator'>{emoticon} {status}</span>"
f"<span class='details_text'>{message}</span>"
"</li>"
)
return "" | [
"def",
"log_html",
"(",
"self",
",",
"log",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"omit_loglevel",
"(",
"log",
"[",
"\"status\"",
"]",
")",
":",
"emoticon",
"=",
"EMOTICON",
"[",
"log",
"[",
"\"status\"",
"]",
"]",
"status",
"=",
"log",
"[",
"\"status\"",
"]",
"message",
"=",
"html",
".",
"escape",
"(",
"log",
"[",
"\"message\"",
"]",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"<br/>\"",
")",
"return",
"(",
"\"<li class='details_item'>\"",
"f\"<span class='details_indicator'>{emoticon} {status}</span>\"",
"f\"<span class='details_text'>{message}</span>\"",
"\"</li>\"",
")",
"return",
"\"\""
] | Return single check sub-result string as HTML or not if below log
level. | [
"Return",
"single",
"check",
"sub",
"-",
"result",
"string",
"as",
"HTML",
"or",
"not",
"if",
"below",
"log",
"level",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L110-L123 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | style | def style(font):
"""Determine font style from canonical filename."""
from fontbakery.constants import STATIC_STYLE_NAMES
filename = os.path.basename(font)
if '-' in filename:
stylename = os.path.splitext(filename)[0].split('-')[1]
if stylename in [name.replace(' ', '') for name in STATIC_STYLE_NAMES]:
return stylename
return None | python | def style(font):
"""Determine font style from canonical filename."""
from fontbakery.constants import STATIC_STYLE_NAMES
filename = os.path.basename(font)
if '-' in filename:
stylename = os.path.splitext(filename)[0].split('-')[1]
if stylename in [name.replace(' ', '') for name in STATIC_STYLE_NAMES]:
return stylename
return None | [
"def",
"style",
"(",
"font",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"STATIC_STYLE_NAMES",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"font",
")",
"if",
"'-'",
"in",
"filename",
":",
"stylename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
"if",
"stylename",
"in",
"[",
"name",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"for",
"name",
"in",
"STATIC_STYLE_NAMES",
"]",
":",
"return",
"stylename",
"return",
"None"
] | Determine font style from canonical filename. | [
"Determine",
"font",
"style",
"from",
"canonical",
"filename",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L140-L148 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | canonical_stylename | def canonical_stylename(font):
""" Returns the canonical stylename of a given font. """
from fontbakery.constants import (STATIC_STYLE_NAMES,
VARFONT_SUFFIXES)
from fontbakery.profiles.shared_conditions import is_variable_font
from fontTools.ttLib import TTFont
# remove spaces in style names
valid_style_suffixes = [name.replace(' ', '') for name in STATIC_STYLE_NAMES]
filename = os.path.basename(font)
basename = os.path.splitext(filename)[0]
s = suffix(font)
varfont = os.path.exists(font) and is_variable_font(TTFont(font))
if ('-' in basename and
(s in VARFONT_SUFFIXES and varfont)
or (s in valid_style_suffixes and not varfont)):
return s | python | def canonical_stylename(font):
""" Returns the canonical stylename of a given font. """
from fontbakery.constants import (STATIC_STYLE_NAMES,
VARFONT_SUFFIXES)
from fontbakery.profiles.shared_conditions import is_variable_font
from fontTools.ttLib import TTFont
# remove spaces in style names
valid_style_suffixes = [name.replace(' ', '') for name in STATIC_STYLE_NAMES]
filename = os.path.basename(font)
basename = os.path.splitext(filename)[0]
s = suffix(font)
varfont = os.path.exists(font) and is_variable_font(TTFont(font))
if ('-' in basename and
(s in VARFONT_SUFFIXES and varfont)
or (s in valid_style_suffixes and not varfont)):
return s | [
"def",
"canonical_stylename",
"(",
"font",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"(",
"STATIC_STYLE_NAMES",
",",
"VARFONT_SUFFIXES",
")",
"from",
"fontbakery",
".",
"profiles",
".",
"shared_conditions",
"import",
"is_variable_font",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"# remove spaces in style names",
"valid_style_suffixes",
"=",
"[",
"name",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"for",
"name",
"in",
"STATIC_STYLE_NAMES",
"]",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"font",
")",
"basename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"s",
"=",
"suffix",
"(",
"font",
")",
"varfont",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"font",
")",
"and",
"is_variable_font",
"(",
"TTFont",
"(",
"font",
")",
")",
"if",
"(",
"'-'",
"in",
"basename",
"and",
"(",
"s",
"in",
"VARFONT_SUFFIXES",
"and",
"varfont",
")",
"or",
"(",
"s",
"in",
"valid_style_suffixes",
"and",
"not",
"varfont",
")",
")",
":",
"return",
"s"
] | Returns the canonical stylename of a given font. | [
"Returns",
"the",
"canonical",
"stylename",
"of",
"a",
"given",
"font",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L224-L241 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_canonical_filename | def com_google_fonts_check_canonical_filename(font):
"""Checking file is named canonically.
A font's filename must be composed in the following manner:
<familyname>-<stylename>.ttf
e.g. Nunito-Regular.ttf,
Oswald-BoldItalic.ttf
Variable fonts must use the "-VF" suffix:
e.g. Roboto-VF.ttf,
Barlow-VF.ttf,
Example-Roman-VF.ttf,
Familyname-Italic-VF.ttf
"""
from fontTools.ttLib import TTFont
from fontbakery.profiles.shared_conditions import is_variable_font
from fontbakery.constants import (STATIC_STYLE_NAMES,
VARFONT_SUFFIXES)
if canonical_stylename(font):
yield PASS, f"{font} is named canonically."
else:
if os.path.exists(font) and is_variable_font(TTFont(font)):
if suffix(font) in STATIC_STYLE_NAMES:
yield FAIL, (f'This is a variable font, but it is using'
' a naming scheme typical of a static font.')
yield FAIL, ('Please change the font filename to use one'
' of the following valid suffixes for variable fonts:'
f' {", ".join(VARFONT_SUFFIXES)}')
else:
style_names = '", "'.join(STATIC_STYLE_NAMES)
yield FAIL, (f'Style name used in "{font}" is not canonical.'
' You should rebuild the font using'
' any of the following'
f' style names: "{style_names}".') | python | def com_google_fonts_check_canonical_filename(font):
"""Checking file is named canonically.
A font's filename must be composed in the following manner:
<familyname>-<stylename>.ttf
e.g. Nunito-Regular.ttf,
Oswald-BoldItalic.ttf
Variable fonts must use the "-VF" suffix:
e.g. Roboto-VF.ttf,
Barlow-VF.ttf,
Example-Roman-VF.ttf,
Familyname-Italic-VF.ttf
"""
from fontTools.ttLib import TTFont
from fontbakery.profiles.shared_conditions import is_variable_font
from fontbakery.constants import (STATIC_STYLE_NAMES,
VARFONT_SUFFIXES)
if canonical_stylename(font):
yield PASS, f"{font} is named canonically."
else:
if os.path.exists(font) and is_variable_font(TTFont(font)):
if suffix(font) in STATIC_STYLE_NAMES:
yield FAIL, (f'This is a variable font, but it is using'
' a naming scheme typical of a static font.')
yield FAIL, ('Please change the font filename to use one'
' of the following valid suffixes for variable fonts:'
f' {", ".join(VARFONT_SUFFIXES)}')
else:
style_names = '", "'.join(STATIC_STYLE_NAMES)
yield FAIL, (f'Style name used in "{font}" is not canonical.'
' You should rebuild the font using'
' any of the following'
f' style names: "{style_names}".') | [
"def",
"com_google_fonts_check_canonical_filename",
"(",
"font",
")",
":",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"from",
"fontbakery",
".",
"profiles",
".",
"shared_conditions",
"import",
"is_variable_font",
"from",
"fontbakery",
".",
"constants",
"import",
"(",
"STATIC_STYLE_NAMES",
",",
"VARFONT_SUFFIXES",
")",
"if",
"canonical_stylename",
"(",
"font",
")",
":",
"yield",
"PASS",
",",
"f\"{font} is named canonically.\"",
"else",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"font",
")",
"and",
"is_variable_font",
"(",
"TTFont",
"(",
"font",
")",
")",
":",
"if",
"suffix",
"(",
"font",
")",
"in",
"STATIC_STYLE_NAMES",
":",
"yield",
"FAIL",
",",
"(",
"f'This is a variable font, but it is using'",
"' a naming scheme typical of a static font.'",
")",
"yield",
"FAIL",
",",
"(",
"'Please change the font filename to use one'",
"' of the following valid suffixes for variable fonts:'",
"f' {\", \".join(VARFONT_SUFFIXES)}'",
")",
"else",
":",
"style_names",
"=",
"'\", \"'",
".",
"join",
"(",
"STATIC_STYLE_NAMES",
")",
"yield",
"FAIL",
",",
"(",
"f'Style name used in \"{font}\" is not canonical.'",
"' You should rebuild the font using'",
"' any of the following'",
"f' style names: \"{style_names}\".'",
")"
] | Checking file is named canonically.
A font's filename must be composed in the following manner:
<familyname>-<stylename>.ttf
e.g. Nunito-Regular.ttf,
Oswald-BoldItalic.ttf
Variable fonts must use the "-VF" suffix:
e.g. Roboto-VF.ttf,
Barlow-VF.ttf,
Example-Roman-VF.ttf,
Familyname-Italic-VF.ttf | [
"Checking",
"file",
"is",
"named",
"canonically",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L250-L285 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | family_directory | def family_directory(fonts):
"""Get the path of font project directory."""
if fonts:
dirname = os.path.dirname(fonts[0])
if dirname == '':
dirname = '.'
return dirname | python | def family_directory(fonts):
"""Get the path of font project directory."""
if fonts:
dirname = os.path.dirname(fonts[0])
if dirname == '':
dirname = '.'
return dirname | [
"def",
"family_directory",
"(",
"fonts",
")",
":",
"if",
"fonts",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fonts",
"[",
"0",
"]",
")",
"if",
"dirname",
"==",
"''",
":",
"dirname",
"=",
"'.'",
"return",
"dirname"
] | Get the path of font project directory. | [
"Get",
"the",
"path",
"of",
"font",
"project",
"directory",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L289-L295 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | descfile | def descfile(family_directory):
"""Get the path of the DESCRIPTION file of a given font project."""
if family_directory:
descfilepath = os.path.join(family_directory, "DESCRIPTION.en_us.html")
if os.path.exists(descfilepath):
return descfilepath | python | def descfile(family_directory):
"""Get the path of the DESCRIPTION file of a given font project."""
if family_directory:
descfilepath = os.path.join(family_directory, "DESCRIPTION.en_us.html")
if os.path.exists(descfilepath):
return descfilepath | [
"def",
"descfile",
"(",
"family_directory",
")",
":",
"if",
"family_directory",
":",
"descfilepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"family_directory",
",",
"\"DESCRIPTION.en_us.html\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"descfilepath",
")",
":",
"return",
"descfilepath"
] | Get the path of the DESCRIPTION file of a given font project. | [
"Get",
"the",
"path",
"of",
"the",
"DESCRIPTION",
"file",
"of",
"a",
"given",
"font",
"project",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L299-L304 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_description_broken_links | def com_google_fonts_check_description_broken_links(description):
"""Does DESCRIPTION file contain broken links?"""
from lxml.html import HTMLParser
import defusedxml.lxml
import requests
doc = defusedxml.lxml.fromstring(description, parser=HTMLParser())
broken_links = []
for link in doc.xpath('//a/@href'):
if link.startswith("mailto:") and \
"@" in link and \
"." in link.split("@")[1]:
yield INFO, (f"Found an email address: {link}")
continue
try:
response = requests.head(link, allow_redirects=True, timeout=10)
code = response.status_code
if code != requests.codes.ok:
broken_links.append(("url: '{}' "
"status code: '{}'").format(link, code))
except requests.exceptions.Timeout:
yield WARN, ("Timedout while attempting to access: '{}'."
" Please verify if that's a broken link.").format(link)
except requests.exceptions.RequestException:
broken_links.append(link)
if len(broken_links) > 0:
yield FAIL, ("The following links are broken"
" in the DESCRIPTION file:"
" '{}'").format("', '".join(broken_links))
else:
yield PASS, "All links in the DESCRIPTION file look good!" | python | def com_google_fonts_check_description_broken_links(description):
"""Does DESCRIPTION file contain broken links?"""
from lxml.html import HTMLParser
import defusedxml.lxml
import requests
doc = defusedxml.lxml.fromstring(description, parser=HTMLParser())
broken_links = []
for link in doc.xpath('//a/@href'):
if link.startswith("mailto:") and \
"@" in link and \
"." in link.split("@")[1]:
yield INFO, (f"Found an email address: {link}")
continue
try:
response = requests.head(link, allow_redirects=True, timeout=10)
code = response.status_code
if code != requests.codes.ok:
broken_links.append(("url: '{}' "
"status code: '{}'").format(link, code))
except requests.exceptions.Timeout:
yield WARN, ("Timedout while attempting to access: '{}'."
" Please verify if that's a broken link.").format(link)
except requests.exceptions.RequestException:
broken_links.append(link)
if len(broken_links) > 0:
yield FAIL, ("The following links are broken"
" in the DESCRIPTION file:"
" '{}'").format("', '".join(broken_links))
else:
yield PASS, "All links in the DESCRIPTION file look good!" | [
"def",
"com_google_fonts_check_description_broken_links",
"(",
"description",
")",
":",
"from",
"lxml",
".",
"html",
"import",
"HTMLParser",
"import",
"defusedxml",
".",
"lxml",
"import",
"requests",
"doc",
"=",
"defusedxml",
".",
"lxml",
".",
"fromstring",
"(",
"description",
",",
"parser",
"=",
"HTMLParser",
"(",
")",
")",
"broken_links",
"=",
"[",
"]",
"for",
"link",
"in",
"doc",
".",
"xpath",
"(",
"'//a/@href'",
")",
":",
"if",
"link",
".",
"startswith",
"(",
"\"mailto:\"",
")",
"and",
"\"@\"",
"in",
"link",
"and",
"\".\"",
"in",
"link",
".",
"split",
"(",
"\"@\"",
")",
"[",
"1",
"]",
":",
"yield",
"INFO",
",",
"(",
"f\"Found an email address: {link}\"",
")",
"continue",
"try",
":",
"response",
"=",
"requests",
".",
"head",
"(",
"link",
",",
"allow_redirects",
"=",
"True",
",",
"timeout",
"=",
"10",
")",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"broken_links",
".",
"append",
"(",
"(",
"\"url: '{}' \"",
"\"status code: '{}'\"",
")",
".",
"format",
"(",
"link",
",",
"code",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"yield",
"WARN",
",",
"(",
"\"Timedout while attempting to access: '{}'.\"",
"\" Please verify if that's a broken link.\"",
")",
".",
"format",
"(",
"link",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
":",
"broken_links",
".",
"append",
"(",
"link",
")",
"if",
"len",
"(",
"broken_links",
")",
">",
"0",
":",
"yield",
"FAIL",
",",
"(",
"\"The following links are broken\"",
"\" in the DESCRIPTION file:\"",
"\" '{}'\"",
")",
".",
"format",
"(",
"\"', '\"",
".",
"join",
"(",
"broken_links",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"All links in the DESCRIPTION file look good!\""
] | Does DESCRIPTION file contain broken links? | [
"Does",
"DESCRIPTION",
"file",
"contain",
"broken",
"links?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L320-L351 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_parses | def com_google_fonts_check_metadata_parses(family_directory):
""" Check METADATA.pb parse correctly. """
from google.protobuf import text_format
from fontbakery.utils import get_FamilyProto_Message
try:
pb_file = os.path.join(family_directory, "METADATA.pb")
get_FamilyProto_Message(pb_file)
yield PASS, "METADATA.pb parsed successfuly."
except text_format.ParseError as e:
yield FAIL, (f"Family metadata at {family_directory} failed to parse.\n"
f"TRACEBACK:\n{e}")
except FileNotFoundError:
yield SKIP, f"Font family at '{family_directory}' lacks a METADATA.pb file." | python | def com_google_fonts_check_metadata_parses(family_directory):
""" Check METADATA.pb parse correctly. """
from google.protobuf import text_format
from fontbakery.utils import get_FamilyProto_Message
try:
pb_file = os.path.join(family_directory, "METADATA.pb")
get_FamilyProto_Message(pb_file)
yield PASS, "METADATA.pb parsed successfuly."
except text_format.ParseError as e:
yield FAIL, (f"Family metadata at {family_directory} failed to parse.\n"
f"TRACEBACK:\n{e}")
except FileNotFoundError:
yield SKIP, f"Font family at '{family_directory}' lacks a METADATA.pb file." | [
"def",
"com_google_fonts_check_metadata_parses",
"(",
"family_directory",
")",
":",
"from",
"google",
".",
"protobuf",
"import",
"text_format",
"from",
"fontbakery",
".",
"utils",
"import",
"get_FamilyProto_Message",
"try",
":",
"pb_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"family_directory",
",",
"\"METADATA.pb\"",
")",
"get_FamilyProto_Message",
"(",
"pb_file",
")",
"yield",
"PASS",
",",
"\"METADATA.pb parsed successfuly.\"",
"except",
"text_format",
".",
"ParseError",
"as",
"e",
":",
"yield",
"FAIL",
",",
"(",
"f\"Family metadata at {family_directory} failed to parse.\\n\"",
"f\"TRACEBACK:\\n{e}\"",
")",
"except",
"FileNotFoundError",
":",
"yield",
"SKIP",
",",
"f\"Font family at '{family_directory}' lacks a METADATA.pb file.\""
] | Check METADATA.pb parse correctly. | [
"Check",
"METADATA",
".",
"pb",
"parse",
"correctly",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L420-L432 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_family_equal_numbers_of_glyphs | def com_google_fonts_check_family_equal_numbers_of_glyphs(ttFonts):
"""Fonts have equal numbers of glyphs?"""
# ttFonts is an iterator, so here we make a list from it
# because we'll have to iterate twice in this check implementation:
the_ttFonts = list(ttFonts)
failed = False
max_stylename = None
max_count = 0
max_glyphs = None
for ttFont in the_ttFonts:
fontname = ttFont.reader.file.name
stylename = canonical_stylename(fontname)
this_count = len(ttFont['glyf'].glyphs)
if this_count > max_count:
max_count = this_count
max_stylename = stylename
max_glyphs = set(ttFont['glyf'].glyphs)
for ttFont in the_ttFonts:
fontname = ttFont.reader.file.name
stylename = canonical_stylename(fontname)
these_glyphs = set(ttFont['glyf'].glyphs)
this_count = len(these_glyphs)
if this_count != max_count:
failed = True
all_glyphs = max_glyphs.union(these_glyphs)
common_glyphs = max_glyphs.intersection(these_glyphs)
diff = all_glyphs - common_glyphs
diff_count = len(diff)
if diff_count < 10:
diff = ", ".join(diff)
else:
diff = ", ".join(list(diff)[:10]) + " (and more)"
yield FAIL, (f"{stylename} has {this_count} glyphs while"
f" {max_stylename} has {max_count} glyphs."
f" There are {diff_count} different glyphs"
f" among them: {diff}")
if not failed:
yield PASS, ("All font files in this family have"
" an equal total ammount of glyphs.") | python | def com_google_fonts_check_family_equal_numbers_of_glyphs(ttFonts):
"""Fonts have equal numbers of glyphs?"""
# ttFonts is an iterator, so here we make a list from it
# because we'll have to iterate twice in this check implementation:
the_ttFonts = list(ttFonts)
failed = False
max_stylename = None
max_count = 0
max_glyphs = None
for ttFont in the_ttFonts:
fontname = ttFont.reader.file.name
stylename = canonical_stylename(fontname)
this_count = len(ttFont['glyf'].glyphs)
if this_count > max_count:
max_count = this_count
max_stylename = stylename
max_glyphs = set(ttFont['glyf'].glyphs)
for ttFont in the_ttFonts:
fontname = ttFont.reader.file.name
stylename = canonical_stylename(fontname)
these_glyphs = set(ttFont['glyf'].glyphs)
this_count = len(these_glyphs)
if this_count != max_count:
failed = True
all_glyphs = max_glyphs.union(these_glyphs)
common_glyphs = max_glyphs.intersection(these_glyphs)
diff = all_glyphs - common_glyphs
diff_count = len(diff)
if diff_count < 10:
diff = ", ".join(diff)
else:
diff = ", ".join(list(diff)[:10]) + " (and more)"
yield FAIL, (f"{stylename} has {this_count} glyphs while"
f" {max_stylename} has {max_count} glyphs."
f" There are {diff_count} different glyphs"
f" among them: {diff}")
if not failed:
yield PASS, ("All font files in this family have"
" an equal total ammount of glyphs.") | [
"def",
"com_google_fonts_check_family_equal_numbers_of_glyphs",
"(",
"ttFonts",
")",
":",
"# ttFonts is an iterator, so here we make a list from it",
"# because we'll have to iterate twice in this check implementation:",
"the_ttFonts",
"=",
"list",
"(",
"ttFonts",
")",
"failed",
"=",
"False",
"max_stylename",
"=",
"None",
"max_count",
"=",
"0",
"max_glyphs",
"=",
"None",
"for",
"ttFont",
"in",
"the_ttFonts",
":",
"fontname",
"=",
"ttFont",
".",
"reader",
".",
"file",
".",
"name",
"stylename",
"=",
"canonical_stylename",
"(",
"fontname",
")",
"this_count",
"=",
"len",
"(",
"ttFont",
"[",
"'glyf'",
"]",
".",
"glyphs",
")",
"if",
"this_count",
">",
"max_count",
":",
"max_count",
"=",
"this_count",
"max_stylename",
"=",
"stylename",
"max_glyphs",
"=",
"set",
"(",
"ttFont",
"[",
"'glyf'",
"]",
".",
"glyphs",
")",
"for",
"ttFont",
"in",
"the_ttFonts",
":",
"fontname",
"=",
"ttFont",
".",
"reader",
".",
"file",
".",
"name",
"stylename",
"=",
"canonical_stylename",
"(",
"fontname",
")",
"these_glyphs",
"=",
"set",
"(",
"ttFont",
"[",
"'glyf'",
"]",
".",
"glyphs",
")",
"this_count",
"=",
"len",
"(",
"these_glyphs",
")",
"if",
"this_count",
"!=",
"max_count",
":",
"failed",
"=",
"True",
"all_glyphs",
"=",
"max_glyphs",
".",
"union",
"(",
"these_glyphs",
")",
"common_glyphs",
"=",
"max_glyphs",
".",
"intersection",
"(",
"these_glyphs",
")",
"diff",
"=",
"all_glyphs",
"-",
"common_glyphs",
"diff_count",
"=",
"len",
"(",
"diff",
")",
"if",
"diff_count",
"<",
"10",
":",
"diff",
"=",
"\", \"",
".",
"join",
"(",
"diff",
")",
"else",
":",
"diff",
"=",
"\", \"",
".",
"join",
"(",
"list",
"(",
"diff",
")",
"[",
":",
"10",
"]",
")",
"+",
"\" (and more)\"",
"yield",
"FAIL",
",",
"(",
"f\"{stylename} has {this_count} glyphs while\"",
"f\" {max_stylename} has {max_count} glyphs.\"",
"f\" There are {diff_count} different glyphs\"",
"f\" among them: {diff}\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"All font files in this family have\"",
"\" an equal total ammount of glyphs.\"",
")"
] | Fonts have equal numbers of glyphs? | [
"Fonts",
"have",
"equal",
"numbers",
"of",
"glyphs?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L452-L493 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_family_equal_glyph_names | def com_google_fonts_check_family_equal_glyph_names(ttFonts):
"""Fonts have equal glyph names?"""
fonts = list(ttFonts)
all_glyphnames = set()
for ttFont in fonts:
all_glyphnames |= set(ttFont["glyf"].glyphs.keys())
missing = {}
available = {}
for glyphname in all_glyphnames:
missing[glyphname] = []
available[glyphname] = []
failed = False
for ttFont in fonts:
fontname = ttFont.reader.file.name
these_ones = set(ttFont["glyf"].glyphs.keys())
for glyphname in all_glyphnames:
if glyphname not in these_ones:
failed = True
missing[glyphname].append(fontname)
else:
available[glyphname].append(fontname)
for gn in missing.keys():
if missing[gn]:
available_styles = [style(k) for k in available[gn]]
missing_styles = [style(k) for k in missing[gn]]
if None not in available_styles + missing_styles:
# if possible, use stylenames in the log messages.
avail = ', '.join(available_styles)
miss = ', '.join(missing_styles)
else:
# otherwise, print filenames:
avail = ', '.join(available[gn])
miss = ', '.join(missing[gn])
yield FAIL, (f"Glyphname '{gn}' is defined on {avail}"
f" but is missing on {miss}.")
if not failed:
yield PASS, "All font files have identical glyph names." | python | def com_google_fonts_check_family_equal_glyph_names(ttFonts):
"""Fonts have equal glyph names?"""
fonts = list(ttFonts)
all_glyphnames = set()
for ttFont in fonts:
all_glyphnames |= set(ttFont["glyf"].glyphs.keys())
missing = {}
available = {}
for glyphname in all_glyphnames:
missing[glyphname] = []
available[glyphname] = []
failed = False
for ttFont in fonts:
fontname = ttFont.reader.file.name
these_ones = set(ttFont["glyf"].glyphs.keys())
for glyphname in all_glyphnames:
if glyphname not in these_ones:
failed = True
missing[glyphname].append(fontname)
else:
available[glyphname].append(fontname)
for gn in missing.keys():
if missing[gn]:
available_styles = [style(k) for k in available[gn]]
missing_styles = [style(k) for k in missing[gn]]
if None not in available_styles + missing_styles:
# if possible, use stylenames in the log messages.
avail = ', '.join(available_styles)
miss = ', '.join(missing_styles)
else:
# otherwise, print filenames:
avail = ', '.join(available[gn])
miss = ', '.join(missing[gn])
yield FAIL, (f"Glyphname '{gn}' is defined on {avail}"
f" but is missing on {miss}.")
if not failed:
yield PASS, "All font files have identical glyph names." | [
"def",
"com_google_fonts_check_family_equal_glyph_names",
"(",
"ttFonts",
")",
":",
"fonts",
"=",
"list",
"(",
"ttFonts",
")",
"all_glyphnames",
"=",
"set",
"(",
")",
"for",
"ttFont",
"in",
"fonts",
":",
"all_glyphnames",
"|=",
"set",
"(",
"ttFont",
"[",
"\"glyf\"",
"]",
".",
"glyphs",
".",
"keys",
"(",
")",
")",
"missing",
"=",
"{",
"}",
"available",
"=",
"{",
"}",
"for",
"glyphname",
"in",
"all_glyphnames",
":",
"missing",
"[",
"glyphname",
"]",
"=",
"[",
"]",
"available",
"[",
"glyphname",
"]",
"=",
"[",
"]",
"failed",
"=",
"False",
"for",
"ttFont",
"in",
"fonts",
":",
"fontname",
"=",
"ttFont",
".",
"reader",
".",
"file",
".",
"name",
"these_ones",
"=",
"set",
"(",
"ttFont",
"[",
"\"glyf\"",
"]",
".",
"glyphs",
".",
"keys",
"(",
")",
")",
"for",
"glyphname",
"in",
"all_glyphnames",
":",
"if",
"glyphname",
"not",
"in",
"these_ones",
":",
"failed",
"=",
"True",
"missing",
"[",
"glyphname",
"]",
".",
"append",
"(",
"fontname",
")",
"else",
":",
"available",
"[",
"glyphname",
"]",
".",
"append",
"(",
"fontname",
")",
"for",
"gn",
"in",
"missing",
".",
"keys",
"(",
")",
":",
"if",
"missing",
"[",
"gn",
"]",
":",
"available_styles",
"=",
"[",
"style",
"(",
"k",
")",
"for",
"k",
"in",
"available",
"[",
"gn",
"]",
"]",
"missing_styles",
"=",
"[",
"style",
"(",
"k",
")",
"for",
"k",
"in",
"missing",
"[",
"gn",
"]",
"]",
"if",
"None",
"not",
"in",
"available_styles",
"+",
"missing_styles",
":",
"# if possible, use stylenames in the log messages.",
"avail",
"=",
"', '",
".",
"join",
"(",
"available_styles",
")",
"miss",
"=",
"', '",
".",
"join",
"(",
"missing_styles",
")",
"else",
":",
"# otherwise, print filenames:",
"avail",
"=",
"', '",
".",
"join",
"(",
"available",
"[",
"gn",
"]",
")",
"miss",
"=",
"', '",
".",
"join",
"(",
"missing",
"[",
"gn",
"]",
")",
"yield",
"FAIL",
",",
"(",
"f\"Glyphname '{gn}' is defined on {avail}\"",
"f\" but is missing on {miss}.\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"All font files have identical glyph names.\""
] | Fonts have equal glyph names? | [
"Fonts",
"have",
"equal",
"glyph",
"names?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L500-L542 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | registered_vendor_ids | def registered_vendor_ids():
"""Get a list of vendor IDs from Microsoft's website."""
from bs4 import BeautifulSoup
from pkg_resources import resource_filename
registered_vendor_ids = {}
CACHED = resource_filename('fontbakery',
'data/fontbakery-microsoft-vendorlist.cache')
content = open(CACHED, encoding='utf-8').read()
soup = BeautifulSoup(content, 'html.parser')
IDs = [chr(c + ord('a')) for c in range(ord('z') - ord('a') + 1)]
IDs.append("0-9-")
for section_id in IDs:
section = soup.find('h2', {'id': section_id})
table = section.find_next_sibling('table')
if not table: continue
#print ("table: '{}'".format(table))
for row in table.findAll('tr'):
#print("ROW: '{}'".format(row))
cells = row.findAll('td')
# pad the code to make sure it is a 4 char string,
# otherwise eg "CF " will not be matched to "CF"
code = cells[0].string.strip()
code = code + (4 - len(code)) * ' '
labels = [label for label in cells[1].stripped_strings]
registered_vendor_ids[code] = labels[0]
return registered_vendor_ids | python | def registered_vendor_ids():
"""Get a list of vendor IDs from Microsoft's website."""
from bs4 import BeautifulSoup
from pkg_resources import resource_filename
registered_vendor_ids = {}
CACHED = resource_filename('fontbakery',
'data/fontbakery-microsoft-vendorlist.cache')
content = open(CACHED, encoding='utf-8').read()
soup = BeautifulSoup(content, 'html.parser')
IDs = [chr(c + ord('a')) for c in range(ord('z') - ord('a') + 1)]
IDs.append("0-9-")
for section_id in IDs:
section = soup.find('h2', {'id': section_id})
table = section.find_next_sibling('table')
if not table: continue
#print ("table: '{}'".format(table))
for row in table.findAll('tr'):
#print("ROW: '{}'".format(row))
cells = row.findAll('td')
# pad the code to make sure it is a 4 char string,
# otherwise eg "CF " will not be matched to "CF"
code = cells[0].string.strip()
code = code + (4 - len(code)) * ' '
labels = [label for label in cells[1].stripped_strings]
registered_vendor_ids[code] = labels[0]
return registered_vendor_ids | [
"def",
"registered_vendor_ids",
"(",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"from",
"pkg_resources",
"import",
"resource_filename",
"registered_vendor_ids",
"=",
"{",
"}",
"CACHED",
"=",
"resource_filename",
"(",
"'fontbakery'",
",",
"'data/fontbakery-microsoft-vendorlist.cache'",
")",
"content",
"=",
"open",
"(",
"CACHED",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"read",
"(",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"content",
",",
"'html.parser'",
")",
"IDs",
"=",
"[",
"chr",
"(",
"c",
"+",
"ord",
"(",
"'a'",
")",
")",
"for",
"c",
"in",
"range",
"(",
"ord",
"(",
"'z'",
")",
"-",
"ord",
"(",
"'a'",
")",
"+",
"1",
")",
"]",
"IDs",
".",
"append",
"(",
"\"0-9-\"",
")",
"for",
"section_id",
"in",
"IDs",
":",
"section",
"=",
"soup",
".",
"find",
"(",
"'h2'",
",",
"{",
"'id'",
":",
"section_id",
"}",
")",
"table",
"=",
"section",
".",
"find_next_sibling",
"(",
"'table'",
")",
"if",
"not",
"table",
":",
"continue",
"#print (\"table: '{}'\".format(table))",
"for",
"row",
"in",
"table",
".",
"findAll",
"(",
"'tr'",
")",
":",
"#print(\"ROW: '{}'\".format(row))",
"cells",
"=",
"row",
".",
"findAll",
"(",
"'td'",
")",
"# pad the code to make sure it is a 4 char string,",
"# otherwise eg \"CF \" will not be matched to \"CF\"",
"code",
"=",
"cells",
"[",
"0",
"]",
".",
"string",
".",
"strip",
"(",
")",
"code",
"=",
"code",
"+",
"(",
"4",
"-",
"len",
"(",
"code",
")",
")",
"*",
"' '",
"labels",
"=",
"[",
"label",
"for",
"label",
"in",
"cells",
"[",
"1",
"]",
".",
"stripped_strings",
"]",
"registered_vendor_ids",
"[",
"code",
"]",
"=",
"labels",
"[",
"0",
"]",
"return",
"registered_vendor_ids"
] | Get a list of vendor IDs from Microsoft's website. | [
"Get",
"a",
"list",
"of",
"vendor",
"IDs",
"from",
"Microsoft",
"s",
"website",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L600-L630 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_unwanted_chars | def com_google_fonts_check_name_unwanted_chars(ttFont):
"""Substitute copyright, registered and trademark
symbols in name table entries."""
failed = False
replacement_map = [("\u00a9", '(c)'),
("\u00ae", '(r)'),
("\u2122", '(tm)')]
for name in ttFont['name'].names:
string = str(name.string, encoding=name.getEncoding())
for mark, ascii_repl in replacement_map:
new_string = string.replace(mark, ascii_repl)
if string != new_string:
yield FAIL, ("NAMEID #{} contains symbol that should be"
" replaced by '{}'.").format(name.nameID,
ascii_repl)
failed = True
if not failed:
yield PASS, ("No need to substitute copyright, registered and"
" trademark symbols in name table entries of this font.") | python | def com_google_fonts_check_name_unwanted_chars(ttFont):
"""Substitute copyright, registered and trademark
symbols in name table entries."""
failed = False
replacement_map = [("\u00a9", '(c)'),
("\u00ae", '(r)'),
("\u2122", '(tm)')]
for name in ttFont['name'].names:
string = str(name.string, encoding=name.getEncoding())
for mark, ascii_repl in replacement_map:
new_string = string.replace(mark, ascii_repl)
if string != new_string:
yield FAIL, ("NAMEID #{} contains symbol that should be"
" replaced by '{}'.").format(name.nameID,
ascii_repl)
failed = True
if not failed:
yield PASS, ("No need to substitute copyright, registered and"
" trademark symbols in name table entries of this font.") | [
"def",
"com_google_fonts_check_name_unwanted_chars",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"replacement_map",
"=",
"[",
"(",
"\"\\u00a9\"",
",",
"'(c)'",
")",
",",
"(",
"\"\\u00ae\"",
",",
"'(r)'",
")",
",",
"(",
"\"\\u2122\"",
",",
"'(tm)'",
")",
"]",
"for",
"name",
"in",
"ttFont",
"[",
"'name'",
"]",
".",
"names",
":",
"string",
"=",
"str",
"(",
"name",
".",
"string",
",",
"encoding",
"=",
"name",
".",
"getEncoding",
"(",
")",
")",
"for",
"mark",
",",
"ascii_repl",
"in",
"replacement_map",
":",
"new_string",
"=",
"string",
".",
"replace",
"(",
"mark",
",",
"ascii_repl",
")",
"if",
"string",
"!=",
"new_string",
":",
"yield",
"FAIL",
",",
"(",
"\"NAMEID #{} contains symbol that should be\"",
"\" replaced by '{}'.\"",
")",
".",
"format",
"(",
"name",
".",
"nameID",
",",
"ascii_repl",
")",
"failed",
"=",
"True",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"No need to substitute copyright, registered and\"",
"\" trademark symbols in name table entries of this font.\"",
")"
] | Substitute copyright, registered and trademark
symbols in name table entries. | [
"Substitute",
"copyright",
"registered",
"and",
"trademark",
"symbols",
"in",
"name",
"table",
"entries",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L666-L684 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | licenses | def licenses(family_directory):
"""Get a list of paths for every license
file found in a font project."""
found = []
search_paths = [family_directory]
gitroot = git_rootdir(family_directory)
if gitroot and gitroot not in search_paths:
search_paths.append(gitroot)
for directory in search_paths:
if directory:
for license in ['OFL.txt', 'LICENSE.txt']:
license_path = os.path.join(directory, license)
if os.path.exists(license_path):
found.append(license_path)
return found | python | def licenses(family_directory):
"""Get a list of paths for every license
file found in a font project."""
found = []
search_paths = [family_directory]
gitroot = git_rootdir(family_directory)
if gitroot and gitroot not in search_paths:
search_paths.append(gitroot)
for directory in search_paths:
if directory:
for license in ['OFL.txt', 'LICENSE.txt']:
license_path = os.path.join(directory, license)
if os.path.exists(license_path):
found.append(license_path)
return found | [
"def",
"licenses",
"(",
"family_directory",
")",
":",
"found",
"=",
"[",
"]",
"search_paths",
"=",
"[",
"family_directory",
"]",
"gitroot",
"=",
"git_rootdir",
"(",
"family_directory",
")",
"if",
"gitroot",
"and",
"gitroot",
"not",
"in",
"search_paths",
":",
"search_paths",
".",
"append",
"(",
"gitroot",
")",
"for",
"directory",
"in",
"search_paths",
":",
"if",
"directory",
":",
"for",
"license",
"in",
"[",
"'OFL.txt'",
",",
"'LICENSE.txt'",
"]",
":",
"license_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"license",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"license_path",
")",
":",
"found",
".",
"append",
"(",
"license_path",
")",
"return",
"found"
] | Get a list of paths for every license
file found in a font project. | [
"Get",
"a",
"list",
"of",
"paths",
"for",
"every",
"license",
"file",
"found",
"in",
"a",
"font",
"project",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L740-L755 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_family_has_license | def com_google_fonts_check_family_has_license(licenses):
"""Check font has a license."""
if len(licenses) > 1:
yield FAIL, Message("multiple",
("More than a single license file found."
" Please review."))
elif not licenses:
yield FAIL, Message("no-license",
("No license file was found."
" Please add an OFL.txt or a LICENSE.txt file."
" If you are running fontbakery on a Google Fonts"
" upstream repo, which is fine, just make sure"
" there is a temporary license file in"
" the same folder."))
else:
yield PASS, "Found license at '{}'".format(licenses[0]) | python | def com_google_fonts_check_family_has_license(licenses):
"""Check font has a license."""
if len(licenses) > 1:
yield FAIL, Message("multiple",
("More than a single license file found."
" Please review."))
elif not licenses:
yield FAIL, Message("no-license",
("No license file was found."
" Please add an OFL.txt or a LICENSE.txt file."
" If you are running fontbakery on a Google Fonts"
" upstream repo, which is fine, just make sure"
" there is a temporary license file in"
" the same folder."))
else:
yield PASS, "Found license at '{}'".format(licenses[0]) | [
"def",
"com_google_fonts_check_family_has_license",
"(",
"licenses",
")",
":",
"if",
"len",
"(",
"licenses",
")",
">",
"1",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"multiple\"",
",",
"(",
"\"More than a single license file found.\"",
"\" Please review.\"",
")",
")",
"elif",
"not",
"licenses",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"no-license\"",
",",
"(",
"\"No license file was found.\"",
"\" Please add an OFL.txt or a LICENSE.txt file.\"",
"\" If you are running fontbakery on a Google Fonts\"",
"\" upstream repo, which is fine, just make sure\"",
"\" there is a temporary license file in\"",
"\" the same folder.\"",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Found license at '{}'\"",
".",
"format",
"(",
"licenses",
"[",
"0",
"]",
")"
] | Check font has a license. | [
"Check",
"font",
"has",
"a",
"license",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L775-L790 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_license | def com_google_fonts_check_name_license(ttFont, license):
"""Check copyright namerecords match license file."""
from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT
failed = False
placeholder = PLACEHOLDER_LICENSING_TEXT[license]
entry_found = False
for i, nameRecord in enumerate(ttFont["name"].names):
if nameRecord.nameID == NameID.LICENSE_DESCRIPTION:
entry_found = True
value = nameRecord.toUnicode()
if value != placeholder:
failed = True
yield FAIL, Message("wrong", \
("License file {} exists but"
" NameID {} (LICENSE DESCRIPTION) value"
" on platform {} ({})"
" is not specified for that."
" Value was: \"{}\""
" Must be changed to \"{}\""
"").format(license,
NameID.LICENSE_DESCRIPTION,
nameRecord.platformID,
PlatformID(nameRecord.platformID).name,
value,
placeholder))
if not entry_found:
yield FAIL, Message("missing", \
("Font lacks NameID {} "
"(LICENSE DESCRIPTION). A proper licensing entry"
" must be set.").format(NameID.LICENSE_DESCRIPTION))
elif not failed:
yield PASS, "Licensing entry on name table is correctly set." | python | def com_google_fonts_check_name_license(ttFont, license):
"""Check copyright namerecords match license file."""
from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT
failed = False
placeholder = PLACEHOLDER_LICENSING_TEXT[license]
entry_found = False
for i, nameRecord in enumerate(ttFont["name"].names):
if nameRecord.nameID == NameID.LICENSE_DESCRIPTION:
entry_found = True
value = nameRecord.toUnicode()
if value != placeholder:
failed = True
yield FAIL, Message("wrong", \
("License file {} exists but"
" NameID {} (LICENSE DESCRIPTION) value"
" on platform {} ({})"
" is not specified for that."
" Value was: \"{}\""
" Must be changed to \"{}\""
"").format(license,
NameID.LICENSE_DESCRIPTION,
nameRecord.platformID,
PlatformID(nameRecord.platformID).name,
value,
placeholder))
if not entry_found:
yield FAIL, Message("missing", \
("Font lacks NameID {} "
"(LICENSE DESCRIPTION). A proper licensing entry"
" must be set.").format(NameID.LICENSE_DESCRIPTION))
elif not failed:
yield PASS, "Licensing entry on name table is correctly set." | [
"def",
"com_google_fonts_check_name_license",
"(",
"ttFont",
",",
"license",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"PLACEHOLDER_LICENSING_TEXT",
"failed",
"=",
"False",
"placeholder",
"=",
"PLACEHOLDER_LICENSING_TEXT",
"[",
"license",
"]",
"entry_found",
"=",
"False",
"for",
"i",
",",
"nameRecord",
"in",
"enumerate",
"(",
"ttFont",
"[",
"\"name\"",
"]",
".",
"names",
")",
":",
"if",
"nameRecord",
".",
"nameID",
"==",
"NameID",
".",
"LICENSE_DESCRIPTION",
":",
"entry_found",
"=",
"True",
"value",
"=",
"nameRecord",
".",
"toUnicode",
"(",
")",
"if",
"value",
"!=",
"placeholder",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"wrong\"",
",",
"(",
"\"License file {} exists but\"",
"\" NameID {} (LICENSE DESCRIPTION) value\"",
"\" on platform {} ({})\"",
"\" is not specified for that.\"",
"\" Value was: \\\"{}\\\"\"",
"\" Must be changed to \\\"{}\\\"\"",
"\"\"",
")",
".",
"format",
"(",
"license",
",",
"NameID",
".",
"LICENSE_DESCRIPTION",
",",
"nameRecord",
".",
"platformID",
",",
"PlatformID",
"(",
"nameRecord",
".",
"platformID",
")",
".",
"name",
",",
"value",
",",
"placeholder",
")",
")",
"if",
"not",
"entry_found",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"missing\"",
",",
"(",
"\"Font lacks NameID {} \"",
"\"(LICENSE DESCRIPTION). A proper licensing entry\"",
"\" must be set.\"",
")",
".",
"format",
"(",
"NameID",
".",
"LICENSE_DESCRIPTION",
")",
")",
"elif",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Licensing entry on name table is correctly set.\""
] | Check copyright namerecords match license file. | [
"Check",
"copyright",
"namerecords",
"match",
"license",
"file",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L799-L830 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_license_url | def com_google_fonts_check_name_license_url(ttFont, familyname):
""""License URL matches License text on name table?"""
from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT
LEGACY_UFL_FAMILIES = ["Ubuntu", "UbuntuCondensed", "UbuntuMono"]
LICENSE_URL = {
'OFL.txt': 'http://scripts.sil.org/OFL',
'LICENSE.txt': 'http://www.apache.org/licenses/LICENSE-2.0',
'UFL.txt': 'https://www.ubuntu.com/legal/terms-and-policies/font-licence'
}
LICENSE_NAME = {
'OFL.txt': 'Open Font',
'LICENSE.txt': 'Apache',
'UFL.txt': 'Ubuntu Font License'
}
detected_license = False
for license in ['OFL.txt', 'LICENSE.txt', 'UFL.txt']:
placeholder = PLACEHOLDER_LICENSING_TEXT[license]
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncoding())
if nameRecord.nameID == NameID.LICENSE_DESCRIPTION and\
string == placeholder:
detected_license = license
break
if detected_license == "UFL.txt" and familyname not in LEGACY_UFL_FAMILIES:
yield FAIL, Message("ufl",
("The Ubuntu Font License is only acceptable on"
" the Google Fonts collection for legacy font"
" families that already adopted such license."
" New Families should use eigther Apache or"
" Open Font License."))
else:
found_good_entry = False
if detected_license:
failed = False
expected = LICENSE_URL[detected_license]
for nameRecord in ttFont['name'].names:
if nameRecord.nameID == NameID.LICENSE_INFO_URL:
string = nameRecord.string.decode(nameRecord.getEncoding())
if string == expected:
found_good_entry = True
else:
failed = True
yield FAIL, Message("licensing-inconsistency",
("Licensing inconsistency in name table"
" entries! NameID={} (LICENSE DESCRIPTION)"
" indicates {} licensing, but NameID={}"
" (LICENSE URL) has '{}'. Expected: '{}'"
"").format(NameID.LICENSE_DESCRIPTION,
LICENSE_NAME[detected_license],
NameID.LICENSE_INFO_URL,
string, expected))
if not found_good_entry:
yield FAIL, Message("no-license-found",
("A known license URL must be provided in the"
" NameID {} (LICENSE INFO URL) entry."
" Currently accepted licenses are Apache or"
" Open Font License. For a small set of legacy"
" families the Ubuntu Font License may be"
" acceptable as well."
"").format(NameID.LICENSE_INFO_URL))
else:
if failed:
yield FAIL, Message("bad-entries",
("Even though a valid license URL was seen in"
" NAME table, there were also bad entries."
" Please review NameIDs {} (LICENSE DESCRIPTION)"
" and {} (LICENSE INFO URL)."
"").format(NameID.LICENSE_DESCRIPTION,
NameID.LICENSE_INFO_URL))
else:
yield PASS, "Font has a valid license URL in NAME table." | python | def com_google_fonts_check_name_license_url(ttFont, familyname):
""""License URL matches License text on name table?"""
from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT
LEGACY_UFL_FAMILIES = ["Ubuntu", "UbuntuCondensed", "UbuntuMono"]
LICENSE_URL = {
'OFL.txt': 'http://scripts.sil.org/OFL',
'LICENSE.txt': 'http://www.apache.org/licenses/LICENSE-2.0',
'UFL.txt': 'https://www.ubuntu.com/legal/terms-and-policies/font-licence'
}
LICENSE_NAME = {
'OFL.txt': 'Open Font',
'LICENSE.txt': 'Apache',
'UFL.txt': 'Ubuntu Font License'
}
detected_license = False
for license in ['OFL.txt', 'LICENSE.txt', 'UFL.txt']:
placeholder = PLACEHOLDER_LICENSING_TEXT[license]
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncoding())
if nameRecord.nameID == NameID.LICENSE_DESCRIPTION and\
string == placeholder:
detected_license = license
break
if detected_license == "UFL.txt" and familyname not in LEGACY_UFL_FAMILIES:
yield FAIL, Message("ufl",
("The Ubuntu Font License is only acceptable on"
" the Google Fonts collection for legacy font"
" families that already adopted such license."
" New Families should use eigther Apache or"
" Open Font License."))
else:
found_good_entry = False
if detected_license:
failed = False
expected = LICENSE_URL[detected_license]
for nameRecord in ttFont['name'].names:
if nameRecord.nameID == NameID.LICENSE_INFO_URL:
string = nameRecord.string.decode(nameRecord.getEncoding())
if string == expected:
found_good_entry = True
else:
failed = True
yield FAIL, Message("licensing-inconsistency",
("Licensing inconsistency in name table"
" entries! NameID={} (LICENSE DESCRIPTION)"
" indicates {} licensing, but NameID={}"
" (LICENSE URL) has '{}'. Expected: '{}'"
"").format(NameID.LICENSE_DESCRIPTION,
LICENSE_NAME[detected_license],
NameID.LICENSE_INFO_URL,
string, expected))
if not found_good_entry:
yield FAIL, Message("no-license-found",
("A known license URL must be provided in the"
" NameID {} (LICENSE INFO URL) entry."
" Currently accepted licenses are Apache or"
" Open Font License. For a small set of legacy"
" families the Ubuntu Font License may be"
" acceptable as well."
"").format(NameID.LICENSE_INFO_URL))
else:
if failed:
yield FAIL, Message("bad-entries",
("Even though a valid license URL was seen in"
" NAME table, there were also bad entries."
" Please review NameIDs {} (LICENSE DESCRIPTION)"
" and {} (LICENSE INFO URL)."
"").format(NameID.LICENSE_DESCRIPTION,
NameID.LICENSE_INFO_URL))
else:
yield PASS, "Font has a valid license URL in NAME table." | [
"def",
"com_google_fonts_check_name_license_url",
"(",
"ttFont",
",",
"familyname",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"PLACEHOLDER_LICENSING_TEXT",
"LEGACY_UFL_FAMILIES",
"=",
"[",
"\"Ubuntu\"",
",",
"\"UbuntuCondensed\"",
",",
"\"UbuntuMono\"",
"]",
"LICENSE_URL",
"=",
"{",
"'OFL.txt'",
":",
"'http://scripts.sil.org/OFL'",
",",
"'LICENSE.txt'",
":",
"'http://www.apache.org/licenses/LICENSE-2.0'",
",",
"'UFL.txt'",
":",
"'https://www.ubuntu.com/legal/terms-and-policies/font-licence'",
"}",
"LICENSE_NAME",
"=",
"{",
"'OFL.txt'",
":",
"'Open Font'",
",",
"'LICENSE.txt'",
":",
"'Apache'",
",",
"'UFL.txt'",
":",
"'Ubuntu Font License'",
"}",
"detected_license",
"=",
"False",
"for",
"license",
"in",
"[",
"'OFL.txt'",
",",
"'LICENSE.txt'",
",",
"'UFL.txt'",
"]",
":",
"placeholder",
"=",
"PLACEHOLDER_LICENSING_TEXT",
"[",
"license",
"]",
"for",
"nameRecord",
"in",
"ttFont",
"[",
"'name'",
"]",
".",
"names",
":",
"string",
"=",
"nameRecord",
".",
"string",
".",
"decode",
"(",
"nameRecord",
".",
"getEncoding",
"(",
")",
")",
"if",
"nameRecord",
".",
"nameID",
"==",
"NameID",
".",
"LICENSE_DESCRIPTION",
"and",
"string",
"==",
"placeholder",
":",
"detected_license",
"=",
"license",
"break",
"if",
"detected_license",
"==",
"\"UFL.txt\"",
"and",
"familyname",
"not",
"in",
"LEGACY_UFL_FAMILIES",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"ufl\"",
",",
"(",
"\"The Ubuntu Font License is only acceptable on\"",
"\" the Google Fonts collection for legacy font\"",
"\" families that already adopted such license.\"",
"\" New Families should use eigther Apache or\"",
"\" Open Font License.\"",
")",
")",
"else",
":",
"found_good_entry",
"=",
"False",
"if",
"detected_license",
":",
"failed",
"=",
"False",
"expected",
"=",
"LICENSE_URL",
"[",
"detected_license",
"]",
"for",
"nameRecord",
"in",
"ttFont",
"[",
"'name'",
"]",
".",
"names",
":",
"if",
"nameRecord",
".",
"nameID",
"==",
"NameID",
".",
"LICENSE_INFO_URL",
":",
"string",
"=",
"nameRecord",
".",
"string",
".",
"decode",
"(",
"nameRecord",
".",
"getEncoding",
"(",
")",
")",
"if",
"string",
"==",
"expected",
":",
"found_good_entry",
"=",
"True",
"else",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"licensing-inconsistency\"",
",",
"(",
"\"Licensing inconsistency in name table\"",
"\" entries! NameID={} (LICENSE DESCRIPTION)\"",
"\" indicates {} licensing, but NameID={}\"",
"\" (LICENSE URL) has '{}'. Expected: '{}'\"",
"\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"LICENSE_DESCRIPTION",
",",
"LICENSE_NAME",
"[",
"detected_license",
"]",
",",
"NameID",
".",
"LICENSE_INFO_URL",
",",
"string",
",",
"expected",
")",
")",
"if",
"not",
"found_good_entry",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"no-license-found\"",
",",
"(",
"\"A known license URL must be provided in the\"",
"\" NameID {} (LICENSE INFO URL) entry.\"",
"\" Currently accepted licenses are Apache or\"",
"\" Open Font License. For a small set of legacy\"",
"\" families the Ubuntu Font License may be\"",
"\" acceptable as well.\"",
"\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"LICENSE_INFO_URL",
")",
")",
"else",
":",
"if",
"failed",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"bad-entries\"",
",",
"(",
"\"Even though a valid license URL was seen in\"",
"\" NAME table, there were also bad entries.\"",
"\" Please review NameIDs {} (LICENSE DESCRIPTION)\"",
"\" and {} (LICENSE INFO URL).\"",
"\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"LICENSE_DESCRIPTION",
",",
"NameID",
".",
"LICENSE_INFO_URL",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Font has a valid license URL in NAME table.\""
] | License URL matches License text on name table? | [
"License",
"URL",
"matches",
"License",
"text",
"on",
"name",
"table?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L848-L919 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_description_max_length | def com_google_fonts_check_name_description_max_length(ttFont):
"""Description strings in the name table must not exceed 200 characters."""
failed = False
for name in ttFont['name'].names:
if (name.nameID == NameID.DESCRIPTION and
len(name.string.decode(name.getEncoding())) > 200):
failed = True
break
if failed:
yield WARN, ("A few name table entries with ID={} (NameID.DESCRIPTION)"
" are longer than 200 characters."
" Please check whether those entries are copyright notices"
" mistakenly stored in the description string entries by"
" a bug in an old FontLab version."
" If that's the case, then such copyright notices must be"
" removed from these entries."
"").format(NameID.DESCRIPTION)
else:
yield PASS, "All description name records have reasonably small lengths." | python | def com_google_fonts_check_name_description_max_length(ttFont):
"""Description strings in the name table must not exceed 200 characters."""
failed = False
for name in ttFont['name'].names:
if (name.nameID == NameID.DESCRIPTION and
len(name.string.decode(name.getEncoding())) > 200):
failed = True
break
if failed:
yield WARN, ("A few name table entries with ID={} (NameID.DESCRIPTION)"
" are longer than 200 characters."
" Please check whether those entries are copyright notices"
" mistakenly stored in the description string entries by"
" a bug in an old FontLab version."
" If that's the case, then such copyright notices must be"
" removed from these entries."
"").format(NameID.DESCRIPTION)
else:
yield PASS, "All description name records have reasonably small lengths." | [
"def",
"com_google_fonts_check_name_description_max_length",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"name",
"in",
"ttFont",
"[",
"'name'",
"]",
".",
"names",
":",
"if",
"(",
"name",
".",
"nameID",
"==",
"NameID",
".",
"DESCRIPTION",
"and",
"len",
"(",
"name",
".",
"string",
".",
"decode",
"(",
"name",
".",
"getEncoding",
"(",
")",
")",
")",
">",
"200",
")",
":",
"failed",
"=",
"True",
"break",
"if",
"failed",
":",
"yield",
"WARN",
",",
"(",
"\"A few name table entries with ID={} (NameID.DESCRIPTION)\"",
"\" are longer than 200 characters.\"",
"\" Please check whether those entries are copyright notices\"",
"\" mistakenly stored in the description string entries by\"",
"\" a bug in an old FontLab version.\"",
"\" If that's the case, then such copyright notices must be\"",
"\" removed from these entries.\"",
"\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"DESCRIPTION",
")",
"else",
":",
"yield",
"PASS",
",",
"\"All description name records have reasonably small lengths.\""
] | Description strings in the name table must not exceed 200 characters. | [
"Description",
"strings",
"in",
"the",
"name",
"table",
"must",
"not",
"exceed",
"200",
"characters",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L935-L954 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_hinting_impact | def com_google_fonts_check_hinting_impact(font, ttfautohint_stats):
"""Show hinting filesize impact.
Current implementation simply logs useful info
but there's no fail scenario for this checker."""
hinted = ttfautohint_stats["hinted_size"]
dehinted = ttfautohint_stats["dehinted_size"]
increase = hinted - dehinted
change = (float(hinted)/dehinted - 1) * 100
def filesize_formatting(s):
if s < 1024:
return f"{s} bytes"
elif s < 1024*1024:
return "{:.1f}kb".format(s/1024)
else:
return "{:.1f}Mb".format(s/(1024*1024))
hinted_size = filesize_formatting(hinted)
dehinted_size = filesize_formatting(dehinted)
increase = filesize_formatting(increase)
results_table = "Hinting filesize impact:\n\n"
results_table += f"| | {font} |\n"
results_table += "|:--- | ---:|\n"
results_table += f"| Dehinted Size | {dehinted_size} |\n"
results_table += f"| Hinted Size | {hinted_size} |\n"
results_table += f"| Increase | {increase} |\n"
results_table += f"| Change | {change:.1f} % |\n"
yield INFO, results_table | python | def com_google_fonts_check_hinting_impact(font, ttfautohint_stats):
"""Show hinting filesize impact.
Current implementation simply logs useful info
but there's no fail scenario for this checker."""
hinted = ttfautohint_stats["hinted_size"]
dehinted = ttfautohint_stats["dehinted_size"]
increase = hinted - dehinted
change = (float(hinted)/dehinted - 1) * 100
def filesize_formatting(s):
if s < 1024:
return f"{s} bytes"
elif s < 1024*1024:
return "{:.1f}kb".format(s/1024)
else:
return "{:.1f}Mb".format(s/(1024*1024))
hinted_size = filesize_formatting(hinted)
dehinted_size = filesize_formatting(dehinted)
increase = filesize_formatting(increase)
results_table = "Hinting filesize impact:\n\n"
results_table += f"| | {font} |\n"
results_table += "|:--- | ---:|\n"
results_table += f"| Dehinted Size | {dehinted_size} |\n"
results_table += f"| Hinted Size | {hinted_size} |\n"
results_table += f"| Increase | {increase} |\n"
results_table += f"| Change | {change:.1f} % |\n"
yield INFO, results_table | [
"def",
"com_google_fonts_check_hinting_impact",
"(",
"font",
",",
"ttfautohint_stats",
")",
":",
"hinted",
"=",
"ttfautohint_stats",
"[",
"\"hinted_size\"",
"]",
"dehinted",
"=",
"ttfautohint_stats",
"[",
"\"dehinted_size\"",
"]",
"increase",
"=",
"hinted",
"-",
"dehinted",
"change",
"=",
"(",
"float",
"(",
"hinted",
")",
"/",
"dehinted",
"-",
"1",
")",
"*",
"100",
"def",
"filesize_formatting",
"(",
"s",
")",
":",
"if",
"s",
"<",
"1024",
":",
"return",
"f\"{s} bytes\"",
"elif",
"s",
"<",
"1024",
"*",
"1024",
":",
"return",
"\"{:.1f}kb\"",
".",
"format",
"(",
"s",
"/",
"1024",
")",
"else",
":",
"return",
"\"{:.1f}Mb\"",
".",
"format",
"(",
"s",
"/",
"(",
"1024",
"*",
"1024",
")",
")",
"hinted_size",
"=",
"filesize_formatting",
"(",
"hinted",
")",
"dehinted_size",
"=",
"filesize_formatting",
"(",
"dehinted",
")",
"increase",
"=",
"filesize_formatting",
"(",
"increase",
")",
"results_table",
"=",
"\"Hinting filesize impact:\\n\\n\"",
"results_table",
"+=",
"f\"| | {font} |\\n\"",
"results_table",
"+=",
"\"|:--- | ---:|\\n\"",
"results_table",
"+=",
"f\"| Dehinted Size | {dehinted_size} |\\n\"",
"results_table",
"+=",
"f\"| Hinted Size | {hinted_size} |\\n\"",
"results_table",
"+=",
"f\"| Increase | {increase} |\\n\"",
"results_table",
"+=",
"f\"| Change | {change:.1f} % |\\n\"",
"yield",
"INFO",
",",
"results_table"
] | Show hinting filesize impact.
Current implementation simply logs useful info
but there's no fail scenario for this checker. | [
"Show",
"hinting",
"filesize",
"impact",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L982-L1012 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_version_format | def com_google_fonts_check_name_version_format(ttFont):
"""Version format is correct in 'name' table?"""
from fontbakery.utils import get_name_entry_strings
import re
def is_valid_version_format(value):
return re.match(r'Version\s0*[1-9]+\.\d+', value)
failed = False
version_entries = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
if len(version_entries) == 0:
failed = True
yield FAIL, Message("no-version-string",
("Font lacks a NameID.VERSION_STRING (nameID={})"
" entry").format(NameID.VERSION_STRING))
for ventry in version_entries:
if not is_valid_version_format(ventry):
failed = True
yield FAIL, Message("bad-version-strings",
("The NameID.VERSION_STRING (nameID={}) value must"
" follow the pattern \"Version X.Y\" with X.Y"
" between 1.000 and 9.999."
" Current version string is:"
" \"{}\"").format(NameID.VERSION_STRING,
ventry))
if not failed:
yield PASS, "Version format in NAME table entries is correct." | python | def com_google_fonts_check_name_version_format(ttFont):
"""Version format is correct in 'name' table?"""
from fontbakery.utils import get_name_entry_strings
import re
def is_valid_version_format(value):
return re.match(r'Version\s0*[1-9]+\.\d+', value)
failed = False
version_entries = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
if len(version_entries) == 0:
failed = True
yield FAIL, Message("no-version-string",
("Font lacks a NameID.VERSION_STRING (nameID={})"
" entry").format(NameID.VERSION_STRING))
for ventry in version_entries:
if not is_valid_version_format(ventry):
failed = True
yield FAIL, Message("bad-version-strings",
("The NameID.VERSION_STRING (nameID={}) value must"
" follow the pattern \"Version X.Y\" with X.Y"
" between 1.000 and 9.999."
" Current version string is:"
" \"{}\"").format(NameID.VERSION_STRING,
ventry))
if not failed:
yield PASS, "Version format in NAME table entries is correct." | [
"def",
"com_google_fonts_check_name_version_format",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"import",
"re",
"def",
"is_valid_version_format",
"(",
"value",
")",
":",
"return",
"re",
".",
"match",
"(",
"r'Version\\s0*[1-9]+\\.\\d+'",
",",
"value",
")",
"failed",
"=",
"False",
"version_entries",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"VERSION_STRING",
")",
"if",
"len",
"(",
"version_entries",
")",
"==",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"no-version-string\"",
",",
"(",
"\"Font lacks a NameID.VERSION_STRING (nameID={})\"",
"\" entry\"",
")",
".",
"format",
"(",
"NameID",
".",
"VERSION_STRING",
")",
")",
"for",
"ventry",
"in",
"version_entries",
":",
"if",
"not",
"is_valid_version_format",
"(",
"ventry",
")",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"bad-version-strings\"",
",",
"(",
"\"The NameID.VERSION_STRING (nameID={}) value must\"",
"\" follow the pattern \\\"Version X.Y\\\" with X.Y\"",
"\" between 1.000 and 9.999.\"",
"\" Current version string is:\"",
"\" \\\"{}\\\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"VERSION_STRING",
",",
"ventry",
")",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Version format in NAME table entries is correct.\""
] | Version format is correct in 'name' table? | [
"Version",
"format",
"is",
"correct",
"in",
"name",
"table?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1018-L1043 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_has_ttfautohint_params | def com_google_fonts_check_has_ttfautohint_params(ttFont):
""" Font has ttfautohint params? """
from fontbakery.utils import get_name_entry_strings
def ttfautohint_version(value):
# example string:
#'Version 1.000; ttfautohint (v0.93) -l 8 -r 50 -G 200 -x 14 -w "G"
import re
results = re.search(r'ttfautohint \(v(.*)\) ([^;]*)', value)
if results:
return results.group(1), results.group(2)
version_strings = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
failed = True
for vstring in version_strings:
values = ttfautohint_version(vstring)
if values:
ttfa_version, params = values
if params:
yield PASS, f"Font has ttfautohint params ({params})"
failed = False
else:
yield SKIP, "Font appears to our heuristic as not hinted using ttfautohint."
failed = False
if failed:
yield FAIL, "Font is lacking ttfautohint params on its version strings on the name table." | python | def com_google_fonts_check_has_ttfautohint_params(ttFont):
""" Font has ttfautohint params? """
from fontbakery.utils import get_name_entry_strings
def ttfautohint_version(value):
# example string:
#'Version 1.000; ttfautohint (v0.93) -l 8 -r 50 -G 200 -x 14 -w "G"
import re
results = re.search(r'ttfautohint \(v(.*)\) ([^;]*)', value)
if results:
return results.group(1), results.group(2)
version_strings = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
failed = True
for vstring in version_strings:
values = ttfautohint_version(vstring)
if values:
ttfa_version, params = values
if params:
yield PASS, f"Font has ttfautohint params ({params})"
failed = False
else:
yield SKIP, "Font appears to our heuristic as not hinted using ttfautohint."
failed = False
if failed:
yield FAIL, "Font is lacking ttfautohint params on its version strings on the name table." | [
"def",
"com_google_fonts_check_has_ttfautohint_params",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"def",
"ttfautohint_version",
"(",
"value",
")",
":",
"# example string:",
"#'Version 1.000; ttfautohint (v0.93) -l 8 -r 50 -G 200 -x 14 -w \"G\"",
"import",
"re",
"results",
"=",
"re",
".",
"search",
"(",
"r'ttfautohint \\(v(.*)\\) ([^;]*)'",
",",
"value",
")",
"if",
"results",
":",
"return",
"results",
".",
"group",
"(",
"1",
")",
",",
"results",
".",
"group",
"(",
"2",
")",
"version_strings",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"VERSION_STRING",
")",
"failed",
"=",
"True",
"for",
"vstring",
"in",
"version_strings",
":",
"values",
"=",
"ttfautohint_version",
"(",
"vstring",
")",
"if",
"values",
":",
"ttfa_version",
",",
"params",
"=",
"values",
"if",
"params",
":",
"yield",
"PASS",
",",
"f\"Font has ttfautohint params ({params})\"",
"failed",
"=",
"False",
"else",
":",
"yield",
"SKIP",
",",
"\"Font appears to our heuristic as not hinted using ttfautohint.\"",
"failed",
"=",
"False",
"if",
"failed",
":",
"yield",
"FAIL",
",",
"\"Font is lacking ttfautohint params on its version strings on the name table.\""
] | Font has ttfautohint params? | [
"Font",
"has",
"ttfautohint",
"params?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1049-L1075 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_old_ttfautohint | def com_google_fonts_check_old_ttfautohint(ttFont, ttfautohint_stats):
"""Font has old ttfautohint applied?
1. find which version was used, by inspecting name table entries
2. find which version of ttfautohint is installed
"""
from fontbakery.utils import get_name_entry_strings
def ttfautohint_version(values):
import re
for value in values:
results = re.search(r'ttfautohint \(v(.*)\)', value)
if results:
return results.group(1)
def installed_version_is_newer(installed, used):
installed = list(map(int, installed.split(".")))
used = list(map(int, used.split(".")))
return installed > used
if not ttfautohint_stats:
yield ERROR, "ttfautohint is not available."
return
version_strings = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
ttfa_version = ttfautohint_version(version_strings)
if len(version_strings) == 0:
yield FAIL, Message("lacks-version-strings",
"This font file lacks mandatory "
"version strings in its name table.")
elif ttfa_version is None:
yield INFO, ("Could not detect which version of"
" ttfautohint was used in this font."
" It is typically specified as a comment"
" in the font version entries of the 'name' table."
" Such font version strings are currently:"
" {}").format(version_strings)
else:
installed_ttfa = ttfautohint_stats["version"]
try:
if installed_version_is_newer(installed_ttfa,
ttfa_version):
yield WARN, ("ttfautohint used in font = {};"
" installed = {}; Need to re-run"
" with the newer version!").format(ttfa_version,
installed_ttfa)
else:
yield PASS, (f"ttfautohint available in the system ({installed_ttfa}) is older"
f" than the one used in the font ({ttfa_version}).")
except ValueError:
yield FAIL, Message("parse-error",
("Failed to parse ttfautohint version values:"
" installed = '{}';"
" used_in_font = '{}'").format(installed_ttfa,
ttfa_version)) | python | def com_google_fonts_check_old_ttfautohint(ttFont, ttfautohint_stats):
"""Font has old ttfautohint applied?
1. find which version was used, by inspecting name table entries
2. find which version of ttfautohint is installed
"""
from fontbakery.utils import get_name_entry_strings
def ttfautohint_version(values):
import re
for value in values:
results = re.search(r'ttfautohint \(v(.*)\)', value)
if results:
return results.group(1)
def installed_version_is_newer(installed, used):
installed = list(map(int, installed.split(".")))
used = list(map(int, used.split(".")))
return installed > used
if not ttfautohint_stats:
yield ERROR, "ttfautohint is not available."
return
version_strings = get_name_entry_strings(ttFont, NameID.VERSION_STRING)
ttfa_version = ttfautohint_version(version_strings)
if len(version_strings) == 0:
yield FAIL, Message("lacks-version-strings",
"This font file lacks mandatory "
"version strings in its name table.")
elif ttfa_version is None:
yield INFO, ("Could not detect which version of"
" ttfautohint was used in this font."
" It is typically specified as a comment"
" in the font version entries of the 'name' table."
" Such font version strings are currently:"
" {}").format(version_strings)
else:
installed_ttfa = ttfautohint_stats["version"]
try:
if installed_version_is_newer(installed_ttfa,
ttfa_version):
yield WARN, ("ttfautohint used in font = {};"
" installed = {}; Need to re-run"
" with the newer version!").format(ttfa_version,
installed_ttfa)
else:
yield PASS, (f"ttfautohint available in the system ({installed_ttfa}) is older"
f" than the one used in the font ({ttfa_version}).")
except ValueError:
yield FAIL, Message("parse-error",
("Failed to parse ttfautohint version values:"
" installed = '{}';"
" used_in_font = '{}'").format(installed_ttfa,
ttfa_version)) | [
"def",
"com_google_fonts_check_old_ttfautohint",
"(",
"ttFont",
",",
"ttfautohint_stats",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"def",
"ttfautohint_version",
"(",
"values",
")",
":",
"import",
"re",
"for",
"value",
"in",
"values",
":",
"results",
"=",
"re",
".",
"search",
"(",
"r'ttfautohint \\(v(.*)\\)'",
",",
"value",
")",
"if",
"results",
":",
"return",
"results",
".",
"group",
"(",
"1",
")",
"def",
"installed_version_is_newer",
"(",
"installed",
",",
"used",
")",
":",
"installed",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"installed",
".",
"split",
"(",
"\".\"",
")",
")",
")",
"used",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"used",
".",
"split",
"(",
"\".\"",
")",
")",
")",
"return",
"installed",
">",
"used",
"if",
"not",
"ttfautohint_stats",
":",
"yield",
"ERROR",
",",
"\"ttfautohint is not available.\"",
"return",
"version_strings",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"VERSION_STRING",
")",
"ttfa_version",
"=",
"ttfautohint_version",
"(",
"version_strings",
")",
"if",
"len",
"(",
"version_strings",
")",
"==",
"0",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"lacks-version-strings\"",
",",
"\"This font file lacks mandatory \"",
"\"version strings in its name table.\"",
")",
"elif",
"ttfa_version",
"is",
"None",
":",
"yield",
"INFO",
",",
"(",
"\"Could not detect which version of\"",
"\" ttfautohint was used in this font.\"",
"\" It is typically specified as a comment\"",
"\" in the font version entries of the 'name' table.\"",
"\" Such font version strings are currently:\"",
"\" {}\"",
")",
".",
"format",
"(",
"version_strings",
")",
"else",
":",
"installed_ttfa",
"=",
"ttfautohint_stats",
"[",
"\"version\"",
"]",
"try",
":",
"if",
"installed_version_is_newer",
"(",
"installed_ttfa",
",",
"ttfa_version",
")",
":",
"yield",
"WARN",
",",
"(",
"\"ttfautohint used in font = {};\"",
"\" installed = {}; Need to re-run\"",
"\" with the newer version!\"",
")",
".",
"format",
"(",
"ttfa_version",
",",
"installed_ttfa",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"f\"ttfautohint available in the system ({installed_ttfa}) is older\"",
"f\" than the one used in the font ({ttfa_version}).\"",
")",
"except",
"ValueError",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"parse-error\"",
",",
"(",
"\"Failed to parse ttfautohint version values:\"",
"\" installed = '{}';\"",
"\" used_in_font = '{}'\"",
")",
".",
"format",
"(",
"installed_ttfa",
",",
"ttfa_version",
")",
")"
] | Font has old ttfautohint applied?
1. find which version was used, by inspecting name table entries
2. find which version of ttfautohint is installed | [
"Font",
"has",
"old",
"ttfautohint",
"applied?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1082-L1137 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_gasp | def com_google_fonts_check_gasp(ttFont):
"""Is 'gasp' table set to optimize rendering?"""
if "gasp" not in ttFont.keys():
yield FAIL, ("Font is missing the 'gasp' table."
" Try exporting the font with autohinting enabled.")
else:
if not isinstance(ttFont["gasp"].gaspRange, dict):
yield FAIL, "'gasp' table has no values."
else:
failed = False
if 0xFFFF not in ttFont["gasp"].gaspRange:
yield WARN, ("'gasp' table does not have an entry for all"
" font sizes (gaspRange 0xFFFF).")
else:
gasp_meaning = {
0x01: "- Use gridfitting",
0x02: "- Use grayscale rendering",
0x04: "- Use gridfitting with ClearType symmetric smoothing",
0x08: "- Use smoothing along multiple axes with ClearType®"
}
table = []
for key in ttFont["gasp"].gaspRange.keys():
value = ttFont["gasp"].gaspRange[key]
meaning = []
for flag, info in gasp_meaning.items():
if value & flag:
meaning.append(info)
meaning = "\n\t".join(meaning)
table.append(f"PPM <= {key}:\n\tflag = 0x{value:02X}\n\t{meaning}")
table = "\n".join(table)
yield INFO, ("These are the ppm ranges declared on the"
f" gasp table:\n\n{table}\n")
for key in ttFont["gasp"].gaspRange.keys():
if key != 0xFFFF:
yield WARN, ("'gasp' table has a gaspRange of {} that"
" may be unneccessary.").format(key)
failed = True
else:
value = ttFont["gasp"].gaspRange[0xFFFF]
if value != 0x0F:
failed = True
yield WARN, (f"gaspRange 0xFFFF value 0x{value:02X}"
" should be set to 0x0F.")
if not failed:
yield PASS, ("'gasp' table is correctly set, with one "
"gaspRange:value of 0xFFFF:0x0F.") | python | def com_google_fonts_check_gasp(ttFont):
"""Is 'gasp' table set to optimize rendering?"""
if "gasp" not in ttFont.keys():
yield FAIL, ("Font is missing the 'gasp' table."
" Try exporting the font with autohinting enabled.")
else:
if not isinstance(ttFont["gasp"].gaspRange, dict):
yield FAIL, "'gasp' table has no values."
else:
failed = False
if 0xFFFF not in ttFont["gasp"].gaspRange:
yield WARN, ("'gasp' table does not have an entry for all"
" font sizes (gaspRange 0xFFFF).")
else:
gasp_meaning = {
0x01: "- Use gridfitting",
0x02: "- Use grayscale rendering",
0x04: "- Use gridfitting with ClearType symmetric smoothing",
0x08: "- Use smoothing along multiple axes with ClearType®"
}
table = []
for key in ttFont["gasp"].gaspRange.keys():
value = ttFont["gasp"].gaspRange[key]
meaning = []
for flag, info in gasp_meaning.items():
if value & flag:
meaning.append(info)
meaning = "\n\t".join(meaning)
table.append(f"PPM <= {key}:\n\tflag = 0x{value:02X}\n\t{meaning}")
table = "\n".join(table)
yield INFO, ("These are the ppm ranges declared on the"
f" gasp table:\n\n{table}\n")
for key in ttFont["gasp"].gaspRange.keys():
if key != 0xFFFF:
yield WARN, ("'gasp' table has a gaspRange of {} that"
" may be unneccessary.").format(key)
failed = True
else:
value = ttFont["gasp"].gaspRange[0xFFFF]
if value != 0x0F:
failed = True
yield WARN, (f"gaspRange 0xFFFF value 0x{value:02X}"
" should be set to 0x0F.")
if not failed:
yield PASS, ("'gasp' table is correctly set, with one "
"gaspRange:value of 0xFFFF:0x0F.") | [
"def",
"com_google_fonts_check_gasp",
"(",
"ttFont",
")",
":",
"if",
"\"gasp\"",
"not",
"in",
"ttFont",
".",
"keys",
"(",
")",
":",
"yield",
"FAIL",
",",
"(",
"\"Font is missing the 'gasp' table.\"",
"\" Try exporting the font with autohinting enabled.\"",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
",",
"dict",
")",
":",
"yield",
"FAIL",
",",
"\"'gasp' table has no values.\"",
"else",
":",
"failed",
"=",
"False",
"if",
"0xFFFF",
"not",
"in",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
":",
"yield",
"WARN",
",",
"(",
"\"'gasp' table does not have an entry for all\"",
"\" font sizes (gaspRange 0xFFFF).\"",
")",
"else",
":",
"gasp_meaning",
"=",
"{",
"0x01",
":",
"\"- Use gridfitting\"",
",",
"0x02",
":",
"\"- Use grayscale rendering\"",
",",
"0x04",
":",
"\"- Use gridfitting with ClearType symmetric smoothing\"",
",",
"0x08",
":",
"\"- Use smoothing along multiple axes with ClearType®\"",
"}",
"table",
"=",
"[",
"]",
"for",
"key",
"in",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
".",
"keys",
"(",
")",
":",
"value",
"=",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
"[",
"key",
"]",
"meaning",
"=",
"[",
"]",
"for",
"flag",
",",
"info",
"in",
"gasp_meaning",
".",
"items",
"(",
")",
":",
"if",
"value",
"&",
"flag",
":",
"meaning",
".",
"append",
"(",
"info",
")",
"meaning",
"=",
"\"\\n\\t\"",
".",
"join",
"(",
"meaning",
")",
"table",
".",
"append",
"(",
"f\"PPM <= {key}:\\n\\tflag = 0x{value:02X}\\n\\t{meaning}\"",
")",
"table",
"=",
"\"\\n\"",
".",
"join",
"(",
"table",
")",
"yield",
"INFO",
",",
"(",
"\"These are the ppm ranges declared on the\"",
"f\" gasp table:\\n\\n{table}\\n\"",
")",
"for",
"key",
"in",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
".",
"keys",
"(",
")",
":",
"if",
"key",
"!=",
"0xFFFF",
":",
"yield",
"WARN",
",",
"(",
"\"'gasp' table has a gaspRange of {} that\"",
"\" may be unneccessary.\"",
")",
".",
"format",
"(",
"key",
")",
"failed",
"=",
"True",
"else",
":",
"value",
"=",
"ttFont",
"[",
"\"gasp\"",
"]",
".",
"gaspRange",
"[",
"0xFFFF",
"]",
"if",
"value",
"!=",
"0x0F",
":",
"failed",
"=",
"True",
"yield",
"WARN",
",",
"(",
"f\"gaspRange 0xFFFF value 0x{value:02X}\"",
"\" should be set to 0x0F.\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"'gasp' table is correctly set, with one \"",
"\"gaspRange:value of 0xFFFF:0x0F.\"",
")"
] | Is 'gasp' table set to optimize rendering? | [
"Is",
"gasp",
"table",
"set",
"to",
"optimize",
"rendering?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1185-L1234 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_familyname_first_char | def com_google_fonts_check_name_familyname_first_char(ttFont):
"""Make sure family name does not begin with a digit.
Font family names which start with a numeral are often not
discoverable in Windows applications.
"""
from fontbakery.utils import get_name_entry_strings
failed = False
for familyname in get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME):
digits = map(str, range(0, 10))
if familyname[0] in digits:
yield FAIL, ("Font family name '{}'"
" begins with a digit!").format(familyname)
failed = True
if failed is False:
yield PASS, "Font family name first character is not a digit." | python | def com_google_fonts_check_name_familyname_first_char(ttFont):
"""Make sure family name does not begin with a digit.
Font family names which start with a numeral are often not
discoverable in Windows applications.
"""
from fontbakery.utils import get_name_entry_strings
failed = False
for familyname in get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME):
digits = map(str, range(0, 10))
if familyname[0] in digits:
yield FAIL, ("Font family name '{}'"
" begins with a digit!").format(familyname)
failed = True
if failed is False:
yield PASS, "Font family name first character is not a digit." | [
"def",
"com_google_fonts_check_name_familyname_first_char",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"failed",
"=",
"False",
"for",
"familyname",
"in",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
":",
"digits",
"=",
"map",
"(",
"str",
",",
"range",
"(",
"0",
",",
"10",
")",
")",
"if",
"familyname",
"[",
"0",
"]",
"in",
"digits",
":",
"yield",
"FAIL",
",",
"(",
"\"Font family name '{}'\"",
"\" begins with a digit!\"",
")",
".",
"format",
"(",
"familyname",
")",
"failed",
"=",
"True",
"if",
"failed",
"is",
"False",
":",
"yield",
"PASS",
",",
"\"Font family name first character is not a digit.\""
] | Make sure family name does not begin with a digit.
Font family names which start with a numeral are often not
discoverable in Windows applications. | [
"Make",
"sure",
"family",
"name",
"does",
"not",
"begin",
"with",
"a",
"digit",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1240-L1255 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_currency_chars | def com_google_fonts_check_currency_chars(ttFont):
"""Font has all expected currency sign characters?"""
def font_has_char(ttFont, codepoint):
for subtable in ttFont['cmap'].tables:
if codepoint in subtable.cmap:
return True
#otherwise
return False
failed = False
OPTIONAL = {
#TODO: Do we want to check for this one?
#0x20A0: "EUROPEAN CURRENCY SIGN"
}
MANDATORY = {
0x20AC: "EURO SIGN"
# TODO: extend this list
}
for codepoint, charname in OPTIONAL.items():
if not font_has_char(ttFont, codepoint):
failed = True
yield WARN, f"Font lacks \"{charname}\" character (unicode: 0x{codepoint:04X})"
for codepoint, charname in MANDATORY.items():
if not font_has_char(ttFont, codepoint):
failed = True
yield FAIL, f"Font lacks \"{charname}\" character (unicode: 0x{codepoint:04X})"
if not failed:
yield PASS, "Font has all expected currency sign characters." | python | def com_google_fonts_check_currency_chars(ttFont):
"""Font has all expected currency sign characters?"""
def font_has_char(ttFont, codepoint):
for subtable in ttFont['cmap'].tables:
if codepoint in subtable.cmap:
return True
#otherwise
return False
failed = False
OPTIONAL = {
#TODO: Do we want to check for this one?
#0x20A0: "EUROPEAN CURRENCY SIGN"
}
MANDATORY = {
0x20AC: "EURO SIGN"
# TODO: extend this list
}
for codepoint, charname in OPTIONAL.items():
if not font_has_char(ttFont, codepoint):
failed = True
yield WARN, f"Font lacks \"{charname}\" character (unicode: 0x{codepoint:04X})"
for codepoint, charname in MANDATORY.items():
if not font_has_char(ttFont, codepoint):
failed = True
yield FAIL, f"Font lacks \"{charname}\" character (unicode: 0x{codepoint:04X})"
if not failed:
yield PASS, "Font has all expected currency sign characters." | [
"def",
"com_google_fonts_check_currency_chars",
"(",
"ttFont",
")",
":",
"def",
"font_has_char",
"(",
"ttFont",
",",
"codepoint",
")",
":",
"for",
"subtable",
"in",
"ttFont",
"[",
"'cmap'",
"]",
".",
"tables",
":",
"if",
"codepoint",
"in",
"subtable",
".",
"cmap",
":",
"return",
"True",
"#otherwise",
"return",
"False",
"failed",
"=",
"False",
"OPTIONAL",
"=",
"{",
"#TODO: Do we want to check for this one?",
"#0x20A0: \"EUROPEAN CURRENCY SIGN\"",
"}",
"MANDATORY",
"=",
"{",
"0x20AC",
":",
"\"EURO SIGN\"",
"# TODO: extend this list",
"}",
"for",
"codepoint",
",",
"charname",
"in",
"OPTIONAL",
".",
"items",
"(",
")",
":",
"if",
"not",
"font_has_char",
"(",
"ttFont",
",",
"codepoint",
")",
":",
"failed",
"=",
"True",
"yield",
"WARN",
",",
"f\"Font lacks \\\"{charname}\\\" character (unicode: 0x{codepoint:04X})\"",
"for",
"codepoint",
",",
"charname",
"in",
"MANDATORY",
".",
"items",
"(",
")",
":",
"if",
"not",
"font_has_char",
"(",
"ttFont",
",",
"codepoint",
")",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"f\"Font lacks \\\"{charname}\\\" character (unicode: 0x{codepoint:04X})\"",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Font has all expected currency sign characters.\""
] | Font has all expected currency sign characters? | [
"Font",
"has",
"all",
"expected",
"currency",
"sign",
"characters?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1262-L1293 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_ascii_only_entries | def com_google_fonts_check_name_ascii_only_entries(ttFont):
"""Are there non-ASCII characters in ASCII-only NAME table entries?"""
bad_entries = []
for name in ttFont["name"].names:
if name.nameID == NameID.COPYRIGHT_NOTICE or \
name.nameID == NameID.POSTSCRIPT_NAME:
string = name.string.decode(name.getEncoding())
try:
string.encode('ascii')
except:
bad_entries.append(name)
yield INFO, ("Bad string at"
" [nameID {}, '{}']:"
" '{}'"
"").format(name.nameID,
name.getEncoding(),
string.encode("ascii",
errors='xmlcharrefreplace'))
if len(bad_entries) > 0:
yield FAIL, ("There are {} strings containing"
" non-ASCII characters in the ASCII-only"
" NAME table entries.").format(len(bad_entries))
else:
yield PASS, ("None of the ASCII-only NAME table entries"
" contain non-ASCII characteres.") | python | def com_google_fonts_check_name_ascii_only_entries(ttFont):
"""Are there non-ASCII characters in ASCII-only NAME table entries?"""
bad_entries = []
for name in ttFont["name"].names:
if name.nameID == NameID.COPYRIGHT_NOTICE or \
name.nameID == NameID.POSTSCRIPT_NAME:
string = name.string.decode(name.getEncoding())
try:
string.encode('ascii')
except:
bad_entries.append(name)
yield INFO, ("Bad string at"
" [nameID {}, '{}']:"
" '{}'"
"").format(name.nameID,
name.getEncoding(),
string.encode("ascii",
errors='xmlcharrefreplace'))
if len(bad_entries) > 0:
yield FAIL, ("There are {} strings containing"
" non-ASCII characters in the ASCII-only"
" NAME table entries.").format(len(bad_entries))
else:
yield PASS, ("None of the ASCII-only NAME table entries"
" contain non-ASCII characteres.") | [
"def",
"com_google_fonts_check_name_ascii_only_entries",
"(",
"ttFont",
")",
":",
"bad_entries",
"=",
"[",
"]",
"for",
"name",
"in",
"ttFont",
"[",
"\"name\"",
"]",
".",
"names",
":",
"if",
"name",
".",
"nameID",
"==",
"NameID",
".",
"COPYRIGHT_NOTICE",
"or",
"name",
".",
"nameID",
"==",
"NameID",
".",
"POSTSCRIPT_NAME",
":",
"string",
"=",
"name",
".",
"string",
".",
"decode",
"(",
"name",
".",
"getEncoding",
"(",
")",
")",
"try",
":",
"string",
".",
"encode",
"(",
"'ascii'",
")",
"except",
":",
"bad_entries",
".",
"append",
"(",
"name",
")",
"yield",
"INFO",
",",
"(",
"\"Bad string at\"",
"\" [nameID {}, '{}']:\"",
"\" '{}'\"",
"\"\"",
")",
".",
"format",
"(",
"name",
".",
"nameID",
",",
"name",
".",
"getEncoding",
"(",
")",
",",
"string",
".",
"encode",
"(",
"\"ascii\"",
",",
"errors",
"=",
"'xmlcharrefreplace'",
")",
")",
"if",
"len",
"(",
"bad_entries",
")",
">",
"0",
":",
"yield",
"FAIL",
",",
"(",
"\"There are {} strings containing\"",
"\" non-ASCII characters in the ASCII-only\"",
"\" NAME table entries.\"",
")",
".",
"format",
"(",
"len",
"(",
"bad_entries",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"None of the ASCII-only NAME table entries\"",
"\" contain non-ASCII characteres.\"",
")"
] | Are there non-ASCII characters in ASCII-only NAME table entries? | [
"Are",
"there",
"non",
"-",
"ASCII",
"characters",
"in",
"ASCII",
"-",
"only",
"NAME",
"table",
"entries?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1313-L1337 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_license | def com_google_fonts_check_metadata_license(family_metadata):
"""METADATA.pb license is "APACHE2", "UFL" or "OFL"?"""
licenses = ["APACHE2", "OFL", "UFL"]
if family_metadata.license in licenses:
yield PASS, ("Font license is declared"
" in METADATA.pb as \"{}\"").format(family_metadata.license)
else:
yield FAIL, ("METADATA.pb license field (\"{}\")"
" must be one of the following:"
" {}").format(family_metadata.license,
licenses) | python | def com_google_fonts_check_metadata_license(family_metadata):
"""METADATA.pb license is "APACHE2", "UFL" or "OFL"?"""
licenses = ["APACHE2", "OFL", "UFL"]
if family_metadata.license in licenses:
yield PASS, ("Font license is declared"
" in METADATA.pb as \"{}\"").format(family_metadata.license)
else:
yield FAIL, ("METADATA.pb license field (\"{}\")"
" must be one of the following:"
" {}").format(family_metadata.license,
licenses) | [
"def",
"com_google_fonts_check_metadata_license",
"(",
"family_metadata",
")",
":",
"licenses",
"=",
"[",
"\"APACHE2\"",
",",
"\"OFL\"",
",",
"\"UFL\"",
"]",
"if",
"family_metadata",
".",
"license",
"in",
"licenses",
":",
"yield",
"PASS",
",",
"(",
"\"Font license is declared\"",
"\" in METADATA.pb as \\\"{}\\\"\"",
")",
".",
"format",
"(",
"family_metadata",
".",
"license",
")",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb license field (\\\"{}\\\")\"",
"\" must be one of the following:\"",
"\" {}\"",
")",
".",
"format",
"(",
"family_metadata",
".",
"license",
",",
"licenses",
")"
] | METADATA.pb license is "APACHE2", "UFL" or "OFL"? | [
"METADATA",
".",
"pb",
"license",
"is",
"APACHE2",
"UFL",
"or",
"OFL",
"?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1448-L1458 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_menu_and_latin | def com_google_fonts_check_metadata_menu_and_latin(family_metadata):
"""METADATA.pb should contain at least "menu" and "latin" subsets."""
missing = []
for s in ["menu", "latin"]:
if s not in list(family_metadata.subsets):
missing.append(s)
if missing != []:
yield FAIL, ("Subsets \"menu\" and \"latin\" are mandatory,"
" but METADATA.pb is missing"
" \"{}\"").format(" and ".join(missing))
else:
yield PASS, "METADATA.pb contains \"menu\" and \"latin\" subsets." | python | def com_google_fonts_check_metadata_menu_and_latin(family_metadata):
"""METADATA.pb should contain at least "menu" and "latin" subsets."""
missing = []
for s in ["menu", "latin"]:
if s not in list(family_metadata.subsets):
missing.append(s)
if missing != []:
yield FAIL, ("Subsets \"menu\" and \"latin\" are mandatory,"
" but METADATA.pb is missing"
" \"{}\"").format(" and ".join(missing))
else:
yield PASS, "METADATA.pb contains \"menu\" and \"latin\" subsets." | [
"def",
"com_google_fonts_check_metadata_menu_and_latin",
"(",
"family_metadata",
")",
":",
"missing",
"=",
"[",
"]",
"for",
"s",
"in",
"[",
"\"menu\"",
",",
"\"latin\"",
"]",
":",
"if",
"s",
"not",
"in",
"list",
"(",
"family_metadata",
".",
"subsets",
")",
":",
"missing",
".",
"append",
"(",
"s",
")",
"if",
"missing",
"!=",
"[",
"]",
":",
"yield",
"FAIL",
",",
"(",
"\"Subsets \\\"menu\\\" and \\\"latin\\\" are mandatory,\"",
"\" but METADATA.pb is missing\"",
"\" \\\"{}\\\"\"",
")",
".",
"format",
"(",
"\" and \"",
".",
"join",
"(",
"missing",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"METADATA.pb contains \\\"menu\\\" and \\\"latin\\\" subsets.\""
] | METADATA.pb should contain at least "menu" and "latin" subsets. | [
"METADATA",
".",
"pb",
"should",
"contain",
"at",
"least",
"menu",
"and",
"latin",
"subsets",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1465-L1477 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_subsets_order | def com_google_fonts_check_metadata_subsets_order(family_metadata):
"""METADATA.pb subsets should be alphabetically ordered."""
expected = list(sorted(family_metadata.subsets))
if list(family_metadata.subsets) != expected:
yield FAIL, ("METADATA.pb subsets are not sorted "
"in alphabetical order: Got ['{}']"
" and expected ['{}']").format("', '".join(family_metadata.subsets),
"', '".join(expected))
else:
yield PASS, "METADATA.pb subsets are sorted in alphabetical order." | python | def com_google_fonts_check_metadata_subsets_order(family_metadata):
"""METADATA.pb subsets should be alphabetically ordered."""
expected = list(sorted(family_metadata.subsets))
if list(family_metadata.subsets) != expected:
yield FAIL, ("METADATA.pb subsets are not sorted "
"in alphabetical order: Got ['{}']"
" and expected ['{}']").format("', '".join(family_metadata.subsets),
"', '".join(expected))
else:
yield PASS, "METADATA.pb subsets are sorted in alphabetical order." | [
"def",
"com_google_fonts_check_metadata_subsets_order",
"(",
"family_metadata",
")",
":",
"expected",
"=",
"list",
"(",
"sorted",
"(",
"family_metadata",
".",
"subsets",
")",
")",
"if",
"list",
"(",
"family_metadata",
".",
"subsets",
")",
"!=",
"expected",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb subsets are not sorted \"",
"\"in alphabetical order: Got ['{}']\"",
"\" and expected ['{}']\"",
")",
".",
"format",
"(",
"\"', '\"",
".",
"join",
"(",
"family_metadata",
".",
"subsets",
")",
",",
"\"', '\"",
".",
"join",
"(",
"expected",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"METADATA.pb subsets are sorted in alphabetical order.\""
] | METADATA.pb subsets should be alphabetically ordered. | [
"METADATA",
".",
"pb",
"subsets",
"should",
"be",
"alphabetically",
"ordered",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1484-L1494 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_familyname | def com_google_fonts_check_metadata_familyname(family_metadata):
"""Check that METADATA.pb family values are all the same."""
name = ""
fail = False
for f in family_metadata.fonts:
if name and f.name != name:
fail = True
name = f.name
if fail:
yield FAIL, ("METADATA.pb: Family name is not the same"
" in all metadata \"fonts\" items.")
else:
yield PASS, ("METADATA.pb: Family name is the same"
" in all metadata \"fonts\" items.") | python | def com_google_fonts_check_metadata_familyname(family_metadata):
"""Check that METADATA.pb family values are all the same."""
name = ""
fail = False
for f in family_metadata.fonts:
if name and f.name != name:
fail = True
name = f.name
if fail:
yield FAIL, ("METADATA.pb: Family name is not the same"
" in all metadata \"fonts\" items.")
else:
yield PASS, ("METADATA.pb: Family name is the same"
" in all metadata \"fonts\" items.") | [
"def",
"com_google_fonts_check_metadata_familyname",
"(",
"family_metadata",
")",
":",
"name",
"=",
"\"\"",
"fail",
"=",
"False",
"for",
"f",
"in",
"family_metadata",
".",
"fonts",
":",
"if",
"name",
"and",
"f",
".",
"name",
"!=",
"name",
":",
"fail",
"=",
"True",
"name",
"=",
"f",
".",
"name",
"if",
"fail",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb: Family name is not the same\"",
"\" in all metadata \\\"fonts\\\" items.\"",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb: Family name is the same\"",
"\" in all metadata \\\"fonts\\\" items.\"",
")"
] | Check that METADATA.pb family values are all the same. | [
"Check",
"that",
"METADATA",
".",
"pb",
"family",
"values",
"are",
"all",
"the",
"same",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1520-L1533 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_family_name | def com_google_fonts_check_metadata_nameid_family_name(ttFont, font_metadata):
"""Checks METADATA.pb font.name field matches
family name declared on the name table.
"""
from fontbakery.utils import get_name_entry_strings
familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
if not familynames:
familynames = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
if len(familynames) == 0:
yield FAIL, Message("missing",
("This font lacks a FONT_FAMILY_NAME entry"
" (nameID={}) in the name"
" table.").format(NameID.FONT_FAMILY_NAME))
else:
if font_metadata.name not in familynames:
yield FAIL, Message("mismatch",
("Unmatched family name in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\"").format(familynames[0],
font_metadata.name))
else:
yield PASS, ("Family name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.name) | python | def com_google_fonts_check_metadata_nameid_family_name(ttFont, font_metadata):
"""Checks METADATA.pb font.name field matches
family name declared on the name table.
"""
from fontbakery.utils import get_name_entry_strings
familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
if not familynames:
familynames = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
if len(familynames) == 0:
yield FAIL, Message("missing",
("This font lacks a FONT_FAMILY_NAME entry"
" (nameID={}) in the name"
" table.").format(NameID.FONT_FAMILY_NAME))
else:
if font_metadata.name not in familynames:
yield FAIL, Message("mismatch",
("Unmatched family name in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\"").format(familynames[0],
font_metadata.name))
else:
yield PASS, ("Family name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.name) | [
"def",
"com_google_fonts_check_metadata_nameid_family_name",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"familynames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"TYPOGRAPHIC_FAMILY_NAME",
")",
"if",
"not",
"familynames",
":",
"familynames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
"if",
"len",
"(",
"familynames",
")",
"==",
"0",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"missing\"",
",",
"(",
"\"This font lacks a FONT_FAMILY_NAME entry\"",
"\" (nameID={}) in the name\"",
"\" table.\"",
")",
".",
"format",
"(",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
")",
"else",
":",
"if",
"font_metadata",
".",
"name",
"not",
"in",
"familynames",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"mismatch\"",
",",
"(",
"\"Unmatched family name in font:\"",
"\" TTF has \\\"{}\\\" while METADATA.pb\"",
"\" has \\\"{}\\\"\"",
")",
".",
"format",
"(",
"familynames",
"[",
"0",
"]",
",",
"font_metadata",
".",
"name",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"Family name \\\"{}\\\" is identical\"",
"\" in METADATA.pb and on the\"",
"\" TTF file.\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"name",
")"
] | Checks METADATA.pb font.name field matches
family name declared on the name table. | [
"Checks",
"METADATA",
".",
"pb",
"font",
".",
"name",
"field",
"matches",
"family",
"name",
"declared",
"on",
"the",
"name",
"table",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1593-L1617 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_post_script_name | def com_google_fonts_check_metadata_nameid_post_script_name(ttFont, font_metadata):
"""Checks METADATA.pb font.post_script_name matches
postscript name declared on the name table.
"""
failed = False
from fontbakery.utils import get_name_entry_strings
postscript_names = get_name_entry_strings(ttFont, NameID.POSTSCRIPT_NAME)
if len(postscript_names) == 0:
failed = True
yield FAIL, Message("missing",
("This font lacks a POSTSCRIPT_NAME"
" entry (nameID={}) in the "
"name table.").format(NameID.POSTSCRIPT_NAME))
else:
for psname in postscript_names:
if psname != font_metadata.post_script_name:
failed = True
yield FAIL, Message("mismatch",
("Unmatched postscript name in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\"."
"").format(psname,
font_metadata.post_script_name))
if not failed:
yield PASS, ("Postscript name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.post_script_name) | python | def com_google_fonts_check_metadata_nameid_post_script_name(ttFont, font_metadata):
"""Checks METADATA.pb font.post_script_name matches
postscript name declared on the name table.
"""
failed = False
from fontbakery.utils import get_name_entry_strings
postscript_names = get_name_entry_strings(ttFont, NameID.POSTSCRIPT_NAME)
if len(postscript_names) == 0:
failed = True
yield FAIL, Message("missing",
("This font lacks a POSTSCRIPT_NAME"
" entry (nameID={}) in the "
"name table.").format(NameID.POSTSCRIPT_NAME))
else:
for psname in postscript_names:
if psname != font_metadata.post_script_name:
failed = True
yield FAIL, Message("mismatch",
("Unmatched postscript name in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\"."
"").format(psname,
font_metadata.post_script_name))
if not failed:
yield PASS, ("Postscript name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.post_script_name) | [
"def",
"com_google_fonts_check_metadata_nameid_post_script_name",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"failed",
"=",
"False",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"postscript_names",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"POSTSCRIPT_NAME",
")",
"if",
"len",
"(",
"postscript_names",
")",
"==",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"missing\"",
",",
"(",
"\"This font lacks a POSTSCRIPT_NAME\"",
"\" entry (nameID={}) in the \"",
"\"name table.\"",
")",
".",
"format",
"(",
"NameID",
".",
"POSTSCRIPT_NAME",
")",
")",
"else",
":",
"for",
"psname",
"in",
"postscript_names",
":",
"if",
"psname",
"!=",
"font_metadata",
".",
"post_script_name",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"mismatch\"",
",",
"(",
"\"Unmatched postscript name in font:\"",
"\" TTF has \\\"{}\\\" while METADATA.pb\"",
"\" has \\\"{}\\\".\"",
"\"\"",
")",
".",
"format",
"(",
"psname",
",",
"font_metadata",
".",
"post_script_name",
")",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"Postscript name \\\"{}\\\" is identical\"",
"\" in METADATA.pb and on the\"",
"\" TTF file.\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"post_script_name",
")"
] | Checks METADATA.pb font.post_script_name matches
postscript name declared on the name table. | [
"Checks",
"METADATA",
".",
"pb",
"font",
".",
"post_script_name",
"matches",
"postscript",
"name",
"declared",
"on",
"the",
"name",
"table",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1623-L1650 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_full_name | def com_google_fonts_check_metadata_nameid_full_name(ttFont, font_metadata):
"""METADATA.pb font.full_name value matches
fullname declared on the name table?
"""
from fontbakery.utils import get_name_entry_strings
full_fontnames = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(full_fontnames) == 0:
yield FAIL, Message("lacks-entry",
("This font lacks a FULL_FONT_NAME"
" entry (nameID={}) in the"
" name table.").format(NameID.FULL_FONT_NAME))
else:
for full_fontname in full_fontnames:
if full_fontname != font_metadata.full_name:
yield FAIL, Message("mismatch",
("Unmatched fullname in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\".").format(full_fontname,
font_metadata.full_name))
else:
yield PASS, ("Font fullname \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(full_fontname) | python | def com_google_fonts_check_metadata_nameid_full_name(ttFont, font_metadata):
"""METADATA.pb font.full_name value matches
fullname declared on the name table?
"""
from fontbakery.utils import get_name_entry_strings
full_fontnames = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(full_fontnames) == 0:
yield FAIL, Message("lacks-entry",
("This font lacks a FULL_FONT_NAME"
" entry (nameID={}) in the"
" name table.").format(NameID.FULL_FONT_NAME))
else:
for full_fontname in full_fontnames:
if full_fontname != font_metadata.full_name:
yield FAIL, Message("mismatch",
("Unmatched fullname in font:"
" TTF has \"{}\" while METADATA.pb"
" has \"{}\".").format(full_fontname,
font_metadata.full_name))
else:
yield PASS, ("Font fullname \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(full_fontname) | [
"def",
"com_google_fonts_check_metadata_nameid_full_name",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"full_fontnames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FULL_FONT_NAME",
")",
"if",
"len",
"(",
"full_fontnames",
")",
"==",
"0",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"lacks-entry\"",
",",
"(",
"\"This font lacks a FULL_FONT_NAME\"",
"\" entry (nameID={}) in the\"",
"\" name table.\"",
")",
".",
"format",
"(",
"NameID",
".",
"FULL_FONT_NAME",
")",
")",
"else",
":",
"for",
"full_fontname",
"in",
"full_fontnames",
":",
"if",
"full_fontname",
"!=",
"font_metadata",
".",
"full_name",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"mismatch\"",
",",
"(",
"\"Unmatched fullname in font:\"",
"\" TTF has \\\"{}\\\" while METADATA.pb\"",
"\" has \\\"{}\\\".\"",
")",
".",
"format",
"(",
"full_fontname",
",",
"font_metadata",
".",
"full_name",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"Font fullname \\\"{}\\\" is identical\"",
"\" in METADATA.pb and on the\"",
"\" TTF file.\"",
")",
".",
"format",
"(",
"full_fontname",
")"
] | METADATA.pb font.full_name value matches
fullname declared on the name table? | [
"METADATA",
".",
"pb",
"font",
".",
"full_name",
"value",
"matches",
"fullname",
"declared",
"on",
"the",
"name",
"table?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1657-L1680 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_font_name | def com_google_fonts_check_metadata_nameid_font_name(ttFont, style, font_metadata):
"""METADATA.pb font.name value should be same as
the family name declared on the name table.
"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
font_familynames = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
nameid = NameID.FONT_FAMILY_NAME
else:
font_familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
nameid = NameID.TYPOGRAPHIC_FAMILY_NAME
if len(font_familynames) == 0:
yield FAIL, Message("lacks-entry",
(f"This font lacks a {NameID(nameid).name} entry"
f" (nameID={nameid}) in the name table."))
else:
for font_familyname in font_familynames:
if font_familyname != font_metadata.name:
yield FAIL, Message("mismatch",
("Unmatched familyname in font:"
" TTF has \"{}\" while METADATA.pb has"
" name=\"{}\".").format(font_familyname,
font_metadata.name))
else:
yield PASS, ("OK: Family name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.name) | python | def com_google_fonts_check_metadata_nameid_font_name(ttFont, style, font_metadata):
"""METADATA.pb font.name value should be same as
the family name declared on the name table.
"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
font_familynames = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
nameid = NameID.FONT_FAMILY_NAME
else:
font_familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
nameid = NameID.TYPOGRAPHIC_FAMILY_NAME
if len(font_familynames) == 0:
yield FAIL, Message("lacks-entry",
(f"This font lacks a {NameID(nameid).name} entry"
f" (nameID={nameid}) in the name table."))
else:
for font_familyname in font_familynames:
if font_familyname != font_metadata.name:
yield FAIL, Message("mismatch",
("Unmatched familyname in font:"
" TTF has \"{}\" while METADATA.pb has"
" name=\"{}\".").format(font_familyname,
font_metadata.name))
else:
yield PASS, ("OK: Family name \"{}\" is identical"
" in METADATA.pb and on the"
" TTF file.").format(font_metadata.name) | [
"def",
"com_google_fonts_check_metadata_nameid_font_name",
"(",
"ttFont",
",",
"style",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"if",
"style",
"in",
"RIBBI_STYLE_NAMES",
":",
"font_familynames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
"nameid",
"=",
"NameID",
".",
"FONT_FAMILY_NAME",
"else",
":",
"font_familynames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"TYPOGRAPHIC_FAMILY_NAME",
")",
"nameid",
"=",
"NameID",
".",
"TYPOGRAPHIC_FAMILY_NAME",
"if",
"len",
"(",
"font_familynames",
")",
"==",
"0",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"lacks-entry\"",
",",
"(",
"f\"This font lacks a {NameID(nameid).name} entry\"",
"f\" (nameID={nameid}) in the name table.\"",
")",
")",
"else",
":",
"for",
"font_familyname",
"in",
"font_familynames",
":",
"if",
"font_familyname",
"!=",
"font_metadata",
".",
"name",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"mismatch\"",
",",
"(",
"\"Unmatched familyname in font:\"",
"\" TTF has \\\"{}\\\" while METADATA.pb has\"",
"\" name=\\\"{}\\\".\"",
")",
".",
"format",
"(",
"font_familyname",
",",
"font_metadata",
".",
"name",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"OK: Family name \\\"{}\\\" is identical\"",
"\" in METADATA.pb and on the\"",
"\" TTF file.\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"name",
")"
] | METADATA.pb font.name value should be same as
the family name declared on the name table. | [
"METADATA",
".",
"pb",
"font",
".",
"name",
"value",
"should",
"be",
"same",
"as",
"the",
"family",
"name",
"declared",
"on",
"the",
"name",
"table",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1687-L1716 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_match_fullname_postscript | def com_google_fonts_check_metadata_match_fullname_postscript(font_metadata):
"""METADATA.pb font.full_name and font.post_script_name
fields have equivalent values ?
"""
import re
regex = re.compile(r"\W")
post_script_name = regex.sub("", font_metadata.post_script_name)
fullname = regex.sub("", font_metadata.full_name)
if fullname != post_script_name:
yield FAIL, ("METADATA.pb font full_name=\"{}\""
" does not match post_script_name ="
" \"{}\"").format(font_metadata.full_name,
font_metadata.post_script_name)
else:
yield PASS, ("METADATA.pb font fields \"full_name\" and"
" \"post_script_name\" have equivalent values.") | python | def com_google_fonts_check_metadata_match_fullname_postscript(font_metadata):
"""METADATA.pb font.full_name and font.post_script_name
fields have equivalent values ?
"""
import re
regex = re.compile(r"\W")
post_script_name = regex.sub("", font_metadata.post_script_name)
fullname = regex.sub("", font_metadata.full_name)
if fullname != post_script_name:
yield FAIL, ("METADATA.pb font full_name=\"{}\""
" does not match post_script_name ="
" \"{}\"").format(font_metadata.full_name,
font_metadata.post_script_name)
else:
yield PASS, ("METADATA.pb font fields \"full_name\" and"
" \"post_script_name\" have equivalent values.") | [
"def",
"com_google_fonts_check_metadata_match_fullname_postscript",
"(",
"font_metadata",
")",
":",
"import",
"re",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"\\W\"",
")",
"post_script_name",
"=",
"regex",
".",
"sub",
"(",
"\"\"",
",",
"font_metadata",
".",
"post_script_name",
")",
"fullname",
"=",
"regex",
".",
"sub",
"(",
"\"\"",
",",
"font_metadata",
".",
"full_name",
")",
"if",
"fullname",
"!=",
"post_script_name",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb font full_name=\\\"{}\\\"\"",
"\" does not match post_script_name =\"",
"\" \\\"{}\\\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"full_name",
",",
"font_metadata",
".",
"post_script_name",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb font fields \\\"full_name\\\" and\"",
"\" \\\"post_script_name\\\" have equivalent values.\"",
")"
] | METADATA.pb font.full_name and font.post_script_name
fields have equivalent values ? | [
"METADATA",
".",
"pb",
"font",
".",
"full_name",
"and",
"font",
".",
"post_script_name",
"fields",
"have",
"equivalent",
"values",
"?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1723-L1738 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_match_filename_postscript | def com_google_fonts_check_metadata_match_filename_postscript(font_metadata):
"""METADATA.pb font.filename and font.post_script_name
fields have equivalent values?
"""
post_script_name = font_metadata.post_script_name
filename = os.path.splitext(font_metadata.filename)[0]
if filename != post_script_name:
yield FAIL, ("METADATA.pb font filename=\"{}\" does not match"
" post_script_name=\"{}\"."
"").format(font_metadata.filename,
font_metadata.post_script_name)
else:
yield PASS, ("METADATA.pb font fields \"filename\" and"
" \"post_script_name\" have equivalent values.") | python | def com_google_fonts_check_metadata_match_filename_postscript(font_metadata):
"""METADATA.pb font.filename and font.post_script_name
fields have equivalent values?
"""
post_script_name = font_metadata.post_script_name
filename = os.path.splitext(font_metadata.filename)[0]
if filename != post_script_name:
yield FAIL, ("METADATA.pb font filename=\"{}\" does not match"
" post_script_name=\"{}\"."
"").format(font_metadata.filename,
font_metadata.post_script_name)
else:
yield PASS, ("METADATA.pb font fields \"filename\" and"
" \"post_script_name\" have equivalent values.") | [
"def",
"com_google_fonts_check_metadata_match_filename_postscript",
"(",
"font_metadata",
")",
":",
"post_script_name",
"=",
"font_metadata",
".",
"post_script_name",
"filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"font_metadata",
".",
"filename",
")",
"[",
"0",
"]",
"if",
"filename",
"!=",
"post_script_name",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb font filename=\\\"{}\\\" does not match\"",
"\" post_script_name=\\\"{}\\\".\"",
"\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"filename",
",",
"font_metadata",
".",
"post_script_name",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb font fields \\\"filename\\\" and\"",
"\" \\\"post_script_name\\\" have equivalent values.\"",
")"
] | METADATA.pb font.filename and font.post_script_name
fields have equivalent values? | [
"METADATA",
".",
"pb",
"font",
".",
"filename",
"and",
"font",
".",
"post_script_name",
"fields",
"have",
"equivalent",
"values?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1748-L1762 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_valid_name_values | def com_google_fonts_check_metadata_valid_name_values(style,
font_metadata,
font_familynames,
typographic_familynames):
"""METADATA.pb font.name field contains font name in right format?"""
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
familynames = font_familynames
else:
familynames = typographic_familynames
failed = False
for font_familyname in familynames:
if font_familyname not in font_metadata.name:
failed = True
yield FAIL, ("METADATA.pb font.name field (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.name,
font_familyname)
if not failed:
yield PASS, ("METADATA.pb font.name field contains"
" font name in right format.") | python | def com_google_fonts_check_metadata_valid_name_values(style,
font_metadata,
font_familynames,
typographic_familynames):
"""METADATA.pb font.name field contains font name in right format?"""
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
familynames = font_familynames
else:
familynames = typographic_familynames
failed = False
for font_familyname in familynames:
if font_familyname not in font_metadata.name:
failed = True
yield FAIL, ("METADATA.pb font.name field (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.name,
font_familyname)
if not failed:
yield PASS, ("METADATA.pb font.name field contains"
" font name in right format.") | [
"def",
"com_google_fonts_check_metadata_valid_name_values",
"(",
"style",
",",
"font_metadata",
",",
"font_familynames",
",",
"typographic_familynames",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"if",
"style",
"in",
"RIBBI_STYLE_NAMES",
":",
"familynames",
"=",
"font_familynames",
"else",
":",
"familynames",
"=",
"typographic_familynames",
"failed",
"=",
"False",
"for",
"font_familyname",
"in",
"familynames",
":",
"if",
"font_familyname",
"not",
"in",
"font_metadata",
".",
"name",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb font.name field (\\\"{}\\\")\"",
"\" does not match correct font name format (\\\"{}\\\").\"",
"\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"name",
",",
"font_familyname",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb font.name field contains\"",
"\" font name in right format.\"",
")"
] | METADATA.pb font.name field contains font name in right format? | [
"METADATA",
".",
"pb",
"font",
".",
"name",
"field",
"contains",
"font",
"name",
"in",
"right",
"format?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1792-L1813 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_valid_full_name_values | def com_google_fonts_check_metadata_valid_full_name_values(style,
font_metadata,
font_familynames,
typographic_familynames):
"""METADATA.pb font.full_name field contains font name in right format?"""
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
familynames = font_familynames
if familynames == []:
yield SKIP, "No FONT_FAMILYNAME"
else:
familynames = typographic_familynames
if familynames == []:
yield SKIP, "No TYPOGRAPHIC_FAMILYNAME"
for font_familyname in familynames:
if font_familyname in font_metadata.full_name:
yield PASS, ("METADATA.pb font.full_name field contains"
" font name in right format."
" ('{}' in '{}')").format(font_familyname,
font_metadata.full_name)
else:
yield FAIL, ("METADATA.pb font.full_name field (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.full_name,
font_familyname) | python | def com_google_fonts_check_metadata_valid_full_name_values(style,
font_metadata,
font_familynames,
typographic_familynames):
"""METADATA.pb font.full_name field contains font name in right format?"""
from fontbakery.constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES:
familynames = font_familynames
if familynames == []:
yield SKIP, "No FONT_FAMILYNAME"
else:
familynames = typographic_familynames
if familynames == []:
yield SKIP, "No TYPOGRAPHIC_FAMILYNAME"
for font_familyname in familynames:
if font_familyname in font_metadata.full_name:
yield PASS, ("METADATA.pb font.full_name field contains"
" font name in right format."
" ('{}' in '{}')").format(font_familyname,
font_metadata.full_name)
else:
yield FAIL, ("METADATA.pb font.full_name field (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.full_name,
font_familyname) | [
"def",
"com_google_fonts_check_metadata_valid_full_name_values",
"(",
"style",
",",
"font_metadata",
",",
"font_familynames",
",",
"typographic_familynames",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"if",
"style",
"in",
"RIBBI_STYLE_NAMES",
":",
"familynames",
"=",
"font_familynames",
"if",
"familynames",
"==",
"[",
"]",
":",
"yield",
"SKIP",
",",
"\"No FONT_FAMILYNAME\"",
"else",
":",
"familynames",
"=",
"typographic_familynames",
"if",
"familynames",
"==",
"[",
"]",
":",
"yield",
"SKIP",
",",
"\"No TYPOGRAPHIC_FAMILYNAME\"",
"for",
"font_familyname",
"in",
"familynames",
":",
"if",
"font_familyname",
"in",
"font_metadata",
".",
"full_name",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb font.full_name field contains\"",
"\" font name in right format.\"",
"\" ('{}' in '{}')\"",
")",
".",
"format",
"(",
"font_familyname",
",",
"font_metadata",
".",
"full_name",
")",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb font.full_name field (\\\"{}\\\")\"",
"\" does not match correct font name format (\\\"{}\\\").\"",
"\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"full_name",
",",
"font_familyname",
")"
] | METADATA.pb font.full_name field contains font name in right format? | [
"METADATA",
".",
"pb",
"font",
".",
"full_name",
"field",
"contains",
"font",
"name",
"in",
"right",
"format?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1821-L1846 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_valid_filename_values | def com_google_fonts_check_metadata_valid_filename_values(font,
family_metadata):
"""METADATA.pb font.filename field contains font name in right format?"""
expected = os.path.basename(font)
failed = True
for font_metadata in family_metadata.fonts:
if font_metadata.filename == expected:
failed = False
yield PASS, ("METADATA.pb filename field contains"
" font name in right format.")
break
if failed:
yield FAIL, ("None of the METADATA.pb filename fields match"
f" correct font name format (\"{expected}\").") | python | def com_google_fonts_check_metadata_valid_filename_values(font,
family_metadata):
"""METADATA.pb font.filename field contains font name in right format?"""
expected = os.path.basename(font)
failed = True
for font_metadata in family_metadata.fonts:
if font_metadata.filename == expected:
failed = False
yield PASS, ("METADATA.pb filename field contains"
" font name in right format.")
break
if failed:
yield FAIL, ("None of the METADATA.pb filename fields match"
f" correct font name format (\"{expected}\").") | [
"def",
"com_google_fonts_check_metadata_valid_filename_values",
"(",
"font",
",",
"family_metadata",
")",
":",
"expected",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"font",
")",
"failed",
"=",
"True",
"for",
"font_metadata",
"in",
"family_metadata",
".",
"fonts",
":",
"if",
"font_metadata",
".",
"filename",
"==",
"expected",
":",
"failed",
"=",
"False",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb filename field contains\"",
"\" font name in right format.\"",
")",
"break",
"if",
"failed",
":",
"yield",
"FAIL",
",",
"(",
"\"None of the METADATA.pb filename fields match\"",
"f\" correct font name format (\\\"{expected}\\\").\"",
")"
] | METADATA.pb font.filename field contains font name in right format? | [
"METADATA",
".",
"pb",
"font",
".",
"filename",
"field",
"contains",
"font",
"name",
"in",
"right",
"format?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1855-L1868 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_valid_post_script_name_values | def com_google_fonts_check_metadata_valid_post_script_name_values(font_metadata,
font_familynames):
"""METADATA.pb font.post_script_name field
contains font name in right format?
"""
for font_familyname in font_familynames:
psname = "".join(str(font_familyname).split())
if psname in "".join(font_metadata.post_script_name.split("-")):
yield PASS, ("METADATA.pb postScriptName field"
" contains font name in right format.")
else:
yield FAIL, ("METADATA.pb postScriptName (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.post_script_name,
font_familyname) | python | def com_google_fonts_check_metadata_valid_post_script_name_values(font_metadata,
font_familynames):
"""METADATA.pb font.post_script_name field
contains font name in right format?
"""
for font_familyname in font_familynames:
psname = "".join(str(font_familyname).split())
if psname in "".join(font_metadata.post_script_name.split("-")):
yield PASS, ("METADATA.pb postScriptName field"
" contains font name in right format.")
else:
yield FAIL, ("METADATA.pb postScriptName (\"{}\")"
" does not match correct font name format (\"{}\")."
"").format(font_metadata.post_script_name,
font_familyname) | [
"def",
"com_google_fonts_check_metadata_valid_post_script_name_values",
"(",
"font_metadata",
",",
"font_familynames",
")",
":",
"for",
"font_familyname",
"in",
"font_familynames",
":",
"psname",
"=",
"\"\"",
".",
"join",
"(",
"str",
"(",
"font_familyname",
")",
".",
"split",
"(",
")",
")",
"if",
"psname",
"in",
"\"\"",
".",
"join",
"(",
"font_metadata",
".",
"post_script_name",
".",
"split",
"(",
"\"-\"",
")",
")",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb postScriptName field\"",
"\" contains font name in right format.\"",
")",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb postScriptName (\\\"{}\\\")\"",
"\" does not match correct font name format (\\\"{}\\\").\"",
"\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"post_script_name",
",",
"font_familyname",
")"
] | METADATA.pb font.post_script_name field
contains font name in right format? | [
"METADATA",
".",
"pb",
"font",
".",
"post_script_name",
"field",
"contains",
"font",
"name",
"in",
"right",
"format?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1876-L1890 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_valid_copyright | def com_google_fonts_check_metadata_valid_copyright(font_metadata):
"""Copyright notices match canonical pattern in METADATA.pb"""
import re
string = font_metadata.copyright
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yield PASS, "METADATA.pb copyright string is good"
else:
yield FAIL, ("METADATA.pb: Copyright notices should match"
" a pattern similar to:"
" 'Copyright 2017 The Familyname"
" Project Authors (git url)'\n"
"But instead we have got:"
" '{}'").format(string) | python | def com_google_fonts_check_metadata_valid_copyright(font_metadata):
"""Copyright notices match canonical pattern in METADATA.pb"""
import re
string = font_metadata.copyright
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yield PASS, "METADATA.pb copyright string is good"
else:
yield FAIL, ("METADATA.pb: Copyright notices should match"
" a pattern similar to:"
" 'Copyright 2017 The Familyname"
" Project Authors (git url)'\n"
"But instead we have got:"
" '{}'").format(string) | [
"def",
"com_google_fonts_check_metadata_valid_copyright",
"(",
"font_metadata",
")",
":",
"import",
"re",
"string",
"=",
"font_metadata",
".",
"copyright",
"does_match",
"=",
"re",
".",
"search",
"(",
"r'Copyright [0-9]{4} The .* Project Authors \\([^\\@]*\\)'",
",",
"string",
")",
"if",
"does_match",
":",
"yield",
"PASS",
",",
"\"METADATA.pb copyright string is good\"",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb: Copyright notices should match\"",
"\" a pattern similar to:\"",
"\" 'Copyright 2017 The Familyname\"",
"\" Project Authors (git url)'\\n\"",
"\"But instead we have got:\"",
"\" '{}'\"",
")",
".",
"format",
"(",
"string",
")"
] | Copyright notices match canonical pattern in METADATA.pb | [
"Copyright",
"notices",
"match",
"canonical",
"pattern",
"in",
"METADATA",
".",
"pb"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1897-L1911 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_font_copyright | def com_google_fonts_check_font_copyright(ttFont):
"""Copyright notices match canonical pattern in fonts"""
import re
from fontbakery.utils import get_name_entry_strings
failed = False
for string in get_name_entry_strings(ttFont, NameID.COPYRIGHT_NOTICE):
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yield PASS, ("Name Table entry: Copyright field '{}'"
" matches canonical pattern.").format(string)
else:
failed = True
yield FAIL, ("Name Table entry: Copyright notices should match"
" a pattern similar to:"
" 'Copyright 2017 The Familyname"
" Project Authors (git url)'\n"
"But instead we have got:"
" '{}'").format(string)
if not failed:
yield PASS, "Name table copyright entries are good" | python | def com_google_fonts_check_font_copyright(ttFont):
"""Copyright notices match canonical pattern in fonts"""
import re
from fontbakery.utils import get_name_entry_strings
failed = False
for string in get_name_entry_strings(ttFont, NameID.COPYRIGHT_NOTICE):
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yield PASS, ("Name Table entry: Copyright field '{}'"
" matches canonical pattern.").format(string)
else:
failed = True
yield FAIL, ("Name Table entry: Copyright notices should match"
" a pattern similar to:"
" 'Copyright 2017 The Familyname"
" Project Authors (git url)'\n"
"But instead we have got:"
" '{}'").format(string)
if not failed:
yield PASS, "Name table copyright entries are good" | [
"def",
"com_google_fonts_check_font_copyright",
"(",
"ttFont",
")",
":",
"import",
"re",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"failed",
"=",
"False",
"for",
"string",
"in",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"COPYRIGHT_NOTICE",
")",
":",
"does_match",
"=",
"re",
".",
"search",
"(",
"r'Copyright [0-9]{4} The .* Project Authors \\([^\\@]*\\)'",
",",
"string",
")",
"if",
"does_match",
":",
"yield",
"PASS",
",",
"(",
"\"Name Table entry: Copyright field '{}'\"",
"\" matches canonical pattern.\"",
")",
".",
"format",
"(",
"string",
")",
"else",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Name Table entry: Copyright notices should match\"",
"\" a pattern similar to:\"",
"\" 'Copyright 2017 The Familyname\"",
"\" Project Authors (git url)'\\n\"",
"\"But instead we have got:\"",
"\" '{}'\"",
")",
".",
"format",
"(",
"string",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Name table copyright entries are good\""
] | Copyright notices match canonical pattern in fonts | [
"Copyright",
"notices",
"match",
"canonical",
"pattern",
"in",
"fonts"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1917-L1938 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_italic_style | def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata):
"""METADATA.pb font.style "italic" matches font internals?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import MacStyle
if font_metadata.style != "italic":
yield SKIP, "This check only applies to italic fonts."
else:
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(font_fullname) == 0:
yield SKIP, "Font lacks fullname entries in name table."
# this fail scenario was already checked above
# (passing those previous checks is a prerequisite for this one)
# FIXME: Could we pack this into a condition ?
else:
# FIXME: here we only check the first name entry.
# Should we iterate over them all ? Or should we check
# if they're all the same?
font_fullname = font_fullname[0]
if not bool(ttFont["head"].macStyle & MacStyle.ITALIC):
yield FAIL, Message("bad-macstyle",
"METADATA.pb style has been set to italic"
" but font macStyle is improperly set.")
elif not font_fullname.split("-")[-1].endswith("Italic"):
yield FAIL, Message("bad-fullfont-name",
("Font macStyle Italic bit is set"
" but nameID {} (\"{}\") is not ended with"
" \"Italic\"").format(NameID.FULL_FONT_NAME,
font_fullname))
else:
yield PASS, ("OK: METADATA.pb font.style \"italic\""
" matches font internals.") | python | def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata):
"""METADATA.pb font.style "italic" matches font internals?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import MacStyle
if font_metadata.style != "italic":
yield SKIP, "This check only applies to italic fonts."
else:
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(font_fullname) == 0:
yield SKIP, "Font lacks fullname entries in name table."
# this fail scenario was already checked above
# (passing those previous checks is a prerequisite for this one)
# FIXME: Could we pack this into a condition ?
else:
# FIXME: here we only check the first name entry.
# Should we iterate over them all ? Or should we check
# if they're all the same?
font_fullname = font_fullname[0]
if not bool(ttFont["head"].macStyle & MacStyle.ITALIC):
yield FAIL, Message("bad-macstyle",
"METADATA.pb style has been set to italic"
" but font macStyle is improperly set.")
elif not font_fullname.split("-")[-1].endswith("Italic"):
yield FAIL, Message("bad-fullfont-name",
("Font macStyle Italic bit is set"
" but nameID {} (\"{}\") is not ended with"
" \"Italic\"").format(NameID.FULL_FONT_NAME,
font_fullname))
else:
yield PASS, ("OK: METADATA.pb font.style \"italic\""
" matches font internals.") | [
"def",
"com_google_fonts_check_metadata_italic_style",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"from",
"fontbakery",
".",
"constants",
"import",
"MacStyle",
"if",
"font_metadata",
".",
"style",
"!=",
"\"italic\"",
":",
"yield",
"SKIP",
",",
"\"This check only applies to italic fonts.\"",
"else",
":",
"font_fullname",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FULL_FONT_NAME",
")",
"if",
"len",
"(",
"font_fullname",
")",
"==",
"0",
":",
"yield",
"SKIP",
",",
"\"Font lacks fullname entries in name table.\"",
"# this fail scenario was already checked above",
"# (passing those previous checks is a prerequisite for this one)",
"# FIXME: Could we pack this into a condition ?",
"else",
":",
"# FIXME: here we only check the first name entry.",
"# Should we iterate over them all ? Or should we check",
"# if they're all the same?",
"font_fullname",
"=",
"font_fullname",
"[",
"0",
"]",
"if",
"not",
"bool",
"(",
"ttFont",
"[",
"\"head\"",
"]",
".",
"macStyle",
"&",
"MacStyle",
".",
"ITALIC",
")",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"bad-macstyle\"",
",",
"\"METADATA.pb style has been set to italic\"",
"\" but font macStyle is improperly set.\"",
")",
"elif",
"not",
"font_fullname",
".",
"split",
"(",
"\"-\"",
")",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"\"Italic\"",
")",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"bad-fullfont-name\"",
",",
"(",
"\"Font macStyle Italic bit is set\"",
"\" but nameID {} (\\\"{}\\\") is not ended with\"",
"\" \\\"Italic\\\"\"",
")",
".",
"format",
"(",
"NameID",
".",
"FULL_FONT_NAME",
",",
"font_fullname",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"OK: METADATA.pb font.style \\\"italic\\\"\"",
"\" matches font internals.\"",
")"
] | METADATA.pb font.style "italic" matches font internals? | [
"METADATA",
".",
"pb",
"font",
".",
"style",
"italic",
"matches",
"font",
"internals?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2029-L2061 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_normal_style | def com_google_fonts_check_metadata_normal_style(ttFont, font_metadata):
"""METADATA.pb font.style "normal" matches font internals?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import MacStyle
if font_metadata.style != "normal":
yield SKIP, "This check only applies to normal fonts."
# FIXME: declare a common condition called "normal_style"
else:
font_familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(font_familyname) == 0 or len(font_fullname) == 0:
yield SKIP, ("Font lacks familyname and/or"
" fullname entries in name table.")
# FIXME: This is the same SKIP condition as in check/metadata/italic_style
# so we definitely need to address them with a common condition!
else:
font_familyname = font_familyname[0]
font_fullname = font_fullname[0]
if bool(ttFont["head"].macStyle & MacStyle.ITALIC):
yield FAIL, Message("bad-macstyle",
("METADATA.pb style has been set to normal"
" but font macStyle is improperly set."))
elif font_familyname.split("-")[-1].endswith('Italic'):
yield FAIL, Message("familyname-italic",
("Font macStyle indicates a non-Italic font, but"
" nameID {} (FONT_FAMILY_NAME: \"{}\") ends with"
" \"Italic\".").format(NameID.FONT_FAMILY_NAME,
font_familyname))
elif font_fullname.split("-")[-1].endswith("Italic"):
yield FAIL, Message("fullfont-italic",
("Font macStyle indicates a non-Italic font but"
" nameID {} (FULL_FONT_NAME: \"{}\") ends with"
" \"Italic\".").format(NameID.FULL_FONT_NAME,
font_fullname))
else:
yield PASS, ("METADATA.pb font.style \"normal\""
" matches font internals.") | python | def com_google_fonts_check_metadata_normal_style(ttFont, font_metadata):
"""METADATA.pb font.style "normal" matches font internals?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import MacStyle
if font_metadata.style != "normal":
yield SKIP, "This check only applies to normal fonts."
# FIXME: declare a common condition called "normal_style"
else:
font_familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(font_familyname) == 0 or len(font_fullname) == 0:
yield SKIP, ("Font lacks familyname and/or"
" fullname entries in name table.")
# FIXME: This is the same SKIP condition as in check/metadata/italic_style
# so we definitely need to address them with a common condition!
else:
font_familyname = font_familyname[0]
font_fullname = font_fullname[0]
if bool(ttFont["head"].macStyle & MacStyle.ITALIC):
yield FAIL, Message("bad-macstyle",
("METADATA.pb style has been set to normal"
" but font macStyle is improperly set."))
elif font_familyname.split("-")[-1].endswith('Italic'):
yield FAIL, Message("familyname-italic",
("Font macStyle indicates a non-Italic font, but"
" nameID {} (FONT_FAMILY_NAME: \"{}\") ends with"
" \"Italic\".").format(NameID.FONT_FAMILY_NAME,
font_familyname))
elif font_fullname.split("-")[-1].endswith("Italic"):
yield FAIL, Message("fullfont-italic",
("Font macStyle indicates a non-Italic font but"
" nameID {} (FULL_FONT_NAME: \"{}\") ends with"
" \"Italic\".").format(NameID.FULL_FONT_NAME,
font_fullname))
else:
yield PASS, ("METADATA.pb font.style \"normal\""
" matches font internals.") | [
"def",
"com_google_fonts_check_metadata_normal_style",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"from",
"fontbakery",
".",
"constants",
"import",
"MacStyle",
"if",
"font_metadata",
".",
"style",
"!=",
"\"normal\"",
":",
"yield",
"SKIP",
",",
"\"This check only applies to normal fonts.\"",
"# FIXME: declare a common condition called \"normal_style\"",
"else",
":",
"font_familyname",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
"font_fullname",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FULL_FONT_NAME",
")",
"if",
"len",
"(",
"font_familyname",
")",
"==",
"0",
"or",
"len",
"(",
"font_fullname",
")",
"==",
"0",
":",
"yield",
"SKIP",
",",
"(",
"\"Font lacks familyname and/or\"",
"\" fullname entries in name table.\"",
")",
"# FIXME: This is the same SKIP condition as in check/metadata/italic_style",
"# so we definitely need to address them with a common condition!",
"else",
":",
"font_familyname",
"=",
"font_familyname",
"[",
"0",
"]",
"font_fullname",
"=",
"font_fullname",
"[",
"0",
"]",
"if",
"bool",
"(",
"ttFont",
"[",
"\"head\"",
"]",
".",
"macStyle",
"&",
"MacStyle",
".",
"ITALIC",
")",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"bad-macstyle\"",
",",
"(",
"\"METADATA.pb style has been set to normal\"",
"\" but font macStyle is improperly set.\"",
")",
")",
"elif",
"font_familyname",
".",
"split",
"(",
"\"-\"",
")",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"'Italic'",
")",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"familyname-italic\"",
",",
"(",
"\"Font macStyle indicates a non-Italic font, but\"",
"\" nameID {} (FONT_FAMILY_NAME: \\\"{}\\\") ends with\"",
"\" \\\"Italic\\\".\"",
")",
".",
"format",
"(",
"NameID",
".",
"FONT_FAMILY_NAME",
",",
"font_familyname",
")",
")",
"elif",
"font_fullname",
".",
"split",
"(",
"\"-\"",
")",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"\"Italic\"",
")",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"fullfont-italic\"",
",",
"(",
"\"Font macStyle indicates a non-Italic font but\"",
"\" nameID {} (FULL_FONT_NAME: \\\"{}\\\") ends with\"",
"\" \\\"Italic\\\".\"",
")",
".",
"format",
"(",
"NameID",
".",
"FULL_FONT_NAME",
",",
"font_fullname",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb font.style \\\"normal\\\"\"",
"\" matches font internals.\"",
")"
] | METADATA.pb font.style "normal" matches font internals? | [
"METADATA",
".",
"pb",
"font",
".",
"style",
"normal",
"matches",
"font",
"internals?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2068-L2106 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_family_and_full_names | def com_google_fonts_check_metadata_nameid_family_and_full_names(ttFont, font_metadata):
"""METADATA.pb font.name and font.full_name fields match
the values declared on the name table?
"""
from fontbakery.utils import get_name_entry_strings
font_familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
if font_familynames:
font_familyname = font_familynames[0]
else:
font_familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)[0]
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)[0]
# FIXME: common condition/name-id check as in the two previous checks.
if font_fullname != font_metadata.full_name:
yield FAIL, Message("fullname-mismatch",
("METADATA.pb: Fullname (\"{}\")"
" does not match name table"
" entry \"{}\" !").format(font_metadata.full_name,
font_fullname))
elif font_familyname != font_metadata.name:
yield FAIL, Message("familyname-mismatch",
("METADATA.pb Family name \"{}\")"
" does not match name table"
" entry \"{}\" !").format(font_metadata.name,
font_familyname))
else:
yield PASS, ("METADATA.pb familyname and fullName fields"
" match corresponding name table entries.") | python | def com_google_fonts_check_metadata_nameid_family_and_full_names(ttFont, font_metadata):
"""METADATA.pb font.name and font.full_name fields match
the values declared on the name table?
"""
from fontbakery.utils import get_name_entry_strings
font_familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)
if font_familynames:
font_familyname = font_familynames[0]
else:
font_familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)[0]
font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)[0]
# FIXME: common condition/name-id check as in the two previous checks.
if font_fullname != font_metadata.full_name:
yield FAIL, Message("fullname-mismatch",
("METADATA.pb: Fullname (\"{}\")"
" does not match name table"
" entry \"{}\" !").format(font_metadata.full_name,
font_fullname))
elif font_familyname != font_metadata.name:
yield FAIL, Message("familyname-mismatch",
("METADATA.pb Family name \"{}\")"
" does not match name table"
" entry \"{}\" !").format(font_metadata.name,
font_familyname))
else:
yield PASS, ("METADATA.pb familyname and fullName fields"
" match corresponding name table entries.") | [
"def",
"com_google_fonts_check_metadata_nameid_family_and_full_names",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"font_familynames",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"TYPOGRAPHIC_FAMILY_NAME",
")",
"if",
"font_familynames",
":",
"font_familyname",
"=",
"font_familynames",
"[",
"0",
"]",
"else",
":",
"font_familyname",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
"[",
"0",
"]",
"font_fullname",
"=",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FULL_FONT_NAME",
")",
"[",
"0",
"]",
"# FIXME: common condition/name-id check as in the two previous checks.",
"if",
"font_fullname",
"!=",
"font_metadata",
".",
"full_name",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"fullname-mismatch\"",
",",
"(",
"\"METADATA.pb: Fullname (\\\"{}\\\")\"",
"\" does not match name table\"",
"\" entry \\\"{}\\\" !\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"full_name",
",",
"font_fullname",
")",
")",
"elif",
"font_familyname",
"!=",
"font_metadata",
".",
"name",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"familyname-mismatch\"",
",",
"(",
"\"METADATA.pb Family name \\\"{}\\\")\"",
"\" does not match name table\"",
"\" entry \\\"{}\\\" !\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"name",
",",
"font_familyname",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"METADATA.pb familyname and fullName fields\"",
"\" match corresponding name table entries.\"",
")"
] | METADATA.pb font.name and font.full_name fields match
the values declared on the name table? | [
"METADATA",
".",
"pb",
"font",
".",
"name",
"and",
"font",
".",
"full_name",
"fields",
"match",
"the",
"values",
"declared",
"on",
"the",
"name",
"table?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2113-L2141 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_match_weight_postscript | def com_google_fonts_check_metadata_match_weight_postscript(font_metadata):
"""METADATA.pb weight matches postScriptName."""
WEIGHTS = {
"Thin": 100,
"ThinItalic": 100,
"ExtraLight": 200,
"ExtraLightItalic": 200,
"Light": 300,
"LightItalic": 300,
"Regular": 400,
"Italic": 400,
"Medium": 500,
"MediumItalic": 500,
"SemiBold": 600,
"SemiBoldItalic": 600,
"Bold": 700,
"BoldItalic": 700,
"ExtraBold": 800,
"ExtraBoldItalic": 800,
"Black": 900,
"BlackItalic": 900
}
pair = []
for k, weight in WEIGHTS.items():
if weight == font_metadata.weight:
pair.append((k, weight))
if not pair:
yield FAIL, ("METADATA.pb: Font weight value ({})"
" is invalid.").format(font_metadata.weight)
elif not (font_metadata.post_script_name.endswith('-' + pair[0][0]) or
font_metadata.post_script_name.endswith('-' + pair[1][0])):
yield FAIL, ("METADATA.pb: Mismatch between postScriptName (\"{}\")"
" and weight value ({}). The name must be"
" ended with \"{}\" or \"{}\"."
"").format(font_metadata.post_script_name,
pair[0][1],
pair[0][0],
pair[1][0])
else:
yield PASS, "Weight value matches postScriptName." | python | def com_google_fonts_check_metadata_match_weight_postscript(font_metadata):
"""METADATA.pb weight matches postScriptName."""
WEIGHTS = {
"Thin": 100,
"ThinItalic": 100,
"ExtraLight": 200,
"ExtraLightItalic": 200,
"Light": 300,
"LightItalic": 300,
"Regular": 400,
"Italic": 400,
"Medium": 500,
"MediumItalic": 500,
"SemiBold": 600,
"SemiBoldItalic": 600,
"Bold": 700,
"BoldItalic": 700,
"ExtraBold": 800,
"ExtraBoldItalic": 800,
"Black": 900,
"BlackItalic": 900
}
pair = []
for k, weight in WEIGHTS.items():
if weight == font_metadata.weight:
pair.append((k, weight))
if not pair:
yield FAIL, ("METADATA.pb: Font weight value ({})"
" is invalid.").format(font_metadata.weight)
elif not (font_metadata.post_script_name.endswith('-' + pair[0][0]) or
font_metadata.post_script_name.endswith('-' + pair[1][0])):
yield FAIL, ("METADATA.pb: Mismatch between postScriptName (\"{}\")"
" and weight value ({}). The name must be"
" ended with \"{}\" or \"{}\"."
"").format(font_metadata.post_script_name,
pair[0][1],
pair[0][0],
pair[1][0])
else:
yield PASS, "Weight value matches postScriptName." | [
"def",
"com_google_fonts_check_metadata_match_weight_postscript",
"(",
"font_metadata",
")",
":",
"WEIGHTS",
"=",
"{",
"\"Thin\"",
":",
"100",
",",
"\"ThinItalic\"",
":",
"100",
",",
"\"ExtraLight\"",
":",
"200",
",",
"\"ExtraLightItalic\"",
":",
"200",
",",
"\"Light\"",
":",
"300",
",",
"\"LightItalic\"",
":",
"300",
",",
"\"Regular\"",
":",
"400",
",",
"\"Italic\"",
":",
"400",
",",
"\"Medium\"",
":",
"500",
",",
"\"MediumItalic\"",
":",
"500",
",",
"\"SemiBold\"",
":",
"600",
",",
"\"SemiBoldItalic\"",
":",
"600",
",",
"\"Bold\"",
":",
"700",
",",
"\"BoldItalic\"",
":",
"700",
",",
"\"ExtraBold\"",
":",
"800",
",",
"\"ExtraBoldItalic\"",
":",
"800",
",",
"\"Black\"",
":",
"900",
",",
"\"BlackItalic\"",
":",
"900",
"}",
"pair",
"=",
"[",
"]",
"for",
"k",
",",
"weight",
"in",
"WEIGHTS",
".",
"items",
"(",
")",
":",
"if",
"weight",
"==",
"font_metadata",
".",
"weight",
":",
"pair",
".",
"append",
"(",
"(",
"k",
",",
"weight",
")",
")",
"if",
"not",
"pair",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb: Font weight value ({})\"",
"\" is invalid.\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"weight",
")",
"elif",
"not",
"(",
"font_metadata",
".",
"post_script_name",
".",
"endswith",
"(",
"'-'",
"+",
"pair",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"or",
"font_metadata",
".",
"post_script_name",
".",
"endswith",
"(",
"'-'",
"+",
"pair",
"[",
"1",
"]",
"[",
"0",
"]",
")",
")",
":",
"yield",
"FAIL",
",",
"(",
"\"METADATA.pb: Mismatch between postScriptName (\\\"{}\\\")\"",
"\" and weight value ({}). The name must be\"",
"\" ended with \\\"{}\\\" or \\\"{}\\\".\"",
"\"\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"post_script_name",
",",
"pair",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"pair",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Weight value matches postScriptName.\""
] | METADATA.pb weight matches postScriptName. | [
"METADATA",
".",
"pb",
"weight",
"matches",
"postScriptName",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2259-L2299 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_unitsperem_strict | def com_google_fonts_check_unitsperem_strict(ttFont):
""" Stricter unitsPerEm criteria for Google Fonts. """
upm_height = ttFont["head"].unitsPerEm
ACCEPTABLE = [16, 32, 64, 128, 256, 500,
512, 1000, 1024, 2000, 2048]
if upm_height not in ACCEPTABLE:
yield FAIL, (f"Font em size (unitsPerEm) is {upm_height}."
" If possible, please consider using 1000"
" or even 2000 (which is ideal for"
" Variable Fonts)."
" The acceptable values for unitsPerEm,"
f" though, are: {ACCEPTABLE}.")
elif upm_height != 2000:
yield WARN, (f"Even though unitsPerEm ({upm_height}) in"
" this font is reasonable. It is strongly"
" advised to consider changing it to 2000,"
" since it will likely improve the quality of"
" Variable Fonts by avoiding excessive"
" rounding of coordinates on interpolations.")
else:
yield PASS, "Font em size is good (unitsPerEm = 2000)." | python | def com_google_fonts_check_unitsperem_strict(ttFont):
""" Stricter unitsPerEm criteria for Google Fonts. """
upm_height = ttFont["head"].unitsPerEm
ACCEPTABLE = [16, 32, 64, 128, 256, 500,
512, 1000, 1024, 2000, 2048]
if upm_height not in ACCEPTABLE:
yield FAIL, (f"Font em size (unitsPerEm) is {upm_height}."
" If possible, please consider using 1000"
" or even 2000 (which is ideal for"
" Variable Fonts)."
" The acceptable values for unitsPerEm,"
f" though, are: {ACCEPTABLE}.")
elif upm_height != 2000:
yield WARN, (f"Even though unitsPerEm ({upm_height}) in"
" this font is reasonable. It is strongly"
" advised to consider changing it to 2000,"
" since it will likely improve the quality of"
" Variable Fonts by avoiding excessive"
" rounding of coordinates on interpolations.")
else:
yield PASS, "Font em size is good (unitsPerEm = 2000)." | [
"def",
"com_google_fonts_check_unitsperem_strict",
"(",
"ttFont",
")",
":",
"upm_height",
"=",
"ttFont",
"[",
"\"head\"",
"]",
".",
"unitsPerEm",
"ACCEPTABLE",
"=",
"[",
"16",
",",
"32",
",",
"64",
",",
"128",
",",
"256",
",",
"500",
",",
"512",
",",
"1000",
",",
"1024",
",",
"2000",
",",
"2048",
"]",
"if",
"upm_height",
"not",
"in",
"ACCEPTABLE",
":",
"yield",
"FAIL",
",",
"(",
"f\"Font em size (unitsPerEm) is {upm_height}.\"",
"\" If possible, please consider using 1000\"",
"\" or even 2000 (which is ideal for\"",
"\" Variable Fonts).\"",
"\" The acceptable values for unitsPerEm,\"",
"f\" though, are: {ACCEPTABLE}.\"",
")",
"elif",
"upm_height",
"!=",
"2000",
":",
"yield",
"WARN",
",",
"(",
"f\"Even though unitsPerEm ({upm_height}) in\"",
"\" this font is reasonable. It is strongly\"",
"\" advised to consider changing it to 2000,\"",
"\" since it will likely improve the quality of\"",
"\" Variable Fonts by avoiding excessive\"",
"\" rounding of coordinates on interpolations.\"",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Font em size is good (unitsPerEm = 2000).\""
] | Stricter unitsPerEm criteria for Google Fonts. | [
"Stricter",
"unitsPerEm",
"criteria",
"for",
"Google",
"Fonts",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2367-L2387 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | remote_styles | def remote_styles(family_metadata):
"""Get a dictionary of TTFont objects of all font files of
a given family as currently hosted at Google Fonts.
"""
def download_family_from_Google_Fonts(family_name):
"""Return a zipfile containing a font family hosted on fonts.google.com"""
from zipfile import ZipFile
from fontbakery.utils import download_file
url_prefix = 'https://fonts.google.com/download?family='
url = '{}{}'.format(url_prefix, family_name.replace(' ', '+'))
return ZipFile(download_file(url))
def fonts_from_zip(zipfile):
'''return a list of fontTools TTFonts'''
from fontTools.ttLib import TTFont
from io import BytesIO
fonts = []
for file_name in zipfile.namelist():
if file_name.lower().endswith(".ttf"):
file_obj = BytesIO(zipfile.open(file_name).read())
fonts.append([file_name, TTFont(file_obj)])
return fonts
if (not listed_on_gfonts_api(family_metadata) or
not family_metadata):
return None
remote_fonts_zip = download_family_from_Google_Fonts(family_metadata.name)
rstyles = {}
for remote_filename, remote_font in fonts_from_zip(remote_fonts_zip):
remote_style = os.path.splitext(remote_filename)[0]
if '-' in remote_style:
remote_style = remote_style.split('-')[1]
rstyles[remote_style] = remote_font
return rstyles | python | def remote_styles(family_metadata):
"""Get a dictionary of TTFont objects of all font files of
a given family as currently hosted at Google Fonts.
"""
def download_family_from_Google_Fonts(family_name):
"""Return a zipfile containing a font family hosted on fonts.google.com"""
from zipfile import ZipFile
from fontbakery.utils import download_file
url_prefix = 'https://fonts.google.com/download?family='
url = '{}{}'.format(url_prefix, family_name.replace(' ', '+'))
return ZipFile(download_file(url))
def fonts_from_zip(zipfile):
'''return a list of fontTools TTFonts'''
from fontTools.ttLib import TTFont
from io import BytesIO
fonts = []
for file_name in zipfile.namelist():
if file_name.lower().endswith(".ttf"):
file_obj = BytesIO(zipfile.open(file_name).read())
fonts.append([file_name, TTFont(file_obj)])
return fonts
if (not listed_on_gfonts_api(family_metadata) or
not family_metadata):
return None
remote_fonts_zip = download_family_from_Google_Fonts(family_metadata.name)
rstyles = {}
for remote_filename, remote_font in fonts_from_zip(remote_fonts_zip):
remote_style = os.path.splitext(remote_filename)[0]
if '-' in remote_style:
remote_style = remote_style.split('-')[1]
rstyles[remote_style] = remote_font
return rstyles | [
"def",
"remote_styles",
"(",
"family_metadata",
")",
":",
"def",
"download_family_from_Google_Fonts",
"(",
"family_name",
")",
":",
"\"\"\"Return a zipfile containing a font family hosted on fonts.google.com\"\"\"",
"from",
"zipfile",
"import",
"ZipFile",
"from",
"fontbakery",
".",
"utils",
"import",
"download_file",
"url_prefix",
"=",
"'https://fonts.google.com/download?family='",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"url_prefix",
",",
"family_name",
".",
"replace",
"(",
"' '",
",",
"'+'",
")",
")",
"return",
"ZipFile",
"(",
"download_file",
"(",
"url",
")",
")",
"def",
"fonts_from_zip",
"(",
"zipfile",
")",
":",
"'''return a list of fontTools TTFonts'''",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"from",
"io",
"import",
"BytesIO",
"fonts",
"=",
"[",
"]",
"for",
"file_name",
"in",
"zipfile",
".",
"namelist",
"(",
")",
":",
"if",
"file_name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".ttf\"",
")",
":",
"file_obj",
"=",
"BytesIO",
"(",
"zipfile",
".",
"open",
"(",
"file_name",
")",
".",
"read",
"(",
")",
")",
"fonts",
".",
"append",
"(",
"[",
"file_name",
",",
"TTFont",
"(",
"file_obj",
")",
"]",
")",
"return",
"fonts",
"if",
"(",
"not",
"listed_on_gfonts_api",
"(",
"family_metadata",
")",
"or",
"not",
"family_metadata",
")",
":",
"return",
"None",
"remote_fonts_zip",
"=",
"download_family_from_Google_Fonts",
"(",
"family_metadata",
".",
"name",
")",
"rstyles",
"=",
"{",
"}",
"for",
"remote_filename",
",",
"remote_font",
"in",
"fonts_from_zip",
"(",
"remote_fonts_zip",
")",
":",
"remote_style",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"remote_filename",
")",
"[",
"0",
"]",
"if",
"'-'",
"in",
"remote_style",
":",
"remote_style",
"=",
"remote_style",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
"rstyles",
"[",
"remote_style",
"]",
"=",
"remote_font",
"return",
"rstyles"
] | Get a dictionary of TTFont objects of all font files of
a given family as currently hosted at Google Fonts. | [
"Get",
"a",
"dictionary",
"of",
"TTFont",
"objects",
"of",
"all",
"font",
"files",
"of",
"a",
"given",
"family",
"as",
"currently",
"hosted",
"at",
"Google",
"Fonts",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2391-L2428 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | github_gfonts_ttFont | def github_gfonts_ttFont(ttFont, license):
"""Get a TTFont object of a font downloaded
from Google Fonts git repository.
"""
if not license:
return
from fontbakery.utils import download_file
from fontTools.ttLib import TTFont
from urllib.request import HTTPError
LICENSE_DIRECTORY = {
"OFL.txt": "ofl",
"UFL.txt": "ufl",
"LICENSE.txt": "apache"
}
filename = os.path.basename(ttFont.reader.file.name)
fontname = filename.split('-')[0].lower()
url = ("https://github.com/google/fonts/raw/master"
"/{}/{}/{}").format(LICENSE_DIRECTORY[license],
fontname,
filename)
try:
fontfile = download_file(url)
return TTFont(fontfile)
except HTTPError:
return None | python | def github_gfonts_ttFont(ttFont, license):
"""Get a TTFont object of a font downloaded
from Google Fonts git repository.
"""
if not license:
return
from fontbakery.utils import download_file
from fontTools.ttLib import TTFont
from urllib.request import HTTPError
LICENSE_DIRECTORY = {
"OFL.txt": "ofl",
"UFL.txt": "ufl",
"LICENSE.txt": "apache"
}
filename = os.path.basename(ttFont.reader.file.name)
fontname = filename.split('-')[0].lower()
url = ("https://github.com/google/fonts/raw/master"
"/{}/{}/{}").format(LICENSE_DIRECTORY[license],
fontname,
filename)
try:
fontfile = download_file(url)
return TTFont(fontfile)
except HTTPError:
return None | [
"def",
"github_gfonts_ttFont",
"(",
"ttFont",
",",
"license",
")",
":",
"if",
"not",
"license",
":",
"return",
"from",
"fontbakery",
".",
"utils",
"import",
"download_file",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"from",
"urllib",
".",
"request",
"import",
"HTTPError",
"LICENSE_DIRECTORY",
"=",
"{",
"\"OFL.txt\"",
":",
"\"ofl\"",
",",
"\"UFL.txt\"",
":",
"\"ufl\"",
",",
"\"LICENSE.txt\"",
":",
"\"apache\"",
"}",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"ttFont",
".",
"reader",
".",
"file",
".",
"name",
")",
"fontname",
"=",
"filename",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"url",
"=",
"(",
"\"https://github.com/google/fonts/raw/master\"",
"\"/{}/{}/{}\"",
")",
".",
"format",
"(",
"LICENSE_DIRECTORY",
"[",
"license",
"]",
",",
"fontname",
",",
"filename",
")",
"try",
":",
"fontfile",
"=",
"download_file",
"(",
"url",
")",
"return",
"TTFont",
"(",
"fontfile",
")",
"except",
"HTTPError",
":",
"return",
"None"
] | Get a TTFont object of a font downloaded
from Google Fonts git repository. | [
"Get",
"a",
"TTFont",
"object",
"of",
"a",
"font",
"downloaded",
"from",
"Google",
"Fonts",
"git",
"repository",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2442-L2467 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_version_bump | def com_google_fonts_check_version_bump(ttFont,
api_gfonts_ttFont,
github_gfonts_ttFont):
"""Version number has increased since previous release on Google Fonts?"""
v_number = ttFont["head"].fontRevision
api_gfonts_v_number = api_gfonts_ttFont["head"].fontRevision
github_gfonts_v_number = github_gfonts_ttFont["head"].fontRevision
failed = False
if v_number == api_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is equal to"
" version on Google Fonts.").format(v_number)
if v_number < api_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is less than"
" version on Google Fonts ({})."
"").format(v_number,
api_gfonts_v_number)
if v_number == github_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is equal to"
" version on Google Fonts GitHub repo."
"").format(v_number)
if v_number < github_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is less than"
" version on Google Fonts GitHub repo ({})."
"").format(v_number,
github_gfonts_v_number)
if not failed:
yield PASS, ("Version number {} is greater than"
" version on Google Fonts GitHub ({})"
" and production servers ({})."
"").format(v_number,
github_gfonts_v_number,
api_gfonts_v_number) | python | def com_google_fonts_check_version_bump(ttFont,
api_gfonts_ttFont,
github_gfonts_ttFont):
"""Version number has increased since previous release on Google Fonts?"""
v_number = ttFont["head"].fontRevision
api_gfonts_v_number = api_gfonts_ttFont["head"].fontRevision
github_gfonts_v_number = github_gfonts_ttFont["head"].fontRevision
failed = False
if v_number == api_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is equal to"
" version on Google Fonts.").format(v_number)
if v_number < api_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is less than"
" version on Google Fonts ({})."
"").format(v_number,
api_gfonts_v_number)
if v_number == github_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is equal to"
" version on Google Fonts GitHub repo."
"").format(v_number)
if v_number < github_gfonts_v_number:
failed = True
yield FAIL, ("Version number {} is less than"
" version on Google Fonts GitHub repo ({})."
"").format(v_number,
github_gfonts_v_number)
if not failed:
yield PASS, ("Version number {} is greater than"
" version on Google Fonts GitHub ({})"
" and production servers ({})."
"").format(v_number,
github_gfonts_v_number,
api_gfonts_v_number) | [
"def",
"com_google_fonts_check_version_bump",
"(",
"ttFont",
",",
"api_gfonts_ttFont",
",",
"github_gfonts_ttFont",
")",
":",
"v_number",
"=",
"ttFont",
"[",
"\"head\"",
"]",
".",
"fontRevision",
"api_gfonts_v_number",
"=",
"api_gfonts_ttFont",
"[",
"\"head\"",
"]",
".",
"fontRevision",
"github_gfonts_v_number",
"=",
"github_gfonts_ttFont",
"[",
"\"head\"",
"]",
".",
"fontRevision",
"failed",
"=",
"False",
"if",
"v_number",
"==",
"api_gfonts_v_number",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Version number {} is equal to\"",
"\" version on Google Fonts.\"",
")",
".",
"format",
"(",
"v_number",
")",
"if",
"v_number",
"<",
"api_gfonts_v_number",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Version number {} is less than\"",
"\" version on Google Fonts ({}).\"",
"\"\"",
")",
".",
"format",
"(",
"v_number",
",",
"api_gfonts_v_number",
")",
"if",
"v_number",
"==",
"github_gfonts_v_number",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Version number {} is equal to\"",
"\" version on Google Fonts GitHub repo.\"",
"\"\"",
")",
".",
"format",
"(",
"v_number",
")",
"if",
"v_number",
"<",
"github_gfonts_v_number",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Version number {} is less than\"",
"\" version on Google Fonts GitHub repo ({}).\"",
"\"\"",
")",
".",
"format",
"(",
"v_number",
",",
"github_gfonts_v_number",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"Version number {} is greater than\"",
"\" version on Google Fonts GitHub ({})\"",
"\" and production servers ({}).\"",
"\"\"",
")",
".",
"format",
"(",
"v_number",
",",
"github_gfonts_v_number",
",",
"api_gfonts_v_number",
")"
] | Version number has increased since previous release on Google Fonts? | [
"Version",
"number",
"has",
"increased",
"since",
"previous",
"release",
"on",
"Google",
"Fonts?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2475-L2515 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_production_glyphs_similarity | def com_google_fonts_check_production_glyphs_similarity(ttFont, api_gfonts_ttFont):
"""Glyphs are similiar to Google Fonts version?"""
def glyphs_surface_area(ttFont):
"""Calculate the surface area of a glyph's ink"""
from fontTools.pens.areaPen import AreaPen
glyphs = {}
glyph_set = ttFont.getGlyphSet()
area_pen = AreaPen(glyph_set)
for glyph in glyph_set.keys():
glyph_set[glyph].draw(area_pen)
area = area_pen.value
area_pen.value = 0
glyphs[glyph] = area
return glyphs
bad_glyphs = []
these_glyphs = glyphs_surface_area(ttFont)
gfonts_glyphs = glyphs_surface_area(api_gfonts_ttFont)
shared_glyphs = set(these_glyphs) & set(gfonts_glyphs)
this_upm = ttFont['head'].unitsPerEm
gfonts_upm = api_gfonts_ttFont['head'].unitsPerEm
for glyph in shared_glyphs:
# Normalize area difference against comparison's upm
this_glyph_area = (these_glyphs[glyph] / this_upm) * gfonts_upm
gfont_glyph_area = (gfonts_glyphs[glyph] / gfonts_upm) * this_upm
if abs(this_glyph_area - gfont_glyph_area) > 7000:
bad_glyphs.append(glyph)
if bad_glyphs:
yield WARN, ("Following glyphs differ greatly from"
" Google Fonts version: [{}]").format(", ".join(bad_glyphs))
else:
yield PASS, ("Glyphs are similar in"
" comparison to the Google Fonts version.") | python | def com_google_fonts_check_production_glyphs_similarity(ttFont, api_gfonts_ttFont):
"""Glyphs are similiar to Google Fonts version?"""
def glyphs_surface_area(ttFont):
"""Calculate the surface area of a glyph's ink"""
from fontTools.pens.areaPen import AreaPen
glyphs = {}
glyph_set = ttFont.getGlyphSet()
area_pen = AreaPen(glyph_set)
for glyph in glyph_set.keys():
glyph_set[glyph].draw(area_pen)
area = area_pen.value
area_pen.value = 0
glyphs[glyph] = area
return glyphs
bad_glyphs = []
these_glyphs = glyphs_surface_area(ttFont)
gfonts_glyphs = glyphs_surface_area(api_gfonts_ttFont)
shared_glyphs = set(these_glyphs) & set(gfonts_glyphs)
this_upm = ttFont['head'].unitsPerEm
gfonts_upm = api_gfonts_ttFont['head'].unitsPerEm
for glyph in shared_glyphs:
# Normalize area difference against comparison's upm
this_glyph_area = (these_glyphs[glyph] / this_upm) * gfonts_upm
gfont_glyph_area = (gfonts_glyphs[glyph] / gfonts_upm) * this_upm
if abs(this_glyph_area - gfont_glyph_area) > 7000:
bad_glyphs.append(glyph)
if bad_glyphs:
yield WARN, ("Following glyphs differ greatly from"
" Google Fonts version: [{}]").format(", ".join(bad_glyphs))
else:
yield PASS, ("Glyphs are similar in"
" comparison to the Google Fonts version.") | [
"def",
"com_google_fonts_check_production_glyphs_similarity",
"(",
"ttFont",
",",
"api_gfonts_ttFont",
")",
":",
"def",
"glyphs_surface_area",
"(",
"ttFont",
")",
":",
"\"\"\"Calculate the surface area of a glyph's ink\"\"\"",
"from",
"fontTools",
".",
"pens",
".",
"areaPen",
"import",
"AreaPen",
"glyphs",
"=",
"{",
"}",
"glyph_set",
"=",
"ttFont",
".",
"getGlyphSet",
"(",
")",
"area_pen",
"=",
"AreaPen",
"(",
"glyph_set",
")",
"for",
"glyph",
"in",
"glyph_set",
".",
"keys",
"(",
")",
":",
"glyph_set",
"[",
"glyph",
"]",
".",
"draw",
"(",
"area_pen",
")",
"area",
"=",
"area_pen",
".",
"value",
"area_pen",
".",
"value",
"=",
"0",
"glyphs",
"[",
"glyph",
"]",
"=",
"area",
"return",
"glyphs",
"bad_glyphs",
"=",
"[",
"]",
"these_glyphs",
"=",
"glyphs_surface_area",
"(",
"ttFont",
")",
"gfonts_glyphs",
"=",
"glyphs_surface_area",
"(",
"api_gfonts_ttFont",
")",
"shared_glyphs",
"=",
"set",
"(",
"these_glyphs",
")",
"&",
"set",
"(",
"gfonts_glyphs",
")",
"this_upm",
"=",
"ttFont",
"[",
"'head'",
"]",
".",
"unitsPerEm",
"gfonts_upm",
"=",
"api_gfonts_ttFont",
"[",
"'head'",
"]",
".",
"unitsPerEm",
"for",
"glyph",
"in",
"shared_glyphs",
":",
"# Normalize area difference against comparison's upm",
"this_glyph_area",
"=",
"(",
"these_glyphs",
"[",
"glyph",
"]",
"/",
"this_upm",
")",
"*",
"gfonts_upm",
"gfont_glyph_area",
"=",
"(",
"gfonts_glyphs",
"[",
"glyph",
"]",
"/",
"gfonts_upm",
")",
"*",
"this_upm",
"if",
"abs",
"(",
"this_glyph_area",
"-",
"gfont_glyph_area",
")",
">",
"7000",
":",
"bad_glyphs",
".",
"append",
"(",
"glyph",
")",
"if",
"bad_glyphs",
":",
"yield",
"WARN",
",",
"(",
"\"Following glyphs differ greatly from\"",
"\" Google Fonts version: [{}]\"",
")",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"bad_glyphs",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"Glyphs are similar in\"",
"\" comparison to the Google Fonts version.\"",
")"
] | Glyphs are similiar to Google Fonts version? | [
"Glyphs",
"are",
"similiar",
"to",
"Google",
"Fonts",
"version?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2522-L2562 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_italic_angle | def com_google_fonts_check_italic_angle(ttFont, style):
"""Checking post.italicAngle value."""
failed = False
value = ttFont["post"].italicAngle
# Checking that italicAngle <= 0
if value > 0:
failed = True
yield FAIL, Message("positive",
("The value of post.italicAngle is positive, which"
" is likely a mistake and should become negative,"
" from {} to {}.").format(value, -value))
# Checking that italicAngle is less than 20° (not good) or 30° (bad)
# Also note we invert the value to check it in a clear way
if abs(value) > 30:
failed = True
yield FAIL, Message("over -30 degrees",
("The value of post.italicAngle ({}) is very"
" high (over -30°!) and should be"
" confirmed.").format(value))
elif abs(value) > 20:
failed = True
yield WARN, Message("over -20 degrees",
("The value of post.italicAngle ({}) seems very"
" high (over -20°!) and should be"
" confirmed.").format(value))
# Checking if italicAngle matches font style:
if "Italic" in style:
if ttFont['post'].italicAngle == 0:
failed = True
yield FAIL, Message("zero-italic",
("Font is italic, so post.italicAngle"
" should be non-zero."))
else:
if ttFont["post"].italicAngle != 0:
failed = True
yield FAIL, Message("non-zero-normal",
("Font is not italic, so post.italicAngle"
" should be equal to zero."))
if not failed:
yield PASS, ("Value of post.italicAngle is {}"
" with style='{}'.").format(value, style) | python | def com_google_fonts_check_italic_angle(ttFont, style):
"""Checking post.italicAngle value."""
failed = False
value = ttFont["post"].italicAngle
# Checking that italicAngle <= 0
if value > 0:
failed = True
yield FAIL, Message("positive",
("The value of post.italicAngle is positive, which"
" is likely a mistake and should become negative,"
" from {} to {}.").format(value, -value))
# Checking that italicAngle is less than 20° (not good) or 30° (bad)
# Also note we invert the value to check it in a clear way
if abs(value) > 30:
failed = True
yield FAIL, Message("over -30 degrees",
("The value of post.italicAngle ({}) is very"
" high (over -30°!) and should be"
" confirmed.").format(value))
elif abs(value) > 20:
failed = True
yield WARN, Message("over -20 degrees",
("The value of post.italicAngle ({}) seems very"
" high (over -20°!) and should be"
" confirmed.").format(value))
# Checking if italicAngle matches font style:
if "Italic" in style:
if ttFont['post'].italicAngle == 0:
failed = True
yield FAIL, Message("zero-italic",
("Font is italic, so post.italicAngle"
" should be non-zero."))
else:
if ttFont["post"].italicAngle != 0:
failed = True
yield FAIL, Message("non-zero-normal",
("Font is not italic, so post.italicAngle"
" should be equal to zero."))
if not failed:
yield PASS, ("Value of post.italicAngle is {}"
" with style='{}'.").format(value, style) | [
"def",
"com_google_fonts_check_italic_angle",
"(",
"ttFont",
",",
"style",
")",
":",
"failed",
"=",
"False",
"value",
"=",
"ttFont",
"[",
"\"post\"",
"]",
".",
"italicAngle",
"# Checking that italicAngle <= 0",
"if",
"value",
">",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"positive\"",
",",
"(",
"\"The value of post.italicAngle is positive, which\"",
"\" is likely a mistake and should become negative,\"",
"\" from {} to {}.\"",
")",
".",
"format",
"(",
"value",
",",
"-",
"value",
")",
")",
"# Checking that italicAngle is less than 20° (not good) or 30° (bad)",
"# Also note we invert the value to check it in a clear way",
"if",
"abs",
"(",
"value",
")",
">",
"30",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"over -30 degrees\"",
",",
"(",
"\"The value of post.italicAngle ({}) is very\"",
"\" high (over -30°!) and should be\"",
"\" confirmed.\"",
")",
".",
"format",
"(",
"value",
")",
")",
"elif",
"abs",
"(",
"value",
")",
">",
"20",
":",
"failed",
"=",
"True",
"yield",
"WARN",
",",
"Message",
"(",
"\"over -20 degrees\"",
",",
"(",
"\"The value of post.italicAngle ({}) seems very\"",
"\" high (over -20°!) and should be\"",
"\" confirmed.\"",
")",
".",
"format",
"(",
"value",
")",
")",
"# Checking if italicAngle matches font style:",
"if",
"\"Italic\"",
"in",
"style",
":",
"if",
"ttFont",
"[",
"'post'",
"]",
".",
"italicAngle",
"==",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"zero-italic\"",
",",
"(",
"\"Font is italic, so post.italicAngle\"",
"\" should be non-zero.\"",
")",
")",
"else",
":",
"if",
"ttFont",
"[",
"\"post\"",
"]",
".",
"italicAngle",
"!=",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"Message",
"(",
"\"non-zero-normal\"",
",",
"(",
"\"Font is not italic, so post.italicAngle\"",
"\" should be equal to zero.\"",
")",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"Value of post.italicAngle is {}\"",
"\" with style='{}'.\"",
")",
".",
"format",
"(",
"value",
",",
"style",
")"
] | Checking post.italicAngle value. | [
"Checking",
"post",
".",
"italicAngle",
"value",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2610-L2655 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_mac_style | def com_google_fonts_check_mac_style(ttFont, style):
"""Checking head.macStyle value."""
from fontbakery.utils import check_bit_entry
from fontbakery.constants import MacStyle
# Checking macStyle ITALIC bit:
expected = "Italic" in style
yield check_bit_entry(ttFont, "head", "macStyle",
expected,
bitmask=MacStyle.ITALIC,
bitname="ITALIC")
# Checking macStyle BOLD bit:
expected = style in ["Bold", "BoldItalic"]
yield check_bit_entry(ttFont, "head", "macStyle",
expected,
bitmask=MacStyle.BOLD,
bitname="BOLD") | python | def com_google_fonts_check_mac_style(ttFont, style):
"""Checking head.macStyle value."""
from fontbakery.utils import check_bit_entry
from fontbakery.constants import MacStyle
# Checking macStyle ITALIC bit:
expected = "Italic" in style
yield check_bit_entry(ttFont, "head", "macStyle",
expected,
bitmask=MacStyle.ITALIC,
bitname="ITALIC")
# Checking macStyle BOLD bit:
expected = style in ["Bold", "BoldItalic"]
yield check_bit_entry(ttFont, "head", "macStyle",
expected,
bitmask=MacStyle.BOLD,
bitname="BOLD") | [
"def",
"com_google_fonts_check_mac_style",
"(",
"ttFont",
",",
"style",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"check_bit_entry",
"from",
"fontbakery",
".",
"constants",
"import",
"MacStyle",
"# Checking macStyle ITALIC bit:",
"expected",
"=",
"\"Italic\"",
"in",
"style",
"yield",
"check_bit_entry",
"(",
"ttFont",
",",
"\"head\"",
",",
"\"macStyle\"",
",",
"expected",
",",
"bitmask",
"=",
"MacStyle",
".",
"ITALIC",
",",
"bitname",
"=",
"\"ITALIC\"",
")",
"# Checking macStyle BOLD bit:",
"expected",
"=",
"style",
"in",
"[",
"\"Bold\"",
",",
"\"BoldItalic\"",
"]",
"yield",
"check_bit_entry",
"(",
"ttFont",
",",
"\"head\"",
",",
"\"macStyle\"",
",",
"expected",
",",
"bitmask",
"=",
"MacStyle",
".",
"BOLD",
",",
"bitname",
"=",
"\"BOLD\"",
")"
] | Checking head.macStyle value. | [
"Checking",
"head",
".",
"macStyle",
"value",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2668-L2685 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_contour_count | def com_google_fonts_check_contour_count(ttFont):
"""Check if each glyph has the recommended amount of contours.
This check is useful to assure glyphs aren't incorrectly constructed.
The desired_glyph_data module contains the 'recommended' countour count
for encoded glyphs. The contour counts are derived from fonts which were
chosen for their quality and unique design decisions for particular glyphs.
In the future, additional glyph data can be included. A good addition would
be the 'recommended' anchor counts for each glyph.
"""
from fontbakery.glyphdata import desired_glyph_data as glyph_data
from fontbakery.utils import (get_font_glyph_data,
pretty_print_list)
# rearrange data structure:
desired_glyph_data = {}
for glyph in glyph_data:
desired_glyph_data[glyph['unicode']] = glyph
bad_glyphs = []
desired_glyph_contours = {f: desired_glyph_data[f]['contours']
for f in desired_glyph_data}
font_glyph_data = get_font_glyph_data(ttFont)
if font_glyph_data is None:
yield FAIL, "This font lacks cmap data."
else:
font_glyph_contours = {f['unicode']: list(f['contours'])[0]
for f in font_glyph_data}
shared_glyphs = set(desired_glyph_contours) & set(font_glyph_contours)
for glyph in shared_glyphs:
if font_glyph_contours[glyph] not in desired_glyph_contours[glyph]:
bad_glyphs.append([glyph,
font_glyph_contours[glyph],
desired_glyph_contours[glyph]])
if len(bad_glyphs) > 0:
cmap = ttFont['cmap'].getcmap(PlatformID.WINDOWS,
WindowsEncodingID.UNICODE_BMP).cmap
bad_glyphs_name = [("Glyph name: {}\t"
"Contours detected: {}\t"
"Expected: {}").format(cmap[name],
count,
pretty_print_list(expected,
shorten=None,
glue="or"))
for name, count, expected in bad_glyphs]
yield WARN, (("This check inspects the glyph outlines and detects the"
" total number of contours in each of them. The expected"
" values are infered from the typical ammounts of"
" contours observed in a large collection of reference"
" font families. The divergences listed below may simply"
" indicate a significantly different design on some of"
" your glyphs. On the other hand, some of these may flag"
" actual bugs in the font such as glyphs mapped to an"
" incorrect codepoint. Please consider reviewing"
" the design and codepoint assignment of these to make"
" sure they are correct.\n"
"\n"
"The following glyphs do not have the recommended"
" number of contours:\n"
"\n{}").format('\n'.join(bad_glyphs_name)))
else:
yield PASS, "All glyphs have the recommended amount of contours" | python | def com_google_fonts_check_contour_count(ttFont):
"""Check if each glyph has the recommended amount of contours.
This check is useful to assure glyphs aren't incorrectly constructed.
The desired_glyph_data module contains the 'recommended' countour count
for encoded glyphs. The contour counts are derived from fonts which were
chosen for their quality and unique design decisions for particular glyphs.
In the future, additional glyph data can be included. A good addition would
be the 'recommended' anchor counts for each glyph.
"""
from fontbakery.glyphdata import desired_glyph_data as glyph_data
from fontbakery.utils import (get_font_glyph_data,
pretty_print_list)
# rearrange data structure:
desired_glyph_data = {}
for glyph in glyph_data:
desired_glyph_data[glyph['unicode']] = glyph
bad_glyphs = []
desired_glyph_contours = {f: desired_glyph_data[f]['contours']
for f in desired_glyph_data}
font_glyph_data = get_font_glyph_data(ttFont)
if font_glyph_data is None:
yield FAIL, "This font lacks cmap data."
else:
font_glyph_contours = {f['unicode']: list(f['contours'])[0]
for f in font_glyph_data}
shared_glyphs = set(desired_glyph_contours) & set(font_glyph_contours)
for glyph in shared_glyphs:
if font_glyph_contours[glyph] not in desired_glyph_contours[glyph]:
bad_glyphs.append([glyph,
font_glyph_contours[glyph],
desired_glyph_contours[glyph]])
if len(bad_glyphs) > 0:
cmap = ttFont['cmap'].getcmap(PlatformID.WINDOWS,
WindowsEncodingID.UNICODE_BMP).cmap
bad_glyphs_name = [("Glyph name: {}\t"
"Contours detected: {}\t"
"Expected: {}").format(cmap[name],
count,
pretty_print_list(expected,
shorten=None,
glue="or"))
for name, count, expected in bad_glyphs]
yield WARN, (("This check inspects the glyph outlines and detects the"
" total number of contours in each of them. The expected"
" values are infered from the typical ammounts of"
" contours observed in a large collection of reference"
" font families. The divergences listed below may simply"
" indicate a significantly different design on some of"
" your glyphs. On the other hand, some of these may flag"
" actual bugs in the font such as glyphs mapped to an"
" incorrect codepoint. Please consider reviewing"
" the design and codepoint assignment of these to make"
" sure they are correct.\n"
"\n"
"The following glyphs do not have the recommended"
" number of contours:\n"
"\n{}").format('\n'.join(bad_glyphs_name)))
else:
yield PASS, "All glyphs have the recommended amount of contours" | [
"def",
"com_google_fonts_check_contour_count",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"glyphdata",
"import",
"desired_glyph_data",
"as",
"glyph_data",
"from",
"fontbakery",
".",
"utils",
"import",
"(",
"get_font_glyph_data",
",",
"pretty_print_list",
")",
"# rearrange data structure:",
"desired_glyph_data",
"=",
"{",
"}",
"for",
"glyph",
"in",
"glyph_data",
":",
"desired_glyph_data",
"[",
"glyph",
"[",
"'unicode'",
"]",
"]",
"=",
"glyph",
"bad_glyphs",
"=",
"[",
"]",
"desired_glyph_contours",
"=",
"{",
"f",
":",
"desired_glyph_data",
"[",
"f",
"]",
"[",
"'contours'",
"]",
"for",
"f",
"in",
"desired_glyph_data",
"}",
"font_glyph_data",
"=",
"get_font_glyph_data",
"(",
"ttFont",
")",
"if",
"font_glyph_data",
"is",
"None",
":",
"yield",
"FAIL",
",",
"\"This font lacks cmap data.\"",
"else",
":",
"font_glyph_contours",
"=",
"{",
"f",
"[",
"'unicode'",
"]",
":",
"list",
"(",
"f",
"[",
"'contours'",
"]",
")",
"[",
"0",
"]",
"for",
"f",
"in",
"font_glyph_data",
"}",
"shared_glyphs",
"=",
"set",
"(",
"desired_glyph_contours",
")",
"&",
"set",
"(",
"font_glyph_contours",
")",
"for",
"glyph",
"in",
"shared_glyphs",
":",
"if",
"font_glyph_contours",
"[",
"glyph",
"]",
"not",
"in",
"desired_glyph_contours",
"[",
"glyph",
"]",
":",
"bad_glyphs",
".",
"append",
"(",
"[",
"glyph",
",",
"font_glyph_contours",
"[",
"glyph",
"]",
",",
"desired_glyph_contours",
"[",
"glyph",
"]",
"]",
")",
"if",
"len",
"(",
"bad_glyphs",
")",
">",
"0",
":",
"cmap",
"=",
"ttFont",
"[",
"'cmap'",
"]",
".",
"getcmap",
"(",
"PlatformID",
".",
"WINDOWS",
",",
"WindowsEncodingID",
".",
"UNICODE_BMP",
")",
".",
"cmap",
"bad_glyphs_name",
"=",
"[",
"(",
"\"Glyph name: {}\\t\"",
"\"Contours detected: {}\\t\"",
"\"Expected: {}\"",
")",
".",
"format",
"(",
"cmap",
"[",
"name",
"]",
",",
"count",
",",
"pretty_print_list",
"(",
"expected",
",",
"shorten",
"=",
"None",
",",
"glue",
"=",
"\"or\"",
")",
")",
"for",
"name",
",",
"count",
",",
"expected",
"in",
"bad_glyphs",
"]",
"yield",
"WARN",
",",
"(",
"(",
"\"This check inspects the glyph outlines and detects the\"",
"\" total number of contours in each of them. The expected\"",
"\" values are infered from the typical ammounts of\"",
"\" contours observed in a large collection of reference\"",
"\" font families. The divergences listed below may simply\"",
"\" indicate a significantly different design on some of\"",
"\" your glyphs. On the other hand, some of these may flag\"",
"\" actual bugs in the font such as glyphs mapped to an\"",
"\" incorrect codepoint. Please consider reviewing\"",
"\" the design and codepoint assignment of these to make\"",
"\" sure they are correct.\\n\"",
"\"\\n\"",
"\"The following glyphs do not have the recommended\"",
"\" number of contours:\\n\"",
"\"\\n{}\"",
")",
".",
"format",
"(",
"'\\n'",
".",
"join",
"(",
"bad_glyphs_name",
")",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"All glyphs have the recommended amount of contours\""
] | Check if each glyph has the recommended amount of contours.
This check is useful to assure glyphs aren't incorrectly constructed.
The desired_glyph_data module contains the 'recommended' countour count
for encoded glyphs. The contour counts are derived from fonts which were
chosen for their quality and unique design decisions for particular glyphs.
In the future, additional glyph data can be included. A good addition would
be the 'recommended' anchor counts for each glyph. | [
"Check",
"if",
"each",
"glyph",
"has",
"the",
"recommended",
"amount",
"of",
"contours",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2706-L2772 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_metadata_nameid_copyright | def com_google_fonts_check_metadata_nameid_copyright(ttFont, font_metadata):
"""Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ?"""
failed = False
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncoding())
if nameRecord.nameID == NameID.COPYRIGHT_NOTICE and\
string != font_metadata.copyright:
failed = True
yield FAIL, ("Copyright field for this font on METADATA.pb ('{}')"
" differs from a copyright notice entry"
" on the name table:"
" '{}'").format(font_metadata.copyright,
string)
if not failed:
yield PASS, ("Copyright field for this font on METADATA.pb matches"
" copyright notice entries on the name table.") | python | def com_google_fonts_check_metadata_nameid_copyright(ttFont, font_metadata):
"""Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ?"""
failed = False
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncoding())
if nameRecord.nameID == NameID.COPYRIGHT_NOTICE and\
string != font_metadata.copyright:
failed = True
yield FAIL, ("Copyright field for this font on METADATA.pb ('{}')"
" differs from a copyright notice entry"
" on the name table:"
" '{}'").format(font_metadata.copyright,
string)
if not failed:
yield PASS, ("Copyright field for this font on METADATA.pb matches"
" copyright notice entries on the name table.") | [
"def",
"com_google_fonts_check_metadata_nameid_copyright",
"(",
"ttFont",
",",
"font_metadata",
")",
":",
"failed",
"=",
"False",
"for",
"nameRecord",
"in",
"ttFont",
"[",
"'name'",
"]",
".",
"names",
":",
"string",
"=",
"nameRecord",
".",
"string",
".",
"decode",
"(",
"nameRecord",
".",
"getEncoding",
"(",
")",
")",
"if",
"nameRecord",
".",
"nameID",
"==",
"NameID",
".",
"COPYRIGHT_NOTICE",
"and",
"string",
"!=",
"font_metadata",
".",
"copyright",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Copyright field for this font on METADATA.pb ('{}')\"",
"\" differs from a copyright notice entry\"",
"\" on the name table:\"",
"\" '{}'\"",
")",
".",
"format",
"(",
"font_metadata",
".",
"copyright",
",",
"string",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"Copyright field for this font on METADATA.pb matches\"",
"\" copyright notice entries on the name table.\"",
")"
] | Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ? | [
"Copyright",
"field",
"for",
"this",
"font",
"on",
"METADATA",
".",
"pb",
"matches",
"all",
"copyright",
"notice",
"entries",
"on",
"the",
"name",
"table",
"?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2800-L2816 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_mandatory_entries | def com_google_fonts_check_name_mandatory_entries(ttFont, style):
"""Font has all mandatory 'name' table entries ?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
required_nameIDs = [NameID.FONT_FAMILY_NAME,
NameID.FONT_SUBFAMILY_NAME,
NameID.FULL_FONT_NAME,
NameID.POSTSCRIPT_NAME]
if style not in RIBBI_STYLE_NAMES:
required_nameIDs += [NameID.TYPOGRAPHIC_FAMILY_NAME,
NameID.TYPOGRAPHIC_SUBFAMILY_NAME]
failed = False
# The font must have at least these name IDs:
for nameId in required_nameIDs:
if len(get_name_entry_strings(ttFont, nameId)) == 0:
failed = True
yield FAIL, (f"Font lacks entry with nameId={nameId}"
f" ({NameID(nameId).name})")
if not failed:
yield PASS, "Font contains values for all mandatory name table entries." | python | def com_google_fonts_check_name_mandatory_entries(ttFont, style):
"""Font has all mandatory 'name' table entries ?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
required_nameIDs = [NameID.FONT_FAMILY_NAME,
NameID.FONT_SUBFAMILY_NAME,
NameID.FULL_FONT_NAME,
NameID.POSTSCRIPT_NAME]
if style not in RIBBI_STYLE_NAMES:
required_nameIDs += [NameID.TYPOGRAPHIC_FAMILY_NAME,
NameID.TYPOGRAPHIC_SUBFAMILY_NAME]
failed = False
# The font must have at least these name IDs:
for nameId in required_nameIDs:
if len(get_name_entry_strings(ttFont, nameId)) == 0:
failed = True
yield FAIL, (f"Font lacks entry with nameId={nameId}"
f" ({NameID(nameId).name})")
if not failed:
yield PASS, "Font contains values for all mandatory name table entries." | [
"def",
"com_google_fonts_check_name_mandatory_entries",
"(",
"ttFont",
",",
"style",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"required_nameIDs",
"=",
"[",
"NameID",
".",
"FONT_FAMILY_NAME",
",",
"NameID",
".",
"FONT_SUBFAMILY_NAME",
",",
"NameID",
".",
"FULL_FONT_NAME",
",",
"NameID",
".",
"POSTSCRIPT_NAME",
"]",
"if",
"style",
"not",
"in",
"RIBBI_STYLE_NAMES",
":",
"required_nameIDs",
"+=",
"[",
"NameID",
".",
"TYPOGRAPHIC_FAMILY_NAME",
",",
"NameID",
".",
"TYPOGRAPHIC_SUBFAMILY_NAME",
"]",
"failed",
"=",
"False",
"# The font must have at least these name IDs:",
"for",
"nameId",
"in",
"required_nameIDs",
":",
"if",
"len",
"(",
"get_name_entry_strings",
"(",
"ttFont",
",",
"nameId",
")",
")",
"==",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"f\"Font lacks entry with nameId={nameId}\"",
"f\" ({NameID(nameId).name})\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"Font contains values for all mandatory name table entries.\""
] | Font has all mandatory 'name' table entries ? | [
"Font",
"has",
"all",
"mandatory",
"name",
"table",
"entries",
"?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2868-L2888 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_copyright_length | def com_google_fonts_check_name_copyright_length(ttFont):
""" Length of copyright notice must not exceed 500 characters. """
from fontbakery.utils import get_name_entries
failed = False
for notice in get_name_entries(ttFont, NameID.COPYRIGHT_NOTICE):
notice_str = notice.string.decode(notice.getEncoding())
if len(notice_str) > 500:
failed = True
yield FAIL, ("The length of the following copyright notice ({})"
" exceeds 500 chars: '{}'"
"").format(len(notice_str),
notice_str)
if not failed:
yield PASS, ("All copyright notice name entries on the"
" 'name' table are shorter than 500 characters.") | python | def com_google_fonts_check_name_copyright_length(ttFont):
""" Length of copyright notice must not exceed 500 characters. """
from fontbakery.utils import get_name_entries
failed = False
for notice in get_name_entries(ttFont, NameID.COPYRIGHT_NOTICE):
notice_str = notice.string.decode(notice.getEncoding())
if len(notice_str) > 500:
failed = True
yield FAIL, ("The length of the following copyright notice ({})"
" exceeds 500 chars: '{}'"
"").format(len(notice_str),
notice_str)
if not failed:
yield PASS, ("All copyright notice name entries on the"
" 'name' table are shorter than 500 characters.") | [
"def",
"com_google_fonts_check_name_copyright_length",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entries",
"failed",
"=",
"False",
"for",
"notice",
"in",
"get_name_entries",
"(",
"ttFont",
",",
"NameID",
".",
"COPYRIGHT_NOTICE",
")",
":",
"notice_str",
"=",
"notice",
".",
"string",
".",
"decode",
"(",
"notice",
".",
"getEncoding",
"(",
")",
")",
"if",
"len",
"(",
"notice_str",
")",
">",
"500",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"The length of the following copyright notice ({})\"",
"\" exceeds 500 chars: '{}'\"",
"\"\"",
")",
".",
"format",
"(",
"len",
"(",
"notice_str",
")",
",",
"notice_str",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"(",
"\"All copyright notice name entries on the\"",
"\" 'name' table are shorter than 500 characters.\"",
")"
] | Length of copyright notice must not exceed 500 characters. | [
"Length",
"of",
"copyright",
"notice",
"must",
"not",
"exceed",
"500",
"characters",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3181-L3196 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_fontv | def com_google_fonts_check_fontv(ttFont):
""" Check for font-v versioning """
from fontv.libfv import FontVersion
fv = FontVersion(ttFont)
if fv.version and (fv.is_development or fv.is_release):
yield PASS, "Font version string looks GREAT!"
else:
yield INFO, ("Version string is: \"{}\"\n"
"The version string must ideally include a git commit hash"
" and either a 'dev' or a 'release' suffix such as in the"
" example below:\n"
"\"Version 1.3; git-0d08353-release\""
"").format(fv.get_name_id5_version_string()) | python | def com_google_fonts_check_fontv(ttFont):
""" Check for font-v versioning """
from fontv.libfv import FontVersion
fv = FontVersion(ttFont)
if fv.version and (fv.is_development or fv.is_release):
yield PASS, "Font version string looks GREAT!"
else:
yield INFO, ("Version string is: \"{}\"\n"
"The version string must ideally include a git commit hash"
" and either a 'dev' or a 'release' suffix such as in the"
" example below:\n"
"\"Version 1.3; git-0d08353-release\""
"").format(fv.get_name_id5_version_string()) | [
"def",
"com_google_fonts_check_fontv",
"(",
"ttFont",
")",
":",
"from",
"fontv",
".",
"libfv",
"import",
"FontVersion",
"fv",
"=",
"FontVersion",
"(",
"ttFont",
")",
"if",
"fv",
".",
"version",
"and",
"(",
"fv",
".",
"is_development",
"or",
"fv",
".",
"is_release",
")",
":",
"yield",
"PASS",
",",
"\"Font version string looks GREAT!\"",
"else",
":",
"yield",
"INFO",
",",
"(",
"\"Version string is: \\\"{}\\\"\\n\"",
"\"The version string must ideally include a git commit hash\"",
"\" and either a 'dev' or a 'release' suffix such as in the\"",
"\" example below:\\n\"",
"\"\\\"Version 1.3; git-0d08353-release\\\"\"",
"\"\"",
")",
".",
"format",
"(",
"fv",
".",
"get_name_id5_version_string",
"(",
")",
")"
] | Check for font-v versioning | [
"Check",
"for",
"font",
"-",
"v",
"versioning"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3239-L3252 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_negative_advance_width | def com_google_fonts_check_negative_advance_width(ttFont):
""" Check that advance widths cannot be inferred as negative. """
failed = False
for glyphName in ttFont["glyf"].glyphs:
coords = ttFont["glyf"][glyphName].coordinates
rightX = coords[-3][0]
leftX = coords[-4][0]
advwidth = rightX - leftX
if advwidth < 0:
failed = True
yield FAIL, ("glyph '{}' has bad coordinates on the glyf table,"
" which may lead to the advance width to be"
" interpreted as a negative"
" value ({}).").format(glyphName,
advwidth)
if not failed:
yield PASS, "The x-coordinates of all glyphs look good." | python | def com_google_fonts_check_negative_advance_width(ttFont):
""" Check that advance widths cannot be inferred as negative. """
failed = False
for glyphName in ttFont["glyf"].glyphs:
coords = ttFont["glyf"][glyphName].coordinates
rightX = coords[-3][0]
leftX = coords[-4][0]
advwidth = rightX - leftX
if advwidth < 0:
failed = True
yield FAIL, ("glyph '{}' has bad coordinates on the glyf table,"
" which may lead to the advance width to be"
" interpreted as a negative"
" value ({}).").format(glyphName,
advwidth)
if not failed:
yield PASS, "The x-coordinates of all glyphs look good." | [
"def",
"com_google_fonts_check_negative_advance_width",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"glyphName",
"in",
"ttFont",
"[",
"\"glyf\"",
"]",
".",
"glyphs",
":",
"coords",
"=",
"ttFont",
"[",
"\"glyf\"",
"]",
"[",
"glyphName",
"]",
".",
"coordinates",
"rightX",
"=",
"coords",
"[",
"-",
"3",
"]",
"[",
"0",
"]",
"leftX",
"=",
"coords",
"[",
"-",
"4",
"]",
"[",
"0",
"]",
"advwidth",
"=",
"rightX",
"-",
"leftX",
"if",
"advwidth",
"<",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"glyph '{}' has bad coordinates on the glyf table,\"",
"\" which may lead to the advance width to be\"",
"\" interpreted as a negative\"",
"\" value ({}).\"",
")",
".",
"format",
"(",
"glyphName",
",",
"advwidth",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"The x-coordinates of all glyphs look good.\""
] | Check that advance widths cannot be inferred as negative. | [
"Check",
"that",
"advance",
"widths",
"cannot",
"be",
"inferred",
"as",
"negative",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3284-L3300 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_varfont_generate_static | def com_google_fonts_check_varfont_generate_static(ttFont):
""" Check a static ttf can be generated from a variable font. """
import tempfile
from fontTools.varLib import mutator
try:
loc = {k.axisTag: float((k.maxValue + k.minValue) / 2)
for k in ttFont['fvar'].axes}
with tempfile.TemporaryFile() as instance:
font = mutator.instantiateVariableFont(ttFont, loc)
font.save(instance)
yield PASS, ("fontTools.varLib.mutator generated a static font "
"instance")
except Exception as e:
yield FAIL, ("fontTools.varLib.mutator failed to generated a static font "
"instance\n{}".format(repr(e))) | python | def com_google_fonts_check_varfont_generate_static(ttFont):
""" Check a static ttf can be generated from a variable font. """
import tempfile
from fontTools.varLib import mutator
try:
loc = {k.axisTag: float((k.maxValue + k.minValue) / 2)
for k in ttFont['fvar'].axes}
with tempfile.TemporaryFile() as instance:
font = mutator.instantiateVariableFont(ttFont, loc)
font.save(instance)
yield PASS, ("fontTools.varLib.mutator generated a static font "
"instance")
except Exception as e:
yield FAIL, ("fontTools.varLib.mutator failed to generated a static font "
"instance\n{}".format(repr(e))) | [
"def",
"com_google_fonts_check_varfont_generate_static",
"(",
"ttFont",
")",
":",
"import",
"tempfile",
"from",
"fontTools",
".",
"varLib",
"import",
"mutator",
"try",
":",
"loc",
"=",
"{",
"k",
".",
"axisTag",
":",
"float",
"(",
"(",
"k",
".",
"maxValue",
"+",
"k",
".",
"minValue",
")",
"/",
"2",
")",
"for",
"k",
"in",
"ttFont",
"[",
"'fvar'",
"]",
".",
"axes",
"}",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"as",
"instance",
":",
"font",
"=",
"mutator",
".",
"instantiateVariableFont",
"(",
"ttFont",
",",
"loc",
")",
"font",
".",
"save",
"(",
"instance",
")",
"yield",
"PASS",
",",
"(",
"\"fontTools.varLib.mutator generated a static font \"",
"\"instance\"",
")",
"except",
"Exception",
"as",
"e",
":",
"yield",
"FAIL",
",",
"(",
"\"fontTools.varLib.mutator failed to generated a static font \"",
"\"instance\\n{}\"",
".",
"format",
"(",
"repr",
"(",
"e",
")",
")",
")"
] | Check a static ttf can be generated from a variable font. | [
"Check",
"a",
"static",
"ttf",
"can",
"be",
"generated",
"from",
"a",
"variable",
"font",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3326-L3341 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_smart_dropout | def com_google_fonts_check_smart_dropout(ttFont):
"""Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
Smart dropout control means activating rules 1, 2 and 5:
Rule 1: If a pixel's center falls within the glyph outline,
that pixel is turned on.
Rule 2: If a contour falls exactly on a pixel's center,
that pixel is turned on.
Rule 5: If a scan line between two adjacent pixel centers
(either vertical or horizontal) is intersected
by both an on-Transition contour and an off-Transition
contour and neither of the pixels was already turned on
by rules 1 and 2, turn on the pixel which is closer to
the midpoint between the on-Transition contour and
off-Transition contour. This is "Smart" dropout control.
"""
INSTRUCTIONS = b"\xb8\x01\xff\x85\xb0\x04\x8d"
if ("prep" in ttFont and
INSTRUCTIONS in ttFont["prep"].program.getBytecode()):
yield PASS, ("'prep' table contains instructions"
" enabling smart dropout control.")
else:
yield FAIL, ("'prep' table does not contain TrueType "
" instructions enabling smart dropout control."
" To fix, export the font with autohinting enabled,"
" or run ttfautohint on the font, or run the "
" `gftools fix-nonhinting` script.") | python | def com_google_fonts_check_smart_dropout(ttFont):
"""Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
Smart dropout control means activating rules 1, 2 and 5:
Rule 1: If a pixel's center falls within the glyph outline,
that pixel is turned on.
Rule 2: If a contour falls exactly on a pixel's center,
that pixel is turned on.
Rule 5: If a scan line between two adjacent pixel centers
(either vertical or horizontal) is intersected
by both an on-Transition contour and an off-Transition
contour and neither of the pixels was already turned on
by rules 1 and 2, turn on the pixel which is closer to
the midpoint between the on-Transition contour and
off-Transition contour. This is "Smart" dropout control.
"""
INSTRUCTIONS = b"\xb8\x01\xff\x85\xb0\x04\x8d"
if ("prep" in ttFont and
INSTRUCTIONS in ttFont["prep"].program.getBytecode()):
yield PASS, ("'prep' table contains instructions"
" enabling smart dropout control.")
else:
yield FAIL, ("'prep' table does not contain TrueType "
" instructions enabling smart dropout control."
" To fix, export the font with autohinting enabled,"
" or run ttfautohint on the font, or run the "
" `gftools fix-nonhinting` script.") | [
"def",
"com_google_fonts_check_smart_dropout",
"(",
"ttFont",
")",
":",
"INSTRUCTIONS",
"=",
"b\"\\xb8\\x01\\xff\\x85\\xb0\\x04\\x8d\"",
"if",
"(",
"\"prep\"",
"in",
"ttFont",
"and",
"INSTRUCTIONS",
"in",
"ttFont",
"[",
"\"prep\"",
"]",
".",
"program",
".",
"getBytecode",
"(",
")",
")",
":",
"yield",
"PASS",
",",
"(",
"\"'prep' table contains instructions\"",
"\" enabling smart dropout control.\"",
")",
"else",
":",
"yield",
"FAIL",
",",
"(",
"\"'prep' table does not contain TrueType \"",
"\" instructions enabling smart dropout control.\"",
"\" To fix, export the font with autohinting enabled,\"",
"\" or run ttfautohint on the font, or run the \"",
"\" `gftools fix-nonhinting` script.\"",
")"
] | Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
Smart dropout control means activating rules 1, 2 and 5:
Rule 1: If a pixel's center falls within the glyph outline,
that pixel is turned on.
Rule 2: If a contour falls exactly on a pixel's center,
that pixel is turned on.
Rule 5: If a scan line between two adjacent pixel centers
(either vertical or horizontal) is intersected
by both an on-Transition contour and an off-Transition
contour and neither of the pixels was already turned on
by rules 1 and 2, turn on the pixel which is closer to
the midpoint between the on-Transition contour and
off-Transition contour. This is "Smart" dropout control. | [
"Font",
"enables",
"smart",
"dropout",
"control",
"in",
"prep",
"table",
"instructions?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3417-L3450 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_aat | def com_google_fonts_check_aat(ttFont):
"""Are there unwanted Apple tables?"""
UNWANTED_TABLES = {
'EBSC', 'Zaph', 'acnt', 'ankr', 'bdat', 'bhed', 'bloc',
'bmap', 'bsln', 'fdsc', 'feat', 'fond', 'gcid', 'just',
'kerx', 'lcar', 'ltag', 'mort', 'morx', 'opbd', 'prop',
'trak', 'xref'
}
unwanted_tables_found = []
for table in ttFont.keys():
if table in UNWANTED_TABLES:
unwanted_tables_found.append(table)
if len(unwanted_tables_found) > 0:
yield FAIL, ("Unwanted AAT tables were found"
" in the font and should be removed, either by"
" fonttools/ttx or by editing them using the tool"
" they built with:"
" {}").format(", ".join(unwanted_tables_found))
else:
yield PASS, "There are no unwanted AAT tables." | python | def com_google_fonts_check_aat(ttFont):
"""Are there unwanted Apple tables?"""
UNWANTED_TABLES = {
'EBSC', 'Zaph', 'acnt', 'ankr', 'bdat', 'bhed', 'bloc',
'bmap', 'bsln', 'fdsc', 'feat', 'fond', 'gcid', 'just',
'kerx', 'lcar', 'ltag', 'mort', 'morx', 'opbd', 'prop',
'trak', 'xref'
}
unwanted_tables_found = []
for table in ttFont.keys():
if table in UNWANTED_TABLES:
unwanted_tables_found.append(table)
if len(unwanted_tables_found) > 0:
yield FAIL, ("Unwanted AAT tables were found"
" in the font and should be removed, either by"
" fonttools/ttx or by editing them using the tool"
" they built with:"
" {}").format(", ".join(unwanted_tables_found))
else:
yield PASS, "There are no unwanted AAT tables." | [
"def",
"com_google_fonts_check_aat",
"(",
"ttFont",
")",
":",
"UNWANTED_TABLES",
"=",
"{",
"'EBSC'",
",",
"'Zaph'",
",",
"'acnt'",
",",
"'ankr'",
",",
"'bdat'",
",",
"'bhed'",
",",
"'bloc'",
",",
"'bmap'",
",",
"'bsln'",
",",
"'fdsc'",
",",
"'feat'",
",",
"'fond'",
",",
"'gcid'",
",",
"'just'",
",",
"'kerx'",
",",
"'lcar'",
",",
"'ltag'",
",",
"'mort'",
",",
"'morx'",
",",
"'opbd'",
",",
"'prop'",
",",
"'trak'",
",",
"'xref'",
"}",
"unwanted_tables_found",
"=",
"[",
"]",
"for",
"table",
"in",
"ttFont",
".",
"keys",
"(",
")",
":",
"if",
"table",
"in",
"UNWANTED_TABLES",
":",
"unwanted_tables_found",
".",
"append",
"(",
"table",
")",
"if",
"len",
"(",
"unwanted_tables_found",
")",
">",
"0",
":",
"yield",
"FAIL",
",",
"(",
"\"Unwanted AAT tables were found\"",
"\" in the font and should be removed, either by\"",
"\" fonttools/ttx or by editing them using the tool\"",
"\" they built with:\"",
"\" {}\"",
")",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"unwanted_tables_found",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"There are no unwanted AAT tables.\""
] | Are there unwanted Apple tables? | [
"Are",
"there",
"unwanted",
"Apple",
"tables?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3477-L3497 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_fvar_name_entries | def com_google_fonts_check_fvar_name_entries(ttFont):
"""All name entries referenced by fvar instances exist on the name table?"""
failed = False
for instance in ttFont["fvar"].instances:
entries = [entry for entry in ttFont["name"].names if entry.nameID == instance.subfamilyNameID]
if len(entries) == 0:
failed = True
yield FAIL, (f"Named instance with coordinates {instance.coordinates}"
f" lacks an entry on the name table (nameID={instance.subfamilyNameID}).")
if not failed:
yield PASS, "OK" | python | def com_google_fonts_check_fvar_name_entries(ttFont):
"""All name entries referenced by fvar instances exist on the name table?"""
failed = False
for instance in ttFont["fvar"].instances:
entries = [entry for entry in ttFont["name"].names if entry.nameID == instance.subfamilyNameID]
if len(entries) == 0:
failed = True
yield FAIL, (f"Named instance with coordinates {instance.coordinates}"
f" lacks an entry on the name table (nameID={instance.subfamilyNameID}).")
if not failed:
yield PASS, "OK" | [
"def",
"com_google_fonts_check_fvar_name_entries",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"instance",
"in",
"ttFont",
"[",
"\"fvar\"",
"]",
".",
"instances",
":",
"entries",
"=",
"[",
"entry",
"for",
"entry",
"in",
"ttFont",
"[",
"\"name\"",
"]",
".",
"names",
"if",
"entry",
".",
"nameID",
"==",
"instance",
".",
"subfamilyNameID",
"]",
"if",
"len",
"(",
"entries",
")",
"==",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"f\"Named instance with coordinates {instance.coordinates}\"",
"f\" lacks an entry on the name table (nameID={instance.subfamilyNameID}).\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"OK\""
] | All name entries referenced by fvar instances exist on the name table? | [
"All",
"name",
"entries",
"referenced",
"by",
"fvar",
"instances",
"exist",
"on",
"the",
"name",
"table?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3509-L3522 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_varfont_weight_instances | def com_google_fonts_check_varfont_weight_instances(ttFont):
"""Variable font weight coordinates must be multiples of 100."""
failed = False
for instance in ttFont["fvar"].instances:
if 'wght' in instance.coordinates and instance.coordinates['wght'] % 100 != 0:
failed = True
yield FAIL, ("Found an variable font instance with"
f" 'wght'={instance.coordinates['wght']}."
" This should instead be a multiple of 100.")
if not failed:
yield PASS, "OK" | python | def com_google_fonts_check_varfont_weight_instances(ttFont):
"""Variable font weight coordinates must be multiples of 100."""
failed = False
for instance in ttFont["fvar"].instances:
if 'wght' in instance.coordinates and instance.coordinates['wght'] % 100 != 0:
failed = True
yield FAIL, ("Found an variable font instance with"
f" 'wght'={instance.coordinates['wght']}."
" This should instead be a multiple of 100.")
if not failed:
yield PASS, "OK" | [
"def",
"com_google_fonts_check_varfont_weight_instances",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"instance",
"in",
"ttFont",
"[",
"\"fvar\"",
"]",
".",
"instances",
":",
"if",
"'wght'",
"in",
"instance",
".",
"coordinates",
"and",
"instance",
".",
"coordinates",
"[",
"'wght'",
"]",
"%",
"100",
"!=",
"0",
":",
"failed",
"=",
"True",
"yield",
"FAIL",
",",
"(",
"\"Found an variable font instance with\"",
"f\" 'wght'={instance.coordinates['wght']}.\"",
"\" This should instead be a multiple of 100.\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"OK\""
] | Variable font weight coordinates must be multiples of 100. | [
"Variable",
"font",
"weight",
"coordinates",
"must",
"be",
"multiples",
"of",
"100",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3549-L3561 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_family_tnum_horizontal_metrics | def com_google_fonts_check_family_tnum_horizontal_metrics(fonts):
"""All tabular figures must have the same width across the RIBBI-family."""
from fontbakery.constants import RIBBI_STYLE_NAMES
from fontTools.ttLib import TTFont
RIBBI_ttFonts = [TTFont(f)
for f in fonts
if style(f) in RIBBI_STYLE_NAMES]
tnum_widths = {}
for ttFont in RIBBI_ttFonts:
glyphs = ttFont.getGlyphSet()
tnum_glyphs = [(glyph_id, glyphs[glyph_id])
for glyph_id in glyphs.keys()
if glyph_id.endswith(".tnum")]
for glyph_id, glyph in tnum_glyphs:
if glyph.width not in tnum_widths:
tnum_widths[glyph.width] = [glyph_id]
else:
tnum_widths[glyph.width].append(glyph_id)
if len(tnum_widths.keys()) > 1:
max_num = 0
most_common_width = None
for width, glyphs in tnum_widths.items():
if len(glyphs) > max_num:
max_num = len(glyphs)
most_common_width = width
del tnum_widths[most_common_width]
yield FAIL, (f"The most common tabular glyph width is {most_common_width}."
" But there are other tabular glyphs with different widths"
f" such as the following ones:\n\t{tnum_widths}.")
else:
yield PASS, "OK" | python | def com_google_fonts_check_family_tnum_horizontal_metrics(fonts):
"""All tabular figures must have the same width across the RIBBI-family."""
from fontbakery.constants import RIBBI_STYLE_NAMES
from fontTools.ttLib import TTFont
RIBBI_ttFonts = [TTFont(f)
for f in fonts
if style(f) in RIBBI_STYLE_NAMES]
tnum_widths = {}
for ttFont in RIBBI_ttFonts:
glyphs = ttFont.getGlyphSet()
tnum_glyphs = [(glyph_id, glyphs[glyph_id])
for glyph_id in glyphs.keys()
if glyph_id.endswith(".tnum")]
for glyph_id, glyph in tnum_glyphs:
if glyph.width not in tnum_widths:
tnum_widths[glyph.width] = [glyph_id]
else:
tnum_widths[glyph.width].append(glyph_id)
if len(tnum_widths.keys()) > 1:
max_num = 0
most_common_width = None
for width, glyphs in tnum_widths.items():
if len(glyphs) > max_num:
max_num = len(glyphs)
most_common_width = width
del tnum_widths[most_common_width]
yield FAIL, (f"The most common tabular glyph width is {most_common_width}."
" But there are other tabular glyphs with different widths"
f" such as the following ones:\n\t{tnum_widths}.")
else:
yield PASS, "OK" | [
"def",
"com_google_fonts_check_family_tnum_horizontal_metrics",
"(",
"fonts",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"RIBBI_ttFonts",
"=",
"[",
"TTFont",
"(",
"f",
")",
"for",
"f",
"in",
"fonts",
"if",
"style",
"(",
"f",
")",
"in",
"RIBBI_STYLE_NAMES",
"]",
"tnum_widths",
"=",
"{",
"}",
"for",
"ttFont",
"in",
"RIBBI_ttFonts",
":",
"glyphs",
"=",
"ttFont",
".",
"getGlyphSet",
"(",
")",
"tnum_glyphs",
"=",
"[",
"(",
"glyph_id",
",",
"glyphs",
"[",
"glyph_id",
"]",
")",
"for",
"glyph_id",
"in",
"glyphs",
".",
"keys",
"(",
")",
"if",
"glyph_id",
".",
"endswith",
"(",
"\".tnum\"",
")",
"]",
"for",
"glyph_id",
",",
"glyph",
"in",
"tnum_glyphs",
":",
"if",
"glyph",
".",
"width",
"not",
"in",
"tnum_widths",
":",
"tnum_widths",
"[",
"glyph",
".",
"width",
"]",
"=",
"[",
"glyph_id",
"]",
"else",
":",
"tnum_widths",
"[",
"glyph",
".",
"width",
"]",
".",
"append",
"(",
"glyph_id",
")",
"if",
"len",
"(",
"tnum_widths",
".",
"keys",
"(",
")",
")",
">",
"1",
":",
"max_num",
"=",
"0",
"most_common_width",
"=",
"None",
"for",
"width",
",",
"glyphs",
"in",
"tnum_widths",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"glyphs",
")",
">",
"max_num",
":",
"max_num",
"=",
"len",
"(",
"glyphs",
")",
"most_common_width",
"=",
"width",
"del",
"tnum_widths",
"[",
"most_common_width",
"]",
"yield",
"FAIL",
",",
"(",
"f\"The most common tabular glyph width is {most_common_width}.\"",
"\" But there are other tabular glyphs with different widths\"",
"f\" such as the following ones:\\n\\t{tnum_widths}.\"",
")",
"else",
":",
"yield",
"PASS",
",",
"\"OK\""
] | All tabular figures must have the same width across the RIBBI-family. | [
"All",
"tabular",
"figures",
"must",
"have",
"the",
"same",
"width",
"across",
"the",
"RIBBI",
"-",
"family",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3579-L3611 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_ligature_carets | def com_google_fonts_check_ligature_carets(ttFont, ligature_glyphs):
"""Are there caret positions declared for every ligature?"""
if ligature_glyphs == -1:
yield FAIL, Message("malformed", "Failed to lookup ligatures."
" This font file seems to be malformed."
" For more info, read:"
" https://github.com"
"/googlefonts/fontbakery/issues/1596")
elif "GDEF" not in ttFont:
yield WARN, Message("GDEF-missing",
("GDEF table is missing, but it is mandatory"
" to declare it on fonts that provide ligature"
" glyphs because the caret (text cursor)"
" positioning for each ligature must be"
" provided in this table."))
else:
lig_caret_list = ttFont["GDEF"].table.LigCaretList
if lig_caret_list is None:
missing = set(ligature_glyphs)
else:
missing = set(ligature_glyphs) - set(lig_caret_list.Coverage.glyphs)
if lig_caret_list is None or lig_caret_list.LigGlyphCount == 0:
yield WARN, Message("lacks-caret-pos",
("This font lacks caret position values for"
" ligature glyphs on its GDEF table."))
elif missing:
missing = "\n\t- ".join(missing)
yield WARN, Message("incomplete-caret-pos-data",
("This font lacks caret positioning"
" values for these ligature glyphs:"
f"\n\t- {missing}\n\n "))
else:
yield PASS, "Looks good!" | python | def com_google_fonts_check_ligature_carets(ttFont, ligature_glyphs):
"""Are there caret positions declared for every ligature?"""
if ligature_glyphs == -1:
yield FAIL, Message("malformed", "Failed to lookup ligatures."
" This font file seems to be malformed."
" For more info, read:"
" https://github.com"
"/googlefonts/fontbakery/issues/1596")
elif "GDEF" not in ttFont:
yield WARN, Message("GDEF-missing",
("GDEF table is missing, but it is mandatory"
" to declare it on fonts that provide ligature"
" glyphs because the caret (text cursor)"
" positioning for each ligature must be"
" provided in this table."))
else:
lig_caret_list = ttFont["GDEF"].table.LigCaretList
if lig_caret_list is None:
missing = set(ligature_glyphs)
else:
missing = set(ligature_glyphs) - set(lig_caret_list.Coverage.glyphs)
if lig_caret_list is None or lig_caret_list.LigGlyphCount == 0:
yield WARN, Message("lacks-caret-pos",
("This font lacks caret position values for"
" ligature glyphs on its GDEF table."))
elif missing:
missing = "\n\t- ".join(missing)
yield WARN, Message("incomplete-caret-pos-data",
("This font lacks caret positioning"
" values for these ligature glyphs:"
f"\n\t- {missing}\n\n "))
else:
yield PASS, "Looks good!" | [
"def",
"com_google_fonts_check_ligature_carets",
"(",
"ttFont",
",",
"ligature_glyphs",
")",
":",
"if",
"ligature_glyphs",
"==",
"-",
"1",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"malformed\"",
",",
"\"Failed to lookup ligatures.\"",
"\" This font file seems to be malformed.\"",
"\" For more info, read:\"",
"\" https://github.com\"",
"\"/googlefonts/fontbakery/issues/1596\"",
")",
"elif",
"\"GDEF\"",
"not",
"in",
"ttFont",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"GDEF-missing\"",
",",
"(",
"\"GDEF table is missing, but it is mandatory\"",
"\" to declare it on fonts that provide ligature\"",
"\" glyphs because the caret (text cursor)\"",
"\" positioning for each ligature must be\"",
"\" provided in this table.\"",
")",
")",
"else",
":",
"lig_caret_list",
"=",
"ttFont",
"[",
"\"GDEF\"",
"]",
".",
"table",
".",
"LigCaretList",
"if",
"lig_caret_list",
"is",
"None",
":",
"missing",
"=",
"set",
"(",
"ligature_glyphs",
")",
"else",
":",
"missing",
"=",
"set",
"(",
"ligature_glyphs",
")",
"-",
"set",
"(",
"lig_caret_list",
".",
"Coverage",
".",
"glyphs",
")",
"if",
"lig_caret_list",
"is",
"None",
"or",
"lig_caret_list",
".",
"LigGlyphCount",
"==",
"0",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"lacks-caret-pos\"",
",",
"(",
"\"This font lacks caret position values for\"",
"\" ligature glyphs on its GDEF table.\"",
")",
")",
"elif",
"missing",
":",
"missing",
"=",
"\"\\n\\t- \"",
".",
"join",
"(",
"missing",
")",
"yield",
"WARN",
",",
"Message",
"(",
"\"incomplete-caret-pos-data\"",
",",
"(",
"\"This font lacks caret positioning\"",
"\" values for these ligature glyphs:\"",
"f\"\\n\\t- {missing}\\n\\n \"",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"\"Looks good!\""
] | Are there caret positions declared for every ligature? | [
"Are",
"there",
"caret",
"positions",
"declared",
"for",
"every",
"ligature?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3660-L3693 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_kerning_for_non_ligated_sequences | def com_google_fonts_check_kerning_for_non_ligated_sequences(ttFont, ligatures, has_kerning_info):
"""Is there kerning info for non-ligated sequences?"""
def look_for_nonligated_kern_info(table):
for pairpos in table.SubTable:
for i, glyph in enumerate(pairpos.Coverage.glyphs):
if not hasattr(pairpos, 'PairSet'):
continue
for pairvalue in pairpos.PairSet[i].PairValueRecord:
kern_pair = (glyph, pairvalue.SecondGlyph)
if kern_pair in ligature_pairs:
ligature_pairs.remove(kern_pair)
def ligatures_str(pairs):
result = [f"\t- {first} + {second}" for first, second in pairs]
return "\n".join(result)
if ligatures == -1:
yield FAIL, Message("malformed", "Failed to lookup ligatures."
" This font file seems to be malformed."
" For more info, read:"
" https://github.com"
"/googlefonts/fontbakery/issues/1596")
else:
ligature_pairs = []
for first, comp in ligatures.items():
for components in comp:
while components:
pair = (first, components[0])
if pair not in ligature_pairs:
ligature_pairs.append(pair)
first = components[0]
components.pop(0)
for record in ttFont["GSUB"].table.FeatureList.FeatureRecord:
if record.FeatureTag == 'kern':
for index in record.Feature.LookupListIndex:
lookup = ttFont["GSUB"].table.LookupList.Lookup[index]
look_for_nonligated_kern_info(lookup)
if ligature_pairs:
yield WARN, Message("lacks-kern-info",
("GPOS table lacks kerning info for the following"
" non-ligated sequences:\n"
"{}\n\n ").format(ligatures_str(ligature_pairs)))
else:
yield PASS, ("GPOS table provides kerning info for "
"all non-ligated sequences.") | python | def com_google_fonts_check_kerning_for_non_ligated_sequences(ttFont, ligatures, has_kerning_info):
"""Is there kerning info for non-ligated sequences?"""
def look_for_nonligated_kern_info(table):
for pairpos in table.SubTable:
for i, glyph in enumerate(pairpos.Coverage.glyphs):
if not hasattr(pairpos, 'PairSet'):
continue
for pairvalue in pairpos.PairSet[i].PairValueRecord:
kern_pair = (glyph, pairvalue.SecondGlyph)
if kern_pair in ligature_pairs:
ligature_pairs.remove(kern_pair)
def ligatures_str(pairs):
result = [f"\t- {first} + {second}" for first, second in pairs]
return "\n".join(result)
if ligatures == -1:
yield FAIL, Message("malformed", "Failed to lookup ligatures."
" This font file seems to be malformed."
" For more info, read:"
" https://github.com"
"/googlefonts/fontbakery/issues/1596")
else:
ligature_pairs = []
for first, comp in ligatures.items():
for components in comp:
while components:
pair = (first, components[0])
if pair not in ligature_pairs:
ligature_pairs.append(pair)
first = components[0]
components.pop(0)
for record in ttFont["GSUB"].table.FeatureList.FeatureRecord:
if record.FeatureTag == 'kern':
for index in record.Feature.LookupListIndex:
lookup = ttFont["GSUB"].table.LookupList.Lookup[index]
look_for_nonligated_kern_info(lookup)
if ligature_pairs:
yield WARN, Message("lacks-kern-info",
("GPOS table lacks kerning info for the following"
" non-ligated sequences:\n"
"{}\n\n ").format(ligatures_str(ligature_pairs)))
else:
yield PASS, ("GPOS table provides kerning info for "
"all non-ligated sequences.") | [
"def",
"com_google_fonts_check_kerning_for_non_ligated_sequences",
"(",
"ttFont",
",",
"ligatures",
",",
"has_kerning_info",
")",
":",
"def",
"look_for_nonligated_kern_info",
"(",
"table",
")",
":",
"for",
"pairpos",
"in",
"table",
".",
"SubTable",
":",
"for",
"i",
",",
"glyph",
"in",
"enumerate",
"(",
"pairpos",
".",
"Coverage",
".",
"glyphs",
")",
":",
"if",
"not",
"hasattr",
"(",
"pairpos",
",",
"'PairSet'",
")",
":",
"continue",
"for",
"pairvalue",
"in",
"pairpos",
".",
"PairSet",
"[",
"i",
"]",
".",
"PairValueRecord",
":",
"kern_pair",
"=",
"(",
"glyph",
",",
"pairvalue",
".",
"SecondGlyph",
")",
"if",
"kern_pair",
"in",
"ligature_pairs",
":",
"ligature_pairs",
".",
"remove",
"(",
"kern_pair",
")",
"def",
"ligatures_str",
"(",
"pairs",
")",
":",
"result",
"=",
"[",
"f\"\\t- {first} + {second}\"",
"for",
"first",
",",
"second",
"in",
"pairs",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"result",
")",
"if",
"ligatures",
"==",
"-",
"1",
":",
"yield",
"FAIL",
",",
"Message",
"(",
"\"malformed\"",
",",
"\"Failed to lookup ligatures.\"",
"\" This font file seems to be malformed.\"",
"\" For more info, read:\"",
"\" https://github.com\"",
"\"/googlefonts/fontbakery/issues/1596\"",
")",
"else",
":",
"ligature_pairs",
"=",
"[",
"]",
"for",
"first",
",",
"comp",
"in",
"ligatures",
".",
"items",
"(",
")",
":",
"for",
"components",
"in",
"comp",
":",
"while",
"components",
":",
"pair",
"=",
"(",
"first",
",",
"components",
"[",
"0",
"]",
")",
"if",
"pair",
"not",
"in",
"ligature_pairs",
":",
"ligature_pairs",
".",
"append",
"(",
"pair",
")",
"first",
"=",
"components",
"[",
"0",
"]",
"components",
".",
"pop",
"(",
"0",
")",
"for",
"record",
"in",
"ttFont",
"[",
"\"GSUB\"",
"]",
".",
"table",
".",
"FeatureList",
".",
"FeatureRecord",
":",
"if",
"record",
".",
"FeatureTag",
"==",
"'kern'",
":",
"for",
"index",
"in",
"record",
".",
"Feature",
".",
"LookupListIndex",
":",
"lookup",
"=",
"ttFont",
"[",
"\"GSUB\"",
"]",
".",
"table",
".",
"LookupList",
".",
"Lookup",
"[",
"index",
"]",
"look_for_nonligated_kern_info",
"(",
"lookup",
")",
"if",
"ligature_pairs",
":",
"yield",
"WARN",
",",
"Message",
"(",
"\"lacks-kern-info\"",
",",
"(",
"\"GPOS table lacks kerning info for the following\"",
"\" non-ligated sequences:\\n\"",
"\"{}\\n\\n \"",
")",
".",
"format",
"(",
"ligatures_str",
"(",
"ligature_pairs",
")",
")",
")",
"else",
":",
"yield",
"PASS",
",",
"(",
"\"GPOS table provides kerning info for \"",
"\"all non-ligated sequences.\"",
")"
] | Is there kerning info for non-ligated sequences? | [
"Is",
"there",
"kerning",
"info",
"for",
"non",
"-",
"ligated",
"sequences?"
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3708-L3755 | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | com_google_fonts_check_name_family_and_style_max_length | def com_google_fonts_check_name_family_and_style_max_length(ttFont):
"""Combined length of family and style must not exceed 27 characters."""
from fontbakery.utils import (get_name_entries,
get_name_entry_strings)
failed = False
for familyname in get_name_entries(ttFont,
NameID.FONT_FAMILY_NAME):
# we'll only match family/style name entries with the same platform ID:
plat = familyname.platformID
familyname_str = familyname.string.decode(familyname.getEncoding())
for stylename_str in get_name_entry_strings(ttFont,
NameID.FONT_SUBFAMILY_NAME,
platformID=plat):
if len(familyname_str + stylename_str) > 27:
failed = True
yield WARN, ("The combined length of family and style"
" exceeds 27 chars in the following '{}' entries:"
" FONT_FAMILY_NAME = '{}' / SUBFAMILY_NAME = '{}'"
"").format(PlatformID(plat).name,
familyname_str,
stylename_str)
yield WARN, ("Please take a look at the conversation at"
" https://github.com/googlefonts/fontbakery/issues/2179"
" in order to understand the reasoning behing these"
" name table records max-length criteria.")
if not failed:
yield PASS, "All name entries are good." | python | def com_google_fonts_check_name_family_and_style_max_length(ttFont):
"""Combined length of family and style must not exceed 27 characters."""
from fontbakery.utils import (get_name_entries,
get_name_entry_strings)
failed = False
for familyname in get_name_entries(ttFont,
NameID.FONT_FAMILY_NAME):
# we'll only match family/style name entries with the same platform ID:
plat = familyname.platformID
familyname_str = familyname.string.decode(familyname.getEncoding())
for stylename_str in get_name_entry_strings(ttFont,
NameID.FONT_SUBFAMILY_NAME,
platformID=plat):
if len(familyname_str + stylename_str) > 27:
failed = True
yield WARN, ("The combined length of family and style"
" exceeds 27 chars in the following '{}' entries:"
" FONT_FAMILY_NAME = '{}' / SUBFAMILY_NAME = '{}'"
"").format(PlatformID(plat).name,
familyname_str,
stylename_str)
yield WARN, ("Please take a look at the conversation at"
" https://github.com/googlefonts/fontbakery/issues/2179"
" in order to understand the reasoning behing these"
" name table records max-length criteria.")
if not failed:
yield PASS, "All name entries are good." | [
"def",
"com_google_fonts_check_name_family_and_style_max_length",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"(",
"get_name_entries",
",",
"get_name_entry_strings",
")",
"failed",
"=",
"False",
"for",
"familyname",
"in",
"get_name_entries",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_FAMILY_NAME",
")",
":",
"# we'll only match family/style name entries with the same platform ID:",
"plat",
"=",
"familyname",
".",
"platformID",
"familyname_str",
"=",
"familyname",
".",
"string",
".",
"decode",
"(",
"familyname",
".",
"getEncoding",
"(",
")",
")",
"for",
"stylename_str",
"in",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
"FONT_SUBFAMILY_NAME",
",",
"platformID",
"=",
"plat",
")",
":",
"if",
"len",
"(",
"familyname_str",
"+",
"stylename_str",
")",
">",
"27",
":",
"failed",
"=",
"True",
"yield",
"WARN",
",",
"(",
"\"The combined length of family and style\"",
"\" exceeds 27 chars in the following '{}' entries:\"",
"\" FONT_FAMILY_NAME = '{}' / SUBFAMILY_NAME = '{}'\"",
"\"\"",
")",
".",
"format",
"(",
"PlatformID",
"(",
"plat",
")",
".",
"name",
",",
"familyname_str",
",",
"stylename_str",
")",
"yield",
"WARN",
",",
"(",
"\"Please take a look at the conversation at\"",
"\" https://github.com/googlefonts/fontbakery/issues/2179\"",
"\" in order to understand the reasoning behing these\"",
"\" name table records max-length criteria.\"",
")",
"if",
"not",
"failed",
":",
"yield",
"PASS",
",",
"\"All name entries are good.\""
] | Combined length of family and style must not exceed 27 characters. | [
"Combined",
"length",
"of",
"family",
"and",
"style",
"must",
"not",
"exceed",
"27",
"characters",
"."
] | b355aea2e619a4477769e060d24c32448aa65399 | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3781-L3807 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.