Converts a Glyphs.app source file into UFO masters and a designspace file.
354792
def glyphs2ufo(options):
    """"""
    if options.output_dir is None:
        options.output_dir = os.path.dirname(options.glyphs_file) or "."

    if options.designspace_path is None:
        options.designspace_path = os.path.join(
            options.output_dir,
            os.path.basename(os.path.splitext(options.glyphs_file)[0]) + ".designspace",
        )

    # If options.instance_dir is None, instance UFO paths in the designspace
    # file will either use the value in customParameter's FULL_FILENAME_KEY or be
    # made relative to "instance_ufos/".
    glyphsLib.build_masters(
        options.glyphs_file,
        options.output_dir,
        options.instance_dir,
        designspace_path=options.designspace_path,
        minimize_glyphs_diffs=options.no_preserve_glyphsapp_metadata,
        propagate_anchors=options.propagate_anchors,
        normalize_ufos=options.normalize_ufos,
        create_background_layers=options.create_background_layers,
        generate_GDEF=options.generate_GDEF,
        store_editor_state=not options.no_store_editor_state,
    )
508074
def install_special_glyphs():
    '''
    
    '''
    from_dir = '~/repos/powerline/font'

    run('mkdir -p ~/.local/share/fonts')
    run(flo('cp {from_dir}/PowerlineSymbols.otf  ~/.local/share/fonts'))

    to_dir = '~/.config/fontconfig/conf.d/'
    run(flo('mkdir -p {to_dir}'))
    run(flo('cp {from_dir}/10-powerline-symbols.conf  {to_dir}'))
32385
def _text_to_graphiz(self, text):
        """"""
        dot = Source(text, format='svg')
        return dot.pipe().decode('utf-8')
544997
def build_variable_font(
        self,
        designspace,
        output_path=None,
        output_dir=None,
        master_bin_dir=None,
        ttf=True,
    ):
        """"""
        assert not (output_path and output_dir), "mutually exclusive args"

        ext = "ttf" if ttf else "otf"

        if hasattr(designspace, "__fspath__"):
            designspace = designspace.__fspath__()
        if isinstance(designspace, basestring):
            designspace = designspaceLib.DesignSpaceDocument.fromfile(designspace)
            if master_bin_dir is None:
                master_bin_dir = self._output_dir(ext, interpolatable=True)
            finder = partial(_varLib_finder, directory=master_bin_dir)
        else:
            assert all(isinstance(s.font, TTFont) for s in designspace.sources)
            finder = lambda s: s  # noqa: E731

        if output_path is None:
            output_path = (
                os.path.splitext(os.path.basename(designspace.path))[0] + "-VF"
            )
            output_path = self._output_path(
                output_path, ext, is_variable=True, output_dir=output_dir
            )

        logger.info("Building variable font " + output_path)

        font, _, _ = varLib.build(designspace, finder)

        font.save(output_path)
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))
957620
private Glyph createGlyphBasics(Entity e, boolean idIsFinal)
	{
		Glyph g = factory.createGlyph();
		g.setId(convertID(e.getUri()));

		String s = typeMatchMap.get(e.getModelInterface());
		if(( //use 'or' sbgn class for special generic physical entities
			e instanceof Complex && !((Complex)e).getMemberPhysicalEntity().isEmpty()
				&& ((Complex) e).getComponent().isEmpty())
			||
			(e instanceof SimplePhysicalEntity && ((SimplePhysicalEntity) e).getEntityReference()==null
				&& !((SimplePhysicalEntity) e).getMemberPhysicalEntity().isEmpty()))
		{
			s = GlyphClazz.OR.getClazz();
		}
		g.setClazz(s);

		// Set the label
		Label label = factory.createLabel();
		label.setText(findLabelFor(e));
		g.setLabel(label);

		// Detect if ubique
		if (ubiqueDet != null && ubiqueDet.isUbique(e))
		{
			g.setClone(factory.createGlyphClone());
		}

		// Put on state variables
		if (!g.getClazz().equals(GlyphClazz.OR.getClazz())) {
			g.getGlyph().addAll(getInformation(e));
		}

		// Record the mapping
		if (idIsFinal) {
			Set<String> uris = new HashSet<String>();
			uris.add(e.getUri());
			sbgn2BPMap.put(g.getId(), uris);
		}

		return g;
	}
906535
def build(
        documentPath,
        outputUFOFormatVersion=3,
        roundGeometry=True,
        verbose=True,           # not supported
        logPath=None,           # not supported
        progressFunc=None,      # not supported
        processRules=True,
        logger=None,
        useVarlib=False,
        ):
    
    import os, glob
    if os.path.isdir(documentPath):
        # process all *.designspace documents in this folder
        todo = glob.glob(os.path.join(documentPath, "*.designspace"))
    else:
        # process the
        todo = [documentPath]
    results = []
    for path in todo:
        document = DesignSpaceProcessor(ufoVersion=outputUFOFormatVersion)
        document.useVarlib = useVarlib
        document.roundGeometry = roundGeometry
        document.read(path)
        try:
            r = document.generateUFO(processRules=processRules)
            results.append(r)
        except:
            if logger:
                logger.exception("ufoProcessor error")
        #results += document.generateUFO(processRules=processRules)
        reader = None
    return results
60528
def run_from_ufos(self, ufos, output=(), **kwargs):
        

        if set(output) == {"ufo"}:
            return

        # the `ufos` parameter can be a list of UFO objects
        # or it can be a path (string) with a glob syntax
        ufo_paths = []
        if isinstance(ufos, basestring):
            ufo_paths = glob.glob(ufos)
            ufos = [Font(x) for x in ufo_paths]
        elif isinstance(ufos, list):
            # ufos can be either paths or open Font objects, so normalize them
            ufos = [Font(x) if isinstance(x, basestring) else x for x in ufos]
            ufo_paths = [x.path for x in ufos]
        else:
            raise FontmakeError(
                "UFOs parameter is neither a defcon.Font object, a path or a glob, "
                "nor a list of any of these.",
                ufos,
            )

        need_reload = False
        if "otf" in output:
            self.build_otfs(ufos, **kwargs)
            need_reload = True

        if "ttf" in output:
            if need_reload:
                ufos = [Font(path) for path in ufo_paths]
            self.build_ttfs(ufos, **kwargs)
            need_reload = True
247180
def designspace(self):
        
        if self._designspace_is_complete:
            return self._designspace

        self._designspace_is_complete = True
        list(self.masters)  # Make sure that the UFOs are built
        self.to_designspace_axes()
        self.to_designspace_sources()
        self.to_designspace_instances()
        self.to_designspace_family_user_data()

        if self.bracket_layers:
            self._apply_bracket_layers()

        # append base style shared by all masters to designspace file name
        base_family = self.family_name or "Unnamed"
        base_style = find_base_style(self.font.masters)
        if base_style:
            base_style = "-" + base_style
        name = (base_family + base_style).replace(" ", "") + ".designspace"
        self.designspace.filename = name

        return self._designspace
213560
def loads(s):
    
    p = Parser(current_type=glyphsLib.classes.GSFont)
    logger.info("Parsing .glyphs file")
    data = p.parse(s)
    return data
660135
def to_glyphs_family_user_data_from_ufo(self, ufo):
    """"""
    target_user_data = self.font.userData
    try:
        for key, value in ufo.lib[FONT_USER_DATA_KEY].items():
            # Existing values taken from the designspace lib take precedence
            if key not in target_user_data.keys():
                target_user_data[key] = value
    except KeyError:
        # No FONT_USER_DATA in ufo.lib
        pass
858121
def importTTX(self):
        
        import os
        import re

        prefix = "com.github.fonttools.ttx"
        sfntVersionRE = re.compile('(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)',
                                   flags=re.MULTILINE)
        if not hasattr(self.ufo, "data"):
            return
        if not self.ufo.data.fileNames:
            return
        for path in self.ufo.data.fileNames:
            foldername, filename = os.path.split(path)
            if (foldername == prefix and filename.endswith(".ttx")):
                ttx = self.ufo.data[path].decode('utf-8')
                # strip 'sfntVersion' attribute from ttFont element,
                # if present, to avoid overwriting the current value
                ttx = sfntVersionRE.sub(r'\1\3', ttx)
                fp = BytesIO(ttx.encode('utf-8'))
                self.otf.importXML(fp)
1336161
def to_ufo_glyph_anchors(self, glyph, anchors):
    """"""

    for anchor in anchors:
        x, y = anchor.position
        anchor_dict = {"name": anchor.name, "x": x, "y": y}
        glyph.appendAnchor(anchor_dict)
135634
def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size):
    """"""
    # Necessary to flush commands before requesting current viewport because
    # There may be a set_viewport command waiting in the queue.
    # TODO: would be nicer if each canvas just remembers and manages its own
    # viewport, rather than relying on the context for this.
    canvas = context.get_current_canvas()
    canvas.context.flush_commands()

    text_vtype = np.dtype([('a_position', np.float32, 2),
                           ('a_texcoord', np.float32, 2)])
    vertices = np.zeros(len(text) * 4, dtype=text_vtype)
    prev = None
    width = height = ascender = descender = 0
    ratio, slop = 1. / font.ratio, font.slop
    x_off = -slop
    # Need to make sure we have a unicode string here (Py2.7 mis-interprets
    # characters like "•" otherwise)
    if sys.version[0] == '2' and isinstance(text, str):
        text = text.decode('utf-8')
    # Need to store the original viewport, because the font[char] will
    # trigger SDF rendering, which changes our viewport
    # todo: get rid of call to glGetParameter!
    orig_viewport = canvas.context.get_viewport()
    for ii, char in enumerate(text):
        glyph = font[char]
        kerning = glyph['kerning'].get(prev, 0.) * ratio
        x0 = x_off + glyph['offset'][0] * ratio + kerning
        y0 = glyph['offset'][1] * ratio + slop
        x1 = x0 + glyph['size'][0]
        y1 = y0 - glyph['size'][1]
        u0, v0, u1, v1 = glyph['texcoords']
        position = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]
        texcoords = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]]
        vi = ii * 4
        vertices['a_position'][vi:vi+4] = position
        vertices['a_texcoord'][vi:vi+4] = texcoords
        x_move = glyph['advance'] * ratio + kerning
        x_off += x_move
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        width += x_move
        height = max(height, glyph['size'][1] - 2*slop)
        prev = char
    # Also analyse chars with large ascender and descender, otherwise the
    # vertical alignment can be very inconsistent
    for char in 'hy':
        glyph = font[char]
        y0 = glyph['offset'][1] * ratio + slop
        y1 = y0 - glyph['size'][1]
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        height = max(height, glyph['size'][1] - 2*slop)

    if orig_viewport is not None:
        canvas.context.set_viewport(*orig_viewport)

    # Tight bounding box (loose would be width, font.height /.asc / .desc)
    width -= glyph['advance'] * ratio - (glyph['size'][0] - 2*slop)
    dx = dy = 0
    if anchor_y == 'top':
        dy = -ascender
    elif anchor_y in ('center', 'middle'):
        dy = -(height / 2 + descender)
    elif anchor_y == 'bottom':
        dy = -descender
    # Already referenced to baseline
    # elif anchor_y == 'baseline':
    #     dy = -descender
    if anchor_x == 'right':
        dx = -width
    elif anchor_x == 'center':
        dx = -width / 2.
    vertices['a_position'] += (dx, dy)
    vertices['a_position'] /= lowres_size
    return vertices
1188775
function generateIcons(sketchfile, dest) {
  return new Promise((resolve, reject) => {

    const startTaskName = swlog.logTaskStart(`build icons from ${sketchfile}`);

    if (!hasSketchtool()) {
      return reject('No sketchtool installed. Skipping create icons...');
    }

    Promise.all([
      createPagesMetadata(sketchfile, dest),
      createIconFiles(sketchfile, dest)
    ])
    .then(res => {
      const thisTask = swlog.logSubStart(`organize icon files`);

      const promises = options.iconFormats.map(format => {
        return sortByFileFormat(dest, format);
      });

      return Promise.all(promises).then(() => {
        swlog.logSubEnd(thisTask)
      });
    })
    .then(res => {
      resolve();
      swlog.logTaskEnd(startTaskName);
    });
  })
  .catch(swlog.error);
}
384358
def to_glyphs_master_user_data(self, ufo, master):
    """"""
    target_user_data = master.userData
    for key, value in ufo.lib.items():
        if _user_data_has_no_special_meaning(key):
            target_user_data[key] = value

    # Save UFO data files
    if ufo.data.fileNames:
        from glyphsLib.types import BinaryData

        ufo_data = {}
        for os_filename in ufo.data.fileNames:
            filename = posixpath.join(*os_filename.split(os.path.sep))
            ufo_data[filename] = BinaryData(ufo.data[os_filename])
        master.userData[UFO_DATA_KEY] = ufo_data
1144545
def convert(filepath, outfilepath):
    """"""

    logger = logging.getLogger("example1")
    logger.setLevel(logging.INFO)
    fmt = logging.Formatter(STD_FORMAT)
    stderrHdlr = logging.StreamHandler()
    stderrHdlr.setFormatter(fmt)
    logger.addHandler(stderrHdlr)

    fi = ImageViewCairo(logger)
    fi.configure(500, 1000)

    # Load fits file
    image = load_data(filepath, logger=logger)

    # Make any adjustments to the image that we want
    fi.set_bg(1.0, 1.0, 1.0)
    fi.set_image(image)
    fi.auto_levels()
    fi.zoom_fit()
    fi.center_image()

    ht_pts = 11.0 / point_in
    wd_pts = 8.5 / point_in
    off_x, off_y = 0, 0

    out_f = open(outfilepath, 'w')
    surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
    # set pixels per inch
    surface.set_fallback_resolution(300, 300)
    surface.set_device_offset(off_x, off_y)
    try:
        fi.save_image_as_surface(surface)
        surface.show_page()
        surface.flush()
        surface.finish()
    finally:
        out_f.close()