Build OpenType variable font from masters in a designspace.
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)
586190
def set_font(self, font):
        """"""
        self.shellwidget._control.setFont(font)
        self.shellwidget.font = font
534470
protected void BuildGSubrsUsed(int Font)
	{
		int LBias = 0;
		int SizeOfNonCIDSubrsUsed = 0;
		if (fonts[Font].privateSubrs>=0)
		{
			LBias = CalcBias(fonts[Font].privateSubrs,Font);
			SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.size();
		}
		
		// For each global subr used 
		for (int i=0;i<lGSubrsUsed.size();i++)
		{
			//Pop the value + check valid 
			int Subr = ((Integer)lGSubrsUsed.get(i)).intValue();
			if (Subr < gsubrOffsets.length-1 && Subr>=0)
			{
				// Read the subr and process
				int Start = gsubrOffsets[Subr];
				int End = gsubrOffsets[Subr+1];
				
				if (fonts[Font].isCID)
					ReadASubr(Start,End,GBias,0,hGSubrsUsed,lGSubrsUsed,null);
				else
				{
					ReadASubr(Start,End,GBias,LBias,hSubrsUsedNonCID,lSubrsUsedNonCID,fonts[Font].SubrsOffsets);
					if (SizeOfNonCIDSubrsUsed < lSubrsUsedNonCID.size())
					{
						for (int j=SizeOfNonCIDSubrsUsed;j<lSubrsUsedNonCID.size();j++)
						{
							//Pop the value + check valid 
							int LSubr = ((Integer)lSubrsUsedNonCID.get(j)).intValue();
							if (LSubr < fonts[Font].SubrsOffsets.length-1 && LSubr>=0)
							{
								// Read the subr and process
								int LStart = fonts[Font].SubrsOffsets[LSubr];
								int LEnd = fonts[Font].SubrsOffsets[LSubr+1];
								ReadASubr(LStart,LEnd,GBias,LBias,hSubrsUsedNonCID,lSubrsUsedNonCID,fonts[Font].SubrsOffsets);
							}
						}
						SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.size();
					}
				}
			}
		}
	}
1289821
def compileGSUB(featureFile, glyphOrder):
    
    font = ttLib.TTFont()
    font.setGlyphOrder(glyphOrder)
    addOpenTypeFeatures(font, featureFile, tables={"GSUB"})
    return font.get("GSUB")
1271129
def _valid_designspace(self, designspace):
        
        # TODO: (jany) really make a copy to avoid modifying the original object
        copy = designspace
        # Load only full UFO masters, sparse or "brace" layer sources are assumed
        # to point to existing layers within one of the full masters.
        for source in (s for s in copy.sources if not s.layerName):
            if not hasattr(source, "font") or source.font is None:
                if source.path:
                    # FIXME: (jany) consider not changing the caller's objects
                    source.font = defcon.Font(source.path)
                else:
                    dirname = os.path.dirname(designspace.path)
                    ufo_path = os.path.join(dirname, source.filename)
                    source.font = defcon.Font(ufo_path)
            if source.location is None:
                source.location = {}
            for name in ("familyName", "styleName"):
                if getattr(source, name) != getattr(source.font.info, name):
                    self.logger.warning(
                        dedent(
                            """\
                    The {name} is different between the UFO and the designspace source:
                        source filename: {filename}
                        source {name}: {source_name}
                        ufo {name}: {ufo_name}

                    The UFO name will be used.
                    """
                        ).format(
                            name=name,
                            filename=source.filename,
                            source_name=getattr(source, name),
                            ufo_name=getattr(source.font.info, name),
                        )
                    )
                    setattr(source, name, getattr(source.font.info, name))
        return copy
248361
private static FontIconData createFontIconData(StatusFontIcon meta) {
        FontIconData result = new FontIconData();
        result.setFontIconHtml(meta.getFontIcon().getHtml());
        result.setTitle(meta.getTitle());
        result.setStyle(meta.getStyle());
        result.setId(meta.getId());
        result.setDisabled(meta.isDisabled());

        return result;
    }
177471
def com_google_fonts_check_metadata_canonical_filename(font_metadata,
                                                       canonical_filename,
                                                       is_variable_font):
  """"""

  if is_variable_font:
    valid_varfont_suffixes = [
      ("Roman-VF", "Regular"),
      ("Italic-VF", "Italic"),
    ]
    for valid_suffix, style in valid_varfont_suffixes:
      if style in canonical_filename:
        canonical_filename = valid_suffix.join(canonical_filename.split(style))

  if canonical_filename != font_metadata.filename:
    yield FAIL, ("METADATA.pb: filename field (\"{}\")"
                 " does not match "
                 "canonical name \"{}\".".format(font_metadata.filename,
                                                 canonical_filename))
  else:
    yield PASS, "Filename in METADATA.pb is set canonically."
1005864
public static Typeface getFont(Context context, String fontName) {
        synchronized (cache) {
            if (!cache.containsKey(fontName)) {
                try {
                    Typeface t = Typeface.createFromAsset(context.getAssets(), fontName);
                    cache.put(fontName, t);
                } catch (Exception e) {
                    return null;
                }
            }
            return cache.get(fontName);
        }
    }
519991
def ufo2glyphs(options):
    """"""
    import fontTools.designspaceLib
    import defcon

    sources = options.designspace_file_or_UFOs
    designspace_file = None
    if (
        len(sources) == 1
        and sources[0].endswith(".designspace")
        and os.path.isfile(sources[0])
    ):
        designspace_file = sources[0]
        designspace = fontTools.designspaceLib.DesignSpaceDocument()
        designspace.read(designspace_file)
        object_to_read = designspace
    elif all(source.endswith(".ufo") and os.path.isdir(source) for source in sources):
        ufos = [defcon.Font(source) for source in sources]
        ufos.sort(
            key=lambda ufo: [  # Order the masters by weight and width
                ufo.info.openTypeOS2WeightClass or 400,
                ufo.info.openTypeOS2WidthClass or 5,
            ]
        )
        object_to_read = ufos
    else:
        print(
            "Please specify just one designspace file *or* one or more "
            "UFOs. They must end in '.designspace' or '.ufo', respectively.",
            file=sys.stderr,
        )
        return 1

    font = glyphsLib.to_glyphs(
        object_to_read, minimize_ufo_diffs=options.no_preserve_glyphsapp_metadata
    )

    # Make the Glyphs file more suitable for roundtrip:
    font.customParameters["Disable Last Change"] = options.enable_last_change
    font.disablesAutomaticAlignment = options.enable_automatic_alignment

    if options.output_path:
        font.save(options.output_path)
    else:
        if designspace_file:
            filename_to_write = os.path.splitext(designspace_file)[0] + ".glyphs"
        else:
            filename_to_write = os.path.join(
                os.path.dirname(sources[0]),
                font.familyName.replace(" ", "") + ".glyphs",
            )
        font.save(filename_to_write)
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
1075908
protected byte[] BuildNewFile(int Font)
    {
		// Prepare linked list for new font components
		OutputList = new LinkedList();

        // copy the header of the font
        CopyHeader();
                
        // create a name index
        BuildIndexHeader(1,1,1);
        OutputList.addLast(new UInt8Item((char)( 1+fonts[Font].name.length() )));
        OutputList.addLast(new StringItem(fonts[Font].name));
        
        // create the topdict Index
        BuildIndexHeader(1,2,1);
        OffsetItem topdictIndex1Ref = new IndexOffsetItem(2);
        OutputList.addLast(topdictIndex1Ref);
        IndexBaseItem topdictBase = new IndexBaseItem();
        OutputList.addLast(topdictBase);
                
        // Initialize the Dict Items for later use
        OffsetItem charsetRef     = new DictOffsetItem();
        OffsetItem charstringsRef = new DictOffsetItem();
        OffsetItem fdarrayRef     = new DictOffsetItem();
        OffsetItem fdselectRef    = new DictOffsetItem();
        OffsetItem privateRef     = new DictOffsetItem();
        
        // If the font is not CID create the following keys
        if ( !fonts[Font].isCID ) {
            // create a ROS key
        	OutputList.addLast(new DictNumberItem(fonts[Font].nstrings));
        	OutputList.addLast(new DictNumberItem(fonts[Font].nstrings+1));
        	OutputList.addLast(new DictNumberItem(0));
        	OutputList.addLast(new UInt8Item((char)12));
        	OutputList.addLast(new UInt8Item((char)30));
            // create a CIDCount key
        	OutputList.addLast(new DictNumberItem(fonts[Font].nglyphs));
        	OutputList.addLast(new UInt8Item((char)12));
            OutputList.addLast(new UInt8Item((char)34));
            // Sivan's comments
            // What about UIDBase (12,35)? Don't know what is it.
            // I don't think we need FontName; the font I looked at didn't have it.
        }
        // Go to the TopDict of the font being processed
        seek(topdictOffsets[Font]);
        // Run until the end of the TopDict
        while (getPosition() < topdictOffsets[Font+1]) {
            int p1 = getPosition();
            getDictItem();
            int p2 = getPosition();
            // The encoding key is disregarded since CID has no encoding
            if (key=="Encoding"
            // These keys will be added manually by the process.
            || key=="Private" 
            || key=="FDSelect"
            || key=="FDArray" 
            || key=="charset" 
            || key=="CharStrings"
            ) {
            }else {
            //OtherWise copy key "as is" to the output list
                OutputList.add(new RangeItem(buf,p1,p2-p1));
            }
        }
        // Create the FDArray, FDSelect, Charset and CharStrings Keys
        CreateKeys(fdarrayRef,fdselectRef,charsetRef,charstringsRef);
        
        // Mark the end of the top dict area
        OutputList.addLast(new IndexMarkerItem(topdictIndex1Ref,topdictBase));
        
        // Copy the string index

        if (fonts[Font].isCID) 
            OutputList.addLast(getEntireIndexRange(stringIndexOffset));
        // If the font is not CID we need to append new strings.
        // We need 3 more strings: Registry, Ordering, and a FontName for one FD.
        // The total length is at most "Adobe"+"Identity"+63 = 76
        else
        	CreateNewStringIndex(Font);
        
        // copy the new subsetted global subroutine index       
        OutputList.addLast(new RangeItem(new RandomAccessFileOrArray(NewGSubrsIndex),0,NewGSubrsIndex.length));
        
        // deal with fdarray, fdselect, and the font descriptors
        // If the font is CID:
        if (fonts[Font].isCID) {
            // copy the FDArray, FDSelect, charset
       
            // Copy FDSelect
        	// Mark the beginning
            OutputList.addLast(new MarkerItem(fdselectRef));
            // If an FDSelect exists copy it
            if (fonts[Font].fdselectOffset>=0)
        		OutputList.addLast(new RangeItem(buf,fonts[Font].fdselectOffset,fonts[Font].FDSelectLength));
            // Else create a new one
            else
            	CreateFDSelect(fdselectRef,fonts[Font].nglyphs);
            	           
          	// Copy the Charset
            // Mark the beginning and copy entirely 
            OutputList.addLast(new MarkerItem(charsetRef));
            OutputList.addLast(new RangeItem(buf,fonts[Font].charsetOffset,fonts[Font].CharsetLength));
            
            // Copy the FDArray
            // If an FDArray exists
            if (fonts[Font].fdarrayOffset>=0)
            {
                // Mark the beginning
	            OutputList.addLast(new MarkerItem(fdarrayRef));
	            // Build a new FDArray with its private dicts and their LSubrs
	            Reconstruct(Font);
            }
            else
            	// Else create a new one
            	CreateFDArray(fdarrayRef,privateRef,Font);
           
        }
        // If the font is not CID
        else 
        {
            // create FDSelect
        	CreateFDSelect(fdselectRef,fonts[Font].nglyphs);            
            // recreate a new charset
        	CreateCharset(charsetRef,fonts[Font].nglyphs);            
            // create a font dict index (fdarray)
        	CreateFDArray(fdarrayRef,privateRef,Font);            
        }
        
        // if a private dict exists insert its subsetted version
        if (fonts[Font].privateOffset>=0)
        {
        	// Mark the beginning of the private dict
        	IndexBaseItem PrivateBase = new IndexBaseItem();
	        OutputList.addLast(PrivateBase);
        	OutputList.addLast(new MarkerItem(privateRef));

        	OffsetItem Subr = new DictOffsetItem();
        	// Build and copy the new private dict
        	CreateNonCIDPrivate(Font,Subr);
        	// Copy the new LSubrs index
        	CreateNonCIDSubrs(Font,PrivateBase,Subr);
        }
        
        // copy the charstring index
        OutputList.addLast(new MarkerItem(charstringsRef));

        // Add the subsetted charstring
        OutputList.addLast(new RangeItem(new RandomAccessFileOrArray(NewCharStringsIndex),0,NewCharStringsIndex.length));
        
        // now create the new CFF font        
        int[] currentOffset = new int[1];
        currentOffset[0] = 0;
        // Count and save the offset for each item
        Iterator listIter = OutputList.iterator();
        while ( listIter.hasNext() ) {
            Item item = (Item) listIter.next();
            item.increment(currentOffset);
        }
        // Compute the Xref for each of the offset items
        listIter = OutputList.iterator();
        while ( listIter.hasNext() ) {
            Item item = (Item) listIter.next();
            item.xref();
        }
        
        int size = currentOffset[0];
        byte[] b = new byte[size];
        
        // Emit all the items into the new byte array
        listIter = OutputList.iterator();
        while ( listIter.hasNext() ) {
            Item item = (Item) listIter.next();
            item.emit(b);
        }
        // Return the new stream
        return b;
    }
906993
public byte[] Process(String fontName)throws IOException{
		try
		{	
			// Verify that the file is open
			buf.reOpen();
			// Find the Font that we will be dealing with
			int j;
	        for (j=0; j<fonts.length; j++)
	            if (fontName.equals(fonts[j].name)) break;
	        if (j==fonts.length) return null;
	        
			// Calc the bias for the global subrs
			if (gsubrIndexOffset >= 0)
				GBias = CalcBias(gsubrIndexOffset,j);

	        // Prepare the new CharStrings Index
			BuildNewCharString(j);
			 // Prepare the new Global and Local Subrs Indices
			BuildNewLGSubrs(j);
			// Build the new file 
			byte[] Ret = BuildNewFile(j);
			return Ret;
		}
		finally {
            try {
                buf.close();
            }
            catch (Exception e) {
                // empty on purpose
            }
		}
	}
1202724
def FontForLabels(self, dc):
        '''  '''
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        scale = dc.GetPPI()[0] / wx.ScreenDC().GetPPI()[0]
        font.SetPointSize(scale*font.GetPointSize())
        return font
445367
def masters(self):
        
        if self._sources:
            for source in self._sources.values():
                yield source.font
            return

        # Store set of actually existing master (layer) ids. This helps with
        # catching dangling layer data that Glyphs may ignore, e.g. when
        # copying glyphs from other fonts with, naturally, different master
        # ids. Note: Masters have unique ids according to the Glyphs
        # documentation and can therefore be stored in a set.
        master_layer_ids = {m.id for m in self.font.masters}

        # stores background data from "associated layers"
        supplementary_layer_data = []

        # TODO(jamesgk) maybe create one font at a time to reduce memory usage
        # TODO: (jany) in the future, return a lazy iterator that builds UFOs
        #     on demand.
        self.to_ufo_font_attributes(self.family_name)

        # Generate the main (master) layers first.
        for glyph in self.font.glyphs:
            for layer in glyph.layers.values():
                if layer.associatedMasterId != layer.layerId:
                    # The layer is not the main layer of a master
                    # Store all layers, even the invalid ones, and just skip
                    # them and print a warning below.
                    supplementary_layer_data.append((glyph, layer))
                    continue

                ufo_layer = self.to_ufo_layer(glyph, layer)
                ufo_glyph = ufo_layer.newGlyph(glyph.name)
                self.to_ufo_glyph(ufo_glyph, layer, glyph)

        # And sublayers (brace, bracket, ...) second.
        for glyph, layer in supplementary_layer_data:
            if (
                layer.layerId not in master_layer_ids
                and layer.associatedMasterId not in master_layer_ids
            ):
                if self.minimize_glyphs_diffs:
                    self.logger.warning(
                        '{}, glyph "{}": Layer "{}" is dangling and will be '
                        "skipped. Did you copy a glyph from a different font?"
                        " If so, you should clean up any phantom layers not "
                        "associated with an actual master.".format(
                            self.font.familyName, glyph.name, layer.layerId
                        )
                    )
                continue

            if not layer.name:
                # Empty layer names are invalid according to the UFO spec.
                if self.minimize_glyphs_diffs:
                    self.logger.warning(
                        '{}, glyph "{}": Contains layer without a name which '
                        "will be skipped.".format(self.font.familyName, glyph.name)
                    )
                continue

            # Save processing bracket layers for when designspace() is called, as we
            # have to extract them to free-standing glyphs.
            if (
                "[" in layer.name
                and "]" in layer.name
                and ".background" not in layer.name
            ):
                self.bracket_layers.append(layer)
            else:
                ufo_layer = self.to_ufo_layer(glyph, layer)
                ufo_glyph = ufo_layer.newGlyph(glyph.name)
                self.to_ufo_glyph(ufo_glyph, layer, layer.parent)

        for source in self._sources.values():
            ufo = source.font
            if self.propagate_anchors:
                self.to_ufo_propagate_font_anchors(ufo)
            for layer in ufo.layers:
                self.to_ufo_layer_lib(layer)

        # Sanitize skip list and write it to both Designspace- and UFO-level lib keys.
        # The latter is unnecessary when using e.g. the `ufo2ft.compile*FromDS`
        # functions, but the data may take a different path. Writing it everywhere can
        # save on surprises/logic in other software.
        skip_export_glyphs = self._designspace.lib.get("public.skipExportGlyphs")
        if skip_export_glyphs is not None:
            skip_export_glyphs = sorted(set(skip_export_glyphs))
            self._designspace.lib["public.skipExportGlyphs"] = skip_export_glyphs
            for source in self._sources.values():
                source.font.lib["public.skipExportGlyphs"] = skip_export_glyphs

        self.to_ufo_features()  # This depends on the glyphOrder key
        self.to_ufo_groups()
        self.to_ufo_kerning()

        for source in self._sources.values():
            yield source.font
737088
public static FontUIResource getFont(PropertyOwner propertyOwner, Map<String,Object> properties, boolean returnDefaultIfNone)
    {
        String strFontName = ScreenUtil.getPropery(ScreenUtil.FONT_NAME, propertyOwner, properties, null);
        String strFontSize = ScreenUtil.getPropery(ScreenUtil.FONT_SIZE, propertyOwner, properties, null);
        String strFontStyle = ScreenUtil.getPropery(ScreenUtil.FONT_STYLE, propertyOwner, properties, null);

        if ((strFontName == null) || (strFontName.length() == 0))
        {
            if (!returnDefaultIfNone)
                return null;
            strFontName = Font.DIALOG;  // Default font
        }
        int iSize = 18; // Default size
        if ((strFontSize != null) && (strFontSize.length() > 0))
            iSize = Integer.parseInt(strFontSize);      
        int iStyle = Font.PLAIN;
        if ((strFontStyle != null) && (strFontStyle.length() > 0))
            iStyle = Integer.parseInt(strFontStyle);
        return new FontUIResource(strFontName, iStyle, iSize);
    }
585379
def set_font_properties(style_less,
                        nbfont=None,
                        tcfont=None,
                        monofont=None,
                        monosize=11,
                        tcfontsize=13,
                        nbfontsize=13,
                        prfontsize=95,
                        dffontsize=93,
                        outfontsize=85,
                        mathfontsize=100,
                        dfonts=False):
    

    fontsizes = [monosize, nbfontsize, tcfontsize, prfontsize, dffontsize, outfontsize]
    monosize, nbfontsize, tcfontsize, prfontsize, dffontsize, outfontsize = convert_fontsizes(fontsizes)
    if dfonts==True:
        monofont, tcfont, nbfont = ['monospace', 'sans-serif', 'sans-serif']
    else:
        if monofont is not None:
            monofont, monofpath = stored_font_dicts(monofont)
            style_less = import_fonts(style_less, monofont, monofpath)
        else:
            monofont='monospace'
        if tcfont is not None:
            tcfont, tcfontpath = stored_font_dicts(tcfont)
            style_less = import_fonts(style_less, tcfont, tcfontpath)
        else:
            tcfont='sans-serif'
        if nbfont is not None:
            if nbfont == 'proxima':
                nbfont, tcfont = ["'Proxima Nova'"]*2
                style_less = proxima_nova_imports(style_less)
            else:
                nbfont, nbfontpath = stored_font_dicts(nbfont)
                style_less = import_fonts(style_less, nbfont, nbfontpath)
        else:
            nbfont='sans-serif'

    style_less += '/* Set Font-Type and Font-Size Variables  */\n'
    # font names and fontfamily info for codecells, notebook & textcells
    style_less += '@monofont: {}; \n'.format(monofont)
    style_less += '@notebook-fontfamily: {}; \n'.format(nbfont)
    style_less += '@text-cell-fontfamily: {}; \n'.format(tcfont)
    # font size for codecells, main notebook, notebook-sub, & textcells
    style_less += '@monofontsize: {}pt; \n'.format(monosize)
    style_less += '@monofontsize-sub: {}pt; \n'.format(float(monosize) - 1)
    style_less += '@nb-fontsize: {}pt; \n'.format(nbfontsize)
    style_less += '@nb-fontsize-sub: {}pt; \n'.format(float(nbfontsize) - 1)
    style_less += '@text-cell-fontsize: {}pt; \n'.format(tcfontsize)
    style_less += '@df-header-fontsize: {}pt; \n'.format(float(dffontsize) + 1)
    style_less += '@df-fontsize: {}pt; \n'.format(dffontsize)
    style_less += '@output-font-size: {}pt; \n'.format(outfontsize)
    style_less += '@prompt-fontsize: {}pt; \n'.format(prfontsize)
    style_less += '@mathfontsize: {}%; \n'.format(mathfontsize)
    style_less += '\n\n'
    style_less += '/* Import Theme Colors and Define Layout Variables */\n'
    return style_less
625689
def generate(env):
    """"""

    cplusplus.generate(env)

    env['CXX']         = 'CC'
    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')
    env['SHCXX']       = '$CXX'
    env['SHOBJSUFFIX'] = '.o'
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1