idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
53,700 | def add_log_file ( logger , log_file , global_log_file = False ) : if global_log_file : add_root_log_file ( log_file ) else : hdlr = logging . FileHandler ( log_file ) formatter = logging . Formatter ( '%(asctime)s %(name)-10s %(levelname)-8s %(message)s' , datefmt = '%m-%d %H:%M:%S' ) hdlr . setFormatter ( formatter ) logger . addHandler ( hdlr ) | Add a log file to this logger . If global_log_file is true log_file will be handed the root logger otherwise it will only be used by this particular logger . |
53,701 | def get_module_profile ( module , name = None ) : try : return module . profile except AttributeError : if 'profile_factory' not in module . __dict__ : return None default_section = Section ( name or module . __name__ ) profile = module . profile_factory ( default_section = default_section ) profile . auto_register ( module . __dict__ ) return profile | Get or create a profile from a module and return it . |
53,702 | def iterargs ( self ) : iterargs = OrderedDict ( ) for name in self . _iterargs : plural = self . _profile . iterargs [ name ] iterargs [ name ] = tuple ( self . _values [ plural ] ) return iterargs | uses the singular name as key |
53,703 | def _exec_check ( self , check : FontbakeryCallable , args : Dict [ str , Any ] ) : try : result = check ( ** args ) if isinstance ( result , types . GeneratorType ) : for sub_result in result : yield self . _check_result ( sub_result ) return except Exception as e : error = FailedCheckError ( e ) result = ( ERROR , error ) yield self . _check_result ( result ) | Yields check sub results . |
53,704 | def check_order ( self , order ) : own_order = self . order for item in order : if item not in own_order : raise ValueError ( f'Order item {item} not found.' ) return order | order must be a subset of self . order |
53,705 | def add_check ( self , check ) : if self . _add_check_callback is not None : if not self . _add_check_callback ( self , check ) : return False self . _checkid2index [ check . id ] = len ( self . _checks ) self . _checks . append ( check ) return True | Please use rather register_check as a decorator . |
53,706 | def merge_section ( self , section , filter_func = None ) : for check in section . checks : if filter_func and not filter_func ( check ) : continue self . add_check ( check ) | Add section . checks to self if not skipped by self . _add_check_callback . order description etc . are not updated . |
53,707 | def validate_values ( self , values ) : format_message = '{}: {} (value: {})' . format messages = [ ] for name , value in values . items ( ) : if name not in self . expected_values : continue valid , message = self . expected_values [ name ] . validate ( value ) if valid : continue messages . append ( format_message ( name , message , value ) ) if len ( messages ) : return False , '\n' . join ( messages ) return True , None | Validate values if they are registered as expected_values and present . |
53,708 | def _get_aggregate_args ( self , item , key ) : if not key in ( 'args' , 'mandatoryArgs' ) : raise TypeError ( 'key must be "args" or "mandatoryArgs", got {}' ) . format ( key ) dependencies = list ( getattr ( item , key ) ) if hasattr ( item , 'conditions' ) : dependencies += [ name for negated , name in map ( is_negated , item . conditions ) ] args = set ( ) while dependencies : name = dependencies . pop ( ) if name in args : continue args . add ( name ) c = self . conditions . get ( name , None ) if c is None : continue dependencies += [ dependency for dependency in getattr ( c , key ) if dependency not in args ] return args | Get all arguments or mandatory arguments of the item . |
53,709 | def get_iterargs ( self , item ) : args = self . _get_aggregate_args ( item , 'mandatoryArgs' ) return tuple ( sorted ( [ arg for arg in args if arg in self . iterargs ] ) ) | Returns a tuple of all iterags for item sorted by name . |
53,710 | def auto_register ( self , symbol_table , filter_func = None , profile_imports = None ) : if profile_imports : symbol_table = symbol_table . copy ( ) symbol_table [ 'profile_imports' ] = profile_imports all_items = list ( symbol_table . values ( ) ) + self . _load_profile_imports ( symbol_table ) namespace_types = ( FontBakeryCondition , FontBakeryExpectedValue ) namespace_items = [ ] for item in all_items : if isinstance ( item , namespace_types ) : namespace_items . append ( item ) elif isinstance ( item , FontBakeryCheck ) : if filter_func and not filter_func ( 'check' , item . id , item ) : continue self . register_check ( item ) elif isinstance ( item , types . ModuleType ) : if filter_func and not filter_func ( 'module' , item . __name__ , item ) : continue profile = get_module_profile ( item ) if profile : self . merge_profile ( profile , filter_func = filter_func ) for item in namespace_items : if isinstance ( item , FontBakeryCondition ) : if filter_func and not filter_func ( 'condition' , item . name , item ) : continue self . register_condition ( item ) elif isinstance ( item , FontBakeryExpectedValue ) : if filter_func and not filter_func ( 'expected_value' , item . name , item ) : continue self . register_expected_value ( item ) | Register items from symbol_table in the profile . |
53,711 | def merge_profile ( self , profile , filter_func = None ) : for ns_type in self . _valid_namespace_types : ns_dict = getattr ( profile , ns_type ) if filter_func : ns_type_singular = self . _valid_namespace_types [ ns_type ] ns_dict = { name : item for name , item in ns_dict . items ( ) if filter_func ( ns_type_singular , name , item ) } self . _add_dict_to_namespace ( ns_type , ns_dict ) check_filter_func = None if not filter_func else lambda check : filter_func ( 'check' , check . id , check ) for section in profile . sections : my_section = self . _sections . get ( str ( section ) , None ) if not len ( section . checks ) : continue if my_section is None : my_section = section . clone ( check_filter_func ) self . add_section ( my_section ) else : my_section . merge_section ( section , check_filter_func ) | Copy all namespace items from profile to self . |
53,712 | def serialize_identity ( self , identity ) : section , check , iterargs = identity values = map ( partial ( json . dumps , separators = ( ',' , ':' ) ) , [ str ( section ) , check . id , sorted ( iterargs ) ] ) return '{{"section":{},"check":{},"iterargs":{}}}' . format ( * values ) | Return a json string that can also be used as a key . |
53,713 | def get_profile ( ) : argument_parser = ThrowingArgumentParser ( add_help = False ) argument_parser . add_argument ( 'profile' ) try : args , _ = argument_parser . parse_known_args ( ) except ArgumentParserError : return Profile ( ) imported = get_module ( args . profile ) profile = get_module_profile ( imported ) if not profile : raise Exception ( f"Can't get a profile from {imported}." ) return profile | Prefetch the profile module to fill some holes in the help text . |
53,714 | def collate_fonts_data ( fonts_data ) : glyphs = { } for family in fonts_data : for glyph in family : if glyph [ 'unicode' ] not in glyphs : glyphs [ glyph [ 'unicode' ] ] = glyph else : c = glyphs [ glyph [ 'unicode' ] ] [ 'contours' ] glyphs [ glyph [ 'unicode' ] ] [ 'contours' ] = c | glyph [ 'contours' ] return glyphs . values ( ) | Collate individual fonts data into a single glyph data list . |
53,715 | def com_adobe_fonts_check_family_consistent_upm ( ttFonts ) : upm_set = set ( ) for ttFont in ttFonts : upm_set . add ( ttFont [ 'head' ] . unitsPerEm ) if len ( upm_set ) > 1 : yield FAIL , ( "Fonts have different units per em: {}." ) . format ( sorted ( upm_set ) ) else : yield PASS , "Fonts have consistent units per em." | Fonts have consistent Units Per Em? |
53,716 | def com_adobe_fonts_check_find_empty_letters ( ttFont ) : cmap = ttFont . getBestCmap ( ) passed = True letter_categories = { 'Ll' , 'Lm' , 'Lo' , 'Lt' , 'Lu' , } invisible_letters = { 0x115F , 0x1160 , 0x3164 , 0xFFA0 , } for unicode_val , glyph_name in cmap . items ( ) : category = unicodedata . category ( chr ( unicode_val ) ) if ( _quick_and_dirty_glyph_is_empty ( ttFont , glyph_name ) ) and ( category in letter_categories ) and ( unicode_val not in invisible_letters ) : yield FAIL , ( "U+%04X should be visible, but its glyph ('%s') is empty." % ( unicode_val , glyph_name ) ) passed = False if passed : yield PASS , "No empty glyphs for letters found." | Letters in font have glyphs that are not empty? |
53,717 | def com_adobe_fonts_check_name_empty_records ( ttFont ) : failed = False for name_record in ttFont [ 'name' ] . names : name_string = name_record . toUnicode ( ) . strip ( ) if len ( name_string ) == 0 : failed = True name_key = tuple ( [ name_record . platformID , name_record . platEncID , name_record . langID , name_record . nameID ] ) yield FAIL , ( "'name' table record with key={} is " "empty and should be removed." ) . format ( name_key ) if not failed : yield PASS , ( "No empty name table records found." ) | Check name table for empty records . |
53,718 | def com_google_fonts_check_name_no_copyright_on_description ( ttFont ) : failed = False for name in ttFont [ 'name' ] . names : if 'opyright' in name . string . decode ( name . getEncoding ( ) ) and name . nameID == NameID . DESCRIPTION : failed = True if failed : yield FAIL , ( "Namerecords with ID={} (NameID.DESCRIPTION)" " should be removed (perhaps these were added by" " a longstanding FontLab Studio 5.x bug that" " copied copyright notices to them.)" "" ) . format ( NameID . DESCRIPTION ) else : yield PASS , ( "Description strings in the name table" " do not contain any copyright string." ) | Description strings in the name table must not contain copyright info . |
53,719 | def com_google_fonts_check_monospace ( ttFont , glyph_metrics_stats ) : from fontbakery . constants import ( IsFixedWidth , PANOSE_Proportion ) failed = False seems_monospaced = glyph_metrics_stats [ "seems_monospaced" ] most_common_width = glyph_metrics_stats [ "most_common_width" ] width_max = glyph_metrics_stats [ 'width_max' ] if ttFont [ 'hhea' ] . advanceWidthMax != width_max : failed = True yield FAIL , Message ( "bad-advanceWidthMax" , ( "Value of hhea.advanceWidthMax" " should be set to {} but got" " {} instead." "" ) . format ( width_max , ttFont [ 'hhea' ] . advanceWidthMax ) ) if seems_monospaced : if ttFont [ 'post' ] . isFixedPitch == IsFixedWidth . NOT_MONOSPACED : failed = True yield FAIL , Message ( "mono-bad-post-isFixedPitch" , ( "On monospaced fonts, the value of" " post.isFixedPitch must be set to a non-zero value" " (meaning 'fixed width monospaced')," " but got {} instead." "" ) . format ( ttFont [ 'post' ] . isFixedPitch ) ) if ttFont [ 'OS/2' ] . panose . bProportion != PANOSE_Proportion . MONOSPACED : failed = True yield FAIL , Message ( "mono-bad-panose-proportion" , ( "On monospaced fonts, the value of" " OS/2.panose.bProportion must be set to {}" " (proportion: monospaced), but got" " {} instead." "" ) . format ( PANOSE_Proportion . MONOSPACED , ttFont [ 'OS/2' ] . panose . bProportion ) ) num_glyphs = len ( ttFont [ 'glyf' ] . glyphs ) unusually_spaced_glyphs = [ g for g in ttFont [ 'glyf' ] . glyphs if g not in [ '.notdef' , '.null' , 'NULL' ] and ttFont [ 'hmtx' ] . metrics [ g ] [ 0 ] != most_common_width ] outliers_ratio = float ( len ( unusually_spaced_glyphs ) ) / num_glyphs if outliers_ratio > 0 : failed = True yield WARN , Message ( "mono-outliers" , ( "Font is monospaced but {} glyphs" " ({}%) have a different width." " You should check the widths of:" " {}" ) . format ( len ( unusually_spaced_glyphs ) , 100.0 * outliers_ratio , unusually_spaced_glyphs ) ) if not failed : yield PASS , Message ( "mono-good" , ( "Font is monospaced and all" " related metadata look good." ) ) else : if ttFont [ 'post' ] . isFixedPitch != IsFixedWidth . NOT_MONOSPACED : failed = True yield FAIL , Message ( "bad-post-isFixedPitch" , ( "On non-monospaced fonts, the" " post.isFixedPitch value must be set to {}" " (not monospaced), but got {} instead." "" ) . format ( IsFixedWidth . NOT_MONOSPACED , ttFont [ 'post' ] . isFixedPitch ) ) if ttFont [ 'OS/2' ] . panose . bProportion == PANOSE_Proportion . MONOSPACED : failed = True yield FAIL , Message ( "bad-panose-proportion" , ( "On non-monospaced fonts, the" " OS/2.panose.bProportion value can be set to " " any value except 9 (proportion: monospaced)" " which is the bad value we got in this font." ) ) if not failed : yield PASS , Message ( "good" , ( "Font is not monospaced and" " all related metadata look good." ) ) | Checking correctness of monospaced metadata . |
53,720 | def com_google_fonts_check_name_line_breaks ( ttFont ) : failed = False for name in ttFont [ "name" ] . names : string = name . string . decode ( name . getEncoding ( ) ) if "\n" in string : failed = True yield FAIL , ( "Name entry {} on platform {} contains" " a line-break." ) . format ( NameID ( name . nameID ) . name , PlatformID ( name . platformID ) . name ) if not failed : yield PASS , ( "Name table entries are all single-line" " (no line-breaks found)." ) | Name table entries should not contain line - breaks . |
53,721 | def com_google_fonts_check_name_match_familyname_fullfont ( ttFont ) : from fontbakery . utils import get_name_entry_strings familyname = get_name_entry_strings ( ttFont , NameID . FONT_FAMILY_NAME ) fullfontname = get_name_entry_strings ( ttFont , NameID . FULL_FONT_NAME ) if len ( familyname ) == 0 : yield FAIL , Message ( "no-font-family-name" , ( "Font lacks a NameID.FONT_FAMILY_NAME" " entry in the 'name' table." ) ) elif len ( fullfontname ) == 0 : yield FAIL , Message ( "no-full-font-name" , ( "Font lacks a NameID.FULL_FONT_NAME" " entry in the 'name' table." ) ) else : fullfontname = fullfontname [ 0 ] familyname = familyname [ 0 ] if not fullfontname . startswith ( familyname ) : yield FAIL , Message ( "does-not" , ( " On the 'name' table, the full font name" " (NameID {} - FULL_FONT_NAME: '{}')" " does not begin with font family name" " (NameID {} - FONT_FAMILY_NAME:" " '{}')" . format ( NameID . FULL_FONT_NAME , familyname , NameID . FONT_FAMILY_NAME , fullfontname ) ) ) else : yield PASS , "Full font name begins with the font family name." | Does full font name begin with the font family name? |
53,722 | def com_google_fonts_check_family_naming_recommendations ( ttFont ) : import re from fontbakery . utils import get_name_entry_strings bad_entries = [ ] bad_psname = re . compile ( "[^A-Za-z0-9-]" ) for string in get_name_entry_strings ( ttFont , NameID . POSTSCRIPT_NAME ) : if bad_psname . search ( string ) : bad_entries . append ( { 'field' : 'PostScript Name' , 'value' : string , 'rec' : ( 'May contain only a-zA-Z0-9' ' characters and an hyphen.' ) } ) if string . count ( '-' ) > 1 : bad_entries . append ( { 'field' : 'Postscript Name' , 'value' : string , 'rec' : ( 'May contain not more' ' than a single hyphen' ) } ) for string in get_name_entry_strings ( ttFont , NameID . FULL_FONT_NAME ) : if len ( string ) >= 64 : bad_entries . append ( { 'field' : 'Full Font Name' , 'value' : string , 'rec' : 'exceeds max length (63)' } ) for string in get_name_entry_strings ( ttFont , NameID . POSTSCRIPT_NAME ) : if len ( string ) >= 30 : bad_entries . append ( { 'field' : 'PostScript Name' , 'value' : string , 'rec' : 'exceeds max length (29)' } ) for string in get_name_entry_strings ( ttFont , NameID . FONT_FAMILY_NAME ) : if len ( string ) >= 32 : bad_entries . append ( { 'field' : 'Family Name' , 'value' : string , 'rec' : 'exceeds max length (31)' } ) for string in get_name_entry_strings ( ttFont , NameID . FONT_SUBFAMILY_NAME ) : if len ( string ) >= 32 : bad_entries . append ( { 'field' : 'Style Name' , 'value' : string , 'rec' : 'exceeds max length (31)' } ) for string in get_name_entry_strings ( ttFont , NameID . TYPOGRAPHIC_FAMILY_NAME ) : if len ( string ) >= 32 : bad_entries . append ( { 'field' : 'OT Family Name' , 'value' : string , 'rec' : 'exceeds max length (31)' } ) for string in get_name_entry_strings ( ttFont , NameID . TYPOGRAPHIC_SUBFAMILY_NAME ) : if len ( string ) >= 32 : bad_entries . append ( { 'field' : 'OT Style Name' , 'value' : string , 'rec' : 'exceeds max length (31)' } ) if len ( bad_entries ) > 0 : table = "| Field | Value | Recommendation |\n" table += "|:----- |:----- |:-------------- |\n" for bad in bad_entries : table += "| {} | {} | {} |\n" . format ( bad [ "field" ] , bad [ "value" ] , bad [ "rec" ] ) yield INFO , ( "Font does not follow " "some family naming recommendations:\n\n" "{}" ) . format ( table ) else : yield PASS , "Font follows the family naming recommendations." | Font follows the family naming recommendations? |
53,723 | def com_google_fonts_check_name_rfn ( ttFont ) : failed = False for entry in ttFont [ "name" ] . names : string = entry . toUnicode ( ) if "reserved font name" in string . lower ( ) : yield WARN , ( "Name table entry (\"{}\")" " contains \"Reserved Font Name\"." " This is an error except in a few specific" " rare cases." ) . format ( string ) failed = True if not failed : yield PASS , ( "None of the name table strings" " contain \"Reserved Font Name\"." ) | Name table strings must not contain the string Reserved Font Name . |
53,724 | def com_adobe_fonts_check_family_max_4_fonts_per_family_name ( ttFonts ) : from collections import Counter from fontbakery . utils import get_name_entry_strings failed = False family_names = list ( ) for ttFont in ttFonts : names_list = get_name_entry_strings ( ttFont , NameID . FONT_FAMILY_NAME ) names_set = set ( names_list ) family_names . extend ( names_set ) counter = Counter ( family_names ) for family_name , count in counter . items ( ) : if count > 4 : failed = True yield FAIL , ( "Family '{}' has {} fonts (should be 4 or fewer)." ) . format ( family_name , count ) if not failed : yield PASS , ( "There were no more than 4 fonts per family name." ) | Verify that each group of fonts with the same nameID 1 has maximum of 4 fonts |
53,725 | def com_google_fonts_check_family_equal_unicode_encodings ( ttFonts ) : encoding = None failed = False for ttFont in ttFonts : cmap = None for table in ttFont [ 'cmap' ] . tables : if table . format == 4 : cmap = table break if not encoding : encoding = cmap . platEncID if encoding != cmap . platEncID : failed = True if failed : yield FAIL , "Fonts have different unicode encodings." else : yield PASS , "Fonts have equal unicode encodings." | Fonts have equal unicode encodings? |
53,726 | def com_google_fonts_check_all_glyphs_have_codepoints ( ttFont ) : failed = False for subtable in ttFont [ 'cmap' ] . tables : if subtable . isUnicode ( ) : for item in subtable . cmap . items ( ) : codepoint = item [ 0 ] if codepoint is None : failed = True yield FAIL , ( "Glyph {} lacks a unicode" " codepoint assignment" ) . format ( codepoint ) if not failed : yield PASS , "All glyphs have a codepoint value assigned." | Check all glyphs have codepoints assigned . |
53,727 | def run ( self , order = None ) : for event in self . runner . run ( order = order ) : self . receive ( event ) | self . runner must be present |
53,728 | def com_google_fonts_check_name_trailing_spaces ( ttFont ) : failed = False for name_record in ttFont [ 'name' ] . names : name_string = name_record . toUnicode ( ) if name_string != name_string . strip ( ) : failed = True name_key = tuple ( [ name_record . platformID , name_record . platEncID , name_record . langID , name_record . nameID ] ) shortened_str = name_record . toUnicode ( ) if len ( shortened_str ) > 20 : shortened_str = shortened_str [ : 10 ] + "[...]" + shortened_str [ - 10 : ] yield FAIL , ( f"Name table record with key = {name_key} has" " trailing spaces that must be removed:" f" '{shortened_str}'" ) if not failed : yield PASS , ( "No trailing spaces on name table entries." ) | Name table records must not have trailing spaces . |
53,729 | def com_google_fonts_check_family_single_directory ( fonts ) : directories = [ ] for target_file in fonts : directory = os . path . dirname ( target_file ) if directory not in directories : directories . append ( directory ) if len ( directories ) == 1 : yield PASS , "All files are in the same directory." else : yield FAIL , ( "Not all fonts passed in the command line" " are in the same directory. This may lead to" " bad results as the tool will interpret all" " font files as belonging to a single" " font family. The detected directories are:" " {}" . format ( directories ) ) | Checking all files are in the same directory . |
53,730 | def com_google_fonts_check_ftxvalidator ( font ) : import plistlib try : import subprocess ftx_cmd = [ "ftxvalidator" , "-t" , "all" , font ] ftx_output = subprocess . check_output ( ftx_cmd , stderr = subprocess . STDOUT ) ftx_data = plistlib . loads ( ftx_output ) if 'kATSFontTestSeverityFatalError' not in ftx_data [ 'kATSFontTestResultKey' ] : yield PASS , "ftxvalidator passed this file" else : ftx_cmd = [ "ftxvalidator" , "-T" , "-r" , "-t" , "all" , font ] ftx_output = subprocess . check_output ( ftx_cmd , stderr = subprocess . STDOUT ) yield FAIL , f"ftxvalidator output follows:\n\n{ftx_output}\n" except subprocess . CalledProcessError as e : yield ERROR , ( "ftxvalidator returned an error code. Output follows:" "\n\n{}\n" ) . format ( e . output . decode ( 'utf-8' ) ) except OSError : yield ERROR , "ftxvalidator is not available!" | Checking with ftxvalidator . |
53,731 | def com_google_fonts_check_ots ( font ) : import ots try : process = ots . sanitize ( font , check = True , capture_output = True ) except ots . CalledProcessError as e : yield FAIL , ( "ots-sanitize returned an error code ({}). Output follows:\n\n{}{}" ) . format ( e . returncode , e . stderr . decode ( ) , e . stdout . decode ( ) ) else : if process . stderr : yield WARN , ( "ots-sanitize passed this file, however warnings were printed:\n\n{}" ) . format ( process . stderr . decode ( ) ) else : yield PASS , "ots-sanitize passed this file" | Checking with ots - sanitize . |
53,732 | def com_google_fonts_check_fontbakery_version ( ) : try : import subprocess installed_str = None latest_str = None is_latest = False failed = False pip_cmd = [ "pip" , "search" , "fontbakery" ] pip_output = subprocess . check_output ( pip_cmd , stderr = subprocess . STDOUT ) for line in pip_output . decode ( ) . split ( '\n' ) : if 'INSTALLED' in line : installed_str = line . split ( 'INSTALLED' ) [ 1 ] . strip ( ) if 'LATEST' in line : latest_str = line . split ( 'LATEST' ) [ 1 ] . strip ( ) if '(latest)' in line : is_latest = True if not ( is_latest or is_up_to_date ( installed_str , latest_str ) ) : failed = True yield FAIL , ( f"Current Font Bakery version is {installed_str}," f" while a newer {latest_str} is already available." " Please upgrade it with 'pip install -U fontbakery'" ) yield INFO , pip_output . decode ( ) except subprocess . CalledProcessError as e : yield ERROR , ( "Running 'pip search fontbakery' returned an error code." " Output follows :\n\n{}\n" ) . format ( e . output . decode ( ) ) if not failed : yield PASS , "Font Bakery is up-to-date" | Do we have the latest version of FontBakery installed? |
53,733 | def com_google_fonts_check_fontforge_stderr ( font , fontforge_check_results ) : if "skip" in fontforge_check_results : yield SKIP , fontforge_check_results [ "skip" ] return filtered_err_msgs = "" for line in fontforge_check_results [ "ff_err_messages" ] . split ( '\n' ) : if ( 'The following table(s) in the font' ' have been ignored by FontForge' ) in line : continue if "Ignoring 'DSIG' digital signature table" in line : continue filtered_err_msgs += line + '\n' if len ( filtered_err_msgs . strip ( ) ) > 0 : yield WARN , ( "FontForge seems to dislike certain aspects of this font file." " The actual meaning of the log messages below is not always" " clear and may require further investigation.\n\n" "{}" ) . format ( filtered_err_msgs ) else : yield PASS , "FontForge validation did not output any error message." | FontForge validation outputs error messages? |
53,734 | def com_google_fonts_check_mandatory_glyphs ( ttFont ) : from fontbakery . utils import glyph_has_ink if ( ttFont . getGlyphOrder ( ) [ 0 ] == ".notdef" and ".notdef" not in ttFont . getBestCmap ( ) . values ( ) and glyph_has_ink ( ttFont , ".notdef" ) ) : yield PASS , ( "Font contains the .notdef glyph as the first glyph, it does " "not have a Unicode value assigned and contains a drawing." ) else : yield WARN , ( "Font should contain the .notdef glyph as the first glyph, " "it should not have a Unicode value assigned and should " "contain a drawing." ) | Font contains . notdef as first glyph? |
53,735 | def com_google_fonts_check_whitespace_ink ( ttFont ) : from fontbakery . utils import get_glyph_name , glyph_has_ink 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? |
53,736 | 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" } 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 ) : 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? |
53,737 | 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' : '' } 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? |
53,738 | 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" ] : 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? |
53,739 | 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? |
53,740 | 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 . |
53,741 | 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!" if os . path . exists ( xml_file ) : os . remove ( xml_file ) | Checking with fontTools . ttx |
53,742 | 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 . |
53,743 | 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 . |
53,744 | 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? |
53,745 | 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 max_advw = ttFont [ 'hhea' ] . advanceWidthMax outliers = [ ] zero_or_double_width_outliers = [ ] glyphSet = ttFont . getGlyphSet ( ) . keys ( ) 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? |
53,746 | 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 . |
53,747 | 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 . |
53,748 | def write ( self , data ) : self . _buffer . append ( data ) self . _current_ticks += 1 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 |
53,749 | 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 . _buffer = [ ] if reset_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 |
53,750 | 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 ) ) status = type ( str ( 'status' ) , ( object , ) , dict ( count = 0 , progressbar = [ ] ) ) def _append ( status , item , length = 1 , separator = '' ) : 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 |
53,751 | 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 |
53,752 | 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 |
53,753 | 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 . |
53,754 | 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 . |
53,755 | 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 . |
53,756 | def condition ( * args , ** kwds ) : if len ( args ) == 1 and len ( kwds ) == 0 and callable ( args [ 0 ] ) : func = args [ 0 ] return wraps ( func ) ( FontBakeryCondition ( func ) ) else : def wrapper ( func ) : return wraps ( func ) ( FontBakeryCondition ( func , * args , ** kwds ) ) return wrapper | Check wrapper a factory for FontBakeryCondition |
53,757 | def check ( * args , ** kwds ) : def wrapper ( checkfunc ) : return wraps ( checkfunc ) ( FontBakeryCheck ( checkfunc , * args , ** kwds ) ) return wrapper | Check wrapper a factory for FontBakeryCheck |
53,758 | 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 |
53,759 | 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 . |
53,760 | 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 : 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 |
53,761 | 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 . |
53,762 | 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 . |
53,763 | def com_google_fonts_check_family_underline_thickness ( ttFonts ) : underTs = { } underlineThickness = None failed = False for ttfont in ttFonts : fontname = ttfont . reader . file . name 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? |
53,764 | def summary_table ( errors : int , fails : int , warns : int , skips : int , infos : int , passes : int , total : int ) -> str : return f | Return summary table with statistics . |
53,765 | def get_html ( self ) -> str : data = self . getdoc ( ) num_checks = 0 body_elements = [ ] 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 ) 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 . |
53,766 | def omit_loglevel ( self , msg ) -> bool : return self . loglevels and ( self . loglevels [ 0 ] > fontbakery . checkrunner . Status ( msg ) ) | Determine if message is below log level . |
53,767 | 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 . |
53,768 | 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 . |
53,769 | 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 . |
53,770 | 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 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 . |
53,771 | 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 . |
53,772 | def family_directory ( fonts ) : if fonts : dirname = os . path . dirname ( fonts [ 0 ] ) if dirname == '' : dirname = '.' return dirname | Get the path of font project directory . |
53,773 | 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 . |
53,774 | 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? |
53,775 | 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 . |
53,776 | def com_google_fonts_check_family_equal_numbers_of_glyphs ( ttFonts ) : 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? |
53,777 | 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 : avail = ', ' . join ( available_styles ) miss = ', ' . join ( missing_styles ) else : 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? |
53,778 | 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 for row in table . findAll ( 'tr' ) : cells = row . findAll ( 'td' ) 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 . |
53,779 | 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 . |
53,780 | 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 . |
53,781 | 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 . |
53,782 | 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 . |
53,783 | 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? |
53,784 | 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 . |
53,785 | 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 . |
53,786 | 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? |
53,787 | def com_google_fonts_check_has_ttfautohint_params ( ttFont ) : from fontbakery . utils import get_name_entry_strings def ttfautohint_version ( value ) : 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? |
53,788 | 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? |
53,789 | 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? |
53,790 | 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 . |
53,791 | 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 return False failed = False OPTIONAL = { } MANDATORY = { 0x20AC : "EURO SIGN" } 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? |
53,792 | 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? |
53,793 | 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 ? |
53,794 | 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 . |
53,795 | 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 . |
53,796 | 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 . |
53,797 | 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 . |
53,798 | 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 . |
53,799 | 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? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.