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
... | 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_bac... | 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... | 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... | 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 prefi... | 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
... | 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 ... | 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 ... | 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_glyp... | 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_... | 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... | 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 ... | 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.gro... | 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(
... | 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 ... | 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 trai... | 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 sel... | 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()
... | 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_matc... | 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... | 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 `... | 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.i... | 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_... | 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:]):
... | 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 dictiona... | 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(glyp... | 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.... | 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]
... | 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 ... | 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)]
... | 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
ass... | 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. Usu... | 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
... | 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()
s... | 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 "b... | 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 n... | 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),
... | 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.gr... | 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_ma... | 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_v... | 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... | 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:
... | 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["Mas... | 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", "... | 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_in... | 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.log... | 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... | 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,
... | 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
... | 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 sha... | 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(
... | 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 lo... | 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)... | 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"]
... | 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=fa... | 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,
fami... | 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.
... | 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]) + ".designspa... | 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]
designspac... | 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_K... | 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 n... | 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:
... | 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_filen... | 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(buil... | 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
on... | 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,
sto... | 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
... | 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,
... | 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_... | 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.