├── __init__.py ├── helpers ├── __init__.py ├── testHelper.py └── removeGlyphs.py ├── .gitignore ├── assets ├── readme.gif ├── varfont-prep-repo_artwork.png └── varfont-prep-repo_artwork.sketch ├── simple-compatibility-check.py ├── flatten_components-remove_anchors.py ├── sort-all-selected-fonts.py ├── .vscode └── tasks.json ├── add-feature_code-to-selected_fonts.py ├── check-if-glyphs-exist-in_selected_fonts.py ├── check-if-glyphorder-same.py ├── remove-list-of-glyphs.py ├── README.md ├── LICENSE └── varfont-prep.py /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /helpers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | venv 3 | node_modules -------------------------------------------------------------------------------- /assets/readme.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arrowtype/varfont-prep/HEAD/assets/readme.gif -------------------------------------------------------------------------------- /assets/varfont-prep-repo_artwork.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arrowtype/varfont-prep/HEAD/assets/varfont-prep-repo_artwork.png -------------------------------------------------------------------------------- /assets/varfont-prep-repo_artwork.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arrowtype/varfont-prep/HEAD/assets/varfont-prep-repo_artwork.sketch -------------------------------------------------------------------------------- /helpers/testHelper.py: -------------------------------------------------------------------------------- 1 | def testReload(): 2 | # print("hello, I'm reloaded") 3 | print("hello, I'm REALLY & TRULY reloaded") 4 | print("hello, I'm REALLY & TRULY reloaded?") -------------------------------------------------------------------------------- /simple-compatibility-check.py: -------------------------------------------------------------------------------- 1 | cf=CurrentFont() 2 | 3 | glyphToCheck= "uni0162" 4 | 5 | for f in AllFonts(): 6 | print(f.info.styleName) 7 | print(cf[glyphToCheck].isCompatible(f[glyphToCheck])) -------------------------------------------------------------------------------- /flatten_components-remove_anchors.py: -------------------------------------------------------------------------------- 1 | from vanilla.dialogs import * 2 | files = getFile("Select files to check for character set similarity", allowsMultipleSelection=True, fileTypes=["ufo"]) 3 | 4 | for file in files: 5 | f = OpenFont(file, showInterface=False) 6 | 7 | for g in f: 8 | g.decompose() 9 | g.clearAnchors() 10 | 11 | 12 | f.save() 13 | 14 | f.close() -------------------------------------------------------------------------------- /sort-all-selected-fonts.py: -------------------------------------------------------------------------------- 1 | from vanilla.dialogs import * 2 | 3 | inputFonts = getFile("select masters for var font", allowsMultipleSelection=True, fileTypes=["ufo"]) 4 | 5 | for fontPath in inputFonts: 6 | f = OpenFont(fontPath, showInterface=False) 7 | newGlyphOrder = f.naked().unicodeData.sortGlyphNames(f.glyphOrder, sortDescriptors=[dict(type="cannedDesign", ascending=True, allowPseudoUnicode=True)]) 8 | f.glyphOrder = newGlyphOrder 9 | f.save() 10 | f.close() -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Run in RoboFont", 6 | "type": "shell", 7 | "command": "robofont", 8 | "args": ["-p", "${file}"], 9 | "group": { 10 | "kind": "build", 11 | "isDefault": true 12 | } 13 | }, 14 | { 15 | "label": "Run Current Python File", 16 | "type": "shell", 17 | "command": "python3", 18 | "args": ["${file}"], 19 | } 20 | ] 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /add-feature_code-to-selected_fonts.py: -------------------------------------------------------------------------------- 1 | from vanilla.dialogs import * 2 | 3 | 4 | inputFonts = getFile("select masters to add feature code to", 5 | allowsMultipleSelection=True, fileTypes=["ufo"]) 6 | 7 | 8 | feaText = """\ 9 | languagesystem DFLT dflt; 10 | languagesystem latn dflt; 11 | 12 | """ 13 | 14 | 15 | def addFeatureCode(f): 16 | f.features.text = feaText 17 | 18 | 19 | for fontPath in inputFonts: 20 | f = OpenFont(fontPath, showInterface=False) 21 | addFeatureCode(f) 22 | fontName = f.info.familyName + " " + f.info.styleName 23 | print("feature code added to " + fontName) 24 | f.save() 25 | f.close() 26 | -------------------------------------------------------------------------------- /check-if-glyphs-exist-in_selected_fonts.py: -------------------------------------------------------------------------------- 1 | 2 | from vanilla.dialogs import * 3 | 4 | inputFonts = getFile("select UFOs", allowsMultipleSelection=True, fileTypes=["ufo"]) 5 | 6 | lettersToCheckFor = ["a","f","g","i","l","r","y","a.roman","f.roman","g.roman","i.roman","l.roman","r.roman","y.roman", "a.italic","f.italic","g.italic","i.italic","l.italic","r.italic","y.italic"] 7 | 8 | 9 | 10 | 11 | for fontPath in inputFonts: 12 | f = OpenFont(fontPath, showInterface=False) 13 | 14 | # do stuff to the font, e.g. sort, check anchors, add fea code, etc 15 | for gName in lettersToCheckFor: 16 | if gName not in f: 17 | print(f.info.styleName + " is missing glyph " + gName) 18 | 19 | f.save() 20 | f.close() -------------------------------------------------------------------------------- /check-if-glyphorder-same.py: -------------------------------------------------------------------------------- 1 | from vanilla.dialogs import * 2 | 3 | glyphOrderDict = {} 4 | 5 | # help(CurrentFont().removeGlyph()) 6 | 7 | inputFonts = getFile("select masters for var font", allowsMultipleSelection=True, fileTypes=["ufo"]) 8 | 9 | for fontPath in inputFonts: 10 | f = OpenFont(fontPath, showInterface=False) 11 | 12 | glyphs = [] 13 | # # open the fonts, then: 14 | for glyphName in f.glyphOrder: 15 | # print(glyphName) 16 | glyphs.append(glyphName) 17 | 18 | # print(glyphs) 19 | glyphOrderDict[f.info.styleName] = glyphs 20 | 21 | # print(glyphOrderDict) 22 | f.save() 23 | f.close() 24 | 25 | # print(glyphOrderDict) 26 | 27 | glyphOrderList = [] 28 | 29 | for val in glyphOrderDict.values(): 30 | glyphOrderList.append(tuple(val)) 31 | # print(val) 32 | 33 | glyphOrderSet = set(glyphOrderList) 34 | 35 | # 36 | 37 | if len(glyphOrderSet) >= 2: 38 | print("different glyph sets") 39 | else: 40 | print("same glyph sets \n") 41 | print(glyphOrderSet) 42 | -------------------------------------------------------------------------------- /helpers/removeGlyphs.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def removeGlyphs(f, glyphsToRemove): 4 | 5 | # FONT KEYs ----------------------------------------------- 6 | 7 | # clean up the rest of the data 8 | for glyphName in glyphsToRemove: 9 | # remove from keys 10 | # if glyphToRemove in f.keys(): 11 | if glyphName in f: 12 | del f[glyphName] 13 | else: 14 | print("font does not contain a glyph named '%s'" % glyphName) 15 | 16 | # LAYERS -------------------------------------------------- 17 | 18 | for layerName in f.layerOrder: 19 | layer = f.getLayer(layerName) 20 | for glyphToRemove in glyphsToRemove: 21 | if glyphToRemove in layer: 22 | del layer[glyphToRemove] 23 | # else: 24 | # print("%s does not contain a glyph named '%s'" % 25 | # (layerName, glyphToRemove)) 26 | 27 | 28 | # GLYPH ORDER --------------------------------------------- 29 | 30 | glyphOrder = f.glyphOrder 31 | 32 | for glyphName in glyphsToRemove: 33 | if glyphName in glyphOrder: 34 | glyphOrder.remove(glyphName) 35 | 36 | f.glyphOrder = glyphOrder 37 | 38 | # KERNING ----------------------------------------------------------- 39 | 40 | for glyphName in glyphsToRemove: 41 | # iterate over all kerning pairs in the font 42 | for kerningPair in f.kerning.keys(): 43 | 44 | # if glyph is in the kerning pair, remove it 45 | if glyphName in kerningPair: 46 | print('removing kerning pair (%s, %s)...' % kerningPair) 47 | del f.kerning[kerningPair] 48 | 49 | # COMPONENTS ------------------------------------------------------- 50 | 51 | # iterate over all glyphs in the font 52 | for glyph in f: 53 | 54 | # skip glyphs which components 55 | if not glyph.components: 56 | continue 57 | 58 | # iterate over all components in glyph 59 | for component in glyph.components: 60 | 61 | # if the base glyph is the glyph to be removed 62 | if component.baseGlyph in glyphsToRemove: 63 | # delete the component 64 | glyph.removeComponent(component) 65 | -------------------------------------------------------------------------------- /remove-list-of-glyphs.py: -------------------------------------------------------------------------------- 1 | import os 2 | from mojo.UI import AskString 3 | from vanilla.dialogs import * 4 | 5 | # copy-paste to fill this list with whatever glyphs fontMake flags as not being interpolatable 6 | # glyphsToDelete = ['LISTOFGLYPHSHERE'] 7 | 8 | glyphsToRemove = AskString( 9 | 'Input glyphnames to remove, then select UFOs').replace("'", "").replace(",", "").split(" ") 10 | 11 | # help(CurrentFont().removeGlyph()) 12 | 13 | instruction = f"select masters to remove {glyphsToRemove} from" 14 | 15 | inputFonts = getFile( 16 | instruction, allowsMultipleSelection=True, fileTypes=["ufo"]) 17 | 18 | # copy space-separated glyph names here 19 | # glyphsToRemove = list(f.selectedGlyphNames) 20 | 21 | def removeGlyphs(glyphsToRemove,f): 22 | 23 | # LAYERS -------------------------------------------------- 24 | 25 | for layerName in f.layerOrder: 26 | layer = f.getLayer(layerName) 27 | for glyphToRemove in glyphsToRemove: 28 | if glyphToRemove in layer: 29 | del layer[glyphToRemove] 30 | # else: 31 | # print("%s does not contain a glyph named '%s'" % 32 | # (layerName, glyphToRemove)) 33 | 34 | 35 | # GLYPH ORDER --------------------------------------------- 36 | 37 | glyphOrder = f.glyphOrder 38 | 39 | for glyphName in glyphsToRemove: 40 | if glyphName in glyphOrder: 41 | glyphOrder.remove(glyphName) 42 | 43 | f.glyphOrder = glyphOrder 44 | 45 | # KERNING ----------------------------------------------------------- 46 | 47 | for glyphName in glyphsToRemove: 48 | # iterate over all kerning pairs in the font 49 | for kerningPair in f.kerning.keys(): 50 | 51 | # if glyph is in the kerning pair, remove it 52 | if glyphName in kerningPair: 53 | print('removing kerning pair (%s, %s)...' % kerningPair) 54 | del f.kerning[kerningPair] 55 | 56 | # COMPONENTS ------------------------------------------------------- 57 | 58 | # iterate over all glyphs in the font 59 | for glyph in f: 60 | 61 | # skip glyphs which components 62 | if not glyph.components: 63 | continue 64 | 65 | # iterate over all components in glyph 66 | for component in glyph.components: 67 | 68 | # if the base glyph is the glyph to be removed 69 | if component.baseGlyph in glyphsToRemove: 70 | # delete the component 71 | glyph.removeComponent(component) 72 | 73 | # FONT KEYs ----------------------------------------------- 74 | 75 | # clean up the rest of the data 76 | for glyphName in glyphsToRemove: 77 | print(glyphName) 78 | # remove from keys 79 | #if glyphName in f: 80 | if glyphName in f.keys(): 81 | del f[glyphName] 82 | else: 83 | print("font does not contain a glyph named '%s'" % glyphName) 84 | 85 | # clearing this list so it's not saved... 86 | glyphsToRemove = [] 87 | 88 | for fontPath in inputFonts: 89 | f = OpenFont(fontPath, showInterface=False) 90 | 91 | removeGlyphs(glyphsToRemove, f) 92 | 93 | print("done!") 94 | f.save() 95 | f.close() 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![varfont-prep repo artwork](assets/varfont-prep-repo_artwork.png) 2 | 3 | # VarFont Prep 4 | 5 | This is a work-in-progress script to prep UFOs for the generation of a variable font ("VF"). 6 | 7 | A current challenge in making variable fonts from UFOs is that FontMake & FontTools expect all input font masters to be almost perfectly in-sync, without any different or incompatible glyphs. If you have any incompatibility – whether in glyphs, character sets, or even guides, the build will fail. During a design project, this kind of synchrony between several masters is nearly impossible, and certainly a counterproductive thing to focus on (because it prevents rapid exploration within masters). 8 | 9 | ![](assets/readme.gif) 10 | 11 | VarFont Prep seeks to make it easy: it checks UFOs for consistency and compatibility, then outputs new, build-ready UFOs which exclude all non-compatible glyphs. It also outputs a text report to make clear what glyphs were deleted. This is a slightly brute-force approach to the problem, but it allows the type design process to be organic (and therefore productive): exploration can be done on alternate glyphs within each master, without worries about making compatible alternate characters in every other master of the font project. The variable font can be prototyped and tested along the way, with fallback fonts used in proofs where useful. The variable font may have flaws – and that's a good thing! During a design process, *testable* is better than perfect. 12 | 13 | **NOTE:** VarFont Prep does not edit the UFOs you select, but rather creates edited copies of these. However, as with any scripting for type design, it is not guaranteed that this workflow is 100% safe to the source fonts. You should always keep backups and use version control to make it simple to revert to earlier versions of the project, in case there are unintended effects on your source files. 14 | 15 | ## Usage 16 | 17 | 1. Use `git clone` to download this repo into your RoboFont scripts folder (or download it as a zip). 18 | 2. Open RoboFont 19 | 3. Run **Scripts > varfont-prep > varfont-prep.py** 20 | 1. This will present a file explorer, allowing you to select the designspace file you want to use for your variable font. 21 | 2. Click "Open" 22 | 3. Wait while the files process. This may take some time, and will make RoboFont temporarily unresponsive. 23 | 4. Find the varfont-prep folder, which will be at the same level as the UFOs you selected. It will contain UFOs that are ready (or close to ready) for interpolation. 24 | 5. Create or adapt a designspace file to describe the variable font you wish to create. 25 | 6. Use [FontMake](https://github.com/googlefonts/fontmake) to generate a variable font: `fontmake -o variable -m [[ PATH/DESIGNSPACE_FILE.designspace ]]` 26 | 27 | 28 | ## Tips 29 | 30 | You can make non-exporting glyphs by adding a `_` in front of their names. For instance, I have made the glyph `_arrowhead`, which I use in lots of arrow glyphs, but do not want to export into final fonts. So, Var Font Prep finds and decomposes these components, then deletes the `_arrowhead` glyph. 31 | 32 | 33 | ### Troubleshooting 34 | 35 | Likely, FontMake will report that there are incompatible glyphs, witha warning like `cu2qu.errors.IncompatibleFontsError: fonts contains incompatible glyphs: 'a.italic', 'd.italic', 'f.italic', 'g', 'g.italic', 'h.italic', 'i.italic', 'n.italic', 'q', 'r', 'u.italic', 'y', 'z.italic'`. This is useful information! Copy the glyph list output from this error. 36 | 37 | 1. Go back to RoboFont, and run the script `remove-list-of-glyphs.py` (also in this repo). 38 | 2. Paste in the copied list of incompatible glyphs to remove. 39 | 3. A file explorer will open. Find the `varfontprep` folder, and select all UFOs within it. This will remove the glyphs that are incompatible. This is a brute-force way to generate a VF for testing, and this is why we're working with duplicates! Obviously, be sure you aren't selecting the actual sources here, or you will need to dig into your backups. 40 | 41 | FontMake may report an error connected to your OpenType features, such as `KeyError: ('a.italic', 'SingleSubst[0]', 'Lookup[0]', 'LookupList')`. 42 | 43 | 1. Use the script `add-feature_code-to-selected_fonts.py` to add (nearly) blank feature code to all selected UFOs. If you prefer, you can edit the feature code in this script to whatever you want as the actual feature code for your output font. However, feature code is often the source of issues in font builds, so only add feature code when you actually want to start testing feature code. 44 | 45 | This is very much a work-in-progress set of techniques, and I will add to it more over time. 46 | 47 | ### Current Limitations 48 | 49 | - VarFont Prep is not currently ready to output production-ready font sources. It is a tool for prototyping rather than for mastering release-ready fonts, and the cleanliness of its outputs is very dependant on the cleanliness of the inputs. Of course, this is an advantage: shortcomings of font sources are often easiest to see in an output font. 50 | - Glyphs compatibility is checked with the [isCompatible](https://fontparts.readthedocs.io/en/stable/objectref/objects/glyph.html?highlight=compatible#fontParts.base.BaseGlyph.isCompatible) method of FontParts, which is not as strict as the requirements of the cu2qu module used in the FontMake VF build process. However, if glyphs remain which are incompatible and this blocks the VF build, FontMake tends to output decently-specific warnings about this. 51 | - When FontMake *does* tell you which glyphs are incompatible, you can either fix them in the original files, then run VarFont Prep again, *or* you can run `remove-list-of-glyphs.py` on the UFOs in the next folder or prepped UFOs. Obviously, be sure not to run this on your source font files. 52 | - This doesn't check and remove all possible incompatibilities from sources. Areas that aren't currently covered are kerning and anchors. 53 | - Sometimes, the `/space` glyph is deleted in the prepped UFOs (though, I haven't experience this issue recently, so it may be solved – I need to verify). If the `/space` glyph is missing, this is patched by re-adding it and giving it a width of `600` units. This is unintended behavior, but shouldn't affect you if you have a `/space` glyph in all sources (as you probably do). This issue may occur with other empty glyphs as well. Please file an issue if you find this happening. 54 | 55 | 56 | ## Needs 57 | 58 | - Refactoring for performance. Currently, this opens and closes font files multiple times, which is wasteful and most likely slows down processing substantially. 59 | - Probably, run `cu2qu -i` to pre-convert to TTF. This will provide a more-accurate view of what can and cannot convert. 60 | - Instead of removing unsupported glyphs, there should be the option to fill them in from the next-closest master. E.G. ExtraBold Italic glyphs could fill in for missing glyphs in Heavy Italic. 61 | - (how would this detect the next-closest master? with the designspace?) 62 | - Can this run as an external script, instead of being tied to RoboFont? 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /varfont-prep.py: -------------------------------------------------------------------------------- 1 | # varfont prep 2 | 3 | 4 | 5 | from vanilla.dialogs import * 6 | import os 7 | import shutil 8 | import datetime 9 | from fontTools.designspaceLib import BaseDocReader, DesignSpaceDocument 10 | from mojo.UI import OutputWindow 11 | import helpers 12 | from helpers.removeGlyphs import * 13 | 14 | 15 | debug = True 16 | 17 | if debug == True: 18 | import importlib 19 | importlib.reload(helpers.removeGlyphs) 20 | from helpers.removeGlyphs import * 21 | 22 | 23 | OutputWindow().show() 24 | OutputWindow().clear() 25 | 26 | report = """ 27 | Var Prep Report 28 | ******************************************** 29 | 30 | """ 31 | 32 | now = datetime.datetime.now() 33 | 34 | def getSourcePathsFromDesignspace(): 35 | 36 | designspacePath = getFile("select designspace for variable font", 37 | allowsMultipleSelection=False, fileTypes=["designspace"])[0] 38 | 39 | designspace = DesignSpaceDocument.fromfile(designspacePath) 40 | 41 | inputFontPaths = [] 42 | for source in designspace.sources: 43 | inputFontPaths.append(source.path) 44 | 45 | return designspacePath, inputFontPaths 46 | 47 | def openFontsInList(fontPaths): 48 | fontsList = [] 49 | for path in fontPaths: 50 | f = OpenFont(path, showInterface=False) 51 | fontsList.append(f) 52 | 53 | return fontsList 54 | 55 | 56 | def checkIfSameFamilyName(fontsList): 57 | fontFamilyNames = [] 58 | global report 59 | 60 | for f in fontsList: 61 | familyName = f.info.familyName 62 | fontFamilyNames.append(familyName) 63 | 64 | sameName = all(x == fontFamilyNames[0] for x in fontFamilyNames) 65 | 66 | if sameName == True: 67 | return sameName, fontFamilyNames[0] 68 | else: 69 | errorMsg = "The input UFOs have different font family names: " + \ 70 | str(set(fontFamilyNames)) 71 | # generateReport(inputFontPaths, errorMsg) 72 | 73 | report += errorMsg + "\n" 74 | 75 | return False, fontFamilyNames[0] 76 | # return errorMsg 77 | 78 | 79 | def makeVarFontPrepFolder(fontsList, designspacePath): 80 | 81 | sameFamily, familyName = checkIfSameFamilyName(fontsList) 82 | 83 | # # check that selected fonts have same family name 84 | if sameFamily == True: 85 | # get family name 86 | familyName = familyName 87 | else: 88 | familyName = "ERROR: families have different names" 89 | 90 | # make new folder name with font family name and "varfontprep" label 91 | newFolderName = familyName.replace(" ", "_").lower() + "-varfontprep" 92 | 93 | # get head of font path 94 | head, tail = os.path.split(designspacePath) 95 | 96 | # make new folder path 97 | newFolderPath = head + "/" + newFolderName 98 | 99 | now = datetime.datetime.now() 100 | newFolderPath += "-" + now.strftime("%Y_%m_%d-%H_%M_%S") 101 | os.mkdir(newFolderPath) 102 | print(newFolderPath) 103 | return str(newFolderPath) 104 | 105 | 106 | def copyFonts(inputFontPaths, newFolderPath): 107 | for fontPath in inputFontPaths: 108 | head, tail = os.path.split(fontPath) 109 | 110 | newPath = newFolderPath + "/" + tail 111 | 112 | if os.path.exists(newPath) == False: 113 | 114 | # copy UFO into newFolderPath 115 | # "+ /varprep- +" was formerly added to path, before tail 116 | shutil.copytree(fontPath, newPath) 117 | 118 | 119 | designspacePath, inputFontPaths = getSourcePathsFromDesignspace() 120 | 121 | inputFontsList = openFontsInList(inputFontPaths) 122 | 123 | newFolderPath = makeVarFontPrepFolder(inputFontsList, designspacePath) 124 | copyFonts(inputFontPaths, newFolderPath) 125 | 126 | print(inputFontsList) 127 | 128 | for f in inputFontsList: 129 | f.close() 130 | 131 | # open copied fonts in new dictionary 132 | copiedFontPaths = [] 133 | for fontPath in inputFontPaths: 134 | head, tail = os.path.split(fontPath) 135 | newPath = newFolderPath + "/" + tail 136 | copiedFontPaths.append(newPath) 137 | print(newPath) 138 | 139 | fontsList = openFontsInList(copiedFontPaths) 140 | 141 | print(fontsList) 142 | 143 | 144 | ############################################### 145 | ######### copy and update designspace ######### 146 | 147 | 148 | def copyDesignSpace(designspacePath, newFolderPath): 149 | 150 | # duplicate designspace into new folder 151 | inputDStail = os.path.split(designspacePath)[1] 152 | outputDSpath = newFolderPath + "/" + inputDStail 153 | 154 | shutil.copyfile(designspacePath, outputDSpath) 155 | 156 | # update source & instance paths in designspace as needed 157 | outputDS = DesignSpaceDocument.fromfile(outputDSpath) 158 | 159 | # updates path if sources were originally in a different directory than designspace file 160 | for source in outputDS.sources: 161 | newFontPath = newFolderPath + '/' + os.path.split(source.path)[1] 162 | source.path = newFontPath 163 | 164 | outputDS.write(outputDSpath) 165 | 166 | 167 | copyDesignSpace(designspacePath, newFolderPath) 168 | 169 | 170 | 171 | 172 | 173 | ######################################### 174 | ######### make fonts compatible ######### 175 | ######################################### 176 | 177 | 178 | 179 | copiedFonts = [] 180 | 181 | # get paths 182 | for file in os.listdir(newFolderPath): 183 | if os.path.splitext(file)[1] == ".ufo": 184 | copiedFonts.append(file) 185 | 186 | listOfGlyphsLists = [] 187 | 188 | def addGlyphListToGlyphLists(f): 189 | 190 | fontName = f.info.familyName + " " + f.info.styleName 191 | 192 | # print(fontName) 193 | 194 | glyphs = [] 195 | 196 | for g in f: 197 | glyphs.append(g.name) 198 | 199 | listOfGlyphsLists.append(glyphs) 200 | 201 | # should you only remove glyphs ONCE? make list of compatible AND similar glyphs? 202 | def constrainCharSetToSimilarGlyphs(f, commonGlyphs): 203 | global report 204 | 205 | report += "Unique glyphs removed from " + \ 206 | f.info.familyName + " " + f.info.styleName + ":\n" 207 | 208 | # print(f.info.familyName + " " + f.info.styleName) 209 | 210 | # print(f.keys()) 211 | 212 | diff = set(f.keys()) - set(commonGlyphs) 213 | 214 | print('diff of font keys vs commonGlyphs') 215 | # print(list(diff).sort()) 216 | print(diff) 217 | 218 | uncommonGlyphs = [] 219 | for g in f: 220 | if g.name not in commonGlyphs: 221 | uncommonGlyphs.append(g.name) 222 | # print(g.name + " removed from " + f.info.styleName) 223 | 224 | report += g.name + ", " 225 | 226 | print("removing uncommon glyphs from ", f.info.styleName) 227 | # print(list(uncommonGlyphs).sort()) 228 | print(uncommonGlyphs) 229 | 230 | diffDiffs = set(diff) - set(uncommonGlyphs) 231 | 232 | print("\n--------------------------") 233 | print('diff of diffs?') 234 | print(diffDiffs) 235 | 236 | removeGlyphs(f, uncommonGlyphs) 237 | 238 | report += "\n \n" 239 | 240 | # -------------------------------------------------------------------------------------------------------- 241 | # decompose non-exporting glyphs (glyphs with a underscore leading in their name, such as "_arrowhead") 242 | 243 | def nonExporting(glyphName): 244 | if glyphName[0] == "_": 245 | return True 246 | 247 | def findAndDecomposeComponents(font, componentNames): 248 | for g in font: 249 | if len(g.components) > 0: 250 | for component in g.components: 251 | if component.baseGlyph in componentNames: 252 | component.decompose() 253 | 254 | def decomposeNonExportingComponents(f): 255 | global report 256 | nonExportingGlyphs = [] 257 | 258 | for g in f: 259 | print("\t",g.name) 260 | if nonExporting(g.name) == True: 261 | # add to list 262 | nonExportingGlyphs.append(g.name) 263 | 264 | findAndDecomposeComponents(f, nonExportingGlyphs) 265 | removeGlyphs(f, nonExportingGlyphs) 266 | 267 | report += f"Decomposed and removed non-exporting glyphs: {nonExportingGlyphs}" 268 | 269 | # -------------------------------------------------------------------------------------------------------- 270 | # remove guides 271 | 272 | 273 | def removeGuides(f): 274 | global report 275 | report += "******************* \n" 276 | report += "Guides removed from " + \ 277 | f.info.familyName + " " + f.info.styleName + ":\n" 278 | 279 | for g in f: 280 | if g.guidelines != (): 281 | g.clearGuidelines() 282 | report += g.name + "; " 283 | 284 | report += "\n \n" 285 | 286 | # -------------------------------------------------------------------------------------------------------- 287 | # compatiblity checks 288 | 289 | def findCompatibleGlyphs(fontsList): 290 | global report 291 | 292 | nonCompatibleGlyphs = [] 293 | nonCompatibleGlyphsReport = "" 294 | 295 | for g in fontsList[0]: 296 | # print(g.name) 297 | # f in all fonts 298 | for checkingFont in fontsList: 299 | print(checkingFont.path) 300 | # test glyphCompatibility 301 | if g.name in checkingFont.keys(): 302 | glyphCompatibility = g.isCompatible(checkingFont[g.name]) 303 | 304 | if glyphCompatibility[0] != True: 305 | print(glyphCompatibility[0]) 306 | nonCompatibleGlyphs.append(g.name) 307 | nonCompatibleGlyphsReport += g.name + \ 308 | "\n" + str(glyphCompatibility) + "\n" 309 | else : 310 | nonCompatibleGlyphs.append(g.name) 311 | nonCompatibleGlyphsReport += g.name + \ 312 | "\n" + str(glyphCompatibility) + "\n" 313 | 314 | report += "\n ******************* \n" 315 | report += "non-compatible glyphs removed: \n" 316 | report += nonCompatibleGlyphsReport 317 | 318 | return nonCompatibleGlyphs 319 | 320 | # remove glyphs that aren't compatible in every font 321 | def removeNonCompatibleGlyphs(f, nonCompatibleGlyphs): 322 | 323 | removeGlyphs(f, nonCompatibleGlyphs) 324 | 325 | for g in f.templateKeys(): 326 | f.removeGlyph(g) 327 | 328 | if 'space' not in f.keys(): 329 | f.newGlyph('space') 330 | f['space'].unicode = '0020' 331 | f['space'].width = 600 332 | 333 | if f['space'].width == 0: 334 | f['space'].width = 600 335 | 336 | 337 | # -------------------------------------------------------------------------------------------------------- 338 | # FIX FILES 339 | 340 | # in first pass, decompose nonExporting glyphs, remove guides, and find common glyphs 341 | print("\n---------------------------------------------------\n") 342 | print("first pass: decompose nonExporting glyphs, remove guides, and find common glyphs") 343 | for f in fontsList: 344 | print(f.info.styleName) 345 | # decompose non-exporting glyphs 346 | decomposeNonExportingComponents(f) 347 | # remove guides 348 | removeGuides(f) 349 | 350 | 351 | # TODO (Urgent) – fix function to find uncommon glyphs. Currently seems to be failing 352 | 353 | # in second pass, remove glyphs that aren't present in every font 354 | print("\n---------------------------------------------------\n") 355 | print("second pass: remove glyphs that aren't present in every font") 356 | 357 | for f in fontsList: 358 | # create lists of glyphs in each font 359 | addGlyphListToGlyphLists(f) 360 | 361 | # print("\n---------------------------------------------------\n") 362 | # print("listOfGlyphsLists") 363 | # print(listOfGlyphsLists) 364 | 365 | # create one list of glyphs present in every font 366 | commonGlyphs = set(listOfGlyphsLists[0]).intersection(*listOfGlyphsLists[1:]) 367 | # commonGlyphs = set(fontsList[0].keys()).intersection(*fontsList[1:].keys()) 368 | 369 | print("commonGlyphs") 370 | print(commonGlyphs) 371 | 372 | for f in fontsList: 373 | constrainCharSetToSimilarGlyphs(f, commonGlyphs) 374 | 375 | 376 | # find compatible glyphs 377 | nonCompatibleGlyphs = findCompatibleGlyphs(fontsList) 378 | 379 | # remove nonCompatibleGlyphs from each font 380 | for f in fontsList: 381 | removeNonCompatibleGlyphs(f, nonCompatibleGlyphs) 382 | 383 | 384 | # -------------------------------------------------------------------------------------------------------- 385 | # kerning compatibility 386 | 387 | # check if there is kerning in any of the UFOs 388 | kerningInFonts = False 389 | 390 | for f in fontsList: 391 | if len(f.kerning) > 0: 392 | kerningInFonts = True 393 | 394 | # if there is kerning in some UFOs, check others and add blank kerning if needed 395 | if kerningInFonts: 396 | report += "\n ******************* \n" 397 | for f in fontsList: 398 | if len(f.kerning) == 0: 399 | f.kerning[("A", "A")] = 0 400 | 401 | print("adding blank kerning to ", f.info.styleName) 402 | report += f"Adding blank kerning to {f.info.styleName}\n" 403 | 404 | report += "\n ******************* \n" 405 | 406 | 407 | # -------------------------------------------------------------------------------------------------------- 408 | # sort fonts 409 | 410 | print("\nsorting fonts\n") 411 | 412 | def sortFont(font): 413 | # the new default is at the end, so this will re-apply a "smart sort" to the font 414 | newGlyphOrder = font.naked().unicodeData.sortGlyphNames(font.glyphOrder, sortDescriptors=[dict(type="cannedDesign", ascending=True, allowPseudoUnicode=True)]) 415 | font.glyphOrder = newGlyphOrder 416 | 417 | for f in fontsList: 418 | sortFont(f) 419 | 420 | 421 | # -------------------------------------------------------------------------------------------------------- 422 | # close fonts 423 | 424 | for f in fontsList: 425 | f.save() 426 | f.close() 427 | 428 | 429 | 430 | 431 | ######################################################################### 432 | ############# TO DO: present vanilla.ProgressBar ######################## 433 | ######################################################################### 434 | 435 | ######################################################################### 436 | ############# TO DO: sort fonts in the same way ######################### 437 | ######################################################################### 438 | 439 | ######################################################################### 440 | ############# TO DO: check anchor compatibility ? ####################### 441 | ######################################################################### 442 | 443 | ######################################### 444 | ############# write report ############## 445 | ######################################### 446 | 447 | reportOutput = open(newFolderPath + "/" + 'varfontprep-report.txt', 'w') 448 | reportOutput.write(now.strftime("%H:%M:%S; %d %B, %Y\n\n")) 449 | reportOutput.write("*******************\n") 450 | reportOutput.write(report) 451 | reportOutput.close() 452 | --------------------------------------------------------------------------------