Determines the vbalidity of the selected font as well as its properties.
This is vital to make sure that the google-font script that we'll generate later
does not contain any invalid options.
192389
public function process_fonts() {

		// Early exit if font-family is empty.
		if ( empty( $this->fonts ) ) {
			return;
		}

		foreach ( $this->fonts as $font => $variants ) {

			// Determine if this is indeed a google font or not.
			// If it's not, then just remove it from the array.
			if ( ! array_key_exists( $font, $this->google_fonts ) ) {
				unset( $this->fonts[ $font ] );
				continue;
			}

			// Get all valid font variants for this font.
			$font_variants = [];
			if ( isset( $this->google_fonts[ $font ]['variants'] ) ) {
				$font_variants = $this->google_fonts[ $font ]['variants'];
			}
			foreach ( $variants as $variant ) {

				// If this is not a valid variant for this font-family
				// then unset it and move on to the next one.
				if ( ! in_array( strval( $variant ), $font_variants, true ) ) {
					$variant_key = array_search( $variant, $this->fonts[ $font ], true );
					unset( $this->fonts[ $font ][ $variant_key ] );
					continue;
				}
			}
		}
	}
1076765
def getFontFace(self):
        """"""
        userFace = self.buildSpec['terminal_font_family'] or self.defaultFont.GetFaceName()
        return (''
                if self.buildSpec['monospace_display']
                else userFace)
1309386
def get_font_options(self):
        
        font_options = FontOptions()
        cairo.cairo_scaled_font_get_font_options(
            self._pointer, font_options._pointer)
        return font_options
545179
function guessFontStyle(basename) {
  return basename
    .split('-')
    .slice(1)
    .map(item => item.toLowerCase())
    .reduce((prev, item) => {
      if (fontStyleKeywords.indexOf(item) >= 0) {
        return `font-style:${item};`
      }

      return prev
    }, '')
}
600977
def assignFont(self):
        
        font = self.currentFont()
        font.setFamily(self._fontPickerWidget.currentFamily())
        font.setPointSize(self._fontPickerWidget.pointSize())
        self.setCurrentFont(font)
1314352
function() {
    var fonts = ["Roboto", "Bitter", "Pacifico"];
    var options = fonts.map(name => {
      // setting style on an <option> does not work in WebView...
      return <option key={name} value={name}>{name}</option>;
    });
    return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>;
  }
1109904
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)
856946
def OnFont(self, event):
        """"""

        font_data = wx.FontData()

        # Disable color chooser on Windows
        font_data.EnableEffects(False)

        if self.chosen_font:
            font_data.SetInitialFont(self.chosen_font)

        dlg = wx.FontDialog(self, font_data)

        if dlg.ShowModal() == wx.ID_OK:
            font_data = dlg.GetFontData()

            font = self.chosen_font = font_data.GetChosenFont()

            self.font_face = font.GetFaceName()
            self.font_size = font.GetPointSize()
            self.font_style = font.GetStyle()
            self.font_weight = font.GetWeight()

        dlg.Destroy()

        post_command_event(self, self.DrawChartMsg)
488377
def com_google_fonts_check_fsselection(ttFont, style):
  """"""
  from fontbakery.utils import check_bit_entry
  from fontbakery.constants import (STATIC_STYLE_NAMES,
                                    RIBBI_STYLE_NAMES,
                                    FsSelection)

  # Checking fsSelection REGULAR bit:
  expected = "Regular" in style or \
             (style in STATIC_STYLE_NAMES and
              style not in RIBBI_STYLE_NAMES and
              "Italic" not in style)
  yield check_bit_entry(ttFont, "OS/2", "fsSelection",
                        expected,
                        bitmask=FsSelection.REGULAR,
                        bitname="REGULAR")

  # Checking fsSelection ITALIC bit:
  expected = "Italic" in style
  yield check_bit_entry(ttFont, "OS/2", "fsSelection",
                        expected,
                        bitmask=FsSelection.ITALIC,
                        bitname="ITALIC")

  # Checking fsSelection BOLD bit:
  expected = style in ["Bold", "BoldItalic"]
  yield check_bit_entry(ttFont, "OS/2", "fsSelection",
                        expected,
                        bitmask=FsSelection.BOLD,
                        bitname="BOLD")
654423
def com_google_fonts_check_fontvalidator(font):
  """"""

  # In some cases we want to override the severity level of
  # certain checks in FontValidator:
  downgrade_to_warn = [
    # There are reports that this fontval check has an out-of-date
    # understanding of valid bits in fsSelection.
    # More info at:
    # https://github.com/googlei18n/fontmake/issues/414#issuecomment-379408127
    "There are undefined bits set in fsSelection field",

    # FIX-ME: Why did we downgrade this one to WARN?
    "Misoriented contour"
  ]

  # Some other checks we want to completely disable:
  disabled_fval_checks = [
    # FontVal E4012 thinks that
    # "Versions 0x00010000 and 0x0001002 are currently
    #  the only defined versions of the GDEF table."
    # but the GDEF chapter of the OpenType specification at
    # https://docs.microsoft.com/en-us/typography/opentype/spec/gdef
    # describes GDEF header version 1.3, which is not yet recognized
    # by FontVal, thus resulting in this spurious false-FAIL:
    "The version number is neither 0x00010000 nor 0x0001002",

    # These messages below are simply fontval given user feedback
    # on the progress of runnint it. It has nothing to do with
    # actual issues on the font files:
    "Validating glyph with index",
    "Table Test:",

    # No software is affected by Mac strings nowadays.
    # More info at: googlei18n/fontmake#414
    "The table doesn't contain strings for Mac platform",
    "The PostScript string is not present for both required platforms",

    # Font Bakery has got a native check for the xAvgCharWidth field
    # which is: com.google.fonts/check/xavgcharwidth
    "The xAvgCharWidth field does not equal the calculated value",

    # The optimal ordering suggested by FVal check W0020 seems to only be
    # relevant to performance optimizations on old versions of Windows
    # running on old hardware. Since such performance considerations
    # are most likely negligible, we're not going to bother users with
    # this check's table ordering requirements.
    # More info at:
    # https://github.com/googlefonts/fontbakery/issues/2105
    "Tables are not in optimal order",

    # Font Bakery has its own check for required/optional tables:
    # com.google.fonts/check/required_tables
    "Recommended table is missing"
  ]

  # There are also some checks that do not make
  # sense when we're dealing with variable fonts:
  VARFONT_disabled_fval_checks = [
    # Variable fonts typically do have lots of self-intersecting
    # contours because they are used to draw each portion
    # of variable glyph features.
    "Intersecting contours",
    "Intersecting components of composite glyph",

    # DeltaFormat = 32768 (same as 0x8000) means VARIATION_INDEX,
    # according to https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2
    # The FontVal problem description for this check (E5200) only mentions
    # the other values as possible valid ones. So apparently this means FontVal
    # implementation is not up-to-date with more recent versions of the OpenType spec
    # and that's why these spurious FAILs are being emitted.
    # That's good enough reason to mute it.
    # More info at:
    # https://github.com/googlefonts/fontbakery/issues/2109
    "The device table's DeltaFormat value is invalid"
  ]

  from fontTools.ttLib import TTFont
  if is_variable_font(TTFont(font)):
    disabled_fval_checks.extend(VARFONT_disabled_fval_checks)

  try:
    import subprocess
    fval_cmd = [
        "FontValidator", "-file", font, "-all-tables",
        "-report-in-font-dir", "-no-raster-tests"
    ]
    subprocess.check_output(fval_cmd, stderr=subprocess.STDOUT)
  except subprocess.CalledProcessError as e:
    filtered_msgs = ""
    for line in e.output.decode().split("\n"):
      disable_it = False
      for substring in disabled_fval_checks:
        if substring in line:
          disable_it = True
      if not disable_it:
        filtered_msgs += line + "\n"
    yield INFO, ("Microsoft Font Validator returned an error code."
                 " Output follows :\n\n{}\n").format(filtered_msgs)
  except (OSError, IOError) as error:
    yield ERROR, ("Mono runtime and/or "
                  "Microsoft Font Validator are not available!")
    raise error

  def report_message(msg, details):
    if details:
      if isinstance(details, list) and len(details) > 1:
        # We'll print lists with one item per line for
        # improved readability.
        if None in details:
          details.remove(None)

        # A designer will likely not need the full list
        # in order to fix a problem.
        # Showing only the 10 first ones is more than enough
        # and helps avoid flooding the report.
        if len(details) > 25:
          num_similar = len(details) - 10
          details = details[:10]
          details.append(f"NOTE: {num_similar} other similar"
                          " results were hidden!")
        details = '\n\t- ' + '\n\t- '.join(details)
      return f"MS-FonVal: {msg} DETAILS: {details}"
    else:
      return f"MS-FonVal: {msg}"

  xml_report_file = f"{font}.report.xml"
  html_report_file = f"{font}.report.html"
  fval_file = os.path.join(os.path.dirname(font), 'fval.xsl')

  grouped_msgs = {}
  with open(xml_report_file, "rb") as xml_report:
    import defusedxml.lxml
    doc = defusedxml.lxml.parse(xml_report)

    for report in doc.iter('Report'):
      msg = report.get("Message")
      details = report.get("Details")

      disable_it = False
      for substring in disabled_fval_checks:
        if substring in msg:
          disable_it = True
      if disable_it:
        continue

      if msg not in grouped_msgs:
        grouped_msgs[msg] = {"errortype": report.get("ErrorType"),
                             "details": [details]}
      else:
        if details not in grouped_msgs[msg]["details"]:
          # avoid cluttering the output with tons of identical reports
          # yield INFO, 'grouped_msgs[msg]["details"]: {}'.format(grouped_msgs[msg]["details"])
          grouped_msgs[msg]["details"].append(details)

  # ---------------------------
  # Clean-up generated files...
  os.remove(xml_report_file)
  # FontVal internal detail: HTML report generated only on non-Windows due to
  # Mono or the used HTML renderer not being able to render XML with a
  # stylesheet directly. https://github.com/googlefonts/fontbakery/issues/1747
  if os.path.exists(html_report_file):
    os.remove(html_report_file)
  os.remove(fval_file)

  # ---------------------------
  # Here we start emitting the grouped log messages
  for msg, data in grouped_msgs.items():
    # But before printing we try to make the "details" more
    # readable. Otherwise the user would get the text terminal
    # flooded with messy data.

    # No need to print is as a list if wereally only
    # got one log message of this kind:
    if len(data["details"]) == 1:
      data["details"] = data["details"][0]

    # Simplify the list of glyph indices by only displaying
    # their numerical values in a list:
    for glyph_index in ["Glyph index ", "glyph# "]:
      if data["details"] and \
         data["details"][0] and \
         glyph_index in data["details"][0]:
        try:
          data["details"] = {'Glyph index': [int(x.split(glyph_index)[1])
                                             for x in data["details"]]}
          break
        except ValueError:
          pass

    # And, finally, the log messages are emitted:
    if data["errortype"] == "P":
      yield PASS, report_message(msg, data["details"])

    elif data["errortype"] == "E":
      status = FAIL
      for substring in downgrade_to_warn:
        if substring in msg:
          status = WARN
      yield status, report_message(msg, data["details"])

    elif data["errortype"] == "W":
      yield WARN, report_message(msg, data["details"])

    else:
      yield INFO, report_message(msg, data["details"])
348824
function measureTextWidth(font, text) {
       var characters = text.split("");
       var width = 0;
       var lastGlyph = null;

       for (var i = 0; i < characters.length; i++) {
         var ch = characters[i].charCodeAt(0);
         var glyph = font.fontData.glyphs[ch];
         var kerning = lastGlyph && lastGlyph.kerning ? lastGlyph.getKerning(ch) : 0;
         width += (glyph.xadvance + kerning) * font.fontScale.x;
         lastGlyph = glyph;
       }

       return width;
     }
619202
def com_google_fonts_check_fontforge(fontforge_check_results, fontforge_skip_checks):
  """"""
  if "skip" in fontforge_check_results:
    yield SKIP, fontforge_check_results["skip"]
    return

  validation_state = fontforge_check_results["validation_state"]
  fontforge_checks = (
      ("Contours are closed?",
       0x2, FAIL,
       "Contours are not closed!", "Contours are closed.")

    , ("Contours do not intersect",
       0x4, WARN,
       "There are countour intersections!",
       "Contours do not intersect.")

    , ("Contours have correct directions",
       0x8, WARN,
       "Contours have incorrect directions!",
       "Contours have correct directions.")

    , ("References in the glyph haven't been flipped",
       0x10, FAIL,
       "References in the glyph have been flipped!",
       "References in the glyph haven't been flipped.")

    , ("Glyphs have points at extremas",
       0x20, WARN,
       "Glyphs do not have points at extremas!",
       "Glyphs have points at extremas.")

    , ("Glyph names referred to from glyphs present in the font",
       0x40, FAIL,
       "Glyph names referred to from glyphs"
       " not present in the font!",
       "Glyph names referred to from glyphs"
       " present in the font.")

    , ("Points (or control points) are not too far apart",
       0x40000, FAIL,
       "Points (or control points) are too far apart!",
       "Points (or control points) are not too far apart.")

    , ("Not more than 1,500 points in any glyph"
       " (a PostScript limit)",
       0x80, FAIL,
       "There are glyphs with more than 1,500 points!"
       "Exceeds a PostScript limit.",
       "Not more than 1,500 points in any glyph"
       " (a PostScript limit).")

    , ("PostScript has a limit of 96 hints in glyphs",
       0x100, FAIL,
       "Exceeds PostScript limit of 96 hints per glyph",
       "Font respects PostScript limit of 96 hints per glyph")

    , ("Font doesn't have invalid glyph names",
       0x200, FAIL,
       "Font has invalid glyph names!",
       "Font doesn't have invalid glyph names.")

    , ("Glyphs have allowed numbers of points defined in maxp",
       0x400, FAIL,
       "Glyphs exceed allowed numbers of points defined in maxp",
       "Glyphs have allowed numbers of points defined in maxp.")

    , ("Glyphs have allowed numbers of paths defined in maxp",
       0x800, FAIL,
       "Glyphs exceed allowed numbers of paths defined in maxp!",
       "Glyphs have allowed numbers of paths defined in maxp.")

    , ("Composite glyphs have allowed numbers"
       " of points defined in maxp?",
       0x1000, FAIL,
       "Composite glyphs exceed allowed numbers"
       " of points defined in maxp!",
       "Composite glyphs have allowed numbers"
       " of points defined in maxp.")

    , ("Composite glyphs have allowed numbers"
       " of paths defined in maxp",
       0x2000, FAIL,
       "Composite glyphs exceed"
       " allowed numbers of paths defined in maxp!",
       "Composite glyphs have"
       " allowed numbers of paths defined in maxp.")

    , ("Glyphs instructions have valid lengths",
       0x4000, FAIL,
       "Glyphs instructions have invalid lengths!",
       "Glyphs instructions have valid lengths.")

    , ("Points in glyphs are integer aligned",
       0x80000, FAIL,
       "Points in glyphs are not integer aligned!",
       "Points in glyphs are integer aligned.")

    # According to the opentype spec, if a glyph contains an anchor point
    # for one anchor class in a subtable, it must contain anchor points
    # for all anchor classes in the subtable. Even it, logically,
    # they do not apply and are unnecessary.
    , ("Glyphs have all required anchors.",
       0x100000, FAIL,
       "Glyphs do not have all required anchors!",
       "Glyphs have all required anchors.")

    , ("Glyph names are unique?",
       0x200000, FAIL,
       "Glyph names are not unique!",
       "Glyph names are unique.")

    , ("Unicode code points are unique?",
       0x400000, FAIL,
       "Unicode code points are not unique!",
       "Unicode code points are unique.")

    , ("Do hints overlap?",
       0x800000, FAIL,
       "Hints should NOT overlap!",
       "Hints do not overlap.")
  )

  for description, bit, failure_status_override, fail_msg, ok_msg in fontforge_checks:
    if fontforge_skip_checks is not None and \
       bool(fontforge_skip_checks & bit) is not False:
      yield SKIP, description
    elif bool(validation_state & bit) is not False:
      yield failure_status_override, f"fontforge-check: {fail_msg}"
    else:
      yield PASS, f"fontforge-check: {ok_msg}"
201632
private static int fontStyleToInt(FontStyle style) {
        switch (style) {
        case PLAIN:
            return java.awt.Font.PLAIN;
        case BOLD:
            return java.awt.Font.BOLD;
        case ITALIC:
            return java.awt.Font.ITALIC;
        default:
            return java.awt.Font.PLAIN;
        }
    }
968058
function () {
    var data = this.data;
    var el = this.el;
    var fontSrc;
    var geometry = this.geometry;
    var self = this;

    if (!data.font) { warn('No font specified. Using the default font.'); }

    // Make invisible during font swap.
    this.mesh.visible = false;

    // Look up font URL to use, and perform cached load.
    fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
    cache.get(fontSrc, function doLoadFont () {
      return loadFont(fontSrc, data.yOffset);
    }).then(function setFont (font) {
      var fontImgSrc;

      if (font.pages.length !== 1) {
        throw new Error('Currently only single-page bitmap fonts are supported.');
      }

      if (!fontWidthFactors[fontSrc]) {
        font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
      }

      // Update geometry given font metrics.
      self.updateGeometry(geometry, font);

      // Set font and update layout.
      self.currentFont = font;
      self.updateLayout();

      // Look up font image URL to use, and perform cached load.
      fontImgSrc = self.getFontImageSrc();
      cache.get(fontImgSrc, function () {
        return loadTexture(fontImgSrc);
      }).then(function (image) {
        // Make mesh visible and apply font image as texture.
        var texture = self.texture;
        texture.image = image;
        texture.needsUpdate = true;
        textures[data.font] = texture;
        self.texture = texture;
        self.mesh.visible = true;
        el.emit('textfontset', {font: data.font, fontObj: font});
      }).catch(function (err) {
        error(err.message);
        error(err.stack);
      });
    }).catch(function (err) {
      error(err.message);
      error(err.stack);
    });
  }
909748
function calculateTextStyle(helper, item)
{
    if (item instanceof TextStyle)
    {
        const font = item.toFontString();

        TextMetrics.measureFont(font);

        return true;
    }

    return false;
}
49670
public static PDFont chooseMatchingCourier(Font font) {
		if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
			return PDType1Font.COURIER_BOLD_OBLIQUE;
		if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
			return PDType1Font.COURIER_OBLIQUE;
		if ((font.getStyle() & Font.BOLD) == Font.BOLD)
			return PDType1Font.COURIER_BOLD;
		return PDType1Font.COURIER;
	}
535747
protected void readFDSelect(int Font)
	{
		// Restore the number of glyphs
		int NumOfGlyphs = fonts[Font].nglyphs;
		int[] FDSelect = new int[NumOfGlyphs];
		// Go to the beginning of the FDSelect
		seek(fonts[Font].fdselectOffset);
		// Read the FDSelect's format
		fonts[Font].FDSelectFormat = getCard8();
		
		switch(fonts[Font].FDSelectFormat){
			// Format==0 means each glyph has an entry that indicated
			// its FD.
			case 0:
				for (int i=0;i<NumOfGlyphs;i++)
				{
					FDSelect[i] = getCard8();
				}
				// The FDSelect's Length is one for each glyph + the format
				// for later use
				fonts[Font].FDSelectLength = fonts[Font].nglyphs+1;
				break;
			case 3:
				// Format==3 means the ranges version
				// The number of ranges
				int nRanges = getCard16();
				int l=0;
				// Read the first in the first range
				int first = getCard16();
				for (int i=0;i<nRanges;i++)
				{
					// Read the FD index
					int fd = getCard8();
					// Read the first of the next range
					int last = getCard16();
					// Calc the steps and write to the array
					int steps = last-first;
					for (int k=0;k<steps;k++)
					{
						FDSelect[l] = fd;
						l++;
					}
					// The last from this iteration is the first of the next
					first = last;
				}
				// Store the length for later use
				fonts[Font].FDSelectLength = 1+2+nRanges*3+2;
				break;
			default:
				break;
		}
		// Save the FDSelect of the font 
		fonts[Font].FDSelect = FDSelect; 
	}