Create a background layer for all glyphs in ufo_font if not present to
    reduce roundtrip differences.
433087
def ufo_create_background_layer_for_all_glyphs(ufo_font):
    # type: (defcon.Font) -> None
    """"""

    if "public.background" in ufo_font.layers:
        background = ufo_font.layers["public.background"]
    else:
        background = ufo_font.newLayer("public.background")

    for glyph in ufo_font:
        if glyph.name not in background:
            background.newGlyph(glyph.name)
1117033
def to_glyphs_family_user_data_from_designspace(self):
    """"""
    target_user_data = self.font.userData
    for key, value in self.designspace.lib.items():
        if key == UFO2FT_FEATURE_WRITERS_KEY and value == DEFAULT_FEATURE_WRITERS:
            # if the designspace contains featureWriters settings that are the
            # same as glyphsLib default settings, there's no need to store them
            continue
        if _user_data_has_no_special_meaning(key):
            target_user_data[key] = value
741659
def write_transparency(selection):
    """"""
    global themefile, transparency, prefix

    if themefile == "":
        return

    lines = themefile.split('\n')

    for line in lines:
        if 'background' in line.lower():
            try:
                background = line.split(':')[1].replace(' ', '')
                background = background.replace('\t', '')
                break
            except:
                msg = ('Cannot determine background color from themefile. '
                       'Defaulting to: #000000')
                print msg
                background = '#000000'
                break
        else:
            background = '#000000'

    background = hex_to_rgb(background)

    fd, tmpfile = tempfile.mkstemp()
    if exists( XRESOURCES ):
        old = open( XRESOURCES )
        new = os.fdopen(fd, 'w')
        for line in old:
            lline = line.lower()

            if 'depth' in lline:
                continue

            elif 'rgba' in lline:
                continue

            elif line == '\n':
                continue

            else:
                os.write(fd, line)

        os.write(fd, '\n%s.depth:\t32' % prefix)
        os.write(fd, '\n%s.background:\trgba:%s/%s\n' %
                 (prefix, background, decimal_to_alpha(transparency)))
        old.close()
        new.close()
        move( tmpfile, XRESOURCES )
967510
def to_glyphs_glyph_anchors(self, ufo_glyph, layer):
    """"""
    for ufo_anchor in ufo_glyph.anchors:
        anchor = self.glyphs_module.GSAnchor()
        anchor.name = ufo_anchor.name
        anchor.position = Point(ufo_anchor.x, ufo_anchor.y)
        layer.anchors.append(anchor)
572918
function glyphDataSize(glyph) {
  // Ignore glyphs without outlines. These will get a length of zero in the “loca” table
  if (!glyph.contours.length) {
    return 0;
  }

  var result = 12; //glyph fixed properties

  result += glyph.contours.length * 2; //add contours

  _.forEach(glyph.ttf_x, function (x) {
    //add 1 or 2 bytes for each coordinate depending of its size
    result += ((-0xFF <= x && x <= 0xFF)) ? 1 : 2;
  });

  _.forEach(glyph.ttf_y, function (y) {
    //add 1 or 2 bytes for each coordinate depending of its size
    result += ((-0xFF <= y && y <= 0xFF)) ? 1 : 2;
  });

  // Add flags length to glyph size.
  result += glyph.ttf_flags.length;

  if (result % 4 !== 0) { // glyph size must be divisible by 4.
    result += 4 - result % 4;
  }
  return result;
}
1075841
def to_ufo_propagate_font_anchors(self, ufo):
    """"""

    processed = set()
    for glyph in ufo:
        _propagate_glyph_anchors(self, ufo, glyph, processed)
479657
def _output_path(
        self,
        ufo_or_font_name,
        ext,
        is_instance=False,
        interpolatable=False,
        autohinted=False,
        is_variable=False,
        output_dir=None,
        suffix=None,
    ):
        """"""

        if isinstance(ufo_or_font_name, basestring):
            font_name = ufo_or_font_name
        elif ufo_or_font_name.path:
            font_name = os.path.splitext(
                os.path.basename(os.path.normpath(ufo_or_font_name.path))
            )[0]
        else:
            font_name = self._font_name(ufo_or_font_name)

        if output_dir is None:
            output_dir = self._output_dir(
                ext, is_instance, interpolatable, autohinted, is_variable
            )
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        if suffix:
            return os.path.join(output_dir, "{}-{}.{}".format(font_name, suffix, ext))
        else:
            return os.path.join(output_dir, "{}.{}".format(font_name, ext))
105010
def _load_glyph(f, char, glyphs_dict):
    """"""
    from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
                                 FT_LOAD_NO_AUTOHINT)
    flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT
    face = _load_font(f['face'], f['bold'], f['italic'])
    face.set_char_size(f['size'] * 64)
    # get the character of interest
    face.load_char(char, flags)
    bitmap = face.glyph.bitmap
    width = face.glyph.bitmap.width
    height = face.glyph.bitmap.rows
    bitmap = np.array(bitmap.buffer)
    w0 = bitmap.size // height if bitmap.size > 0 else 0
    bitmap.shape = (height, w0)
    bitmap = bitmap[:, :width].astype(np.ubyte)

    left = face.glyph.bitmap_left
    top = face.glyph.bitmap_top
    advance = face.glyph.advance.x / 64.
    glyph = dict(char=char, offset=(left, top), bitmap=bitmap,
                 advance=advance, kerning={})
    glyphs_dict[char] = glyph
    # Generate kerning
    for other_char, other_glyph in glyphs_dict.items():
        kerning = face.get_kerning(other_char, char)
        glyph['kerning'][other_char] = kerning.x / 64.
        kerning = face.get_kerning(char, other_char)
        other_glyph['kerning'][char] = kerning.x / 64.
519505
def closeGlyphsOverGSUB(gsub, glyphs):
    
    subsetter = subset.Subsetter()
    subsetter.glyphs = glyphs
    gsub.closure_glyphs(subsetter)
1199146
def font(self):
        """"""
        if self._font is not None:
            return self._font

        # Sort UFOS in the original order from the Glyphs file
        sorted_sources = self.to_glyphs_ordered_masters()

        # Convert all full source UFOs to Glyphs masters. Sources with layer names
        # are assumed to be sparse or "brace" layers and are ignored because Glyphs
        # considers them to be special layers and will handle them itself.
        self._font = self.glyphs_module.GSFont()
        self._sources = OrderedDict()  # Same as in UFOBuilder
        for index, source in enumerate(s for s in sorted_sources if not s.layerName):
            master = self.glyphs_module.GSFontMaster()

            # Filter bracket glyphs out of public.glyphOrder.
            if GLYPH_ORDER_KEY in source.font.lib:
                source.font.lib[GLYPH_ORDER_KEY] = [
                    glyph_name
                    for glyph_name in source.font.lib[GLYPH_ORDER_KEY]
                    if ".BRACKET." not in glyph_name
                ]

            self.to_glyphs_font_attributes(source, master, is_initial=(index == 0))
            self.to_glyphs_master_attributes(source, master)
            self._font.masters.insert(len(self._font.masters), master)
            self._sources[master.id] = source

            # First, move free-standing bracket glyphs back to layers to avoid dealing
            # with GSLayer transplantation.
            for bracket_glyph in [g for g in source.font if ".BRACKET." in g.name]:
                base_glyph, threshold = bracket_glyph.name.split(".BRACKET.")
                try:
                    int(threshold)
                except ValueError:
                    raise ValueError(
                        "Glyph '{}' has malformed bracket layer name. Must be '<glyph "
                        "name>.BRACKET.<crossover value>'.".format(bracket_glyph)
                    )
                layer_name = bracket_glyph.lib.get(
                    GLYPHLIB_PREFIX + "_originalLayerName", "[{}]".format(threshold)
                )
                if layer_name not in source.font.layers:
                    ufo_layer = source.font.newLayer(layer_name)
                else:
                    ufo_layer = source.font.layers[layer_name]
                bracket_glyph_new = ufo_layer.newGlyph(base_glyph)
                bracket_glyph_new.copyDataFromGlyph(bracket_glyph)

                # Remove all freestanding bracket layer glyphs from all layers.
                for layer in source.font.layers:
                    if bracket_glyph.name in layer:
                        del layer[bracket_glyph.name]

            for layer in _sorted_backgrounds_last(source.font.layers):
                self.to_glyphs_layer_lib(layer)
                for glyph in layer:
                    self.to_glyphs_glyph(glyph, layer, master)

        self.to_glyphs_features()
        self.to_glyphs_groups()
        self.to_glyphs_kerning()

        # Now that all GSGlyph are built, restore the glyph order
        if self.designspace.sources:
            first_ufo = self.designspace.sources[0].font
            if GLYPH_ORDER_KEY in first_ufo.lib:
                glyph_order = first_ufo.lib[GLYPH_ORDER_KEY]
                lookup = {name: i for i, name in enumerate(glyph_order)}
                self.font.glyphs = sorted(
                    self.font.glyphs, key=lambda glyph: lookup.get(glyph.name, 1 << 63)
                )
            # FIXME: (jany) We only do that on the first one. Maybe we should
            # merge the various `public.glyphorder` values?

            # Restore the layer ordering in each glyph
            for glyph in self._font.glyphs:
                self.to_glyphs_layer_order(glyph)

        self.to_glyphs_family_user_data_from_designspace()
        self.to_glyphs_axes()
        self.to_glyphs_sources()
        self.to_glyphs_instances()

        return self._font
630287
def makeMissingRequiredGlyphs(font, glyphSet):
        
        if ".notdef" in glyphSet:
            return

        unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm"))
        ascender = otRound(getAttrWithFallback(font.info, "ascender"))
        descender = otRound(getAttrWithFallback(font.info, "descender"))
        defaultWidth = otRound(unitsPerEm * 0.5)
        glyphSet[".notdef"] = StubGlyph(name=".notdef",
                                        width=defaultWidth,
                                        unitsPerEm=unitsPerEm,
                                        ascender=ascender,
                                        descender=descender)
104456
def com_google_fonts_check_points_out_of_bounds(ttFont):
  """"""
  failed = False
  out_of_bounds = []
  for glyphName in ttFont['glyf'].keys():
    glyph = ttFont['glyf'][glyphName]
    coords = glyph.getCoordinates(ttFont['glyf'])[0]
    for x, y in coords:
      if x < glyph.xMin or x > glyph.xMax or \
         y < glyph.yMin or y > glyph.yMax or \
         abs(x) > 32766 or abs(y) > 32766:
        failed = True
        out_of_bounds.append((glyphName, x, y))

  if failed:
    yield WARN, ("The following glyphs have coordinates which are"
                 " out of bounds:\n{}\nThis happens a lot when points"
                 " are not extremes, which is usually bad. However,"
                 " fixing this alert by adding points on extremes may"
                 " do more harm than good, especially with italics,"
                 " calligraphic-script, handwriting, rounded and"
                 " other fonts. So it is common to"
                 " ignore this message".format(out_of_bounds))
  else:
    yield PASS, "All glyph paths have coordinates within bounds!"
433171
def to_glyphs_glyph(self, ufo_glyph, ufo_layer, master):
    

    # FIXME: (jany) split between glyph and layer attributes
    #        have a write the first time, compare the next times for glyph
    #        always write for the layer

    if ufo_glyph.name in self.font.glyphs:
        glyph = self.font.glyphs[ufo_glyph.name]
    else:
        glyph = self.glyphs_module.GSGlyph(name=ufo_glyph.name)
        # FIXME: (jany) ordering?
        self.font.glyphs.append(glyph)

    if ufo_glyph.unicodes:
        glyph.unicodes = ["{:04X}".format(c) for c in ufo_glyph.unicodes]
    glyph.note = ufo_glyph.note or ""
    if GLYPHLIB_PREFIX + "lastChange" in ufo_glyph.lib:
        last_change = ufo_glyph.lib[GLYPHLIB_PREFIX + "lastChange"]
        # We cannot be strict about the dateformat because it's not an official
        # UFO field mentioned in the spec so it could happen to have a timezone
        glyph.lastChange = from_loose_ufo_time(last_change)
    if ufo_glyph.markColor:
        glyph.color = _to_glyphs_color(ufo_glyph.markColor)

    # The export flag can be stored in the glyph's lib key (for upgrading legacy
    # sources) or the Designspace-level public.skipExportGlyphs lib key (canonical
    # place to store the information). The UFO level lib key is ignored.
    if GLYPHLIB_PREFIX + "Export" in ufo_glyph.lib:
        glyph.export = ufo_glyph.lib[GLYPHLIB_PREFIX + "Export"]
    if ufo_glyph.name in self.designspace.lib.get("public.skipExportGlyphs", []):
        glyph.export = False

    ps_names_key = PUBLIC_PREFIX + "postscriptNames"
    if (
        ps_names_key in ufo_glyph.font.lib
        and ufo_glyph.name in ufo_glyph.font.lib[ps_names_key]
    ):
        glyph.production = ufo_glyph.font.lib[ps_names_key][ufo_glyph.name]
        # FIXME: (jany) maybe put something in glyphinfo? No, it's readonly
        #        maybe don't write in glyph.production if glyphinfo already
        #        has something
        # glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)
        # production_name = glyph.production or glyphinfo.production_name

    glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)

    layer = self.to_glyphs_layer(ufo_layer, glyph, master)

    for key in ["leftMetricsKey", "rightMetricsKey", "widthMetricsKey"]:
        # Also read the old version of the key that didn't have a prefix and
        # store it on the layer (because without the "glyph"/"layer" prefix we
        # didn't know whether it originally came from the layer of the glyph,
        # so it's easier to put it back on the most specific level, i.e. the
        # layer)
        for prefix, glyphs_object in (
            ("glyph.", glyph),
            ("", layer),
            ("layer.", layer),
        ):
            full_key = GLYPHLIB_PREFIX + prefix + key
            if full_key in ufo_glyph.lib:
                value = ufo_glyph.lib[full_key]
                setattr(glyphs_object, key, value)

    if SCRIPT_LIB_KEY in ufo_glyph.lib:
        glyph.script = ufo_glyph.lib[SCRIPT_LIB_KEY]

    if GLYPHLIB_PREFIX + "category" in ufo_glyph.lib:
        # TODO: (jany) store category only if different from glyphinfo?
        category = ufo_glyph.lib[GLYPHLIB_PREFIX + "category"]
        glyph.category = category
    else:
        category = glyphinfo.category
    if GLYPHLIB_PREFIX + "subCategory" in ufo_glyph.lib:
        sub_category = ufo_glyph.lib[GLYPHLIB_PREFIX + "subCategory"]
        glyph.subCategory = sub_category
    else:
        sub_category = glyphinfo.subCategory

    # load width before background, which is loaded with lib data
    if hasattr(layer, "foreground"):
        if ufo_glyph.width:
            # Don't store "0", it's the default in UFO.
            # Store in userData because the background's width is not relevant
            # in Glyphs.
            layer.userData[BACKGROUND_WIDTH_KEY] = ufo_glyph.width
    else:
        layer.width = ufo_glyph.width
    if category == "Mark" and sub_category == "Nonspacing" and layer.width == 0:
        # Restore originalWidth
        if ORIGINAL_WIDTH_KEY in ufo_glyph.lib:
            layer.width = ufo_glyph.lib[ORIGINAL_WIDTH_KEY]
            # TODO: (jany) check for customParam DisableAllAutomaticBehaviour?

    self.to_glyphs_background_image(ufo_glyph, layer)
    self.to_glyphs_guidelines(ufo_glyph, layer)
    self.to_glyphs_annotations(ufo_glyph, layer)
    self.to_glyphs_hints(ufo_glyph, layer)
    self.to_glyphs_glyph_user_data(ufo_glyph.font, glyph)
    self.to_glyphs_layer_user_data(ufo_glyph, layer)
    self.to_glyphs_smart_component_axes(ufo_glyph, glyph)

    self.to_glyphs_paths(ufo_glyph, layer)
    self.to_glyphs_components(ufo_glyph, layer)
    self.to_glyphs_glyph_anchors(ufo_glyph, layer)
548807
def com_daltonmaag_check_ufolint(font):
  """"""
  import subprocess
  ufolint_cmd = ["ufolint", font]

  try:
    subprocess.check_output(ufolint_cmd, stderr=subprocess.STDOUT)
  except subprocess.CalledProcessError as e:
    yield FAIL, ("ufolint failed the UFO source. Output follows :"
                 "\n\n{}\n").format(e.output.decode())
  except OSError:
    yield ERROR, "ufolint is not available!"
  else:
    yield PASS, "ufolint passed the UFO source."
351888
def com_google_fonts_check_production_glyphs_similarity(ttFont, api_gfonts_ttFont):
  """"""

  def glyphs_surface_area(ttFont):
    """Calculate the surface area of a glyph's ink"""
    from fontTools.pens.areaPen import AreaPen
    glyphs = {}
    glyph_set = ttFont.getGlyphSet()
    area_pen = AreaPen(glyph_set)

    for glyph in glyph_set.keys():
      glyph_set[glyph].draw(area_pen)

      area = area_pen.value
      area_pen.value = 0
      glyphs[glyph] = area
    return glyphs

  bad_glyphs = []
  these_glyphs = glyphs_surface_area(ttFont)
  gfonts_glyphs = glyphs_surface_area(api_gfonts_ttFont)

  shared_glyphs = set(these_glyphs) & set(gfonts_glyphs)

  this_upm = ttFont['head'].unitsPerEm
  gfonts_upm = api_gfonts_ttFont['head'].unitsPerEm

  for glyph in shared_glyphs:
    # Normalize area difference against comparison's upm
    this_glyph_area = (these_glyphs[glyph] / this_upm) * gfonts_upm
    gfont_glyph_area = (gfonts_glyphs[glyph] / gfonts_upm) * this_upm

    if abs(this_glyph_area - gfont_glyph_area) > 7000:
      bad_glyphs.append(glyph)

  if bad_glyphs:
    yield WARN, ("Following glyphs differ greatly from"
                 " Google Fonts version: [{}]").format(", ".join(bad_glyphs))
  else:
    yield PASS, ("Glyphs are similar in"
                 " comparison to the Google Fonts version.")
708019
function allGlyphs(rawGlyphs, colors, fileFormat) {
  var unique = nodupes();
  rawGlyphs = fixNames(rawGlyphs);
  return rawGlyphs.map(function(rawGlyph) {
    var name = rawGlyph.css;
    var collection = rawGlyph.src;
    return createGlyph(name, collection, unique(name), colors, fileFormat);
  });
}
1020612
def _init_glyph(self, plot, mapping, properties):
        
        tile_source = mapping['tile_source']
        level = properties.pop('level', 'underlay')
        renderer = plot.add_tile(tile_source, level=level)
        renderer.alpha = properties.get('alpha', 1)

        # Remove save tool
        plot.tools = [t for t in plot.tools if not isinstance(t, SaveTool)]
        return renderer, tile_source