### Example: Set and Get Glyph Order Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Demonstrates how to set and assert the glyph order for a font object. ```python font = Font() font.glyphOrder = ["A", "B", "C"] assert font.glyphOrder == ["A", "B", "C"] ``` -------------------------------- ### Install ufoLib2 Extras Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/errors.md Command-line instructions for installing optional extras for ufoLib2, such as JSON or MessagePack support. ```bash # For JSON support pip install ufoLib2[json] # For MessagePack support pip install ufoLib2[msgpack] # For both pip install ufoLib2[json,msgpack] # For all converters pip install ufoLib2[converters] ``` -------------------------------- ### Install ufoLib2 with all serialization support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/serialization.md Install ufoLib2 with both `json` and `msgpack` extras for full serialization capabilities. Alternatively, use the `converters` extra which includes both. ```bash pip install ufoLib2[json,msgpack] ``` ```bash pip install ufoLib2[converters] ``` -------------------------------- ### Install ufolib2 with All Serialization Support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/README.md Installs the ufolib2 library with support for both JSON and MessagePack serialization. ```bash # All serialization pip install ufoLib2[json,msgpack] ``` -------------------------------- ### Install ufoLib2 with MessagePack support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/serialization.md Install ufoLib2 with the `msgpack` extra to enable MessagePack serialization. This installs `cattrs` and `msgpack` libraries. ```bash pip install ufoLib2[msgpack] ``` -------------------------------- ### MessagePack Serialization Example Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/configuration.md Export a UFO font to a compact MessagePack binary file and import it back. Requires `pip install ufoLib2[msgpack]`. ```python from ufo2library import Font # Export to MessagePack font = Font.open("MyFont.ufo") font.msgpack_dump("export.msgpack") # Import from MessagePack font2 = Font.msgpack_load("export.msgpack") ``` -------------------------------- ### Install ufolib2 with JSON Serialization Support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/README.md Installs the ufolib2 library with optional JSON serialization capabilities. ```bash # JSON serialization pip install ufoLib2[json] ``` -------------------------------- ### Install ufolib2 with MessagePack Serialization Support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/README.md Installs the ufolib2 library with optional MessagePack serialization capabilities. ```bash # MessagePack serialization pip install ufoLib2[msgpack] ``` -------------------------------- ### Get Glyph Bounds from GlyphSet Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Example demonstrating how to check for a glyph's existence in a GlyphSet and access its bounds. Requires importing GlyphSet. ```python from ufoLib2.typing import GlyphSet def get_bounds(glyphset: GlyphSet, name: str): if name in glyphset: glyph = glyphset[name] return glyph.bounds ``` -------------------------------- ### LayerSet Dict-like Interface Examples Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md Demonstrates common dictionary operations for accessing, setting, checking existence, deleting, iterating, and getting the count of layers within a LayerSet. ```python # Get a layer layer = layers["public.default"] ``` ```python # Set a layer (overwrites) layers["myLayer"] = Layer("myLayer") ``` ```python # Check if exists if "myLayer" in layers: pass ``` ```python # Delete a layer del layers["myLayer"] # Cannot delete default layer ``` ```python # Iterate layer names for name in layers: print(name) ``` ```python # Get count count = len(layers) ``` -------------------------------- ### Install ufoLib2 with Serialization Support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/api-index.md Install ufoLib2 with JSON, MessagePack, or both serialization formats. Use the appropriate pip command based on your needs. ```bash pip install ufoLib2[json] # JSON support pip install ufoLib2[msgpack] # MessagePack support pip install ufoLib2[json,msgpack] # Both ``` -------------------------------- ### Configuration Examples Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/configuration.md Illustrates various ways to use the `save()` method with different configuration options. ```APIDOC ## Configuration Examples ### Auto-detect Structure Saves the font to the same path and structure it was loaded from. ```python font = Font.open("MyFont.ufo") font.info.familyName = "Updated" font.save() # Preserves original structure ``` ### Package Structure (Recommended) Saves the font as a directory-based UFO, which is human-readable. ```python font = Font() font.save("MyFont.ufo", structure="package", overwrite=True) # Resulting structure: # MyFont.ufo/ # glyphs/ # lib.plist # fontinfo.plist # etc. ``` ### Zip Structure (Compact) Saves the font as a single zip file. ```python font = Font() font.save("MyFont.ufo", structure="zip", overwrite=True) # Result: # MyFont.ufo (single zip file) ``` ### Overwrite Handling Demonstrates how to handle existing files during saving. ```python # Error if path exists (default behavior) font = Font() font.save("MyFont.ufo") # Raises FileExistsError if file exists # Overwrite existing file font.save("MyFont.ufo", overwrite=True) ``` ### Validation Options Shows how to control validation before saving. ```python # Validate before saving (strict, default) font = Font() font.save("MyFont.ufo", validate=True) # Save without validation (faster) font.save("MyFont.ufo", validate=False) ``` ``` -------------------------------- ### Install ufoLib2 with JSON support Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/serialization.md Install ufoLib2 with the `json` extra to enable JSON serialization. This also installs `cattrs` and optionally `orjson` for faster encoding on CPython. ```bash pip install ufoLib2[json] ``` -------------------------------- ### Layer Dict-like Interface Examples Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md Demonstrates common dictionary-like operations for accessing, setting, checking existence, deleting, iterating over glyph names, and getting the count of glyphs within a layer. ```python # Get a glyph glyph = layer["A"] # Set a glyph (overwrites existing) layer["A"] = Glyph(name="A") # Check if exists if "A" in layer: pass # Delete a glyph del layer["A"] # Iterate glyph names for name in layer: print(name) # Get count count = len(layer) ``` -------------------------------- ### JSON Serialization Example Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/configuration.md Export a UFO font to a human-readable JSON file and import it back. Requires `pip install ufoLib2[json]`. ```python from ufo2library import Font # Export to JSON font = Font.open("MyFont.ufo") font.json_dump("export.json") # Import from JSON font2 = Font.json_load("export.json") ``` -------------------------------- ### Example Usage of KerningPair Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Demonstrates how to create a KerningPair instance. Ensure the ufoLib2.objects.kerning module is imported. ```python from ufoLib2.objects.kerning import KerningPair pair: KerningPair = ("A", "T") ``` -------------------------------- ### Guideline Class Constructor and Usage Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/kerning-guideline-features.md Demonstrates how to instantiate the Guideline class with various parameters and provides examples of its usage for different types of guidelines. ```APIDOC ## Guideline Class ### Constructor ```python from ufoLib2.objects import Guideline guideline = Guideline( x=100, y=None, angle=90, name="Cap Height", color="FF0000FF", identifier="com.example.guideline1" ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | x | float | None | No | None | X origin coordinate | | y | float | None | No | None | Y origin coordinate | | angle | float | None | No | None | Angle in degrees (0-360) | | name | str | None | No | None | Guideline name | | color | str | None | No | None | Color code (e.g., "FF0000FF") | | identifier | str | None | No | None | Globally unique identifier | ### Example Usage ```python from ufoLib2.objects import Guideline # Vertical guideline at x=100 guideline1 = Guideline(x=100, angle=90, name="Cap Height") # Horizontal guideline at y=0 guideline2 = Guideline(y=0, angle=0, name="Baseline") # Diagonal guideline guideline3 = Guideline(x=100, y=100, angle=45, name="Diagonal") ``` ### Serialization ```python # Assuming 'guideline' is an instance of Guideline guideline.json_dump("guideline.json") # To load a guideline from a JSON file loaded_guideline = Guideline.json_load("guideline.json") ``` ``` -------------------------------- ### Create Guideline Instances Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/kerning-guideline-features.md Shows examples of creating different types of guidelines: vertical, horizontal, and diagonal. Ensure to set appropriate parameters like x, y, and angle. ```python from ufoLib2.objects import Guideline # Vertical guideline at x=100 guideline1 = Guideline(x=100, angle=90, name="Cap Height") # Horizontal guideline at y=0 guideline2 = Guideline(y=0, angle=0, name="Baseline") # Diagonal guideline guideline3 = Guideline(x=100, y=100, angle=45, name="Diagonal") ``` -------------------------------- ### Example Usage of BoundingBox Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Shows how to instantiate and use the BoundingBox NamedTuple. Requires importing BoundingBox from ufoLib2.objects.misc. ```python from ufoLib2.objects.misc import BoundingBox bounds = BoundingBox(0, 0, 600, 700) print(bounds.xMin, bounds.yMin, bounds.xMax, bounds.yMax) ``` -------------------------------- ### Generic Method Signature Example Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Illustrates a generic method signature using the 'T' type variable, indicating that the 'get' method can return a type 'T', a 'Glyph', or None. ```python def get( self, name: str, default: T | None = None ) -> T | Glyph | None: ``` -------------------------------- ### Handle Missing Serialization Extras Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/serialization.md Catch `ExtrasNotInstalledError` if the necessary libraries for JSON or MessagePack serialization are not installed. Install them using `pip install ufoLib2[json]` or `pip install ufoLib2[msgpack]`. ```python from ufoLib2 import Font from ufoLib2.errors import ExtrasNotInstalledError font = Font() try: font.json_dump("font.json") except ExtrasNotInstalledError as e: print(f"Install with: pip install ufoLib2[json]") ``` -------------------------------- ### Transform Matrix Examples Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Demonstrates creating and applying various affine transformations using the Transform type, including identity, scaling, translation, and rotation. ```python from fontTools.misc.transform import Transform, Identity # Identity (no transformation) t = Identity # Scale 2x t = Transform(2, 0, 0, 2, 0, 0) # Translate t = Transform(1, 0, 0, 1, 100, 200) # Scale and translate t = Transform(2, 0, 0, 2, 100, 200) # Rotate (45 degrees) import math angle = math.radians(45) cos_a, sin_a = math.cos(angle), math.sin(angle) t = Transform(cos_a, sin_a, -sin_a, cos_a, 0, 0) ``` -------------------------------- ### Glyph Contour Access Examples Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/glyph-class.md Illustrates using a list-like interface to access and manipulate contours within a Glyph object. Includes getting a specific contour, iterating through all contours, and checking contour count and membership. ```python # Get a contour contour = glyph[0] # Iterate contours for contour in glyph: print(len(contour)) # Get count count = len(glyph) # Check membership if contour in glyph: pass ``` -------------------------------- ### Append Component Example Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/glyph-class.md Demonstrates appending components to a Glyph object. Shows how to add a simple base glyph component and another with a transformation matrix. ```python glyph = Glyph(name="Aacute") glyph.appendComponent({"baseGlyph": "A"}) glyph.appendComponent({"baseGlyph": "acutecomb", "transformation": (1, 0, 0, 1, 0, 700)}) ``` -------------------------------- ### Create GaspRangeRecord Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Example of creating a GaspRangeRecord with specified maximum PPEM and a list of GaspBehavior flags. ```python from ufoLib2.objects.info import GaspBehavior, GaspRangeRecord record = GaspRangeRecord( rangeMaxPPEM=7, rangeGaspBehavior=[GaspBehavior.GRIDFIT, GaspBehavior.DOGRAY] ) ``` -------------------------------- ### Handle ufoLib2 Errors Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/INDEX.md Illustrates basic error handling for ufoLib2 operations, specifically catching `ExtrasNotInstalledError` which occurs when attempting to use features like JSON serialization without the necessary dependencies installed. Provides installation instructions. ```python from ufoLib2 import Font from ufoLib2.errors import ExtrasNotInstalledError font = Font() try: font.json_dump("font.json") except ExtrasNotInstalledError: print("Install: pip install ufoLib2[json]") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Get Font Guidelines Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the font's global guidelines. ```python @property def guidelines() -> list[Guideline] ``` -------------------------------- ### Render Drawable Object Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Example of how to use the Drawable protocol to render an object's contents using a RecordingPen. Requires importing RecordingPen and Drawable. ```python from fontTools.pens.recordingPen import RecordingPen from ufoLib2.typing import Drawable def render(obj: Drawable): pen = RecordingPen() obj.draw(pen) return pen.value ``` -------------------------------- ### Catch ExtrasNotInstalledError Example Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/errors.md Demonstrates catching ExtrasNotInstalledError when attempting to use a feature that requires uninstalled optional extras, such as JSON serialization. ```python from ufoLib2 import Font from ufoLib2.errors import ExtrasNotInstalledError font = Font() try: font.json_dump("font.json") except ExtrasNotInstalledError as e: print(f"Error: {e}") print("Install with: pip install ufoLib2[json]") ``` -------------------------------- ### Initialize Lib with Data Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Create a new Lib instance and initialize it with a dictionary of key-value pairs. ```python from ufoLib2.objects.lib import Lib lib = Lib({ "public.glyphOrder": ["A", "B", "C"], "com.example.customKey": "custom value", "com.example.data": [1, 2, 3] }) ``` -------------------------------- ### Serializing Font Objects to JSON Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Illustrates how to serialize and deserialize Font objects using JSON. Requires the 'json' extra to be installed. Supports dumping to a file, loading from a file, dumping to a string, and loading from a string. ```python # JSON font.json_dump("font.json") font2 = Font.json_load("font.json") json_str = font.json_dumps() font3 = Font.json_loads(json_str) ``` -------------------------------- ### DataSet Class Methods for Data Manipulation Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Provides examples of static methods for interacting with the data directory of a UFO, including listing contents, reading, writing, and removing data using UFOReader and UFOWriter instances. ```python @staticmethod def list_contents(reader: UFOReader) -> list[str]: # Returns a list of POSIX filename strings in the data directory. pass ``` ```python @staticmethod def read_data(reader: UFOReader, filename: str) -> bytes: # Reads data from the data directory. pass ``` ```python @staticmethod def write_data(writer: UFOWriter, filename: str, data: bytes) -> None: # Writes data to the data directory. pass ``` ```python @staticmethod def remove_data(writer: UFOWriter, filename: str) -> None: # Removes data from the data directory. pass ``` -------------------------------- ### Instantiate Guideline Class Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/kerning-guideline-features.md Demonstrates how to create a Guideline object with various parameters including position, angle, name, color, and identifier. ```python from ufoLib2.objects import Guideline guideline = Guideline( x=100, y=None, angle=90, name="Cap Height", color="FF0000FF", identifier="com.example.guideline1" ) ``` -------------------------------- ### Create and Move a Component Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/contour-point-anchor-component.md Demonstrates how to create a Component instance and move it by updating its transformation. This is useful for positioning referenced glyphs. ```python from ufoLib2.objects import Component comp = Component("A") comp.move((100, 200)) ``` -------------------------------- ### Serialize UFO Font to JSON and MessagePack Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/INDEX.md Shows how to serialize a UFO font object to JSON and MessagePack files, and then load them back into new font objects. Requires the respective extras to be installed. ```python from ufoLib2 import Font font = Font.open("MyFont.ufo") # To JSON font.json_dump("export.json") font2 = Font.json_load("export.json") # To MessagePack font.msgpack_dump("export.msgpack") font3 = Font.msgpack_load("export.msgpack") ``` -------------------------------- ### Instantiate Info Class Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/info-class.md Create a new Info object. It can be initialized with no arguments or with specific metadata values. ```python info = Info() # or with values info = Info( familyName="MyFont", styleName="Regular", unitsPerEm=1000 ) ``` -------------------------------- ### Get Layer Count Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md To get the number of layers in the font, use the len() function on the LayerSet. ```python layerCount = len(font.layers) ``` -------------------------------- ### DataSet Dict-like Interface Operations Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Illustrates the common dictionary operations available on a DataSet object, including setting, getting, checking existence, deleting, iterating, and retrieving keys, values, and items. ```python # Set data dataset["filename.txt"] = b"content" # Get data data = dataset["filename.txt"] # Check existence if "filename.txt" in dataset: pass # Delete data del dataset["filename.txt"] # Iterate filenames for filename in dataset: print(filename) # Get count count = len(dataset) # Get keys filenames = list(dataset.keys()) # Get values all_data = list(dataset.values()) # Get items for filename, data in dataset.items(): pass ``` -------------------------------- ### Get Glyph Count in Layer Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md To get the number of glyphs in a layer, use the len() function. This is useful for understanding the size of the layer. ```python glyphCount = len(layer) ``` -------------------------------- ### Create, Set, and Save Font Info Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/info-class.md Demonstrates creating a new Font object, setting various basic and OpenType specific info properties, and saving the font to a UFO file. Also shows how to load the font and access its info properties. ```python from ufoLib2 import Font # Create a new font with basic info font = Font() font.info.familyName = "My Font" font.info.styleName = "Regular" font.info.unitsPerEm = 1000 font.info.ascender = 800 font.info.descender = -200 font.info.capHeight = 700 font.info.xHeight = 500 # Set OpenType metrics font.info.openTypeOS2WeightClass = 400 font.info.openTypeOS2WidthClass = 5 # Normal width font.info.openTypeHheaAscender = 900 font.info.openTypeHheaDescender = -300 font.info.openTypeOS2TypoAscender = 800 font.info.openTypeOS2TypoDescender = -200 # Save the font font.save("MyFont.ufo", overwrite=True) # Load and read font2 = Font.open("MyFont.ufo") print(font2.info.familyName) # "My Font" print(font2.info.unitsPerEm) # 1000 ``` -------------------------------- ### Get Glyph by Name with Default Fallback Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md Use `get` to retrieve a glyph by its name. If the glyph is not found, it returns the specified default value instead of raising an error. ```python def get( name: str, default: T | None = None ) -> T | Glyph | None: ... layer = Layer.default() glyph = layer.get("A", None) ``` -------------------------------- ### Get Glyph with Default Value Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md The get() method allows you to retrieve a Glyph object by name, returning a specified default value if the glyph is not found. This prevents KeyError exceptions. ```python layer.get(name: str, default: [T](#ufoLib2.typing.T) | None = None) ``` -------------------------------- ### Initialize Image Object Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Create an Image object with a filename, transformation, and color. The transformation is an affine matrix, and the color is a hex string. ```python image = Image( fileName="background.png", transformation=(1, 0, 0, 1, 0, 0), # Identity color="FF0000FF" ) ``` -------------------------------- ### name Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Get the name of the glyph. ```APIDOC ## property name: str | None ### Description The name of the glyph. ### Returns str | None ``` -------------------------------- ### Serialize and Deserialize Lib using JSON Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Demonstrates how to save a Lib object to a JSON file and load it back into a new Lib instance. ```python from ufoLib2.objects.lib import Lib # Assuming 'lib' is an existing Lib object # lib.json_dump("lib.json") # lib2 = Lib.json_load("lib.json") ``` -------------------------------- ### height Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Get the height of the glyph. ```APIDOC ## property height: float ### Description The height of the glyph. ### Returns float ``` -------------------------------- ### Lib Constructor Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Initializes a new Lib object with optional initial data. The data should be a dictionary with plist-encodable values. ```APIDOC ## Lib Constructor ### Description Initializes a new Lib object with optional initial data. The data should be a dictionary with plist-encodable values. ### Code Example ```python lib = Lib({ "public.glyphOrder": ["A", "B", "C"], "com.example.customKey": "custom value", "com.example.data": [1, 2, 3] }) ``` ``` -------------------------------- ### objectLib Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Get the lib for an object with an identifier. ```APIDOC ## objectLib(object: HasIdentifier) -> dict[str, Any] ### Description Return the lib for an object with an identifier, as stored in a glyph’s lib. If the object does not yet have an identifier, a new one is assigned to it. If the font lib does not yet contain the object’s lib, a new one is inserted and returned. ### Parameters #### Path Parameters * **object** (HasIdentifier) - Required - The object to get the lib for. ``` -------------------------------- ### Create New UFO Font from Scratch Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/INDEX.md Shows how to create a new UFO font, set basic metadata, add a glyph with a contour, and save it to a file. Requires ufoLib2 and its objects. ```python from ufoLib2 import Font from ufoLib2.objects import Contour, Point font = Font() font.info.familyName = "MyFont" glyph = font.newGlyph("A") contour = Contour() contour.append(Point(0, 0, "move")) glyph.contours.append(contour) font.save("MyFont.ufo", overwrite=True) ``` -------------------------------- ### Create and Save a Font Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/api-index.md Demonstrates how to create a new UFO font from scratch, add glyphs with contours, and save it to disk. Use this to programmatically generate UFO files. ```python from ufoLib2 import Font from ufoLib2.objects import Glyph, Contour, Point # Create font font = Font() font.info.familyName = "MyFont" font.info.unitsPerEm = 1000 font.info.ascender = 800 font.info.descender = -200 # Create glyph glyph = font.newGlyph("A") glyph.width = 600 contour = Contour() contour.points = [ Point(0, 0, "move"), Point(600, 0, "line"), Point(600, 700, "line"), Point(0, 700, "line"), ] glyph.contours.append(contour) # Save font.save("MyFont.ufo", overwrite=True) ``` -------------------------------- ### verticalOrigin Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Gets or sets the vertical origin of the glyph. ```APIDOC ## verticalOrigin: float | None ### Description The vertical origin of the glyph. ### Getter Returns the vertical origin or None. ### Setter Sets the vertical origin. If value is None, deletes the key from the lib if present. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### note Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Get or set a free-form text note about the glyph. ```APIDOC ## property note: str | None ### Description A free form text note about the glyph. ### Returns str | None ``` -------------------------------- ### Create and Move an Anchor Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/contour-point-anchor-component.md Demonstrates creating an Anchor object and then moving it by a specified offset. Use this to initialize and adjust anchor positions. ```python from ufoLib2.objects import Anchor anchor = Anchor(300, 700, name="top") anchor.move((10, 10)) assert anchor.x == 310 and anchor.y == 710 ``` -------------------------------- ### markColor Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Get or set the mark color assigned to the glyph. ```APIDOC ## property markColor: str | None ### Description The color assigned to the glyph. See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#publicmarkcolor. ### Getter Returns the mark color or None. ### Setter Sets the mark color. If value is None, deletes the key from the lib if present. ``` -------------------------------- ### Get Font Kerning Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the font's kerning dictionary. ```python @property def kerning() -> Kerning ``` -------------------------------- ### Image Constructor Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Initializes an Image object with optional filename, transformation, and color. ```APIDOC ## Image Constructor ### Description Initializes an Image object with optional filename, transformation, and color. ### Parameters - **fileName** (str | None) - Optional - Filename of the image in the images directory - **transformation** (Transform) - Optional - Affine transformation applied to the image - **color** (str | None) - Optional - Color code overlay ### Request Example ```python from ufoLib2.objects import Image image = Image( fileName="background.png", transformation=(1, 0, 0, 1, 0, 0), # Identity color="FF0000FF" ) ``` ``` -------------------------------- ### unicode Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Gets or sets the first assigned Unicode code point for the glyph. ```APIDOC ## unicode: int | None ### Description The first assigned Unicode code point or None. ### Getter Returns the first assigned Unicode code point or None. ### Setter Sets the value to be the first of the assigned Unicode code points. Will remove a duplicate if exists. Will clear the list of Unicode points if value is None. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### Get Font Lib Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the font's persistent lib dictionary, which is saved to disk. ```python @property def lib() -> Lib ``` -------------------------------- ### Using DataSet as a Dictionary Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Demonstrates basic dictionary operations like adding, accessing, deleting, and listing items within a DataSet. Always use forward slashes for directory separators. ```python >>> from ufoLib2 import Font >>> font = Font() >>> font.data["test.txt"] = b"123" >>> font.data["directory/my_binary_blob.bin"] = b"456" >>> font.data["test.txt"] b'123' >>> del font.data["test.txt"] >>> list(font.data.items()) [('directory/my_binary_blob.bin', b'456')] ``` -------------------------------- ### Serialize and Deserialize Lib using MessagePack Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Demonstrates how to save a Lib object to a MessagePack file and load it back into a new Lib instance. ```python from ufoLib2.objects.lib import Lib # Assuming 'lib' is an existing Lib object # lib.msgpack_dump("lib.msgpack") # lib3 = Lib.msgpack_load("lib.msgpack") ``` -------------------------------- ### Info Class Constructor Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/info-class.md Initializes an Info object, which represents font-wide metadata. Many attributes are optional and can be set during initialization or later. ```APIDOC ## Info Class Constructor ### Description Initializes an Info object, which represents font-wide metadata according to the UFO3 specification. Attributes can be set during initialization or modified later. ### Method Constructor ### Parameters All parameters are optional. - **familyName** (str | None) - Optional - The family name of the font (e.g., "Helvetica"). - **styleName** (str | None) - Optional - The style name of the font (e.g., "Bold", "Italic"). - **unitsPerEm** (int | None) - Optional - The units per em value for the font (e.g., 1000, 2048). - **descender** (int | float | None) - Optional - The descender y-coordinate. - **capHeight** (int | float | None) - Optional - The capital letter height. - **ascender** (int | float | None) - Optional - The ascender y-coordinate. - **xHeight** (int | float | None) - Optional - The x-height (x glyph height). - **italicAngle** (int | float | None) - Optional - The italic angle in degrees (negative values indicate a right lean). - **styleMapFamilyName** (str | None) - Optional - The name used for style mapping, often used to separate bold/italic. - **styleMapStyleName** ("regular" | "bold" | "italic" | "bold italic" | None) - Optional - The style map style name. - **uniqueFontIdentifier** (str | None) - Optional - A unique identifier for the font. - **fullName** (str | None) - Optional - The full name of the font. - **postscriptFontName** (str | None) - Optional - The PostScript font name. - **postscriptSlantAngle** (int | float | None) - Optional - The PostScript slant angle. ### Request Example ```python from ufoLib2.objects.info import Info # Initialize with default values info = Info() # Initialize with specific values info = Info( familyName="MyFont", styleName="Regular", unitsPerEm=1000, ascender=700, descender=-300 ) ``` ### Response #### Success Response (Instance of Info) An Info object with the specified properties set. If no arguments are provided, default values (usually None) are used. #### Response Example ```json { "familyName": "MyFont", "styleName": "Regular", "unitsPerEm": 1000, "ascender": 700, "descender": -300, "capHeight": null, "xHeight": null, "italicAngle": null, "styleMapFamilyName": null, "styleMapStyleName": null, "uniqueFontIdentifier": null, "fullName": null, "postscriptFontName": null, "postscriptSlantAngle": null } ``` ``` -------------------------------- ### Handle Base ufoLib2 Error Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/errors.md Example of how to catch the base ufoLib2 Error class during an operation. ```python from ufoLib2.errors import Error try: # some ufoLib2 operation pass except Error as e: print(f"ufoLib2 error: {e}") ``` -------------------------------- ### Get Specific Layer Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md To retrieve a specific layer from the LayerSet, access it by its name using dictionary-like syntax. ```python font.layers["myLayerName"] ``` -------------------------------- ### Initialize Features Class Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/kerning-guideline-features.md Instantiate the Features class with FEA text content. The 'text' parameter accepts a string containing the feature code. ```python features = Features(""" feature kern { pos A T -100; } kern; """) ``` -------------------------------- ### Get UFO Reader Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Returns the underlying UFOReader if the font is lazily loaded, or None if it was eagerly loaded. ```python @property def reader() -> UFOReader | None ``` -------------------------------- ### Get Temporary Font Lib Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the font's temporary lib dictionary, which is not saved to disk. ```python @property def tempLib() -> Lib ``` -------------------------------- ### Overwrite Handling for Saving Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/configuration.md Demonstrates how to handle existing files during saving. By default, saving to an existing path raises a FileExistsError. Setting overwrite=True allows overwriting. ```python # Error if path exists font = Font() font.save("MyFont.ufo") # FileExistsError if file exists # Overwrite existing font.save("MyFont.ufo", overwrite=True) ``` -------------------------------- ### get Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves a glyph from the default layer by its name, with an optional default value to return if the glyph is not found. ```APIDOC ## get ### Description Gets a glyph from the default layer by name, with a default fallback. ### Method ```python def get( name: str, default: T | None = None ) -> T | Glyph | None ``` ### Parameters #### Path Parameters - **name** (str) - Required - Glyph name - **default** (T | None) - Optional - Value to return if glyph not found ### Returns Glyph or default value ### Request Example ```python font = Font() font.newGlyph("A") glyph = font.get("A") missing = font.get("Z", None) ``` ``` -------------------------------- ### open Source: https://github.com/fonttools/ufolib2/blob/main/docs/source/reference.md Opens a UFO font from a given path, with options for lazy loading and validation. ```APIDOC ## *classmethod* open(path: str | bytes | PathLike[str] | PathLike[bytes], lazy: bool = True, validate: bool = True) -> [Font](#ufoLib2.objects.Font) ### Description Instantiates a new Font object from a path to a UFO. ### Parameters #### Parameters - **path** (str | bytes | PathLike[str] | PathLike[bytes]) - The path to the UFO to load. - **lazy** (bool, optional) - If True, load glyphs, data files and images as they are accessed. If False, load everything up front. Defaults to True. - **validate** (bool, optional) - If True, enable UFO data model validation during loading. If False, load whatever is deserializable. Defaults to True. ``` -------------------------------- ### Layer Instance Methods Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md Provides documentation for instance methods of the Layer object, allowing users to manipulate glyphs and layer properties. ```APIDOC ## newGlyph(name: str) -> Glyph ### Description Creates and returns a new Glyph in this layer. ### Parameters #### Path Parameters - **name** (str) - Required - Glyph name ### Returns Glyph ### Raises - **KeyError**: Glyph with this name already exists ### Example ```python layer = Layer.default() glyph = layer.newGlyph("A") ``` ``` ```APIDOC ## addGlyph(glyph: Glyph) -> None ### Description Adds a Glyph to this layer without overwriting existing glyphs. ### Parameters #### Path Parameters - **glyph** (Glyph) - Required - Glyph object ### Raises - **KeyError**: Glyph with this name already exists ### Example ```python layer = Layer.default() glyph = Glyph(name="B") layer.addGlyph(glyph) ``` ``` ```APIDOC ## renameGlyph(name: str, newName: str, overwrite: bool = False) -> None ### Description Renames a glyph in this layer. ### Parameters #### Path Parameters - **name** (str) - Required - Current glyph name - **newName** (str) - Required - New glyph name - **overwrite** (bool) - Optional - If False, error if newName exists. Default: False ### Example ```python layer = Layer.default() layer.newGlyph("oldName") layer.renameGlyph("oldName", "newName") ``` ``` ```APIDOC ## get(name: str, default: T | None = None) -> T | Glyph | None ### Description Gets a glyph by name with a default fallback. ### Parameters #### Path Parameters - **name** (str) - Required - Glyph name - **default** (T | None) - Optional - Value to return if not found. Default: None ### Returns Glyph or default ### Example ```python layer = Layer.default() glyph = layer.get("A", None) ``` ``` ```APIDOC ## keys() -> KeysView[str] ### Description Returns the names of all glyphs in this layer. ### Returns KeysView[str] ### Example ```python layer = Layer.default() for name in layer.keys(): print(name) ``` ``` ```APIDOC ## values() -> ValuesView[Glyph] ### Description Returns an iterator over all glyphs in this layer. ### Returns ValuesView[Glyph] ``` ```APIDOC ## items() -> ItemsView[str, Glyph] ### Description Returns (name, glyph) pairs for all glyphs in this layer. ### Returns ItemsView[str, Glyph] ``` ```APIDOC ## unlazify() -> None ### Description Forces all lazily-loaded glyphs into memory. ### Example ```python layer = Layer.read(reader, "public.default", lazy=True) layer.unlazify() ``` ``` ```APIDOC ## write(writer: UFOWriter, saveAs: bool = False) -> None ### Description Writes this layer to a UFOWriter. ### Parameters #### Path Parameters - **writer** (UFOWriter) - Required - UFOWriter instance - **saveAs** (bool) - Optional - If True, clean resources before writing. Default: False ``` -------------------------------- ### Get All Glyphs in Layer Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md The `values` method returns an iterator over all Glyph objects stored within the layer. ```python def values() -> ValuesView[Glyph]: ... ``` -------------------------------- ### Work with UFO Font Layers Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/INDEX.md Illustrates accessing existing layers, creating new layers with specified colors, and renaming layers within a UFO font. Assumes a UFO font is already open. ```python from ufoLib2 import Font font = Font.open("MyFont.ufo") # Access layers layer = font.layers["public.default"] # Create new layer color_layer = font.newLayer("Color", color="FF0000FF") # Rename font.renameLayer("Color", "ColorOutlines") ``` -------------------------------- ### Get Name-Glyph Pairs Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md The `items` method returns an iterator yielding (name, glyph) pairs for all glyphs in the layer. ```python def items() -> ItemsView[str, Glyph]: ... ``` -------------------------------- ### Get Font Path Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the file path of the UFO font. Returns None if the path was not set during opening or saving. ```python @property def path() -> PathLike | None ``` -------------------------------- ### Dict-like Interface Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md The Lib class provides a familiar dictionary-like interface for getting, setting, checking, and deleting key-value pairs. ```APIDOC ## Dict-like Interface ### Description The Lib class provides a familiar dictionary-like interface for getting, setting, checking, and deleting key-value pairs. ### Code Example ```python lib = Lib() # Set a value lib["com.example.key"] = "value" lib["public.glyphOrder"] = ["A", "B", "C"] # Get a value value = lib["com.example.key"] # Check if key exists if "com.example.key" in lib: pass # Delete a key del lib["com.example.key"] # Iterate keys for key in lib: print(key) # Get all keys keys = list(lib.keys()) # Get all values values = list(lib.values()) # Get items for key, value in lib.items(): pass # Get with default value = lib.get("missing.key", "default") # Count keys count = len(lib) # Clear all lib.clear() ``` ``` -------------------------------- ### Set OpenType OS/2 Width Class Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/types.md Example of setting the openTypeOS2WidthClass attribute using the WidthClass enum or its integer value. ```python from ufoLib2.objects.info import WidthClass font.info.openTypeOS2WidthClass = WidthClass.CONDENSED # or font.info.openTypeOS2WidthClass = 3 ``` -------------------------------- ### Store and Retrieve Binary Data with DataSet Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md Demonstrates how to store, retrieve, iterate, delete, and check for the existence of binary data within a Font object's DataSet. Always use forward slashes for paths. ```python from ufoLib2 import Font font = Font() # Store binary data font.data["test.txt"] = b"Hello" font.data["directory/binary.bin"] = b"\x00\x01\x02" # Retrieve data data = font.data["test.txt"] # b"Hello" # Iterate for filename, data in font.data.items(): print(f"{filename}: {len(data)} bytes") # Delete del font.data["test.txt"] # Check if exists if "directory/binary.bin" in font.data: pass # Get count count = len(font.data) ``` ```python # Correct - forward slashes font.data["path/to/file.bin"] = b"data" # Wrong - backslashes (Windows-style) # font.data["path\to\file.bin"] = b"data" ``` -------------------------------- ### Configure Font Info Metrics Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/configuration.md Set essential font metrics like unitsPerEm, ascender, descender, capHeight, and xHeight. Also configure naming and OpenType specific properties. ```python from ufoLib2 import Font font = Font() # Essential metrics font.info.unitsPerEm = 1000 font.info.ascender = 800 font.info.descender = -200 font.info.capHeight = 700 font.info.xHeight = 500 # Naming font.info.familyName = "MyFont" font.info.styleName = "Regular" # OpenType metrics font.info.openTypeOS2WeightClass = 400 font.info.openTypeOS2WidthClass = 5 # Licensing font.info.copyright = "© 2024" font.info.trademark = "MyFont™" font.info.openTypeNameDesigner = "Designer Name" ``` -------------------------------- ### Get Glyph by Name with Default Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves a glyph from the default layer by its name. A default value can be provided to return if the glyph is not found. ```python font = Font() font.newGlyph("A") glyph = font.get("A") missing = font.get("Z", None) ``` -------------------------------- ### Set Font Guidelines Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Sets the font's global guidelines. ```python @guidelines.setter def guidelines(value: Iterable[Guideline | Mapping[str, Any]]) -> None ``` -------------------------------- ### Open UFO from Path Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Loads a UFO from the filesystem. Supports lazy loading and validation options. ```python from ufoLib2 import Font # Load a UFO with lazy loading (default) font = Font.open("MyFont.ufo") # Load a UFO with eager loading font = Font.open("MyFont.ufo", lazy=False) # Load without validation font = Font.open("MyFont.ufo", validate=False) ``` -------------------------------- ### Define ExtrasNotInstalledError Class Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/errors.md Custom exception raised when optional extras required for a feature are not installed. It takes the name of the missing extras as a parameter. ```python class ExtrasNotInstalledError(Error): """The extras required for this feature are not installed.""" def __init__(self, extras: str) -> None: super().__init__(f"Extras not installed: ufoLib2[{extras}]") ``` -------------------------------- ### Get Font Glyph Order Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/font-class.md Retrieves the font's glyph order from lib. Returns an empty list if the glyph order is not set. ```python @property def glyphOrder() -> list[str] ``` -------------------------------- ### Access and Set Layer Color Property Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/layer-and-layerset.md The `color` property allows getting and setting the layer's color code, which can be a string or None. ```python @property def color() -> str | None: ... @color.setter def color(value: str | None) -> None: ... ``` -------------------------------- ### Initialize Kerning Object Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/kerning-guideline-features.md Create a Kerning object by passing a dictionary of kerning pairs and their values to the constructor. ```python from ufoLib2.objects import Kerning kerning = Kerning({ ("A", "T"): -100, ("A", "V"): -150, ("group1", "group2"): -50 }) ``` -------------------------------- ### Get Component Bounds Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/contour-point-anchor-component.md Calculates the bounding box of a component by considering the base glyph's contours. This requires the layer containing the base glyph. ```python from ufoLib2 import Font font = Font() font.newGlyph("A").width = 600 comp = font.newGlyph("Aacute").components[0] = Component("A") bounds = comp.getBounds(font) ``` -------------------------------- ### Create and Save UFO Font with Data Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/data-image-lib.md This snippet demonstrates creating a new UFO font object, populating its lib, tempLib, data, and image sections, and then saving it. Ensure necessary files like 'backup.zip' and 'outline.png' exist for binary data and image storage. ```python from ufoLib2 import Font font = Font() # Use lib for metadata font.lib["com.example.designer"] = "John Doe" font.lib["public.glyphOrder"] = ["A", "B", "C"] # Use tempLib during processing font.tempLib["statistics"] = {"glyphCount": len(font)} # Store binary data font.data["custom_data.bin"] = b"\x00\x01\x02" font.data["backup/archive.zip"] = open("backup.zip", "rb").read() # Store background images with open("outline.png", "rb") as f: font.images["outline.png"] = f.read() # Set glyph image reference glyph = font.newGlyph("A") glyph.image.fileName = "outline.png" glyph.image.transformation = (1, 0, 0, 1, 0, 0) # Save (only lib and data/images, not tempLib) font.save("MyFont.ufo", overwrite=True) ``` -------------------------------- ### Point Move Method Source: https://github.com/fonttools/ufolib2/blob/main/_autodocs/contour-point-anchor-component.md Demonstrates how to move a point by a specified delta. Ensures the point's coordinates are updated correctly. ```python from ufoLib2.objects import Point point = Point(100, 200) point.move((50, 50)) assert point.x == 150 and point.y == 250 ```