Debian Codegraph @

doc/sphinx/techref/pyextend.rst

raw
1 Extending FontForge With Python
2 ===============================
3
4 FontForge includes an extensive :doc:`Python API </scripting/python>` which is
5 most often used in scripts to alter and generate font files. However, this API
6 also provides ways of extending the functionality of the FontForge program,
7 including the user interface. Most of these are documented in the :ref:`User
8 Interface Module Functions <fontforge.ui_functions>` section of the Python
9 documentation.
10
11 Modifying Points and Contours, References, and Anchor Points
12 ------------------------------------------------------------
13
14 Given that points and contours are basis of vector font data many extensions
15 will want to modify them. There is one misleading aspect of the "layer" API
16 that must be clarified in order to do so. It is also important to be aware
17 of layers and how they relate to the FontForge user interface.
18
19 The Basics
20 ^^^^^^^^^^
21
22 A ``point`` is (typically) an element of a ``contour`` and a ``contour`` is
23 (typically) an element of a ``layer``. Confusingly, however, there are really
24 two meanings of the term "layer" in the FontForge Python API. One is the
25 ``fontforge.layer`` object, which is the object that can contain
26 ``fontforge.contour`` objects. The other is a layer *internal* to a font
27 object.
28
29 The confusion arises when a developer attempts to modify a point in this way: ::
30
31 f = fontforge.open('foo.otf')
32 g = f['a']
33 l = g.foreground
34 for c in l:
35 for p in c:
36 p.x += 15
37 f.generate('foo_new.otf')
38
39 After this script executes the points of the glyph "a" in ``foo_new.otf`` will
40 be the same as those in ``foo.otf``. And this is true even though the points in
41 the ``fontforge.layer`` object ``l`` have been changed. This is because ``l``
42 is not a *reference* to ``g.foreground`` (which represents the internal state
43 of the layer) but a *copy* of it. Any changes to the layer must therefore be
44 "copied back" to have an effect on the font. This can be done with an
45 assignment but we now recommend using the ``glyph.setLayer()`` method instead,
46 as this gives you more control over how point types are preserved or converted
47 as they are copied back.::
48
49 f = fontforge.open('foo.otf')
50 g = f['a']
51 l = g.foreground
52 for c in l:
53 for p in c:
54 p.x += 15
55 g.setLayer(l, 'Fore')
56 f.generate('foo_new.otf')
57
58 Layer Awareness and Undo Preservation
59 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
60
61 The author of a "top-down" script for modifying a font will typically know what
62 layer to modify—most often ``glyph.foreground`` (which is also identified as
63 "0" or "Fore"). A script that extends the FontForge UI with a new menu option
64 should not make such assumptions. At a given time the user may be editing the
65 foreground or background layer or even one of a few layers in a multi-layer
66 font. Such a function should therefore typically not reference specific layers
67 at all and use ``glyph.activeLayer`` instead, as in: ::
68
69 def shiftBy15(u, glyph):
70 l = glyph.layers[glyph.activeLayer]
71 for c in l:
72 for p in c:
73 p.x += 15
74 glyph.preserveLayerAsUndo(glyph.activeLayer)
75 g.setLayer(l, glyph.activeLayer)
76
77 This function also demonstrates an appropriate use of the
78 ``preserveLayerAsUndo()`` method. Setting an "internal" layer (either through
79 assignment for with the ``glyph.setLayer()`` method) does not automatically add
80 the previous layer to the Undo/Redo state. By calling
81 ``glyph.preserveLayerAsUndo()`` you give the user the option of reversing your
82 change with "Edit -> Undo".
83
84 References
85 ^^^^^^^^^^
86
87 The reference API is similar to the layer API, with the same caveats. You can
88 get the list of references for the current UI layer with ``rl =
89 g.layerrefs[g.activeLayer]`` (where ``g`` is a ``fontforge.glyph`` object). To
90 effect changes in the references you need to assign back to
91 ``g.layerrefs[g.activeLayer]``. Each reference is represented by a tuple of
92 glyph name, transformation matrix tuple (that is, a sub-tuple of six floating
93 point numbers representing the transformation) and a boolean ``selected`` status.
94 This script accordingly shifts the references in the current layer by 15 points: ::
95
96 def shiftRefsBy15(u, glyph):
97 rl = glyph.layerrefs[glyph.activeLayer]
98 nl = []
99 tr = psMat.translate(15,0)
100 for r in rl:
101 nl.append((r[0], psMat.compose(r[1], tr), r[2]))
102 glyph.preserveLayerAsUndo(glyph.activeLayer)
103 glyph.layerrefs[glyph.activeLayer] = nl
104
105 (One could also have used a transformation matrix to move the points in the earlier
106 fragments by passing it to ``p.transform()``.)
107
108 As noted in the API documentation, when assigning to the reference list the
109 transformation matrix and selection status tuple elements are optional (with
110 respective defaults of the identity matrix and ``False``).
111
112 Anchor Points
113 ^^^^^^^^^^^^^
114
115 In contrast with points and references, all anchor points are considered part
116 of the foreground layer. They can be accessed and edited through the
117 ``glyph.anchorPointsWithSel`` property. When editing the list care must be
118 taken to construct the tuples so that the name, type, position, selection and
119 (when relevant) ligature information are preserved or changed as desired.
120
121 .. _fontforge.plugin_menu:
122
123 Adding a Menu Item
124 ------------------
125
126 The functions ``shiftBy15()`` and ``shiftRefsBy15()`` above were written to
127 be added as menu items using :py:meth:`fontforge.registerMenuItem`. This is
128 the most common form of FontForge UI extension and we recommend familiarizing
129 (or re-familiarizing) yourself with the documentation as the API has recently
130 been enhanced.
131
132 Selection State
133 ^^^^^^^^^^^^^^^
134
135 In the case of many menu items, probably most of them, the user should have
136 some "input" into how one applies in a given situation. Sometimes this is a
137 reason to raise a dialog asking the user for input, but in the majority of
138 cases a menu callback will "interact" with a user by way of *selection state*.
139
140 Each point, both on-curve and control, has a boolean selection state. The
141 selection state of on-curve points is generally more important or "primary".
142 The "Transform ..." dialog, for example, transforms selected on-curve points
143 (and references) and their associated off-curve points regardless of the
144 latter's selection status. (This is true unless no points are selected, in
145 which case all points are transformed.) Other contour-level facilities, such as
146 "Correct Direction", consider a contour to be selected if at least one of its
147 on-curve points is selected, and changes those contours accordingly.
148
149 Still, in some cases you may want to attend to the selection state of
150 control points.
151
152 Each reference and anchor point also has a selection state. The Python
153 reference API has recently been enhanced to make the state available.
154
155 As an example, consider the ``shiftRefsBy15`` function above. We could
156 enhance it to shift only *selected* references unless there are none,
157 in all references are shifted: ::
158
159 def shiftRefsBy15(u, glyph):
160 rl = glyph.layerrefs[glyph.activeLayer]
161 has_selected = False
162 for r in rl:
163 if r[2]:
164 has_selected = True
165 nl = []
166 tr = psMat.translate(15,0)
167 for r in rl:
168 if not has_selected or r[2]:
169 nl.append((r[0], psMat.compose(r[1], tr), r[2]))
170 else:
171 nl.append(r)
172 glyph.preserveLayerAsUndo(glyph.activeLayer)
173 glyph.layerrefs[glyph.activeLayer] = nl
174
175 At the font level each font has its own selection state accessible via the
176 :py:attr:`fontforge.font.selection` property. Many useful font-level tools will
177 be selection-agnostic but some should only apply to selected glyphs. When
178 these are added as menu items they should include enable_functions analogous to
179 those of a glyph-level tool, so that a user learns whey they do and do not
180 apply.
181
182 Enable Functions
183 ^^^^^^^^^^^^^^^^
184
185 Some menu items, such as one that adds a new point in a CharView, may always be
186 "applicable". Others can only do something sensible if the character (or font)
187 has certain features, such as at least one point or reference, or if certain
188 combinations of points, anchor points, and references are selected. When adding
189 a new option you should help the user understand when it is and is not
190 applicable by writing and registering an ``enable`` function. This will allow
191 FontForge to display the item as enabled in the menu when it applies and as
192 disabled when it does not apply.
193
194 The enhanced version of ``shiftRefsBy15()`` only applies if there is at least
195 one reference, so it's enable function could be: ::
196
197 def SRB15Enable(u, glyph):
198 return len(glyph.layerrefs[glyph.activeLayer])>0
199
200 See the next section for an example of how to register this function.
201
202 Hotkeys and Mnemonics
203 ^^^^^^^^^^^^^^^^^^^^^
204
205 A menu item can have both a Hotkey and a Mnemonic. These are two different means
206 of picking a menu item using the keyboard.
207
208 A Hotkey is a single key combination, usually including modifiers like Control,
209 Alt, and Shift, that directly invokes a menu item or other action. Because
210 hotkeys are a "limited resource", unless you are confident that a menu item you
211 register should have one it may be better to let the user add their own if they
212 find your addition particularly useful. As the
213 :py:meth:`fontforge.registerMenuItem` documentation notes, even if you do
214 include a ``hotkey`` string when registering that key combination may already
215 be taken, in which case no hotkey will be assigned.
216
217 Mnemonics provide a *per-menu* key accelerator, usually activated by pressing
218 Alt and then the mnemonic key displayed with an underline. Using sequences of
219 mnemonic key combinations a user can navigate from the menu bar down through
220 sub-menus and choose a menu action entirely with the keyboard. Mnemonics are also
221 a "limited resource" but *less* limited, and we encourage all plugin developers to
222 specify them.
223
224 You specify a mnemonic key by preceding it with an underscore in the name, as in: ::
225
226 fontforge.registerMenuItem(callback=shiftRefsBy15, enable=SRB15Enable,
227 context=("Glyph"), name=("_Shift References by 15", "MyExt.shiftRefsBy15"),
228 submenu=("_MyExt", "MyExt.submenu"))
229
230 which specifes "M" as the mnemonic for the "MyExt" submenu and "S" as the mnemonic for
231 the action.
232
233 Note, however, that the specified mnemonic for the top level is only taken as a
234 suggestion, and if it is not available another will be assigned. This is
235 because different users will have different combinations of plugins and init
236 scripts installed in different orders, so any given mnemonic may already be
237 in use. Because lower menu levels will typically have entries for one plugin
238 or script you can count on getting the mnemonic you specify.
239
240 Best Practices
241 ^^^^^^^^^^^^^^
242
243 In addition to the advice above, we recommend that a plugin put all of its
244 added menu items into or under a single sub-menu of "Tools". A user may have
245 many plugins installed or have their own init scripts so a single plugin should
246 avoid taking up a lot of space.
247
248 Storing Per-Font and Per-Glyph Information
249 ------------------------------------------
250
251 The FontForge SFD file format and python API includes
252 :py:attr:`fontforge.font.persistent` for storing per-font information and
253 :py:attr:`fontforge.glyph.persistent` for storing per-glyph information.
254 These are fragile interfaces, however, and should only be used when strictly
255 necessary.
256
257 The FontForge program does not enforce any pattern of use on these attributes.
258 We suggest the following conventions:
259
260 1. If the contents are *empty*, create a dictionary and add an entry to it
261 with your plugin name as the key. Store your data in or "under" the value
262 of that entry. Then assign it to the ``persistent`` attribute.
263 2. If the content is a dictionary add your entry to it if it is not already
264 present and store the result.
265 3. If the content is not a dictionary warn the user with an
266 :py:meth:`fontforge.ask` dialog that allows them to opt-out of overwriting
267 the value. If they give permission you can create a dictionary as in step
268 1 and overwrite the existing data.
269
270 .. _fontforge.plugin_api:
271
272 Writing a FontForge Plugin
273 --------------------------
274
275 Even when you eventually plan on writing a FontForge Python plugin it will
276 generally be easiest to start by writing an "Init Script". This is a script
277 that, when placed in one of the directories listed by the
278 :py:meth:`fontforge.scriptPath() <fontforge.scriptPath>` function, is
279 automatically run when FontForge is started.
280
281 As a simple example, here is a script that adds an "Add Midpoint Contour" entry
282 to the Char View Tools menu. When any two on-curve points of a glyph are
283 selected this adds a new contour containing a single point that is located
284 midway between the two selected points.::
285
286 import fontforge
287
288 def getSelectedPoints(l):
289 pl = []
290 for c in l:
291 pl.extend( [ p for p in c if p.on_curve and p.selected ] )
292 return pl
293
294 def midContourEnable(u, glyph):
295 return len(getSelectedPoints(glyph.layers[glyph.activeLayer]))==2
296
297 def addMidContour(u, glyph):
298 layer_id = glyph.activeLayer
299 l = glyph.layers[layer_id]
300 pl = getSelectedPoints(l)
301 if len(pl) != 2:
302 fontforge.postError("Bad selection", "You must select "
303 "exactly two on-curve points to add a midpoint contour.")
304 return
305 nc = fontforge.contour()
306 nc.insertPoint(((pl[0].x+pl[1].x)/2, (pl[0].y+pl[1].y)/2, True,
307 fontforge.splineCorner, True))
308 l += nc
309 glyph.preserveLayerAsUndo(layer_id)
310 glyph.layers[layer_id] = l
311
312 fontforge.registerMenuItem(callback=addMidContour, enable=midContourEnable,
313 context=("Glyph"), name="_Add Midpoint Contour")
314
315 This script is typical in that it starts with some imports, defines some
316 functions, and ends by invoking :py:meth:`fontforge.registerMenuItem`. Other
317 scripts may import other modules, define more elaborate functions or classes,
318 or register more menu items or other callbacks. Still, this is a common
319 general pattern.
320
321 The first step in converting the script to a plugin is to wrap the last
322 section in a function called ``fontforge_plugin_init()``. Once the file
323 is packaged appropriately this function will be called after FontForge
324 discovers and loads the plugin (if the user has Enabled it).::
325
326 def fontforge_plugin_init(**kw):
327 fontforge.registerMenuItem(callback=addMidContour,
328 enable=midContourEnable, context=("Glyph"),
329 name="_Add Midpoint Contour")
330
331 The ``**kw`` function argument will capture any keyword arguments passed
332 to the function. There is currently one, discussed below, but more may
333 be added in the future. (Note that while the function can be located
334 in other places (see the section on Entry-points below) it must be a
335 *function*, not a *method*.
336
337 The remaining steps have to do with python "packaging", which is too
338 large a topic to discuss extensively in this guide. A good starting
339 point is `Packaging Python Projects
340 <https://packaging.python.org/tutorials/packaging-projects/>`_ from the
341 Python documentation. The following are the very basics.
342
343 First we create a new directory for our project with the following files:
344
345 1. ``fontforge_midpoint.py`` (The script itself as a single module file.)
346 2. ``LICENSE`` (Containing the license text.)
347 3. ``README.md`` (A file containing basic documentation for the plugin, in this
348 case written in `Python-Mark-down format
349 <https://pypi.org/project/Markdown/>`_.
350 4. ``pyproject.toml``
351 5. ``setup.cfg`` or ``setup.py``
352
353 ``pyproject.toml`` is a short helper file for the ``setuptools`` package
354 builder. It will typically have these contents: ::
355
356 [build-system]
357 requires = [
358 "setuptools>=42",
359 "wheel"
360 ]
361 build-backend = "setuptools.build_meta"
362
363 Finally there is the ``setup.cfg`` file (or, less typically these days, the
364 ``setup.py`` file). It should have contents analogous to these: ::
365
366 [metadata]
367 name = fontforge-midcontour
368 version = 1.0.0
369 author = Example Author
370 author_email = [email protected]
371 description = A FontForge_plugin to add a single-point contour between points
372 long_description = file: README.md
373 long_description_content_type = text/markdown
374 url = https::/github.com/author/MidContour
375 classifiers =
376 Programming Language :: Python :: 3
377 License :: OSI Approved :: MIT License
378 Operating System :: OS Independent
379 Topic :: Text Processing :: Fonts
380
381 [options]
382 py_modules = fontforge_midcontour
383 python_requires = >=3.6
384
385 [options.entry_points]
386 fontforge_plugin =
387 MidContour = fontforge_midcontour
388
389 The ``name`` field is the name of the *package*. Recent Python documentation
390 encourages developers to add their PyPI username to the package name but
391 this practice has not been widely adopted. For now we recommend that you
392 include "fontforge" in the package name along with a string that either
393 specifically identifies what your plugin does or is just a distinctive
394 project name. Therefore ambiguous names like "Point" or "Contour" should
395 be avoided as these are more likely to also be used by someone else. Please
396 search the PyPI database for a candidate name to help ensure it is not already
397 in use. Package names should be all lower case but can contain dashes and
398 underscores.
399
400 The ``url`` should point to your project page or a GitHub (or other such
401 service) repository for the plugin code.
402
403 Obviously the ``description`` field should contain a one-line description of
404 the plugin. However, it is important that this description (or, if that is not
405 possible, the README file) contain the exact string "FontForge_plugin".
406 FontForge does not maintain its own database of plugins; it instead links to
407 the PyPI database query system passing that string.
408
409 ``classifiers`` help users people searching on PyPI to find
410 relevant packages (although the list of classifiers is, unfortunately, fixed).
411 This is a reasonable selection.
412
413 ``py_modules`` should be the list of modules provided by the package without
414 any ``.py`` extensions. (More complicated packages with sub-directories
415 could benefit from using ``packages = find:`` instead.
416
417 The last directives specify the Python package "Entry-points", which are
418 the basis of FontForge's discovery system. The Entry-point identifier
419 must be ``fontforge_plugin``.
420
421 The token on the left of the indented line is the *plugin name*. This will
422 appear in the "Configure Plugins..." dialog and other contexts. It will
423 normally be the name of your package except without "fontforge" and with
424 optional capitalization. It can contain the usual
425 alphanumerics-plus-underscores and also spaces (although spaces are not
426 recommended).
427
428 The token on the right of the equals sign identifies the location of the
429 ``fontforge_plugin_init`` function. In this case it is just at the top
430 level of the module so the identifier is just the module name. If it were
431 instead a property of object "MC" in that module the string would be
432 ``fontforge_midcontour.MC``.
433
434 In some cases you may want to use a ``setup.py`` file instead. The file
435 equivalent to the ``setup.cfg`` above is: ::
436
437 import setuptools
438
439 with open("README.md", "r", encoding="utf-8") as fh:
440 long_description = fh.read()
441
442 setuptools.setup(
443 name="fontforge_midcontour-author",
444 version="1.0.0",
445 author="Example Author",
446 author_email="[email protected]",
447 description="A FontForge_plugin to add a single-point contour between points",
448 long_description = long_description,
449 long_description_content_type = "text/markdown",
450 url="https::/github.com/author/MidContour",
451 py_modules=["fontforge_midcontour"],
452 classifiers=[
453 "Programming Language :: Python :: 3",
454 "License :: OSI Approved :: MIT License",
455 "Operating System :: OS Independent",
456 "Topic :: Text Processing :: Fonts",
457 ],
458 python_requires=">=3.6",
459 entry_points={ 'fontforge_plugin': [ 'MidContour = fontforge_midcontour' ],},
460 )
461
462 Once the directory has the five files with the appropriate contents you can
463 build the package by entering the directory and running ``python -m build`` .
464 If there are no errors the package archive will be added to the ``dist``
465 subdirectory (which will be created if necessary). This package can be
466 installed directly with ``pip install [name]`` or `published on PyPI
467 <https://realpython.com/pypi-publish-python-package/#publishing-to-pypi>`_.
468
469 Marking Dependencies
470 ^^^^^^^^^^^^^^^^^^^^
471
472 A simple plugin may have no dependencies beyond FontForge itself, and because
473 only FontForge will attempt to discover and load plugins it is not necessary
474 to mark that dependency. Other plugins may import numerical processing modules
475 or use ``tkinter`` to raise dialogs.
476
477 "Hard" dependencies—those that a plugin cannot operate without—should be marked
478 in the ``[options]`` section of ``setup.cfg`` with an ``install_requires``
479 directive. If any version of the package will suffice just use its name. If
480 your code requires a minimum version add ``>=`` and then that version. For
481 example, these directives specify that ``tkinter`` and ``numpy`` must be
482 installed, with a minimum ``numpy`` version of 1.19.3: ::
483
484 [options]
485 ...
486 install_requires
487 tkinter
488 numpy>=1.19.3
489
490 Use of the more complex ``requirements.txt`` Python dependency mechanism is not
491 recommended, as it implies more control over the Python environment than makes
492 sense for a FontForge plugin.
493
494 When possible you should avoid dependencies on Python packages that require
495 compilation, either because they are written in another language or because
496 they rely on "external" libraries. The Windows version of FontForge has an
497 embedded Python environment that is not capable of compiling packages, so
498 (at least for now) Windows users will not be able to use your plugin if it
499 has such dependencies.
500
501 The Configuration System
502 ^^^^^^^^^^^^^^^^^^^^^^^^
503
504 The plugin API offers an optional convention for setting and storing plugin-
505 specific parameters. It has two parts:
506
507 1. The initializing call to ``fontforge_plugin_init`` is passed a keyword
508 parameter ``preferences_path``. This is a filesystem path that points to
509 an appropriate location for storing plugin data. It is recommended that
510 plugins either add an appropriate extension to the path (if they only
511 need a single file) or to create a directory of that name and store
512 files within it. The content should point to the same directory on every
513 initialization unless the name of the plugin is changed.
514
515 The parameter can be extracted from the ``**kw`` dictionary (see above)
516 or caught explicitly by changing the definition to
517 ``def fontforge_plugin_init(preferences_path=None, **kw):``
518 2. Plugin configuration is triggered by a call to ``fontforge_plugin_config``,
519 which is a function defined on the same module or object as
520 ``fontforge_plugin_init``. If a plugin defines that function it will be
521 called when a user presses the "Configure" button in the Plugin dialog.
522 If ``fontforge_plugin_init`` is *not* defined the button will be disabled.
523
524 Beyond this API it is entirely up to the plugin to store, retrieve, and offer
525 configuration choices to the user. Until FontForge provides more dialog choices
526 the latter may be difficult without resorting to ``tkinter``. It is also possible
527 to support file-based configuration and use an :py:meth:`fontforge.openFilename()`
528 dialog to ask for the file so that it can be copied into the appropriate location.