本文整理汇总了Python中fontTools.designspaceLib.DesignSpaceDocument类的典型用法代码示例。如果您正苦于以下问题:Python DesignSpaceDocument类的具体用法?Python DesignSpaceDocument怎么用?Python DesignSpaceDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DesignSpaceDocument类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(args=None):
from fontTools import configLogger
if args is None:
args = sys.argv[1:]
# configure the library logger (for >= WARNING)
configLogger()
# comment this out to enable debug messages from logger
# log.setLevel(logging.DEBUG)
if len(args) < 1:
print("usage: fonttools varLib.plot source.designspace", file=sys.stderr)
print(" or")
print("usage: fonttools varLib.plot location1 location2 ...", file=sys.stderr)
sys.exit(1)
fig = pyplot.figure()
if len(args) == 1 and args[0].endswith('.designspace'):
doc = DesignSpaceDocument()
doc.read(args[0])
plotDocument(doc, fig)
else:
axes = [chr(c) for c in range(ord('A'), ord('Z')+1)]
locs = [dict(zip(axes, (float(v) for v in s.split(',')))) for s in args]
plotLocationsSurfaces(locs, fig)
pyplot.show()
示例2: main
def main(args):
from fontTools import configLogger
args = args[1:]
# TODO: allow user to configure logging via command-line options
configLogger(level="INFO")
if len(args) < 1:
print("usage: fonttools varLib.models source.designspace", file=sys.stderr)
print(" or")
print("usage: fonttools varLib.models location1 location2 ...", file=sys.stderr)
sys.exit(1)
from pprint import pprint
if len(args) == 1 and args[0].endswith('.designspace'):
from fontTools.designspaceLib import DesignSpaceDocument
doc = DesignSpaceDocument()
doc.read(args[0])
locs = [s.location for s in doc.sources]
print("Original locations:")
pprint(locs)
doc.normalize()
print("Normalized locations:")
pprint(locs)
else:
axes = [chr(c) for c in range(ord('A'), ord('Z')+1)]
locs = [dict(zip(axes, (float(v) for v in s.split(',')))) for s in args]
model = VariationModel(locs)
print("Sorted locations:")
pprint(model.locations)
print("Supports:")
pprint(model.supports)
示例3: test_with_with_path_object
def test_with_with_path_object(tmpdir):
import pathlib
tmpdir = str(tmpdir)
dest = pathlib.Path(tmpdir) / "test.designspace"
doc = DesignSpaceDocument()
doc.write(dest)
assert dest.exists()
示例4: test_load_masters_layerName_without_required_font
def test_load_masters_layerName_without_required_font():
ds = DesignSpaceDocument()
s = SourceDescriptor()
s.font = None
s.layerName = "Medium"
ds.addSource(s)
with pytest.raises(
AttributeError,
match="specified a layer name but lacks the required TTFont object",
):
load_masters(ds)
示例5: test_findDefault_axis_mapping
def test_findDefault_axis_mapping():
designspace_string = """\
<?xml version='1.0' encoding='UTF-8'?>
<designspace format="4.0">
<axes>
<axis tag="wght" name="Weight" minimum="100" maximum="800" default="400">
<map input="100" output="20"/>
<map input="300" output="40"/>
<map input="400" output="80"/>
<map input="700" output="126"/>
<map input="800" output="170"/>
</axis>
<axis tag="ital" name="Italic" minimum="0" maximum="1" default="1"/>
</axes>
<sources>
<source filename="Font-Light.ufo">
<location>
<dimension name="Weight" xvalue="20"/>
<dimension name="Italic" xvalue="0"/>
</location>
</source>
<source filename="Font-Regular.ufo">
<location>
<dimension name="Weight" xvalue="80"/>
<dimension name="Italic" xvalue="0"/>
</location>
</source>
<source filename="Font-Bold.ufo">
<location>
<dimension name="Weight" xvalue="170"/>
<dimension name="Italic" xvalue="0"/>
</location>
</source>
<source filename="Font-LightItalic.ufo">
<location>
<dimension name="Weight" xvalue="20"/>
<dimension name="Italic" xvalue="1"/>
</location>
</source>
<source filename="Font-Italic.ufo">
<location>
<dimension name="Weight" xvalue="80"/>
<dimension name="Italic" xvalue="1"/>
</location>
</source>
<source filename="Font-BoldItalic.ufo">
<location>
<dimension name="Weight" xvalue="170"/>
<dimension name="Italic" xvalue="1"/>
</location>
</source>
</sources>
</designspace>
"""
designspace = DesignSpaceDocument.fromstring(designspace_string)
assert designspace.findDefault().filename == "Font-Italic.ufo"
designspace.axes[1].default = 0
assert designspace.findDefault().filename == "Font-Regular.ufo"
示例6: test_normalise4
def test_normalise4():
# normalisation with a map
doc = DesignSpaceDocument()
# write some axes
a4 = AxisDescriptor()
a4.minimum = 0
a4.maximum = 1000
a4.default = 0
a4.name = "ddd"
a4.map = [(0,100), (300, 500), (600, 500), (1000,900)]
doc.addAxis(a4)
doc.normalize()
r = []
for axis in doc.axes:
r.append((axis.name, axis.map))
r.sort()
assert r == [('ddd', [(0, 0.1), (300, 0.5), (600, 0.5), (1000, 0.9)])]
示例7: test_axisMapping
def test_axisMapping():
# note: because designspance lib does not do any actual
# processing of the mapping data, we can only check if there data is there.
doc = DesignSpaceDocument()
# write some axes
a4 = AxisDescriptor()
a4.minimum = 0
a4.maximum = 1000
a4.default = 0
a4.name = "ddd"
a4.map = [(0,100), (300, 500), (600, 500), (1000,900)]
doc.addAxis(a4)
doc.normalize()
r = []
for axis in doc.axes:
r.append((axis.name, axis.map))
r.sort()
assert r == [('ddd', [(0, 0.1), (300, 0.5), (600, 0.5), (1000, 0.9)])]
示例8: test_documentLib
def test_documentLib(tmpdir):
# roundtrip test of the document lib with some nested data
tmpdir = str(tmpdir)
testDocPath1 = os.path.join(tmpdir, "testDocumentLibTest.designspace")
doc = DesignSpaceDocument()
a1 = AxisDescriptor()
a1.tag = "TAGA"
a1.name = "axisName_a"
a1.minimum = 0
a1.maximum = 1000
a1.default = 0
doc.addAxis(a1)
dummyData = dict(a=123, b=u"äbc", c=[1,2,3], d={'a':123})
dummyKey = "org.fontTools.designspaceLib"
doc.lib = {dummyKey: dummyData}
doc.write(testDocPath1)
new = DesignSpaceDocument()
new.read(testDocPath1)
assert dummyKey in new.lib
assert new.lib[dummyKey] == dummyData
示例9: test_varlib_build_from_ttx_paths
def test_varlib_build_from_ttx_paths(self):
ds_path = self.get_test_input("Build.designspace")
ttx_dir = self.get_test_input("master_ttx_interpolatable_ttf")
expected_ttx_path = self.get_test_output("BuildMain.ttx")
ds = DesignSpaceDocument.fromfile(ds_path)
for source in ds.sources:
source.path = os.path.join(
ttx_dir, os.path.basename(source.filename).replace(".ufo", ".ttx")
)
ds.updatePaths()
varfont, _, _ = build(ds)
varfont = reload_font(varfont)
tables = [table_tag for table_tag in varfont.keys() if table_tag != "head"]
self.expect_ttx(varfont, expected_ttx_path, tables)
示例10: test_varlib_build_sparse_CFF2
def test_varlib_build_sparse_CFF2(self):
ds_path = self.get_test_input('TestSparseCFF2VF.designspace')
ttx_dir = self.get_test_input("master_sparse_cff2")
expected_ttx_path = self.get_test_output("TestSparseCFF2VF.ttx")
self.temp_dir()
for path in self.get_file_list(ttx_dir, '.ttx', 'MasterSet_Kanji-'):
self.compile_font(path, ".otf", self.tempdir)
ds = DesignSpaceDocument.fromfile(ds_path)
for source in ds.sources:
source.path = os.path.join(
self.tempdir, os.path.basename(source.filename).replace(".ufo", ".otf")
)
ds.updatePaths()
varfont, _, _ = build(ds)
varfont = reload_font(varfont)
tables = ["fvar", "CFF2"]
self.expect_ttx(varfont, expected_ttx_path, tables)
示例11: test_normalise3
def test_normalise3():
# normalisation of negative values, with default == maximum
doc = DesignSpaceDocument()
# write some axes
a3 = AxisDescriptor()
a3.minimum = -1000
a3.maximum = 0
a3.default = 0
a3.name = "ccc"
doc.addAxis(a3)
assert doc.normalizeLocation(dict(ccc=0)) == {'ccc': 0.0}
assert doc.normalizeLocation(dict(ccc=1)) == {'ccc': 0.0}
assert doc.normalizeLocation(dict(ccc=-1000)) == {'ccc': -1.0}
assert doc.normalizeLocation(dict(ccc=-1001)) == {'ccc': -1.0}
doc.normalize()
r = []
for axis in doc.axes:
r.append((axis.name, axis.minimum, axis.default, axis.maximum))
r.sort()
assert r == [('ccc', -1.0, 0.0, 0.0)]
示例12: test_varlib_build_from_ds_object_in_memory_ttfonts
def test_varlib_build_from_ds_object_in_memory_ttfonts(self):
ds_path = self.get_test_input("Build.designspace")
ttx_dir = self.get_test_input("master_ttx_interpolatable_ttf")
expected_ttx_path = self.get_test_output("BuildMain.ttx")
self.temp_dir()
for path in self.get_file_list(ttx_dir, '.ttx', 'TestFamily-'):
self.compile_font(path, ".ttf", self.tempdir)
ds = DesignSpaceDocument.fromfile(ds_path)
for source in ds.sources:
filename = os.path.join(
self.tempdir, os.path.basename(source.filename).replace(".ufo", ".ttf")
)
source.font = TTFont(
filename, recalcBBoxes=False, recalcTimestamp=False, lazy=True
)
source.filename = None # Make sure no file path gets into build()
varfont, _, _ = build(ds)
varfont = reload_font(varfont)
tables = [table_tag for table_tag in varfont.keys() if table_tag != "head"]
self.expect_ttx(varfont, expected_ttx_path, tables)
示例13: test_varlib_build_VVAR_CFF2
def test_varlib_build_VVAR_CFF2(self):
ds_path = self.get_test_input('TestVVAR.designspace')
ttx_dir = self.get_test_input("master_vvar_cff2")
expected_ttx_name = 'TestVVAR'
suffix = '.otf'
self.temp_dir()
for path in self.get_file_list(ttx_dir, '.ttx', 'TestVVAR'):
font, savepath = self.compile_font(path, suffix, self.tempdir)
ds = DesignSpaceDocument.fromfile(ds_path)
for source in ds.sources:
source.path = os.path.join(
self.tempdir, os.path.basename(source.filename).replace(".ufo", suffix)
)
ds.updatePaths()
varfont, _, _ = build(ds)
varfont = reload_font(varfont)
expected_ttx_path = self.get_test_output(expected_ttx_name + '.ttx')
tables = ["VVAR"]
self.expect_ttx(varfont, expected_ttx_path, tables)
self.check_ttx_dump(varfont, expected_ttx_path, tables, suffix)
示例14: load_designspace
def load_designspace(designspace_filename):
ds = DesignSpaceDocument.fromfile(designspace_filename)
masters = ds.sources
if not masters:
raise VarLibError("no sources found in .designspace")
instances = ds.instances
standard_axis_map = OrderedDict([
('weight', ('wght', {'en':'Weight'})),
('width', ('wdth', {'en':'Width'})),
('slant', ('slnt', {'en':'Slant'})),
('optical', ('opsz', {'en':'Optical Size'})),
])
# Setup axes
axes = OrderedDict()
for axis in ds.axes:
axis_name = axis.name
if not axis_name:
assert axis.tag is not None
axis_name = axis.name = axis.tag
if axis_name in standard_axis_map:
if axis.tag is None:
axis.tag = standard_axis_map[axis_name][0]
if not axis.labelNames:
axis.labelNames.update(standard_axis_map[axis_name][1])
else:
assert axis.tag is not None
if not axis.labelNames:
axis.labelNames["en"] = axis_name
axes[axis_name] = axis
log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()]))
# Check all master and instance locations are valid and fill in defaults
for obj in masters+instances:
obj_name = obj.name or obj.styleName or ''
loc = obj.location
for axis_name in loc.keys():
assert axis_name in axes, "Location axis '%s' unknown for '%s'." % (axis_name, obj_name)
for axis_name,axis in axes.items():
if axis_name not in loc:
loc[axis_name] = axis.default
else:
v = axis.map_backward(loc[axis_name])
assert axis.minimum <= v <= axis.maximum, "Location for axis '%s' (mapped to %s) out of range for '%s' [%s..%s]" % (axis_name, v, obj_name, axis.minimum, axis.maximum)
# Normalize master locations
internal_master_locs = [o.location for o in masters]
log.info("Internal master locations:\n%s", pformat(internal_master_locs))
# TODO This mapping should ideally be moved closer to logic in _add_fvar/avar
internal_axis_supports = {}
for axis in axes.values():
triple = (axis.minimum, axis.default, axis.maximum)
internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple]
log.info("Internal axis supports:\n%s", pformat(internal_axis_supports))
normalized_master_locs = [models.normalizeLocation(m, internal_axis_supports) for m in internal_master_locs]
log.info("Normalized master locations:\n%s", pformat(normalized_master_locs))
# Find base master
base_idx = None
for i,m in enumerate(normalized_master_locs):
if all(v == 0 for v in m.values()):
assert base_idx is None
base_idx = i
assert base_idx is not None, "Base master not found; no master at default location?"
log.info("Index of base master: %s", base_idx)
return _DesignSpaceData(
axes,
internal_axis_supports,
base_idx,
normalized_master_locs,
masters,
instances,
ds.rules,
)
示例15: test_normalise2
def test_normalise2():
# normalisation with minimum > 0
doc = DesignSpaceDocument()
# write some axes
a2 = AxisDescriptor()
a2.minimum = 100
a2.maximum = 1000
a2.default = 100
a2.name = "axisName_b"
doc.addAxis(a2)
assert doc.normalizeLocation(dict(axisName_b=0)) == {'axisName_b': 0.0}
assert doc.normalizeLocation(dict(axisName_b=1000)) == {'axisName_b': 1.0}
# clipping beyond max values:
assert doc.normalizeLocation(dict(axisName_b=1001)) == {'axisName_b': 1.0}
assert doc.normalizeLocation(dict(axisName_b=500)) == {'axisName_b': 0.4444444444444444}
assert doc.normalizeLocation(dict(axisName_b=-1000)) == {'axisName_b': 0.0}
assert doc.normalizeLocation(dict(axisName_b=-1001)) == {'axisName_b': 0.0}
# anisotropic coordinates normalise to isotropic
assert doc.normalizeLocation(dict(axisName_b=(1000,-1000))) == {'axisName_b': 1.0}
assert doc.normalizeLocation(dict(axisName_b=1001)) == {'axisName_b': 1.0}
doc.normalize()
r = []
for axis in doc.axes:
r.append((axis.name, axis.minimum, axis.default, axis.maximum))
r.sort()
assert r == [('axisName_b', 0.0, 0.0, 1.0)]