| 1 |
from dataclasses import dataclass, fields, field |
| 2 |
from typing import Union |
| 3 |
import orjson |
| 4 |
from collections import namedtuple |
| 5 |
import datetime |
| 6 |
|
| 7 |
|
| 8 |
class IncompatibleMastersError(ValueError): |
| 9 |
pass |
| 10 |
|
| 11 |
|
| 12 |
Color = namedtuple("Color", "r,g,b,a", defaults=[0, 0, 0, 0]) |
| 13 |
Position = namedtuple("Position", "x,y,angle", defaults=[0, 0, 0]) |
| 14 |
Number = Union[int, float] |
| 15 |
|
| 16 |
|
| 17 |
class I18NDictionary(dict): |
| 18 |
@classmethod |
| 19 |
def with_default(cls, s): |
| 20 |
inst = cls() |
| 21 |
inst.set_default(s) |
| 22 |
return inst |
| 23 |
|
| 24 |
def copy_in(self, other): |
| 25 |
if isinstance(other, dict): |
| 26 |
for k, v in other.items(): |
| 27 |
self[k] = v |
| 28 |
else: |
| 29 |
self.set_default(other) |
| 30 |
|
| 31 |
def default_or_dict(self): |
| 32 |
if len(self.values()) > 1: |
| 33 |
return self |
| 34 |
else: |
| 35 |
return self.get_default() |
| 36 |
|
| 37 |
def get_default(self): |
| 38 |
if "dflt" in self: |
| 39 |
return self["dflt"] |
| 40 |
elif len(list(self.values())): |
| 41 |
return list(self.values())[0] |
| 42 |
|
| 43 |
def set_default(self, value): |
| 44 |
if value: |
| 45 |
self["dflt"] = value |
| 46 |
|
| 47 |
def write(self, stream, indent): |
| 48 |
if len(self.keys()) > 1: |
| 49 |
stream.write(orjson.dumps(self)) |
| 50 |
else: |
| 51 |
stream.write('"{0}"'.format(self.get_default()).encode()) |
| 52 |
|
| 53 |
@property |
| 54 |
def as_fonttools_dict(self): |
| 55 |
rv = dict(self) |
| 56 |
if "dflt" in rv: |
| 57 |
if "en" not in rv: |
| 58 |
rv["en"] = rv["dflt"] |
| 59 |
del rv["dflt"] |
| 60 |
return rv |
| 61 |
|
| 62 |
|
| 63 |
@dataclass |
| 64 |
class BaseObject: |
| 65 |
# OK, what's going on here? And why do we split _FoobarFields from Foobar? |
| 66 |
# We want to achieve the following: |
| 67 |
# * A ``_formatspecific`` field on *every* derived object... |
| 68 |
# * ...which does not need to be added to the constructor arguments |
| 69 |
# * ...but which (for convenience when instantiating from JSON) has an |
| 70 |
# alias of ``_`` which *can* be added to the constructor arguments |
| 71 |
|
| 72 |
# dataclasses load up their fields by walking the inheritance tree, but |
| 73 |
# (just like Python function declarations) dataclasses don't support putting |
| 74 |
# defaultable fields after non-defaultable fields. |
| 75 |
|
| 76 |
# Because we want ``_formatspecific`` (and particularly ``_``) to be optional |
| 77 |
# on __init__ it needs to be defaultable. So it needs to appear after the |
| 78 |
# other fields in the inheritance hierarchy. So we inherit from a _...Fields |
| 79 |
# class first and then BaseObject second. Ugly but it works. |
| 80 |
|
| 81 |
# dataclasses also don't support field aliases. The ``_`` field is only |
| 82 |
# really used for initialization, so in ``__post_init__`` we move its |
| 83 |
# contents into the `_formatspecific` field where it really lives. |
| 84 |
|
| 85 |
_formatspecific: dict = field( |
| 86 |
default_factory=dict, |
| 87 |
repr=False, |
| 88 |
metadata={ |
| 89 |
"skip_serialize": True, |
| 90 |
"description": """ |
| 91 |
Each object in Babelfont has an optional attached dictionary to allow the storage |
| 92 |
of format-specific information. Font creation software may store any additional |
| 93 |
information that they wish to have preserved on import and export under a |
| 94 |
namespaced (reverse-domain) key in this dictionary. For example, information |
| 95 |
specific to the Glyphs software should be stored under the key `com.glyphsapp`. |
| 96 |
The value stored under this key may be any data serializable in JSON; typically |
| 97 |
it will be a `dict`. |
| 98 |
|
| 99 |
Note that there is an important distinction between the Python object format |
| 100 |
of this field and the Babelfont-JSON representation. When stored to JSON, this key |
| 101 |
is exported not as `_formatspecific` but as a simple underscore (`_`). |
| 102 |
""", |
| 103 |
}, |
| 104 |
) |
| 105 |
_: dict = field(default=None, repr=False, metadata={"skip_serialize": True}) |
| 106 |
|
| 107 |
def __post_init__(self): |
| 108 |
if self._: |
| 109 |
self._formatspecific = self._ |
| 110 |
|
| 111 |
_write_one_line = False |
| 112 |
_separate_items = {} |
| 113 |
|
| 114 |
def _should_separate_when_serializing(self, key): |
| 115 |
if ( |
| 116 |
key in self.__dataclass_fields__ |
| 117 |
and "separate_items" in self.__dataclass_fields__[key].metadata |
| 118 |
): |
| 119 |
return True |
| 120 |
return False |
| 121 |
|
| 122 |
def _write_value(self, stream, k, v, indent=0): |
| 123 |
if hasattr(v, "write"): |
| 124 |
v.write(stream, indent + 1) |
| 125 |
elif isinstance(v, tuple): |
| 126 |
stream.write(b"[") |
| 127 |
for ix, entry in enumerate(v): |
| 128 |
self._write_value(stream, k, entry, indent + 1) |
| 129 |
if ix < len(v) - 1: |
| 130 |
stream.write(b", ") |
| 131 |
stream.write(b"]") |
| 132 |
elif isinstance(v, dict): |
| 133 |
stream.write(b"{") |
| 134 |
for ix, (k1, v1) in enumerate(v.items()): |
| 135 |
if self._should_separate_when_serializing(k): |
| 136 |
stream.write(b"\n") |
| 137 |
stream.write(b" " * (indent + 2)) |
| 138 |
if not isinstance(k1, str): |
| 139 |
# XXX kerning keys are tuples |
| 140 |
self._write_value(stream, k, "//".join(k1), indent + 1) |
| 141 |
else: |
| 142 |
self._write_value(stream, k, k1, indent + 1) |
| 143 |
stream.write(b": ") |
| 144 |
self._write_value(stream, k, v1, indent + 1) |
| 145 |
if ix < len(v.items()) - 1: |
| 146 |
stream.write(b", ") |
| 147 |
stream.write(b"}") |
| 148 |
elif isinstance(v, list): |
| 149 |
stream.write(b"[") |
| 150 |
for ix, item in enumerate(v): |
| 151 |
if self._should_separate_when_serializing(k): |
| 152 |
stream.write(b"\n") |
| 153 |
stream.write(b" " * (indent + 2)) |
| 154 |
self._write_value(stream, k, item, indent + 1) |
| 155 |
if ix < len(v) - 1: |
| 156 |
stream.write(b", ") |
| 157 |
if self._should_separate_when_serializing(k): |
| 158 |
stream.write(b"\n") |
| 159 |
stream.write(b" " * (indent + 1)) |
| 160 |
stream.write(b"]") |
| 161 |
elif isinstance(v, datetime.datetime): |
| 162 |
stream.write('"{0}"'.format(v.__str__()).encode()) |
| 163 |
else: |
| 164 |
stream.write(orjson.dumps(v)) |
| 165 |
|
| 166 |
def write(self, stream, indent=0): |
| 167 |
if not self._write_one_line: |
| 168 |
stream.write(b" " * indent) |
| 169 |
stream.write(b"{") |
| 170 |
towrite = [] |
| 171 |
for f in fields(self): |
| 172 |
k = f.name |
| 173 |
if "skip_serialize" in f.metadata or "python_only" in f.metadata: |
| 174 |
continue |
| 175 |
v = getattr(self, k) |
| 176 |
default = f.default |
| 177 |
if (not v and "serialize_if_false" not in f.metadata) or ( |
| 178 |
default and v == default |
| 179 |
): |
| 180 |
continue |
| 181 |
towrite.append((k, v)) |
| 182 |
|
| 183 |
for ix, (k, v) in enumerate(towrite): |
| 184 |
if not self._write_one_line: |
| 185 |
stream.write(b"\n") |
| 186 |
stream.write(b" " * (indent + 1)) |
| 187 |
|
| 188 |
stream.write('"{0}": '.format(k).encode()) |
| 189 |
self._write_value(stream, k, v, indent) |
| 190 |
if ix != len(towrite) - 1: |
| 191 |
stream.write(b", ") |
| 192 |
|
| 193 |
if hasattr(self, "_formatspecific") and self._formatspecific: |
| 194 |
stream.write(b",") |
| 195 |
if not self._write_one_line: |
| 196 |
stream.write(b"\n") |
| 197 |
stream.write(b" " * (indent + 1)) |
| 198 |
stream.write(b'"_":') |
| 199 |
if self._write_one_line: |
| 200 |
stream.write(orjson.dumps(self._formatspecific)) |
| 201 |
else: |
| 202 |
stream.write(b"\n") |
| 203 |
stream.write( |
| 204 |
orjson.dumps(self._formatspecific, option=orjson.OPT_INDENT_2) |
| 205 |
) |
| 206 |
|
| 207 |
if not self._write_one_line: |
| 208 |
stream.write(b"\n") |
| 209 |
stream.write(b"}") |
| 210 |
if not self._write_one_line: |
| 211 |
stream.write(b"\n") |