code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
font = self.font
# "date" can be missing; Glyphs.app removes it on saving if it's empty:
# https://github.com/googlei18n/glyphsLib/issues/134
date_created = getattr(font, "date", None)
if date_created is not None:
date_created = to_ufo_time(date_created)
units_per_em = font.upm
version_major = font.versionMajor
version_minor = font.versionMinor
copyright = font.copyright
designer = font.designer
designer_url = font.designerURL
manufacturer = font.manufacturer
manufacturer_url = font.manufacturerURL
# XXX note is unused?
# note = font.note
glyph_order = list(glyph.name for glyph in font.glyphs)
for index, master in enumerate(font.masters):
source = self._designspace.newSourceDescriptor()
ufo = self.ufo_module.Font()
source.font = ufo
ufo.lib[APP_VERSION_LIB_KEY] = font.appVersion
ufo.lib[KEYBOARD_INCREMENT_KEY] = font.keyboardIncrement
if date_created is not None:
ufo.info.openTypeHeadCreated = date_created
ufo.info.unitsPerEm = units_per_em
ufo.info.versionMajor = version_major
ufo.info.versionMinor = version_minor
if copyright:
ufo.info.copyright = copyright
if designer:
ufo.info.openTypeNameDesigner = designer
if designer_url:
ufo.info.openTypeNameDesignerURL = designer_url
if manufacturer:
ufo.info.openTypeNameManufacturer = manufacturer
if manufacturer_url:
ufo.info.openTypeNameManufacturerURL = manufacturer_url
ufo.glyphOrder = glyph_order
self.to_ufo_names(ufo, master, family_name)
self.to_ufo_family_user_data(ufo)
self.to_ufo_custom_params(ufo, font)
self.to_ufo_master_attributes(source, master)
ufo.lib[MASTER_ORDER_LIB_KEY] = index
# FIXME: (jany) in the future, yield this UFO (for memory, lazy iter)
self._designspace.addSource(source)
self._sources[master.id] = source
|
def to_ufo_font_attributes(self, family_name)
|
Generate a list of UFOs with metadata loaded from .glyphs data.
Modifies the list of UFOs in the UFOBuilder (self) in-place.
| 3.053799
| 2.963806
| 1.030364
|
if is_initial:
_set_glyphs_font_attributes(self, source)
else:
_compare_and_merge_glyphs_font_attributes(self, source)
|
def to_glyphs_font_attributes(self, source, master, is_initial)
|
Copy font attributes from `ufo` either to `self.font` or to `master`.
Arguments:
self -- The UFOBuilder
ufo -- The current UFO being read
master -- The current master being written
is_initial -- True iff this the first UFO that we process
| 4.141016
| 4.274051
| 0.968874
|
if not layer.hasBackground:
return
background = layer.background
ufo_layer = self.to_ufo_background_layer(glyph)
new_glyph = ufo_layer.newGlyph(glyph.name)
width = background.userData[BACKGROUND_WIDTH_KEY]
if width is not None:
new_glyph.width = width
self.to_ufo_background_image(new_glyph, background)
self.to_ufo_paths(new_glyph, background)
self.to_ufo_components(new_glyph, background)
self.to_ufo_glyph_anchors(new_glyph, background.anchors)
self.to_ufo_guidelines(new_glyph, background)
|
def to_ufo_glyph_background(self, glyph, layer)
|
Set glyph background.
| 2.595088
| 2.512019
| 1.033069
|
for instance in self.font.instances:
if self.minimize_glyphs_diffs or (
is_instance_active(instance)
and _is_instance_included_in_family(self, instance)
):
_to_designspace_instance(self, instance)
|
def to_designspace_instances(self)
|
Write instance data from self.font to self.designspace.
| 6.071894
| 5.174009
| 1.173538
|
from fontTools.designspaceLib import DesignSpaceDocument
from os.path import normcase, normpath
if hasattr(designspace, "__fspath__"):
designspace = designspace.__fspath__()
if isinstance(designspace, basestring):
designspace = DesignSpaceDocument.fromfile(designspace)
basedir = os.path.dirname(designspace.path)
instance_ufos = []
if include_filenames is not None:
include_filenames = {normcase(normpath(p)) for p in include_filenames}
for designspace_instance in designspace.instances:
fname = designspace_instance.filename
assert fname is not None, "instance %r missing required filename" % getattr(
designspace_instance, "name", designspace_instance
)
if include_filenames is not None:
fname = normcase(normpath(fname))
if fname not in include_filenames:
continue
logger.debug("Applying instance data to %s", fname)
# fontmake <= 1.4.0 compares the ufo paths returned from this function
# to the keys of a dict of designspace locations that have been passed
# through normpath (but not normcase). We do the same.
ufo = Font(normpath(os.path.join(basedir, fname)))
set_weight_class(ufo, designspace, designspace_instance)
set_width_class(ufo, designspace, designspace_instance)
glyphs_instance = InstanceDescriptorAsGSInstance(designspace_instance)
to_ufo_custom_params(None, ufo, glyphs_instance)
ufo.save()
instance_ufos.append(ufo)
return instance_ufos
|
def apply_instance_data(designspace, include_filenames=None, Font=defcon.Font)
|
Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
designspace: DesignSpaceDocument object or path (str or PathLike) to
a designspace file.
include_filenames: optional set of instance filenames (relative to
the designspace path) to be included. By default all instaces are
processed.
Font: the class used to load the UFO (default: defcon.Font).
Returns:
List of opened and updated instance UFOs.
| 3.491136
| 3.389603
| 1.029954
|
# Recover the original feature code if it was stored in the user data
original = master.userData[ORIGINAL_FEATURE_CODE_KEY]
if original is not None:
ufo.features.text = original
return
prefixes = []
for prefix in self.font.featurePrefixes:
strings = []
if prefix.name != ANONYMOUS_FEATURE_PREFIX_NAME:
strings.append("# Prefix: %s\n" % prefix.name)
strings.append(autostr(prefix.automatic))
strings.append(prefix.code)
prefixes.append("".join(strings))
prefix_str = "\n\n".join(prefixes)
class_defs = []
for class_ in self.font.classes:
prefix = "@" if not class_.name.startswith("@") else ""
name = prefix + class_.name
class_defs.append(
"{}{} = [ {} ];".format(autostr(class_.automatic), name, class_.code)
)
class_str = "\n\n".join(class_defs)
feature_defs = []
for feature in self.font.features:
code = feature.code
lines = ["feature %s {" % feature.name]
if feature.notes:
lines.append("# notes:")
lines.extend("# " + line for line in feature.notes.splitlines())
if feature.automatic:
lines.append("# automatic")
if feature.disabled:
lines.append("# disabled")
lines.extend("#" + line for line in code.splitlines())
else:
lines.append(code)
lines.append("} %s;" % feature.name)
feature_defs.append("\n".join(lines))
fea_str = "\n\n".join(feature_defs)
# Don't add a GDEF table when planning to round-trip. To get Glyphs.app-like
# results, we would need anchor propagation or user intervention. Glyphs.app
# only generates it on generating binaries.
gdef_str = None
if self.generate_GDEF:
if re.search(r"^\s*table\s+GDEF\s+{", prefix_str, flags=re.MULTILINE):
raise ValueError(
"The features already contain a `table GDEF {...}` statement. "
"Either delete it or set generate_GDEF to False."
)
gdef_str = _build_gdef(
ufo, self._designspace.lib.get("public.skipExportGlyphs")
)
# make sure feature text is a unicode string, for defcon
full_text = (
"\n\n".join(filter(None, [class_str, prefix_str, fea_str, gdef_str])) + "\n"
)
ufo.features.text = full_text if full_text.strip() else ""
|
def _to_ufo_features(self, master, ufo)
|
Write an UFO's OpenType feature file.
| 3.956642
| 3.880121
| 1.019721
|
from glyphsLib import glyphdata
bases, ligatures, marks, carets = set(), set(), set(), {}
category_key = GLYPHLIB_PREFIX + "category"
subCategory_key = GLYPHLIB_PREFIX + "subCategory"
for glyph in ufo:
# Do not generate any entries for non-export glyphs, as looking them up on
# compilation will fail.
if skipExportGlyphs is not None:
if glyph.name in skipExportGlyphs:
continue
has_attaching_anchor = False
for anchor in glyph.anchors:
name = anchor.name
if name and not name.startswith("_"):
has_attaching_anchor = True
if name and name.startswith("caret_") and "x" in anchor:
carets.setdefault(glyph.name, []).append(round(anchor["x"]))
# First check glyph.lib for category/subCategory overrides. Otherwise,
# use global values from GlyphData.
glyphinfo = glyphdata.get_glyph(glyph.name)
category = glyph.lib.get(category_key) or glyphinfo.category
subCategory = glyph.lib.get(subCategory_key) or glyphinfo.subCategory
if subCategory == "Ligature" and has_attaching_anchor:
ligatures.add(glyph.name)
elif category == "Mark" and (
subCategory == "Nonspacing" or subCategory == "Spacing Combining"
):
marks.add(glyph.name)
elif has_attaching_anchor:
bases.add(glyph.name)
if not any((bases, ligatures, marks, carets)):
return None
def fmt(g):
return ("[%s]" % " ".join(sorted(g, key=ufo.glyphOrder.index))) if g else ""
lines = [
"table GDEF {",
" # automatic",
" GlyphClassDef",
" %s, # Base" % fmt(bases),
" %s, # Liga" % fmt(ligatures),
" %s, # Mark" % fmt(marks),
" ;",
]
for glyph, caretPos in sorted(carets.items()):
lines.append(
" LigatureCaretByPos %s %s;"
% (glyph, " ".join(unicode(p) for p in sorted(caretPos)))
)
lines.append("} GDEF;")
return "\n".join(lines)
|
def _build_gdef(ufo, skipExportGlyphs=None)
|
Build a GDEF table statement (GlyphClassDef and LigatureCaretByPos).
Building GlyphClassDef requires anchor propagation or user care to work as
expected, as Glyphs.app also looks at anchors for classification:
* Base: any glyph that has an attaching anchor (such as "top"; "_top" does
not count) and is neither classified as Ligature nor Mark using the
definitions below;
* Ligature: if subCategory is "Ligature" and the glyph has at least one
attaching anchor;
* Mark: if category is "Mark" and subCategory is either "Nonspacing" or
"Spacing Combining";
* Compound: never assigned by Glyphs.app.
See:
* https://github.com/googlei18n/glyphsLib/issues/85
* https://github.com/googlei18n/glyphsLib/pull/100#issuecomment-275430289
| 3.282728
| 2.892091
| 1.135071
|
res = []
match = None
for st in statements:
if match or not isinstance(st, ast.Comment):
res.append(st)
continue
match = comment_re.match(st.text)
if not match:
res.append(st)
return match, res
|
def _pop_comment(self, statements, comment_re)
|
Look for the comment that matches the given regex.
If it matches, return the regex match object and list of statements
without the special one.
| 3.177494
| 2.421307
| 1.312305
|
res = []
comments = []
match = None
st_iter = iter(statements)
# Look for the header
for st in st_iter:
if isinstance(st, ast.Comment):
match = header_re.match(st.text)
if match:
# Drop this comment an move on to consuming the block
break
else:
res.append(st)
else:
res.append(st)
# Consume consecutive comments
for st in st_iter:
if isinstance(st, ast.Comment):
comments.append(st)
else:
# The block is over, keep the rest of the statements
res.append(st)
break
# Keep the rest of the statements
res.extend(list(st_iter))
# Inside the comment block, drop the pound sign and any common indent
return match, dedent("".join(c.text[1:] + "\n" for c in comments)), res
|
def _pop_comment_block(self, statements, header_re)
|
Look for a series of comments that start with one that matches the
regex. If the first comment is found, all subsequent comments are
popped from statements, concatenated and dedented and returned.
| 3.860441
| 3.721856
| 1.037235
|
try:
return plugin.openapi.refs[schema]
except KeyError:
plugin.spec.definition(schema.__name__, schema=schema)
return schema.__name__
|
def get_marshmallow_schema_name(self, plugin, schema)
|
Get the schema name.
If the schema doesn't exist, create it.
| 8.813327
| 7.434944
| 1.185393
|
pen = ufo_glyph.getPointPen()
for index, component in enumerate(layer.components):
pen.addComponent(component.name, component.transform)
if component.anchor:
if COMPONENT_INFO_KEY not in ufo_glyph.lib:
ufo_glyph.lib[COMPONENT_INFO_KEY] = []
ufo_glyph.lib[COMPONENT_INFO_KEY].append(
{"name": component.name, "index": index, "anchor": component.anchor}
)
# data related to components stored in lists of booleans
# each list's elements correspond to the components in order
for key in ["alignment", "locked", "smartComponentValues"]:
values = [getattr(c, key) for c in layer.components]
if any(values):
ufo_glyph.lib[_lib_key(key)] = values
|
def to_ufo_components(self, ufo_glyph, layer)
|
Draw .glyphs components onto a pen, adding them to the parent glyph.
| 3.90748
| 3.80756
| 1.026242
|
args = flask.request.args
data_raw = {}
for field_name, field in self.args_schema.fields.items():
alternate_field_name = field.load_from if MA2 else field.data_key
if alternate_field_name and alternate_field_name in args:
field_name = alternate_field_name
elif field_name not in args:
# getlist will return an empty list instead of raising a
# KeyError for args that aren't present.
continue
value = args.getlist(field_name)
if not self.is_list_field(field) and len(value) == 1:
value = value[0]
data_raw[field_name] = value
return self.deserialize_args(data_raw)
|
def request_args(self)
|
Use args_schema to parse request query arguments.
| 3.809781
| 3.414126
| 1.115888
|
query = self.query_raw
query = self.authorization.filter_query(query, self)
query = query.options(
*itertools.chain(self.base_query_options, self.query_options)
)
return query
|
def query(self)
|
The SQLAlchemy query for the view.
Override this to customize the query to fetch items in this view.
By default, this applies the filter from the view's `authorization` and
the query options from `base_query_options` and `query_options`.
| 6.670789
| 3.723092
| 1.791734
|
if not hasattr(self.serializer, 'get_query_options'):
return ()
return self.serializer.get_query_options(Load(self.model))
|
def query_options(self)
|
Options to apply to the query for the view.
Set this to configure relationship and column loading.
By default, this calls the ``get_query_options`` method on the
serializer with a `Load` object bound to the model, if that serializer
method exists.
| 7.397831
| 3.738538
| 1.978803
|
pen = ufo_glyph.getPointPen()
for path in layer.paths:
# the list is changed below, otherwise you can't draw more than once
# per session.
nodes = list(path.nodes)
for node in nodes:
self.to_ufo_node_user_data(ufo_glyph, node)
pen.beginPath()
if not nodes:
pen.endPath()
continue
if not path.closed:
node = nodes.pop(0)
assert node.type == "line", "Open path starts with off-curve points"
pen.addPoint(tuple(node.position), segmentType="move")
else:
# In Glyphs.app, the starting node of a closed contour is always
# stored at the end of the nodes list.
nodes.insert(0, nodes.pop())
for node in nodes:
node_type = _to_ufo_node_type(node.type)
pen.addPoint(
tuple(node.position), segmentType=node_type, smooth=node.smooth
)
pen.endPath()
|
def to_ufo_paths(self, ufo_glyph, layer)
|
Draw .glyphs paths onto a pen.
| 4.122246
| 3.957442
| 1.041644
|
@property
@functools.wraps(func)
def wrapped(self):
cached_value = context.get_for_view(self, func.__name__, UNDEFINED)
if cached_value is not UNDEFINED:
return cached_value
value = func(self)
context.set_for_view(self, func.__name__, value)
return value
return wrapped
|
def request_cached_property(func)
|
Make the given method a per-request cached property.
This caches the value on the request context rather than on the object
itself, preventing problems if the object gets reused across multiple
requests.
| 2.584678
| 2.903486
| 0.890198
|
if ufo.path:
return os.path.basename(ufo.path)
return ufo.info.styleName
|
def _ufo_logging_ref(ufo)
|
Return a string that can identify this UFO in logs.
| 4.336854
| 3.510366
| 1.235442
|
if src is None:
return None
string = src.replace('"', "")
# parse timezone ourselves, since %z is not always supported
# see: http://bugs.python.org/issue6641
m = UTC_OFFSET_RE.match(string)
if m:
sign = 1 if m.group("sign") == "+" else -1
tz_hours = sign * int(m.group("hours"))
tz_minutes = sign * int(m.group("minutes"))
offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
string = string[:-6]
else:
# no explicit timezone
offset = datetime.timedelta(0)
if "AM" in string or "PM" in string:
datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %I:%M:%S %p")
else:
datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
return datetime_obj + offset
|
def parse_datetime(src=None)
|
Parse a datetime object from a string.
| 2.349124
| 2.312001
| 1.016057
|
# type: (Optional[str]) -> Optional[Union[Tuple[int, ...], int]]
if src is None:
return None
# Tuple.
if src[0] == "(":
rgba = tuple(int(v) for v in src[1:-1].split(",") if v)
if not (len(rgba) == 4 and all(0 <= v < 256 for v in rgba)):
raise ValueError(
"Broken color tuple: {}. Must have four values from 0 to 255.".format(
src
)
)
return rgba
# Constant.
return int(src)
|
def parse_color(src=None)
|
Parse a string representing a color value.
Color is either a fixed color (when coloring something from the UI, see
the GLYPHS_COLORS constant) or a list of the format [u8, u8, u8, u8],
Glyphs does not support an alpha channel as of 2.5.1 (confirmed by Georg
Seifert), and always writes a 1 to it. This was brought up and is probably
corrected in the next versions.
https://github.com/googlei18n/glyphsLib/pull/363#issuecomment-390418497
| 3.106598
| 3.481725
| 0.892258
|
writer = Writer(fp)
logger.info("Writing .glyphs file")
writer.write(obj)
|
def dump(obj, fp)
|
Write a GSFont object to a .glyphs file.
'fp' should be a (writable) file object.
| 10.265806
| 5.539214
| 1.853297
|
p = Parser(current_type=glyphsLib.classes.GSFont)
logger.info("Parsing .glyphs file")
data = p.parse(s)
return data
|
def loads(s)
|
Read a .glyphs file from a (unicode) str object, or from
a UTF-8 encoded bytes object.
Return a GSFont object.
| 14.858929
| 11.658991
| 1.274461
|
for arg in args:
glyphsLib.dump(load(open(arg, "r", encoding="utf-8")), sys.stdout)
|
def main(args=None)
|
Roundtrip the .glyphs file given as an argument.
| 12.123252
| 5.935864
| 2.042373
|
text = tounicode(text, encoding="utf-8")
result, i = self._parse(text, 0)
if text[i:].strip():
self._fail("Unexpected trailing content", text, i)
return result
|
def parse(self, text)
|
Do the parsing.
| 5.19408
| 4.735467
| 1.096846
|
text = tounicode(text, encoding="utf-8")
m = self.start_dict_re.match(text, 0)
if m:
i = self._parse_dict_into_object(res, text, 1)
else:
self._fail("not correct file format", text, 0)
if text[i:].strip():
self._fail("Unexpected trailing content", text, i)
return i
|
def parse_into_object(self, res, text)
|
Parse data into an existing GSFont instance.
| 4.841806
| 4.772418
| 1.014539
|
m = self.start_dict_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_dict(text, i)
m = self.start_list_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_list(text, i)
m = self.value_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
if hasattr(self.current_type, "read"):
reader = self.current_type()
# Give the escaped value to `read` to be symetrical with
# `plistValue` which handles the escaping itself.
value = reader.read(m.group(1))
return value, i
value = self._trim_value(m.group(1))
if self.current_type in (None, dict, OrderedDict):
self.current_type = self._guess_current_type(parsed, value)
if self.current_type == bool:
value = bool(int(value)) # bool(u'0') returns True
return value, i
value = self.current_type(value)
return value, i
m = self.hex_re.match(text, i)
if m:
from glyphsLib.types import BinaryData
parsed, value = m.group(0), m.group(1)
decoded = BinaryData.fromHex(value)
i += len(parsed)
return decoded, i
else:
self._fail("Unexpected content", text, i)
|
def _parse(self, text, i)
|
Recursive function to parse a single dictionary, list, or value.
| 3.17414
| 3.0648
| 1.035676
|
old_current_type = self.current_type
new_type = self.current_type
if new_type is None:
# customparameter.value needs to be set from the found value
new_type = dict
elif type(new_type) == list:
new_type = new_type[0]
res = new_type()
i = self._parse_dict_into_object(res, text, i)
self.current_type = old_current_type
return res, i
|
def _parse_dict(self, text, i)
|
Parse a dictionary from source text starting at i.
| 4.443001
| 4.464358
| 0.995216
|
res = []
end_match = self.end_list_re.match(text, i)
old_current_type = self.current_type
while not end_match:
list_item, i = self._parse(text, i)
res.append(list_item)
end_match = self.end_list_re.match(text, i)
if not end_match:
m = self.list_delim_re.match(text, i)
if not m:
self._fail("Missing delimiter in list before content", text, i)
parsed = m.group(0)
i += len(parsed)
self.current_type = old_current_type
parsed = end_match.group(0)
i += len(parsed)
return res, i
|
def _parse_list(self, text, i)
|
Parse a list from source text starting at i.
| 3.027406
| 2.861954
| 1.057811
|
if value[0] == '"':
assert value[-1] == '"'
value = value[1:-1].replace('\\"', '"').replace("\\\\", "\\")
return Parser._unescape_re.sub(Parser._unescape_fn, value)
return value
|
def _trim_value(self, value)
|
Trim double quotes off the ends of a value, un-escaping inner
double quotes and literal backslashes. Also convert escapes to unicode.
If the string is not quoted, return it unmodified.
| 4.436782
| 3.667143
| 1.209874
|
raise ValueError("{}:\n{}".format(message, text[i : i + 79]))
|
def _fail(self, message, text, i)
|
Raise an exception with given message and text at i.
| 10.97333
| 9.26123
| 1.184867
|
styleMapStyleName = (
" ".join(
s for s in ("bold" if is_bold else "", "italic" if is_italic else "") if s
)
or "regular"
)
if not linked_style or linked_style == "Regular":
linked_style = _get_linked_style(style_name, is_bold, is_italic)
if linked_style:
styleMapFamilyName = (family_name or "") + " " + linked_style
else:
styleMapFamilyName = family_name
return styleMapFamilyName, styleMapStyleName
|
def build_stylemap_names(
family_name, style_name, is_bold=False, is_italic=False, linked_style=None
)
|
Build UFO `styleMapFamilyName` and `styleMapStyleName` based on the
family and style names, and the entries in the "Style Linking" section
of the "Instances" tab in the "Font Info".
The value of `styleMapStyleName` can be either "regular", "bold", "italic"
or "bold italic", depending on the values of `is_bold` and `is_italic`.
The `styleMapFamilyName` is a combination of the `family_name` and the
`linked_style`.
If `linked_style` is unset or set to 'Regular', the linked style is equal
to the style_name with the last occurrences of the strings 'Regular',
'Bold' and 'Italic' stripped from it.
| 2.626724
| 2.221632
| 1.182339
|
alignment_zones = master.alignmentZones
blue_values = []
other_blues = []
for zone in sorted(alignment_zones):
pos = zone.position
size = zone.size
val_list = blue_values if pos == 0 or size >= 0 else other_blues
val_list.extend(sorted((pos, pos + size)))
ufo.info.postscriptBlueValues = blue_values
ufo.info.postscriptOtherBlues = other_blues
|
def to_ufo_blue_values(self, ufo, master)
|
Set postscript blue values from Glyphs alignment zones.
| 4.391502
| 3.29072
| 1.334511
|
zones = []
blue_values = _pairs(ufo.info.postscriptBlueValues)
other_blues = _pairs(ufo.info.postscriptOtherBlues)
for y1, y2 in blue_values:
size = y2 - y1
if y2 == 0:
pos = 0
size = -size
else:
pos = y1
zones.append(self.glyphs_module.GSAlignmentZone(pos, size))
for y1, y2 in other_blues:
size = y1 - y2
pos = y2
zones.append(self.glyphs_module.GSAlignmentZone(pos, size))
master.alignmentZones = sorted(zones, key=lambda zone: -zone.position)
|
def to_glyphs_blue_values(self, ufo, master)
|
Sets the GSFontMaster alignmentZones from the postscript blue values.
| 3.172648
| 2.668828
| 1.188779
|
elements = filter_str.split(";")
if elements[0] == "":
logger.error(
"Failed to parse glyphs filter, expecting a filter name: \
%s",
filter_str,
)
return None
result = {"name": elements[0]}
for idx, elem in enumerate(elements[1:]):
if not elem:
# skip empty arguments
continue
if ":" in elem:
# Key value pair
key, value = elem.split(":", 1)
if key.lower() in ["include", "exclude"]:
if idx != len(elements[1:]) - 1:
logger.error(
"{} can only present as the last argument in the filter. "
"{} is ignored.".format(key, elem)
)
continue
result[key.lower()] = re.split("[ ,]+", value)
else:
if "kwargs" not in result:
result["kwargs"] = {}
result["kwargs"][key] = cast_to_number_or_bool(value)
else:
if "args" not in result:
result["args"] = []
result["args"].append(cast_to_number_or_bool(elem))
if is_pre:
result["pre"] = True
return result
|
def parse_glyphs_filter(filter_str, is_pre=False)
|
Parses glyphs custom filter string into a dict object that
ufo2ft can consume.
Reference:
ufo2ft: https://github.com/googlei18n/ufo2ft
Glyphs 2.3 Handbook July 2016, p184
Args:
filter_str - a string of glyphs app filter
Return:
A dictionary contains the structured filter.
Return None if parse failed.
| 2.901038
| 2.900476
| 1.000194
|
return os.path.join(
out_dir,
"%s-%s.ufo"
% ((family_name or "").replace(" ", ""), (style_name or "").replace(" ", "")),
)
|
def build_ufo_path(out_dir, family_name, style_name)
|
Build string to use as a UFO path.
| 3.19761
| 2.639511
| 1.21144
|
out_path = build_ufo_path(out_dir, ufo.info.familyName, ufo.info.styleName)
logger.info("Writing %s" % out_path)
clean_ufo(out_path)
ufo.save(out_path)
|
def write_ufo(ufo, out_dir)
|
Write a UFO.
| 2.66205
| 2.695261
| 0.987678
|
if path.endswith(".ufo") and os.path.exists(path):
shutil.rmtree(path)
|
def clean_ufo(path)
|
Make sure old UFO data is removed, as it may contain deleted glyphs.
| 3.764967
| 2.845958
| 1.322917
|
# 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)
|
def ufo_create_background_layer_for_all_glyphs(ufo_font)
|
Create a background layer for all glyphs in ufo_font if not present to
reduce roundtrip differences.
| 2.567644
| 2.464235
| 1.041964
|
if inputstr.strip().lower() == "true":
return True
elif inputstr.strip().lower() == "false":
return False
try:
return int(inputstr)
except ValueError:
try:
return float(inputstr)
except ValueError:
return inputstr
|
def cast_to_number_or_bool(inputstr)
|
Cast a string to int, float or bool. Return original string if it can't be
converted.
Scientific expression is converted into float.
| 1.604334
| 1.789948
| 0.896302
|
image = layer.backgroundImage
if image is None:
return
ufo_image = ufo_glyph.image
ufo_image.fileName = image.path
ufo_image.transformation = image.transform
ufo_glyph.lib[CROP_KEY] = list(image.crop)
ufo_glyph.lib[LOCKED_KEY] = image.locked
ufo_glyph.lib[ALPHA_KEY] = image.alpha
|
def to_ufo_background_image(self, ufo_glyph, layer)
|
Copy the backgound image from the GSLayer to the UFO Glyph.
| 3.289372
| 3.069532
| 1.07162
|
ufo_image = ufo_glyph.image
if ufo_image.fileName is None:
return
image = self.glyphs_module.GSBackgroundImage()
image.path = ufo_image.fileName
image.transform = Transform(*ufo_image.transformation)
if CROP_KEY in ufo_glyph.lib:
x, y, w, h = ufo_glyph.lib[CROP_KEY]
image.crop = Rect(Point(x, y), Size(w, h))
if LOCKED_KEY in ufo_glyph.lib:
image.locked = ufo_glyph.lib[LOCKED_KEY]
if ALPHA_KEY in ufo_glyph.lib:
image.alpha = ufo_glyph.lib[ALPHA_KEY]
layer.backgroundImage = image
|
def to_glyphs_background_image(self, ufo_glyph, layer)
|
Copy the background image from the UFO Glyph to the GSLayer.
| 2.36625
| 2.240593
| 1.056082
|
guidelines = glyphs_obj.guides
if not guidelines:
return
new_guidelines = []
for guideline in guidelines:
new_guideline = {}
x, y = guideline.position
angle = guideline.angle % 360
if _is_vertical(x, y, angle):
new_guideline["x"] = x
elif _is_horizontal(x, y, angle):
new_guideline["y"] = y
else:
new_guideline["x"] = x
new_guideline["y"] = y
new_guideline["angle"] = angle
name = guideline.name
if name is not None:
# Identifier
m = IDENTIFIER_NAME_RE.match(name)
if m:
new_guideline["identifier"] = m.group(2)
name = name[: -len(m.group(1))]
# Color
m = COLOR_NAME_RE.match(name)
if m:
new_guideline["color"] = m.group(2)
name = name[: -len(m.group(1))]
if guideline.locked:
name = (name or "") + LOCKED_NAME_SUFFIX
if name:
new_guideline["name"] = name
new_guidelines.append(new_guideline)
ufo_obj.guidelines = new_guidelines
|
def to_ufo_guidelines(self, ufo_obj, glyphs_obj)
|
Set guidelines.
| 2.049163
| 2.016165
| 1.016367
|
if not ufo_obj.guidelines:
return
for guideline in ufo_obj.guidelines:
new_guideline = self.glyphs_module.GSGuideLine()
name = guideline.name
# Locked
if name is not None and name.endswith(LOCKED_NAME_SUFFIX):
name = name[: -len(LOCKED_NAME_SUFFIX)]
new_guideline.locked = True
if guideline.color:
name = (name or "") + COLOR_NAME_SUFFIX % str(guideline.color)
if guideline.identifier:
name = (name or "") + IDENTIFIER_NAME_SUFFIX % guideline.identifier
new_guideline.name = name
new_guideline.position = Point(guideline.x or 0, guideline.y or 0)
if guideline.angle is not None:
new_guideline.angle = guideline.angle % 360
elif _is_vertical(guideline.x, guideline.y, None):
new_guideline.angle = 90
glyphs_obj.guides.append(new_guideline)
|
def to_glyphs_guidelines(self, ufo_obj, glyphs_obj)
|
Set guidelines.
| 2.36726
| 2.317706
| 1.021381
|
if alternate_view:
if not alternate_rule:
id_rule = id_rule or DEFAULT_ID_RULE
alternate_rule = posixpath.join(base_rule, id_rule)
else:
assert id_rule is None
else:
assert alternate_rule is None
assert id_rule is None
app = self._get_app(app)
endpoint = self._get_endpoint(base_view, alternate_view)
# Store the view rules for reference. Doesn't support multiple routes
# mapped to same view.
views = app.extensions['resty'].views
base_rule_full = '{}{}'.format(self.prefix, base_rule)
base_view_func = base_view.as_view(endpoint)
if not alternate_view:
app.add_url_rule(base_rule_full, view_func=base_view_func)
views[base_view] = Resource(base_view, base_rule_full)
return
alternate_rule_full = '{}{}'.format(self.prefix, alternate_rule)
alternate_view_func = alternate_view.as_view(endpoint)
@functools.wraps(base_view_func)
def view_func(*args, **kwargs):
if flask.request.url_rule.rule == base_rule_full:
return base_view_func(*args, **kwargs)
else:
return alternate_view_func(*args, **kwargs)
app.add_url_rule(
base_rule_full, view_func=view_func, endpoint=endpoint,
methods=base_view.methods,
)
app.add_url_rule(
alternate_rule_full, view_func=view_func, endpoint=endpoint,
methods=alternate_view.methods,
)
views[base_view] = Resource(base_view, base_rule_full)
views[alternate_view] = Resource(alternate_view, alternate_rule_full)
|
def add_resource(
self,
base_rule,
base_view,
alternate_view=None,
alternate_rule=None,
id_rule=None,
app=None,
)
|
Add route or routes for a resource.
:param str base_rule: The URL rule for the resource. This will be
prefixed by the API prefix.
:param base_view: Class-based view for the resource.
:param alternate_view: If specified, an alternate class-based view for
the resource. Usually, this will be a detail view, when the base
view is a list view.
:param alternate_rule: If specified, the URL rule for the alternate
view. This will be prefixed by the API prefix. This is mutually
exclusive with id_rule, and must not be specified if alternate_view
is not specified.
:type alternate_rule: str or None
:param id_rule: If specified, a suffix to append to base_rule to get
the alternate view URL rule. If alternate_view is specified, and
alternate_rule is not, then this defaults to '<id>'. This is
mutually exclusive with alternate_rule, and must not be specified
if alternate_view is not specified.
:type id_rule: str or None
:param app: If specified, the application to which to add the route(s).
Otherwise, this will be the bound application, if present.
| 2.04703
| 2.102886
| 0.973438
|
app = self._get_app(app)
@app.route(rule)
def ping():
return '', status_code
|
def add_ping(self, rule, status_code=200, app=None)
|
Add a ping route.
:param str rule: The URL rule. This will not use the API prefix, as the
ping endpoint is not really part of the API.
:param int status_code: The ping response status code. The default is
200 rather than the more correct 204 because many health checks
look for 200s.
:param app: If specified, the application to which to add the route.
Otherwise, this will be the bound application, if present.
| 4.267376
| 5.194771
| 0.821475
|
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
|
def designspace(self)
|
Get a designspace Document instance that links the masters together
and holds instance data.
| 4.5884
| 4.427819
| 1.036267
|
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
|
def font(self)
|
Get the GSFont built from the UFOs + designspace.
| 4.144592
| 3.979433
| 1.041503
|
# 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(
).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
|
def _valid_designspace(self, designspace)
|
Make sure that the user-provided designspace has loaded fonts and
that names are the same as those from the UFOs.
| 4.594884
| 4.34626
| 1.057204
|
designspace = designspaceLib.DesignSpaceDocument()
ufo_to_location = defaultdict(dict)
# Make weight and width axis if relevant
for info_key, axis_def in zip(
("openTypeOS2WeightClass", "openTypeOS2WidthClass"),
(WEIGHT_AXIS_DEF, WIDTH_AXIS_DEF),
):
axis = designspace.newAxisDescriptor()
axis.tag = axis_def.tag
axis.name = axis_def.name
mapping = []
for ufo in ufos:
user_loc = getattr(ufo.info, info_key)
if user_loc is not None:
design_loc = class_to_value(axis_def.tag, user_loc)
mapping.append((user_loc, design_loc))
ufo_to_location[ufo][axis_def.name] = design_loc
mapping = sorted(set(mapping))
if len(mapping) > 1:
axis.map = mapping
axis.minimum = min([user_loc for user_loc, _ in mapping])
axis.maximum = max([user_loc for user_loc, _ in mapping])
axis.default = min(
axis.maximum, max(axis.minimum, axis_def.default_user_loc)
)
designspace.addAxis(axis)
for ufo in ufos:
source = designspace.newSourceDescriptor()
source.font = ufo
source.familyName = ufo.info.familyName
source.styleName = ufo.info.styleName
# source.name = '%s %s' % (source.familyName, source.styleName)
source.path = ufo.path
source.location = ufo_to_location[ufo]
designspace.addSource(source)
# UFO-level skip list lib keys are usually ignored, except when we don't have a
# Designspace file to start from. If they exist in the UFOs, promote them to a
# Designspace-level lib key. However, to avoid accidents, expect the list to
# exist in none or be the same in all UFOs.
if any("public.skipExportGlyphs" in ufo.lib for ufo in ufos):
skip_export_glyphs = {
frozenset(ufo.lib.get("public.skipExportGlyphs", [])) for ufo in ufos
}
if len(skip_export_glyphs) == 1:
designspace.lib["public.skipExportGlyphs"] = sorted(
next(iter(skip_export_glyphs))
)
else:
raise ValueError(
"The `public.skipExportGlyphs` list of all UFOs must either not "
"exist or be the same in every UFO."
)
return designspace
|
def _fake_designspace(self, ufos)
|
Build a fake designspace with the given UFOs as sources, so that all
builder functions can rely on the presence of a designspace.
| 3.220061
| 3.149639
| 1.022359
|
warning_msg = "Non-existent glyph class %s found in kerning rules."
for left, pairs in kerning_data.items():
match = re.match(r"@MMK_L_(.+)", left)
left_is_class = bool(match)
if left_is_class:
left = "public.kern1.%s" % match.group(1)
if left not in ufo.groups:
self.logger.warning(warning_msg % left)
for right, kerning_val in pairs.items():
match = re.match(r"@MMK_R_(.+)", right)
right_is_class = bool(match)
if right_is_class:
right = "public.kern2.%s" % match.group(1)
if right not in ufo.groups:
self.logger.warning(warning_msg % right)
ufo.kerning[left, right] = kerning_val
|
def _to_ufo_kerning(self, ufo, kerning_data)
|
Add .glyphs kerning to an UFO.
| 2.446962
| 2.338079
| 1.046569
|
for master_id, source in self._sources.items():
for (left, right), value in source.font.kerning.items():
left_match = UFO_KERN_GROUP_PATTERN.match(left)
right_match = UFO_KERN_GROUP_PATTERN.match(right)
if left_match:
left = "@MMK_L_{}".format(left_match.group(2))
if right_match:
right = "@MMK_R_{}".format(right_match.group(2))
self.font.setKerningForPair(master_id, left, right, value)
|
def to_glyphs_kerning(self)
|
Add UFO kerning to GSFont.
| 2.571899
| 2.413436
| 1.065659
|
replacements = (("\u2018", "'"), ("\u2019", "'"), ("\u201C", '"'), ("\u201D", '"'))
for orig, replacement in replacements:
name = name.replace(orig, replacement)
return name
|
def _normalize_custom_param_name(name)
|
Replace curved quotes with straight quotes in a custom parameter name.
These should be the only keys with problematic (non-ascii) characters,
since they can be user-generated.
| 2.477928
| 2.040562
| 1.214336
|
for _, ufo_name, default_value in DEFAULT_PARAMETERS:
if getattr(ufo.info, ufo_name) is None:
if isinstance(default_value, list):
# Prevent problem if the same default value list is put in
# several unrelated objects.
default_value = default_value[:]
setattr(ufo.info, ufo_name, default_value)
|
def _set_default_params(ufo)
|
Set Glyphs.app's default parameters when different from ufo2ft ones.
| 4.964195
| 4.609338
| 1.076987
|
for glyphs_name, _, default_value in DEFAULT_PARAMETERS:
if (
glyphs_name in glyphs.customParameters
and glyphs.customParameters[glyphs_name] == default_value
):
del (glyphs.customParameters[glyphs_name])
# These parameters can be referred to with the two names in Glyphs
if (
glyphs_name in glyphs.customParameters
and glyphs.customParameters[glyphs_name] == default_value
):
del (glyphs.customParameters[glyphs_name])
|
def _unset_default_params(glyphs)
|
Unset Glyphs.app's parameters that have default values.
FIXME: (jany) maybe this should be taken care of in the writer? and/or
classes should have better default values?
| 3.079803
| 2.915424
| 1.056382
|
self._handled.add(key)
values = self._lookup[key]
if len(values) > 1:
raise RuntimeError(
"More than one value for this customParameter: {}".format(key)
)
if values:
return values[0]
return None
|
def get_custom_value(self, key)
|
Return the first and only custom parameter matching the given name.
| 4.615848
| 4.306488
| 1.071836
|
self._handled.add(key)
return self._lookup[key]
|
def get_custom_values(self, key)
|
Return a set of values for the given customParameter name.
| 14.804911
| 15.528843
| 0.953381
|
self._owner.customParameters.append(
self._glyphs_module.GSCustomParameter(name=key, value=value)
)
|
def set_custom_value(self, key, value)
|
Set one custom parameter with the given value.
We assume that the list of custom parameters does not already contain
the given parameter so we only append.
| 11.802564
| 9.10551
| 1.2962
|
for value in values:
self.set_custom_value(key, value)
|
def set_custom_values(self, key, values)
|
Set several values for the customParameter with the given key.
We append one GSCustomParameter per value.
| 3.470051
| 2.805103
| 1.23705
|
if self.name in self._CUSTOM_INT_PARAMS:
value = int(value)
elif self.name in self._CUSTOM_FLOAT_PARAMS:
value = float(value)
elif self.name in self._CUSTOM_BOOL_PARAMS:
value = bool(value)
elif self.name in self._CUSTOM_INTLIST_PARAMS:
value = readIntlist(value)
elif self.name in self._CUSTOM_DICT_PARAMS:
parser = Parser()
value = parser.parse(value)
elif self.name == "note":
value = unicode(value)
self._value = value
|
def setValue(self, value)
|
Cast some known data in custom parameters.
| 2.67999
| 2.479149
| 1.081012
|
weight, width, custom_name = self._splitName(name)
self.set_all_name_components(name, weight, width, custom_name)
|
def name(self, name)
|
This function will take the given name and split it into components
weight, width, customName, and possibly the full name.
This is what Glyphs 1113 seems to be doing, approximately.
| 11.013148
| 4.595959
| 2.396268
|
self.weight = weight or "Regular"
self.width = width or "Regular"
self.customName = custom_name or ""
# Only store the requested name if we can't build it from the parts
if self._joinName() == name:
self._name = None
del self.customParameters["Master Name"]
else:
self._name = name
self.customParameters["Master Name"] = name
|
def set_all_name_components(self, name, weight, width, custom_name)
|
This function ensures that after being called, the master.name,
master.weight, master.width, and master.customName match the given
values.
| 6.529825
| 6.244772
| 1.045647
|
# Strip the first and last newlines
if value.startswith("{\n"):
value = "{" + value[2:]
if value.endswith("\n}"):
value = value[:-2] + "}"
# escape double quotes and newlines
return value.replace('"', '\\"').replace("\\n", "\\\\n").replace("\n", "\\n")
|
def _encode_dict_as_string(value)
|
Takes the PLIST string of a dict, and returns the same string
encoded such that it can be included in the string representation
of a GSNode.
| 3.439141
| 3.33737
| 1.030494
|
path = self.parent
layer = path.parent
for path_index in range(len(layer.paths)):
if path == layer.paths[path_index]:
for node_index in range(len(path.nodes)):
if self == path.nodes[node_index]:
return Point(path_index, node_index)
return None
|
def _indices(self)
|
Find the path_index and node_index that identify the given node.
| 3.626488
| 2.771803
| 1.30835
|
path_index, node_index = point
path = self.paths[int(path_index)]
node = path.nodes[int(node_index)]
return node
|
def _find_node_by_indices(self, point)
|
Find the GSNode that is refered to by the given indices.
See GSNode::_indices()
| 3.631823
| 3.560138
| 1.020135
|
if self._background is None:
self._background = GSBackgroundLayer()
self._background._foreground = self
return self._background
|
def background(self)
|
Only a getter on purpose. See the tests.
| 6.068473
| 4.77779
| 1.270142
|
processed = set()
for glyph in ufo:
_propagate_glyph_anchors(self, ufo, glyph, processed)
|
def to_ufo_propagate_font_anchors(self, ufo)
|
Copy anchors from parent glyphs' components to the parent.
| 7.511072
| 5.343915
| 1.405537
|
if parent.name in processed:
return
processed.add(parent.name)
base_components = []
mark_components = []
anchor_names = set()
to_add = {}
for component in parent.components:
try:
glyph = ufo[component.baseGlyph]
except KeyError:
self.logger.warning(
"Anchors not propagated for inexistent component {} in glyph {}".format(
component.baseGlyph, parent.name
)
)
else:
_propagate_glyph_anchors(self, ufo, glyph, processed)
if any(a.name.startswith("_") for a in glyph.anchors):
mark_components.append(component)
else:
base_components.append(component)
anchor_names |= {a.name for a in glyph.anchors}
for anchor_name in anchor_names:
# don't add if parent already contains this anchor OR any associated
# ligature anchors (e.g. "top_1, top_2" for "top")
if not any(a.name.startswith(anchor_name) for a in parent.anchors):
_get_anchor_data(to_add, ufo, base_components, anchor_name)
for component in mark_components:
_adjust_anchors(to_add, ufo, component)
# we sort propagated anchors to append in a deterministic order
for name, (x, y) in sorted(to_add.items()):
anchor_dict = {"name": name, "x": x, "y": y}
parent.appendAnchor(glyph.anchorClass(anchorDict=anchor_dict))
|
def _propagate_glyph_anchors(self, ufo, parent, processed)
|
Propagate anchors for a single parent glyph.
| 3.426257
| 3.215493
| 1.065546
|
glyph = ufo[component.baseGlyph]
t = Transform(*component.transformation)
for anchor in glyph.anchors:
# only adjust if this anchor has data and the component also contains
# the associated mark anchor (e.g. "_top" for "top")
if anchor.name in anchor_data and any(
a.name == "_" + anchor.name for a in glyph.anchors
):
anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
|
def _adjust_anchors(anchor_data, ufo, component)
|
Adjust anchors to which a mark component may have been attached.
| 5.67024
| 5.081729
| 1.115809
|
for anchor in anchors:
x, y = anchor.position
anchor_dict = {"name": anchor.name, "x": x, "y": y}
glyph.appendAnchor(anchor_dict)
|
def to_ufo_glyph_anchors(self, glyph, anchors)
|
Add .glyphs anchors to a glyph.
| 3.36716
| 2.726898
| 1.234795
|
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)
|
def to_glyphs_glyph_anchors(self, ufo_glyph, layer)
|
Add UFO glif anchors to a GSLayer.
| 2.316221
| 2.141352
| 1.081663
|
name = func.__name__
doc = func.__doc__
def getter(self, name=name):
try:
return self.__dict__[name]
except KeyError:
self.__dict__[name] = value = func(self)
return value
getter.func_name = name
return property(getter, doc=doc)
|
def cached_property(func)
|
Special property decorator that caches the computed
property value in the object's instance dict the first
time it is accessed.
| 2.141421
| 2.333431
| 0.917713
|
deg = deg % 360.0
if deg == 90.0:
return 0.0, 1.0
elif deg == 180.0:
return -1.0, 0
elif deg == 270.0:
return 0, -1.0
rad = math.radians(deg)
return math.cos(rad), math.sin(rad)
|
def cos_sin_deg(deg)
|
Return the cosine and sin for the given angle
in degrees, with special-case handling of multiples
of 90 for perfect right angles
| 1.703537
| 1.78898
| 0.952239
|
if len(scaling) == 1:
sx = sy = float(scaling[0])
else:
sx, sy = scaling
return tuple.__new__(cls, (sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0))
|
def scale(cls, *scaling)
|
Create a scaling transform from a scalar or vector.
:param scaling: The scaling factor. A scalar value will
scale in both dimensions equally. A vector scaling
value scales the dimensions independently.
:type scaling: float or sequence
:rtype: Affine
| 1.977957
| 2.075199
| 0.953141
|
sx = math.tan(math.radians(x_angle))
sy = math.tan(math.radians(y_angle))
return tuple.__new__(cls, (1.0, sy, 0.0, sx, 1.0, 0.0, 0.0, 0.0, 1.0))
|
def shear(cls, x_angle=0, y_angle=0)
|
Create a shear transform along one or both axes.
:param x_angle: Angle in degrees to shear along the x-axis.
:type x_angle: float
:param y_angle: Angle in degrees to shear along the y-axis.
:type y_angle: float
:rtype: Affine
| 2.111425
| 2.352838
| 0.897395
|
ca, sa = cos_sin_deg(angle)
if pivot is None:
return tuple.__new__(cls, (ca, sa, 0.0, -sa, ca, 0.0, 0.0, 0.0, 1.0))
else:
px, py = pivot
return tuple.__new__(
cls,
(
ca,
sa,
px - px * ca + py * sa,
-sa,
ca,
py - px * sa - py * ca,
0.0,
0.0,
1.0,
),
)
|
def rotation(cls, angle, pivot=None)
|
Create a rotation transform at the specified angle,
optionally about the specified pivot point.
:param angle: Rotation angle in degrees
:type angle: float
:param pivot: Point to rotate about, if omitted the
rotation is about the origin.
:type pivot: sequence
:rtype: Affine
| 1.945413
| 2.25364
| 0.863231
|
a, b, c, d, e, f, g, h, i = self
return a * e - b * d
|
def determinant(self)
|
The determinant of the transform matrix. This value
is equal to the area scaling factor when the transform
is applied to a shape.
| 3.612139
| 3.969429
| 0.90999
|
a, b, c, d, e, f, g, h, i = self
return (abs(a) < EPSILON and abs(e) < EPSILON) or (
abs(d) < EPSILON and abs(b) < EPSILON
)
|
def is_rectilinear(self)
|
True if the transform is rectilinear, i.e., whether a shape would
remain axis-aligned, within rounding limits, after applying the
transform.
| 3.066772
| 3.115785
| 0.98427
|
a, b, c, d, e, f, g, h, i = self
return abs(a * b + d * e) < EPSILON
|
def is_conformal(self)
|
True if the transform is conformal, i.e., if angles between points
are preserved after applying the transform, within rounding limits.
This implies that the transform has no effective shear.
| 6.055296
| 4.706316
| 1.286632
|
a, b, c, d, e, f, g, h, i = self
return (
self.is_conformal
and abs(1.0 - (a * a + d * d)) < EPSILON
and abs(1.0 - (b * b + e * e)) < EPSILON
)
|
def is_orthonormal(self)
|
True if the transform is orthonormal, which means that the
transform represents a rigid motion, which has no effective scaling or
shear. Mathematically, this means that the axis vectors of the
transform matrix are perpendicular and unit-length. Applying an
orthonormal transform to a shape always results in a congruent shape.
| 3.305191
| 3.267014
| 1.011686
|
a, b, c, d, e, f, _, _, _ = self
return (a, d), (b, e), (c, f)
|
def column_vectors(self)
|
The values of the transform as three 2D column vectors
| 4.408071
| 4.129379
| 1.06749
|
for i in (0, 1, 2, 3, 4, 5):
if abs(self[i] - other[i]) >= EPSILON:
return False
return True
|
def almost_equals(self, other)
|
Compare transforms for approximate equality.
:param other: Transform being compared.
:type other: Affine
:return: True if absolute difference between each element
of each respective tranform matrix < ``EPSILON``.
| 2.658086
| 2.832498
| 0.938425
|
if self is not identity and self != identity:
sa, sb, sc, sd, se, sf, _, _, _ = self
for i, (x, y) in enumerate(seq):
seq[i] = (x * sa + y * sd + sc, x * sb + y * se + sf)
|
def itransform(self, seq)
|
Transform a sequence of points or vectors in place.
:param seq: Mutable sequence of :class:`~planar.Vec2` to be
transformed.
:returns: None, the input sequence is mutated in place.
| 4.730082
| 4.82237
| 0.980863
|
# Read data on first use.
if data is None:
global GLYPHDATA
if GLYPHDATA is None:
GLYPHDATA = GlyphData.from_files(
os.path.join(
os.path.dirname(glyphsLib.__file__), "data", "GlyphData.xml"
),
os.path.join(
os.path.dirname(glyphsLib.__file__),
"data",
"GlyphData_Ideographs.xml",
),
)
data = GLYPHDATA
# Look up data by full glyph name first.
attributes = _lookup_attributes(glyph_name, data)
production_name = attributes.get("production")
if production_name is None:
production_name = _construct_production_name(glyph_name, data=data)
unicode_value = attributes.get("unicode")
category = attributes.get("category")
sub_category = attributes.get("subCategory")
if category is None:
category, sub_category = _construct_category(glyph_name, data)
# TODO: Determine script in ligatures.
script = attributes.get("script")
description = attributes.get("description")
return Glyph(
glyph_name,
production_name,
unicode_value,
category,
sub_category,
script,
description,
)
|
def get_glyph(glyph_name, data=None)
|
Return a named tuple (Glyph) containing information derived from a glyph
name akin to GSGlyphInfo.
The information is derived from an included copy of GlyphData.xml
and GlyphData_Ideographs.xml, going purely by the glyph name.
| 2.876464
| 2.534703
| 1.134833
|
attributes = (
data.names.get(glyph_name)
or data.alternative_names.get(glyph_name)
or data.production_names.get(glyph_name)
or {}
)
return attributes
|
def _lookup_attributes(glyph_name, data)
|
Look up glyph attributes in data by glyph name, alternative name or
production name in order or return empty dictionary.
Look up by alternative and production names for legacy projects and
because of issue #232.
| 3.940933
| 3.011539
| 1.308611
|
MAX_GLYPH_NAME_LENGTH = 63
clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name)
if len(clean_name) > MAX_GLYPH_NAME_LENGTH:
return None
return clean_name
|
def _agl_compliant_name(glyph_name)
|
Return an AGL-compliant name string or None if we can't make one.
| 2.649388
| 2.344119
| 1.130228
|
# Glyphs creates glyphs that start with an underscore as "non-exportable" glyphs or
# construction helpers without a category.
if glyph_name.startswith("_"):
return None, None
# Glyph variants (e.g. "fi.alt") don't have their own entry, so we strip e.g. the
# ".alt" and try a second lookup with just the base name. A variant is hopefully in
# the same category as its base glyph.
base_name = glyph_name.split(".", 1)[0]
base_attribute = data.names.get(base_name) or {}
if base_attribute:
category = base_attribute.get("category")
sub_category = base_attribute.get("subCategory")
return category, sub_category
# Detect ligatures.
if "_" in base_name:
base_names = base_name.split("_")
base_names_attributes = [_lookup_attributes(name, data) for name in base_names]
first_attribute = base_names_attributes[0]
# If the first part is a Mark, Glyphs 2.6 declares the entire glyph a Mark
if first_attribute.get("category") == "Mark":
category = first_attribute.get("category")
sub_category = first_attribute.get("subCategory")
return category, sub_category
# If the first part is a Letter...
if first_attribute.get("category") == "Letter":
# ... and the rest are only marks or separators or don't exist, the
# sub_category is that of the first part ...
if all(
a.get("category") in (None, "Mark", "Separator")
for a in base_names_attributes[1:]
):
category = first_attribute.get("category")
sub_category = first_attribute.get("subCategory")
return category, sub_category
# ... otherwise, a ligature.
category = first_attribute.get("category")
sub_category = "Ligature"
return category, sub_category
# TODO: Cover more cases. E.g. "one_one" -> ("Number", "Ligature") but
# "one_onee" -> ("Number", "Composition").
# Still nothing? Maybe we're looking at something like "uni1234.alt", try
# using fontTools' AGL module to convert the base name to something meaningful.
# Corner case: when looking at ligatures, names that don't exist in the AGLFN
# are skipped, so len("acutecomb_o") == 2 but len("dotaccentcomb_o") == 1.
character = fontTools.agl.toUnicode(base_name)
if character:
category, sub_category = _translate_category(
glyph_name, unicodedata.category(character[0])
)
return category, sub_category
return None, None
|
def _construct_category(glyph_name, data)
|
Derive (sub)category of a glyph name.
| 4.681942
| 4.613242
| 1.014892
|
DEFAULT_CATEGORIES = {
None: ("Letter", None),
"Cc": ("Separator", None),
"Cf": ("Separator", "Format"),
"Cn": ("Symbol", None),
"Co": ("Letter", "Compatibility"),
"Ll": ("Letter", "Lowercase"),
"Lm": ("Letter", "Modifier"),
"Lo": ("Letter", None),
"Lt": ("Letter", "Uppercase"),
"Lu": ("Letter", "Uppercase"),
"Mc": ("Mark", "Spacing Combining"),
"Me": ("Mark", "Enclosing"),
"Mn": ("Mark", "Nonspacing"),
"Nd": ("Number", "Decimal Digit"),
"Nl": ("Number", None),
"No": ("Number", "Decimal Digit"),
"Pc": ("Punctuation", None),
"Pd": ("Punctuation", "Dash"),
"Pe": ("Punctuation", "Parenthesis"),
"Pf": ("Punctuation", "Quote"),
"Pi": ("Punctuation", "Quote"),
"Po": ("Punctuation", None),
"Ps": ("Punctuation", "Parenthesis"),
"Sc": ("Symbol", "Currency"),
"Sk": ("Mark", "Spacing"),
"Sm": ("Symbol", "Math"),
"So": ("Symbol", None),
"Zl": ("Separator", None),
"Zp": ("Separator", None),
"Zs": ("Separator", "Space"),
}
glyphs_category = DEFAULT_CATEGORIES.get(unicode_category, ("Letter", None))
# Exception: Something like "one_two" should be a (_, Ligature),
# "acutecomb_brevecomb" should however stay (Mark, Nonspacing).
if "_" in glyph_name and glyphs_category[0] != "Mark":
return glyphs_category[0], "Ligature"
return glyphs_category
|
def _translate_category(glyph_name, unicode_category)
|
Return a translation from Unicode category letters to Glyphs
categories.
| 2.37747
| 2.320784
| 1.024426
|
name_mapping = {}
alt_name_mapping = {}
production_name_mapping = {}
for glyphdata_file in glyphdata_files:
glyph_data = xml.etree.ElementTree.parse(glyphdata_file).getroot()
for glyph in glyph_data:
glyph_name = glyph.attrib["name"]
glyph_name_alternatives = glyph.attrib.get("altNames")
glyph_name_production = glyph.attrib.get("production")
name_mapping[glyph_name] = glyph.attrib
if glyph_name_alternatives:
alternatives = glyph_name_alternatives.replace(" ", "").split(",")
for glyph_name_alternative in alternatives:
alt_name_mapping[glyph_name_alternative] = glyph.attrib
if glyph_name_production:
production_name_mapping[glyph_name_production] = glyph.attrib
return cls(name_mapping, alt_name_mapping, production_name_mapping)
|
def from_files(cls, *glyphdata_files)
|
Return GlyphData holding data from a list of XML file paths.
| 1.886794
| 1.846418
| 1.021867
|
if hasattr(file_or_path, "read"):
font = load(file_or_path)
else:
with open(file_or_path, "r", encoding="utf-8") as ifile:
font = load(ifile)
logger.info("Loading to UFOs")
return to_ufos(
font,
include_instances=include_instances,
family_name=family_name,
propagate_anchors=propagate_anchors,
)
|
def load_to_ufos(
file_or_path, include_instances=False, family_name=None, propagate_anchors=True
)
|
Load an unpacked .glyphs object to UFO objects.
| 2.091593
| 1.997934
| 1.046878
|
font = GSFont(filename)
if not os.path.isdir(master_dir):
os.mkdir(master_dir)
if designspace_instance_dir is None:
instance_dir = None
else:
instance_dir = os.path.relpath(designspace_instance_dir, master_dir)
designspace = to_designspace(
font,
family_name=family_name,
propagate_anchors=propagate_anchors,
instance_dir=instance_dir,
minimize_glyphs_diffs=minimize_glyphs_diffs,
generate_GDEF=generate_GDEF,
store_editor_state=store_editor_state,
)
# Only write full masters to disk. This assumes that layer sources are always part
# of another full master source, which must always be the case in a .glyphs file.
ufos = {}
for source in designspace.sources:
if source.filename in ufos:
assert source.font is ufos[source.filename]
continue
if create_background_layers:
ufo_create_background_layer_for_all_glyphs(source.font)
ufo_path = os.path.join(master_dir, source.filename)
clean_ufo(ufo_path)
source.font.save(ufo_path)
if normalize_ufos:
import ufonormalizer
ufonormalizer.normalizeUFO(ufo_path, writeModTimes=False)
ufos[source.filename] = source.font
if not designspace_path:
designspace_path = os.path.join(master_dir, designspace.filename)
designspace.write(designspace_path)
return Masters(ufos, designspace_path)
|
def build_masters(
filename,
master_dir,
designspace_instance_dir=None,
designspace_path=None,
family_name=None,
propagate_anchors=True,
minimize_glyphs_diffs=False,
normalize_ufos=False,
create_background_layers=False,
generate_GDEF=True,
store_editor_state=True,
)
|
Write and return UFOs from the masters and the designspace defined in a
.glyphs file.
Args:
master_dir: Directory where masters are written.
designspace_instance_dir: If provided, a designspace document will be
written alongside the master UFOs though no instances will be built.
family_name: If provided, the master UFOs will be given this name and
only instances with this name will be included in the designspace.
Returns:
A named tuple of master UFOs (`ufos`) and the path to the designspace
file (`designspace_path`).
| 2.64302
| 2.670458
| 0.989725
|
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,
)
|
def glyphs2ufo(options)
|
Converts a Glyphs.app source file into UFO masters and a designspace file.
| 4.40772
| 4.16648
| 1.0579
|
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)
|
def ufo2glyphs(options)
|
Convert one designspace file or one or more UFOs to a Glyphs.app source file.
| 2.966519
| 2.865951
| 1.035091
|
return any(f for f in font.features if f.name == "kern" and not f.automatic)
|
def _has_manual_kern_feature(font)
|
Return true if the GSFont contains a manually written 'kern' feature.
| 4.379985
| 3.784934
| 1.157216
|
if not self.use_designspace:
ufo.lib[FONT_USER_DATA_KEY] = dict(self.font.userData)
|
def to_ufo_family_user_data(self, ufo)
|
Set family-wide user data as Glyphs does.
| 8.739837
| 6.044531
| 1.445908
|
for key in master.userData.keys():
if _user_data_has_no_special_meaning(key):
ufo.lib[key] = master.userData[key]
# Restore UFO data files. This code assumes that all paths are POSIX paths.
if UFO_DATA_KEY in master.userData:
for filename, data in master.userData[UFO_DATA_KEY].items():
ufo.data[filename] = bytes(data)
|
def to_ufo_master_user_data(self, ufo, master)
|
Set master-specific user data as Glyphs does.
| 4.84903
| 4.463076
| 1.086477
|
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
|
def to_glyphs_family_user_data_from_designspace(self)
|
Set the GSFont userData from the designspace family-wide lib data.
| 6.486568
| 5.718441
| 1.134325
|
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
|
def to_glyphs_family_user_data_from_ufo(self, ufo)
|
Set the GSFont userData from the UFO family-wide lib data.
| 4.919399
| 4.314198
| 1.140281
|
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
|
def to_glyphs_master_user_data(self, ufo, master)
|
Set the GSFontMaster userData from the UFO master-specific lib data.
| 4.098877
| 3.77677
| 1.085286
|
builder = UFOBuilder(
font,
ufo_module=ufo_module,
family_name=family_name,
propagate_anchors=propagate_anchors,
minimize_glyphs_diffs=minimize_glyphs_diffs,
generate_GDEF=generate_GDEF,
store_editor_state=store_editor_state,
)
result = list(builder.masters)
if include_instances:
return result, builder.instance_data
return result
|
def to_ufos(
font,
include_instances=False,
family_name=None,
propagate_anchors=True,
ufo_module=defcon,
minimize_glyphs_diffs=False,
generate_GDEF=True,
store_editor_state=True,
)
|
Take a GSFont object and convert it into one UFO per master.
Takes in data as Glyphs.app-compatible classes, as documented at
https://docu.glyphsapp.com/
If include_instances is True, also returns the parsed instance data.
If family_name is provided, the master UFOs will be given this name and
only instances with this name will be returned.
If generate_GDEF is True, write a `table GDEF {...}` statement in the
UFO's features.fea, containing GlyphClassDef and LigatureCaretByPos.
| 2.033847
| 2.309693
| 0.88057
|
builder = UFOBuilder(
font,
ufo_module=ufo_module,
family_name=family_name,
instance_dir=instance_dir,
propagate_anchors=propagate_anchors,
use_designspace=True,
minimize_glyphs_diffs=minimize_glyphs_diffs,
generate_GDEF=generate_GDEF,
store_editor_state=store_editor_state,
)
return builder.designspace
|
def to_designspace(
font,
family_name=None,
instance_dir=None,
propagate_anchors=True,
ufo_module=defcon,
minimize_glyphs_diffs=False,
generate_GDEF=True,
store_editor_state=True,
)
|
Take a GSFont object and convert it into a Designspace Document + UFOS.
The UFOs are available as the attribute `font` of each SourceDescriptor of
the DesignspaceDocument:
ufos = [source.font for source in designspace.sources]
The designspace and the UFOs are not written anywhere by default, they
are all in-memory. If you want to write them to the disk, consider using
the `filename` attribute of the DesignspaceDocument and of its
SourceDescriptor as possible file names.
Takes in data as Glyphs.app-compatible classes, as documented at
https://docu.glyphsapp.com/
If include_instances is True, also returns the parsed instance data.
If family_name is provided, the master UFOs will be given this name and
only instances with this name will be returned.
If generate_GDEF is True, write a `table GDEF {...}` statement in the
UFO's features.fea, containing GlyphClassDef and LigatureCaretByPos.
| 1.774289
| 2.089381
| 0.849194
|
if hasattr(ufos_or_designspace, "sources"):
builder = GlyphsBuilder(
designspace=ufos_or_designspace,
glyphs_module=glyphs_module,
minimize_ufo_diffs=minimize_ufo_diffs,
)
else:
builder = GlyphsBuilder(
ufos=ufos_or_designspace,
glyphs_module=glyphs_module,
minimize_ufo_diffs=minimize_ufo_diffs,
)
return builder.font
|
def to_glyphs(ufos_or_designspace, glyphs_module=classes, minimize_ufo_diffs=False)
|
Take a list of UFOs or a single DesignspaceDocument with attached UFOs
and converts it into a GSFont object.
The GSFont object is in-memory, it's up to the user to write it to the disk
if needed.
This should be the inverse function of `to_ufos` and `to_designspace`,
so we should have to_glyphs(to_ufos(font)) == font
and also to_glyphs(to_designspace(font)) == font
| 1.652705
| 1.813097
| 0.911537
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.